branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
|---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<repo_name>lg0812/new-point<file_sep>/src/index.js
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux'
import {Provider} from 'react-redux'
import {Route, HashRouter} from 'react-router-dom'
import thunk from "redux-thunk"
import logger from "redux-logger"
import './index.css';
import reducers from './store/reducers'
import App from './App';
import BizIndex from './components/BizIndex';
import registerServiceWorker from './registerServiceWorker';
// const store = applyMiddleware(thunk, logger)(createStore)(reducers);
const store = createStore(
reducers,
applyMiddleware(thunk, logger)
)
console.log("%c yltfy %c Copyright \xa9 2016-%s",
'font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;font-size:64px;color:#00bbee;-webkit-text-fill-color:#00bbee;-webkit-text-stroke: 1px #00bbee;',
"font-size:12px;color:#999999;",
(new Date()).getFullYear());
const Routes = () => (
<div>
<Route path="/biz" component={BizIndex}/>
<Route path="/app" component={App}/>
</div>
)
ReactDOM.render(
(<Provider store={store}>
<HashRouter>
<Route path="/" component={Routes}/>
</HashRouter>
</Provider >),
document.getElementById('root')
);
registerServiceWorker();
|
e6e50e0946755a43f983a85e8669485aa68e7fbd
|
[
"JavaScript"
] | 1
|
JavaScript
|
lg0812/new-point
|
712050eef8f1e5881dca4663bc9b793bbca46817
|
5d75f36d4de983bba6a14b829198f6fb6efe2756
|
refs/heads/master
|
<repo_name>compomics/ProteinAssociationPair<file_sep>/sourceCode/ProteinPairWithCommonPepCheck.py
__author__ = 'surya'
######################################################################################################################################################
##################### ## import methods and files and file pathways pathways ###################################################################
######################################################################################################################################################
import os
from Analysis import PathwayCoverage, createPairsByComparing
from GeneralMethods import Generalmethods
from DatabasePreprocessing import protein2pathway, SelectingIntActForSignallingProteins
from PreProcessing import filterings
from DatabaseAnnotation import AddParalogueInformation,CheckPairForComplex,RemovePairHavingCrapProteins, \
GetDistinctivePeptidesNames, ComparePairwithLocalization,checkForBioGridInteraction
from datetime import datetime
from PostProcessing import GetUniprotName, GetKeratinAndIgAnnotation
PPI_MSPath="C:/Users/surya/Desktop/ProjectData/PPI_MSdata/"
DatabasePath="C:/Users/surya/Desktop/PPI_and_functional_interaction_among_species/Database_data/"
MSprotein2Assay2PepCountFile="RespinData/Pandey/prot2assay2DistinctPep.txt"## this is for pandey dataset
# MSprotein2Assay2PepCountFile="RespinData/protein2EachAssay2Distinct_PeptideName_OnlyHuman.txt"
prot2pathFile="Reactome/ver56_7Jun/UniProt2Reactome_lowestLevel_humanOnly_7Jun.txt"
pathwaysFile="Reactome/ver56_7Jun/ReactomeCompleterListOfPathway_AllSpecies_7June.txt" ## for all species
crapFile="cRAP/crapProt2Names1March.txt"
UniprotFile="uniprot/human/uniprot_20201human_reviewed_6Jun.tab"
# Uniprot2GOFile="uniprot/6JuneFile/749ProteinMapped2uniprotwithGOOntology_15Sep.tab"
Uniprot2GOFile="uniprot/6JuneFile/489UniqueProteinsSelectedOnlyGO_13Oct.tab"## this is for pandey dataset
Uniprot2GeneIdFile="uniprot/6JuneFile/HumanProtein6JuneSelectedInfo.txt"
IntActFile="IntAct/MergingIntAct8Feb16.txt"
BioGridFile="biogrid/BIOGRIDhuman34145tab2.txt" #onlyhuman
Uniprot2EnsemblFile="uniprot/human/UniprotAll_18963_Proteins2EnsemblGeneID_6Jun2016.txt"
# UniprotFile="database/"
paralogFile="ensembl/human/geneParalog15Feb.txt"
complexFile="corum_complexDatabase/coreComplexes_07Dec16.txt"
protein2PepetideFile="RespinData/Pandey/protein2distinctPeptide.txt" ## this is for pandey dataset
# protein2PepetideFile="RespinData/EachProtein2DistinctPepetides9March.txt"
interproFile="InterPro/InterproDomainSearch_20204humanReviewed_OnlyCanonicalFasta_15April.tsv"
######################################################################################################################################################
###################################### cutoff selections ############################################################################################
######################################################################################################################################################
start= datetime.now()
print start
minAssayCount=9
jaccCutoff=0.4
todayDate="16Feb"
######################################################################################################################################################
###################################### use cutoff selection to write files ##########################################################################
######################################################################################################################################################
newPath=PPI_MSPath+"CheckingMSPairForAllMSProteins/newDataFileteredDataset/pandey/UniprotWithRemovedTop10Assay/"
# if not os.path.isdir(newPath):
# os.makedirs(newPath)
log=[str(datetime.now())+" starting time..."]
logFile = open(newPath + "logFile.txt", "w")
outWrite1=open(newPath+"UniProtPairWith0.1Jacc_"+todayDate+".txt","w")
outWrite2=open(newPath+"UniProtPairUsedForPathwayMappingwith"+str(minAssayCount+1)+"CommAssay"+str(jaccCutoff)+"jacc_"+todayDate+".txt","w")
outWrite3=open(newPath+"UniProtPairNotUsedForPathwayMappingwith"+str(minAssayCount+1)+"CommAssay"+str(jaccCutoff)+"jacc_"+todayDate+".txt","w")
outWrite4=open(newPath+"PathWithUniProtFound"+str(minAssayCount+1)+"CommAssay"+str(jaccCutoff)+"jacc_"+todayDate+".txt","w")
outWrite5=open(newPath+"proteinPair2With0.1_CommonAssayNames.txt","w")
selectedProteinFile=open(newPath+"SelectedProteinPresentInUniprot.txt","w")
paraOutname=newPath + "UniProteinAllPairWithParalogue"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
complexOutname=newPath+"UniProteinAllPairWithParalogueComplex"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
PepOutname=newPath+"UniProteinAllPairWithParalogueComplexPepCount"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
crapOut=newPath+"UniProteinAllPairWithParalogueComplexPepCountCrapLabel"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
uniNamesOut=newPath+"UniProtAllPairWithParaCompxCrapName"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
BiogridOut=newPath+"UniAllPairWithParaCompxCrpNameBiogrid"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
keratinOut=newPath+"UniAllPairWithParaCompxCrpNameBGkerIg"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
bp=newPath+"UniAllPairWithParaCompxCrpNameBGKerIgIntBP"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
mf=newPath+"UniAllPairWithParaCompxCrpNameBGKerIgIntBPMF"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
cc=newPath+"UniAllPairWithParaCompxCrpNameBGKerIgIntBPMFCC"+str(jaccCutoff)+"jacc_"+todayDate+".txt"
######################################################################################################################################################
###################################### tissue based protein filtrations #############################################################################
######################################################################################################################################################
## get all the crapProteins lists
CrapProtIdsDic=Generalmethods.createDic(DatabasePath+crapFile,1,0,header=False,multiple=False)
print "total crap proteins are ", len(CrapProtIdsDic)
## get all the uniprot proteins and filter the mS proteins
UniprotDic=Generalmethods.createDic(DatabasePath+UniprotFile,0,val_list=[1,3],header=True)
#get protein to geneID mapping
Uni2GenIDDic=Generalmethods.createDic(DatabasePath+Uniprot2GeneIdFile,5,val_list=[0,2,3,10],header=True)
print "total uniprot proteins are ", len(UniprotDic)
## get the GO ontologies
Uni2GODic=Generalmethods.createDic(DatabasePath+Uniprot2GOFile,0,[2,3,4],header=True)
## get the dic for protein 2 Assay 2 pepcount
FilProt2Ass2PepNameListDic,AssayList,protein2AssayPepString,logP=filterings.CheckAssayWithPeptideIds\
(PPI_MSPath+MSprotein2Assay2PepCountFile,AssayLen=minAssayCount,
proteincheck=True,proteinList=UniprotDic,MinPep=1,
selectedProteinFile=selectedProteinFile)
log+=[logP]
## get all intact pair for all proteins
IntActPair= SelectingIntActForSignallingProteins.selectPairsIntAct(DatabasePath+IntActFile,FilProt2Ass2PepNameListDic) # dic with protein pairs and score as value
######################################################################################################################################################
###################################### pathway selection #############################################################################################
######################################################################################################################################################
## get all pathways with there names
PathId2NameDic=Generalmethods.createDic(DatabasePath+pathwaysFile,0,1,header=False,multiple=False,checkCol=True,CheckcolNumValue=[2,"Homo sapiens"])
ln=str(len(PathId2NameDic))+"total pathways present\n"
log.append(ln)
print ln
## get all the proteins for the leaf pathway and dic from prot to pathway
prot2pathDic,ReactomeDic= protein2pathway.dicFromProtein2Pathway(DatabasePath+prot2pathFile)#,UniprotDic) ## checking with all selected pathways
ln="total protein found in hierarchy are "+str(len(prot2pathDic))+"\n"
log.append(ln)
print ln
######################################################################################################################################################
###################################### Run protein co-occurrence #############################################################################################
######################################################################################################################################################
# select the pair which have atleast one com assay with more than 2 peptide
## determine the correaltion btw the proteins
pairList,protAfterselection,logP2=createPairsByComparing.createPairsWithPepCheck(FilProt2Ass2PepNameListDic,minAssayCount,
IntActPair,jaccCutoff,outWrite1,1,protein2AssayPepString,outWrite5)
log += [logP2]
# check for how many proteins have their pathway present
protWithPath=list(set(protAfterselection.keys()).intersection(prot2pathDic.keys()))
ln = "total protein with pathways are " + str(len(protWithPath)) + " from total " + str(len(protAfterselection)) + "\n"
print ln
log.append(ln)
print datetime.now()-start,"total time for finding pairs"
######################################################################################################################################################
###################################### check for biological relevance ###############################################################################
######################################################################################################################################################
## check the pair with the pathways
pair2pathTags,pathHeader=PathwayCoverage.checkTheCoverageForLeafPathway(prot2pathDic,pairList,outWrite4,outWrite2,outWrite3,PathId2NameDic,prot2PathDicAvailable=True,ReactDic=ReactomeDic)
## first look for the proteins in uniprot if they have chaged names
## add paralogue information
paraTaggedPair,Pheader=AddParalogueInformation.findParalogue(DatabasePath+paralogFile,DatabasePath+Uniprot2EnsemblFile,
pair2pathTags,paraOutname,pathHeader)#,old2newProtName)
print "Done with paralog tagging"
## than determine if they are part of any complex
#
complexPairdDic,CHeader=CheckPairForComplex.tagComplexPair(DatabasePath+complexFile,paraTaggedPair,complexOutname,Pheader)
print "done with complex tagging"
## before using further check if proteins names are changed in uniprot or protein which are removed
## than select common peptide between each pair of proteins
PeptideDic,PpHeader=GetDistinctivePeptidesNames.tagPeptideCount(complexPairdDic,PPI_MSPath+protein2PepetideFile,PepOutname,CHeader)
print "done with peptide tagging"
## labelle crap proteins
crapPairDic,cheader=RemovePairHavingCrapProteins.tagCraps(CrapProtIdsDic,PeptideDic,crapOut,PpHeader)
## add protein name
UniprotNameDic,Uheader=GetUniprotName.AddProteinName(crapPairDic,UniprotDic,uniNamesOut,cheader)
## get the protein interaction from Biogrid
biogridPairDic,bioHeader=checkForBioGridInteraction.checkForProteinList(UniprotNameDic,BiogridOut,Uni2GenIDDic,
DatabasePath+BioGridFile,Uheader)
## get the Ig and keratin annotation
keratinPairDic,kerHeader=GetKeratinAndIgAnnotation.labelPairWithFilteredProteins(biogridPairDic,keratinOut,bioHeader)
## get GO
bpheader=kerHeader+"\tBPComCont\tBPCom"
bpheadOut,bpPairDic=ComparePairwithLocalization.DetermineCellularComponentForPair(Uni2GODic,keratinPairDic,bp,bpheader,location=True,locIndex=0)
print "finished writing BP",len(bpPairDic)
mfheader=bpheader+"\tMFComCont\tMFCom"
mfheadOut,mfPairDic=ComparePairwithLocalization.DetermineCellularComponentForPair(Uni2GODic,bpPairDic,mf,mfheader,location=True,locIndex=1)
print "finished writing mf",len(mfPairDic)
ccheader=mfheader+"\tCCComCont\tCcCom"
ccheadOut,ccPairDic=ComparePairwithLocalization.DetermineCellularComponentForPair(Uni2GODic,mfPairDic,cc,ccheader,location=True,locIndex=2)
print "finished writing cc",len(ccPairDic)
ln=str(datetime.now()-start) +" total time"
log.append(ln)
for eachL in log:
logFile.write(eachL)
logFile.close()
print datetime.now()-start,"total time"<file_sep>/sourceCode/Analysis/PathwayCoverage.py
__author__ = 'surya'
from DatabasePreprocessing import protein2pathway
## check for each pathway how many proteins retrieve back
## check for each pathway how many proteins retrieve back
def checkTheCoverageForLeafPathway(prot2pathwayFile,AllProteinPairsDic,outWrite4,outWrite2,outWrite3,PathId2NameDic,prot2PathDicAvailable=False,ReactDic={}):
header="protein1\tprotein2\tscore\tassay1\tassay2\tCommAssay\tintAct\tpath1\tpath2\tpathC1\tpathC2\tComPath\tComPathCount"
outWrite2.write(header+"\n")
outWrite3.write(header+"\n")
pairFound={}
if prot2PathDicAvailable:
prot2path=prot2pathwayFile
ReactomeDic=ReactDic
else:
prot2path,ReactomeDic=protein2pathway.dicFromProtein2Pathway(prot2pathwayFile)#,leafPathways)
path2PPI={}
path2uniqueProtein={}
pair2pathTag={}
for pairP in AllProteinPairsDic:
p1=pairP.split("_")[0]
p2=pairP.split("_")[1]
if p1 in prot2path and p2 in prot2path:
for pathP1 in prot2path[p1]:
if pathP1 in prot2path[p2]:
if pairP not in pairFound:
pairFound[pairP]=[pathP1]
else:
pairFound[pairP].append(pathP1)
if pathP1 in path2PPI:
if p1 not in path2uniqueProtein[pathP1]:
path2uniqueProtein[pathP1].append(p1)
if p2 not in path2uniqueProtein[pathP1]:
path2uniqueProtein[pathP1].append(p2)
if pairP not in path2PPI[pathP1][0]:
path2PPI[pathP1][0].append(pairP)
path2PPI[pathP1][1]+=1
path2PPI[pathP1][2].append(str(AllProteinPairsDic[pairP][0])) # score
path2PPI[pathP1][3]+=AllProteinPairsDic[pairP][1] # intact
else:
path2uniqueProtein[pathP1]=[p1,p2]
path2PPI[pathP1]=[[pairP],1,[str(AllProteinPairsDic[pairP][0])],AllProteinPairsDic[pairP][1]]
print "total leaf pathway remaining are ",len(path2PPI), " out of "
print "total pairs use to map to pathways are ", len(pairFound)
for eachPair in AllProteinPairsDic:
prot1=eachPair.split("_")[0].strip()
prot2=eachPair.split("_")[1].strip()
if eachPair in pairFound:
pair2pathTag[eachPair]=[prot1,prot2,str(AllProteinPairsDic[eachPair][0])
,str(AllProteinPairsDic[eachPair][2]),str(AllProteinPairsDic[eachPair][3])
,str(AllProteinPairsDic[eachPair][4]),str(AllProteinPairsDic[eachPair][1]),
";".join(prot2path[prot1]),";".join(prot2path[prot2]),
str(len(prot2path[prot1])),str(len(prot2path[prot2])),
";".join(pairFound[eachPair]),str(len(pairFound[eachPair]))]
outWrite2.write("\t".join(pair2pathTag[eachPair])+"\n")
elif eachPair not in pairFound:
if prot1 not in prot2path:
ppath1="NF"
p1pathcount=0
else:
ppath1=";".join(prot2path[prot1])
p1pathcount=len(prot2path[prot1])
if prot2 not in prot2path:
ppath2="NF"
p2pathcount=0
else:
ppath2=";".join(prot2path[prot2])
p2pathcount=len(prot2path[prot2])
pair2pathTag[eachPair] = [eachPair.split("_")[0].strip(), eachPair.split("_")[1].strip(),
str(AllProteinPairsDic[eachPair][0]),str(AllProteinPairsDic[eachPair][2]),
str(AllProteinPairsDic[eachPair][3]),str(AllProteinPairsDic[eachPair][4]),
str(AllProteinPairsDic[eachPair][1]),ppath1,ppath2,str(p1pathcount),
str(p2pathcount),"NF\t0"]
outWrite3.write("\t".join(pair2pathTag[eachPair])+"\n")
outWrite2.close()
outWrite3.close()
outWrite4.write("pathway\tpathwayName\tproteins\tTotalProtCount\tPPI\tPPICount\tAllPPIScores\tProtFound\tProtFoundCount\tpercentage\tInIntActFound\tminScore\tMaxScore\n")
for eachpath in path2PPI:
limit=len(path2PPI[eachpath][0])
# if len(path2PPI[eachpath][0])>100:
# limit=100
# else:
# limit=len(path2PPI[eachpath][0])
#print path2PPI[eachpath][2][0:limit]
AllScore=path2PPI[eachpath][2]
outWrite4.write(eachpath+"\t"+PathId2NameDic[eachpath]+"\t"+"_".join(ReactomeDic[eachpath])+"\t"+str(len(ReactomeDic[eachpath]))
+"\t"+";".join(path2PPI[eachpath][0][0:limit])+"\t"+str(path2PPI[eachpath][1])+"\t"+";".join(AllScore[0:limit])
+"\t"+";".join(path2uniqueProtein[eachpath])+"\t"+str(len(path2uniqueProtein[eachpath]))
+"\t"+str(round((float(len(path2uniqueProtein[eachpath]))/len(ReactomeDic[eachpath]))*100,2))+"\t"+str(path2PPI[eachpath][3])
+"\t"+str(min(AllScore))+"\t"+str(max(AllScore))+"\n")
outWrite4.close()
return pair2pathTag,header
<file_sep>/sourceCode/Analysis/createPairsByComparing.py
from GeneralMethods import GeneralStat
from Analysis import DetermineCorrelation
import pdb
## create the pairs from the file
# select the pair which have atleast one com assay with more than 2 peptide
## determine the correaltion btw the proteins
def createPairsWithPepCheck(FilProt2Ass2PepCountDic,minAssayCount,IntActPairDic,jaccCutoff,outWrite1,
minPepCount,protein2AssayPepString,outWrite5):
outWrite1.write("protein1\tprotein2\tjaccSim\tCommonAssayCount\tAssay1\tAssay2\tIntActFound\n")
pairDic={}
c,oc,tp=0,0,0
protAfterselection={}
uniqueProteinList=FilProt2Ass2PepCountDic.keys()
for index1 in range(len(uniqueProteinList)-1):
protein1=uniqueProteinList[index1]
for index2 in range(index1+1,len(uniqueProteinList)):
protein2=uniqueProteinList[index2]
pair1=protein1+"_"+protein2
pair2=protein2+"_"+protein1
if pair1 not in pairDic and pair2 not in pairDic and protein2AssayPepString[protein1]!=protein2AssayPepString[protein2]:
## get the assay dic for each proteins
assayDic1=FilProt2Ass2PepCountDic[protein1]
assayDic2=FilProt2Ass2PepCountDic[protein2]
## compare the assays to see common entries between them
CommonAssayList=list(set(assayDic1.keys()).intersection(assayDic2.keys()))
if len(CommonAssayList) >minAssayCount:
CommonGood,NewAss2PepCount1,NewAss2PepCount2,newassCommon=DetermineCorrelation.OnlyReturnNotCommonPepCount(assayDic1,assayDic2,CommonAssayList,minAssayCount,minPepCount)
# CommonAssayCount,AllAssayList=GetAssayCount.compare2Dic(assayDic1,assayDic2)
## make a list of the values in the assays if there is no entry than add 0
if CommonGood==True:
allAssay1,allAssay2=DetermineCorrelation.createArrays(NewAss2PepCount1,NewAss2PepCount2,CommonAssayList)
JaccardSim=GeneralStat.jaccardSimilarity(allAssay1,allAssay2) ## this takes two list of two arrays and check the pearson correlations
if JaccardSim>=0.1:
if pair1 in IntActPairDic or pair2 in IntActPairDic:
intactC=1
else:
intactC=0
outWrite1.write(protein1+"\t"+protein2+"\t"+str(JaccardSim)+"\t"+str(len(newassCommon))+"\t"+str(len(NewAss2PepCount1))+"\t"+str(len(NewAss2PepCount2))+"\t"+str(intactC)+"\n")
outWrite5.write(protein1+"\t"+protein2+"\t"+str(JaccardSim)+"\t".join(newassCommon)+"\n")
tp+=1
if JaccardSim>=jaccCutoff:
pairDic[pair1]=[JaccardSim,intactC,len(NewAss2PepCount1),len(NewAss2PepCount2),len(newassCommon)] ## pearson correlation,intactCount (if presnt in intact
if protein1 not in protAfterselection:
protAfterselection[protein1]=0
if protein2 not in protAfterselection:
protAfterselection[protein2]=0
c+=1
ln="total pair found are "+str(len(pairDic))+ " from total pairs "+str(tp)+" from total unique proteins are "+str(len(protAfterselection))+"\n"
print ln
outWrite1.close()
outWrite5.close()
return pairDic,protAfterselection,ln
<file_sep>/sourceCode/DatabasePreprocessing/SelectingIntActForSignallingProteins.py
__author__ = 'surya'
def selectPairsIntAct(intActFile,proteinList):
pairDic={}
with open(intActFile) as intact:
next(intact)
for line in intact:
splits=line.split("\t")
if splits[0].strip() in proteinList and splits[1].strip() in proteinList:
pair1=splits[0].strip()+"_"+splits[1].strip()
pair2=splits[1].strip()+"_"+splits[0].strip()
if pair1 not in pairDic and pair2 not in pairDic:
pairDic[pair1]=splits[5].strip() ## IntActScore
print "with total ", len(proteinList), " protein total pair found in intact are ", len(pairDic)
return pairDic<file_sep>/sourceCode/PostProcessing/GetUniprotName.py
__author__ = 'surya'
## get all the pairs and parse
def AddProteinName(pairdic,UniprotDic,outputfilename,header):
protDic={}
outfile = open(outputfilename, "w")
newheader = "protein1\tprotein2\tpName1\tpName2\t" + "\t".join(header.split("\t")[2:])
outfile.write(newheader+"\n")
found=0
for eachPair in pairdic:
p1=pairdic[eachPair][0]
p2=pairdic[eachPair][1]
if p1 in UniprotDic and p2 in UniprotDic:
wline = [pairdic[eachPair][0],pairdic[eachPair][1],UniprotDic[p1][1],UniprotDic[p2][1]]+pairdic[eachPair][2:]
protDic[eachPair]=wline
outfile.write("\t".join(wline) + "\n")
outfile.close()
print 'total pairs reamining after naming are ',len(protDic)
return protDic,newheader
<file_sep>/sourceCode/DatabaseAnnotation/AddParalogueInformation.py
__author__ = 'surya'
""" add the paralog information about the two genes both proteins comes from and than check if they come from paralog proteins or same genes """
from GeneralMethods import Generalmethods
def findParalogue(paralogFile,Uniprot2EnsemblFile,pairDic,outname,header,geneParalogDic=False):#,old2newUniName):
paralogDic={}
out = open(outname, "w")
header=header+"\tGene1\tGene2\tComGenesCount\tComGenes\tParalog"
out.write(header+"\n")
## get all the genes ids for the specific proteins
protein2genes=Generalmethods.createDic(Uniprot2EnsemblFile,0,1,header=True,multiple=False,addDublicate=True)
print "total prot2gene entries are " ,len(protein2genes)
## get the gene paralogue
if not geneParalogDic:
geneParalogDic=Generalmethods.createDic(paralogFile,0,1,header=True,multiple=False,addDublicate=True)
print "total number of gene pralog are: ",len(geneParalogDic)
else:
geneParalogDic=paralogFile
# now look for the genes either which are common to proteins or have paralogs
paracount=0
for eachPair in pairDic:
newp1=pairDic[eachPair][0]
newp2=pairDic[eachPair][1]
if newp1 in protein2genes and newp2 in protein2genes:
# if protein2genes[p1]!="NF" and protein2genes[p2]!="NF":
gene2=protein2genes[newp2]
gene1=protein2genes[newp1]
geneNAme1=";".join(protein2genes[newp1])
geneNAme2=";".join(protein2genes[newp2])
comGene=list(set(gene1).intersection(gene2))
paralogList=[]
for eachGene2 in gene2:
if eachGene2 in geneParalogDic:
paralogList+=geneParalogDic[eachGene2]
paralogList=list(set(paralogList))
paralogPresent=list(set(gene1).intersection(paralogList))
if len(paralogPresent)!=0:
paralog="yes"
paracount+=1
else:
paralog="No"
if len(comGene)!=0:
common=";".join(protein2genes[newp2])
comNum=str(len(comGene))
else:
common="NF"
comNum="0"
else:
if newp1 in protein2genes:
geneNAme1=";".join(protein2genes[newp1])
geneNAme2="NF"
elif newp2 in protein2genes:
geneNAme2=";".join(protein2genes[newp2])
geneNAme1="NF"
else:
geneNAme1="NF"
geneNAme2="NF"
paralog="NA"
common="NA"
comNum="NA"
wline=pairDic[eachPair]+[geneNAme1,geneNAme2,comNum,common,paralog]
paralogDic[eachPair]=pairDic[eachPair]+[geneNAme1,geneNAme2,comNum,common,paralog]
out.write("\t".join(wline)+"\n")
out.close()
print "total paralog found are ",paracount
return paralogDic,header
def paralogueAnnotationForRandomSample(geneParalogDic,protein2genes,pairDic):
paracount = 0
for eachPair in pairDic:
pairSplit=eachPair.split("_")
newp1 = pairSplit[0]
newp2 = pairSplit[1]
if newp1 in protein2genes and newp2 in protein2genes:
# if protein2genes[p1]!="NF" and protein2genes[p2]!="NF":
gene2 = protein2genes[newp2]
gene1 = protein2genes[newp1]
geneNAme1 = ";".join(protein2genes[newp1])
geneNAme2 = ";".join(protein2genes[newp2])
comGene = list(set(gene1).intersection(gene2))
paralogList = []
for eachGene2 in gene2:
if eachGene2 in geneParalogDic:
paralogList += geneParalogDic[eachGene2]
paralogList = list(set(paralogList))
paralogPresent = list(set(gene1).intersection(paralogList))
if len(paralogPresent) != 0:
paralog = "yes"
paracount += 1
return paracount
<file_sep>/sourceCode/DatabaseAnnotation/ComparePairwithLocalization.py
__author__ = 'surya'
############################################################################################################################################
############################################################################################################################################
## check the pair with the GO cellular componenets
def DetermineCellularComponentForPair(prot2loc,pairdic,out,header="",location=False,locIndex=0):
protDic={}
outfile = open(out, "w")
outfile.write(header+"\n")
found=0
for eachPair in pairdic:
p1 = pairdic[eachPair][0]
p2 = pairdic[eachPair][1]
if p1 in prot2loc and p2 in prot2loc:
if location:
loc1=[loc.strip(" \"") for loc in prot2loc[p1][locIndex].split(";")]
loc2=[loc.strip(" \"") for loc in prot2loc[p2][locIndex].split(";")]
else:
loc1=prot2loc[p1]
loc2=prot2loc[p2]
if loc1!="" and loc2!="":
common=list(set(loc1).intersection(loc2))
if len(common)!=0:
comlocName=";".join(common)
else:
comlocName="NF"
else:
if loc1=="":
loc1=[]
if loc2=="":
loc2=[]
comlocName="NA"
common=[]
# print common
else:
comlocName = "NA"
common = []
wline=pairdic[eachPair]+[str(len(common)),comlocName]
protDic[eachPair] = wline
line2write="\t".join(wline) + "\n"
outfile.write(line2write)
outfile.close()
return header,protDic
<file_sep>/README.md
# ProteinAssociationPair
* [Project Description](#project-description)
* [Usage](#usage)
* [Project Support](#project-support)
----

----
## Project Description
In this study, we have used publicly available mass-spectrometry data from pride to investigate the biological importance of protein co-occurrence in various experiments. To calculate the statistical weight of protein co-occurrence we have used Jaccard similarity method. Protein pairs with a similarity above 0.4 were mapped to knowledgebases; [Uniprot](http://www.uniprot.org/), [Reactome](http://www.reactome.org), [Ensembl](http://www.ensembl.org), [IntAct](http://www.ebi.ac.uk/intact/), [BioGRID](https://thebiogrid.org/), and [CORUM](http://mips.helmholtz-muenchen.de/corum/), to assign potential biological relevance. Moreover, using published articles and [String](http://string-db.org/) database, we were able to determine the possible biological connection between unannotated protein pairs with no known biological correspondence.
### Citation
“*Unbiased Protein Association Study on the Public Human Proteome Reveals Biological Connections between Co-Occurring Protein Pairs*”
<NAME>, <NAME>, <NAME>, and <NAME>. *Journal of Proteome Research 2017*, PMID: [28480704](http://www.ncbi.nlm.nih.gov/pubmed/28480704)
[Go to top of the page](#projectassociationpair)
----
## Usage
Use main python file "ProteinPairWithCommonPepCheck.py" for running the method
direct the location to the database files in the "ProteinPairWithCommonPepCheck.py"
[Go to top of the page](#projectassociationpair)
----
## Project Support
Protein-Association project is supported by:
| Compomics | VIB | Ghent University|
|:--:|:--:|:--:|
| [](http://www.compomics.com) | [](http://www.vib.be) | [](http://www.ugent.be/en) |
[Go to top of the page](#projectassociationpair)
<file_sep>/sourceCode/GeneralMethods/GeneralStat.py
__author__ = 'surya'
## import
import scipy.stats
import math
from math import factorial as fac
## to determine the correlation
def determinePearsonCorrelation(array1,array2):
return scipy.stats.pearsonr(array1,array2) ## (pearson coefficient,2 tailed pvalue)
## to calculate the cosine correlation
def cosine_similarity(v1,v2):
"compute cosine similarity of v1 to v2: (v1 dot v1)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
return sumxy/math.sqrt(sumxx*sumyy)
## to calculate a newScore
def ImprovedCosSim(v1,v2,commonExp):
"compute cosine similarity of v1 to v2: (v1 dot v1)/{||v1||*||v2||)"
sumxx, sumxy, sumyy = 0, 0, 0
for i in range(len(v1)):
x = v1[i]; y = v2[i]
sumxx += x*x
sumyy += y*y
sumxy += x*y
top=float(sumxy*commonExp*2)
down1=float(sumxx*len(v1))
down2=float(sumyy*len(v2))
# if commonExp!=0:
# print float(top)/(down1+down2),top,down1,down2
return top/(down1+down2)
def BionomialScore(n,p,k):
C = fac(n) // fac(k) // fac(n - k)
bionom=C*math.pow(p,k)*math.pow(1-p,n-k)
return bionom
## calculate newscoring using probability
def ProbScore(common1,total1,common2,total2):
return (float(common1)/total1)*(float(common2)/total2)
def jaccardSimilarity(list1,list2):
minList,maxList=0,0
if len(list1)!=len(list2):
print "check the list length are not same"
else:
# print list1,list2
for index in range(len(list1)):
minList+=min(list1[index],list2[index])
maxList+=max(list1[index],list2[index])
return round(float(minList)/float(maxList),2)
<file_sep>/sourceCode/PostProcessing/GetKeratinAndIgAnnotation.py
__author__ = 'surya'
def labelPairWithFilteredProteins(pairDic,outputfilename,header):
count=0
newPairDic={}
outfile=open(outputfilename,"w")
newheader = header + "\tkeratin\tIg"
outfile.write(newheader + "\n")
for eachPair in pairDic:
p1Name=pairDic[eachPair][2]
p2Name=pairDic[eachPair][3]
keraPresent,IgPresent=0,0
if "Ig" in p1Name or "Immunoglobulin" in p1Name:
IgPresent += 1
elif "Keratin," in p1Name:
keraPresent += 1
if "Ig" in p2Name or "Immunoglobulin" in p2Name:
IgPresent += 1
elif "Keratin," in p2Name:
keraPresent += 1
ln=pairDic[eachPair]+[str(keraPresent),str(IgPresent)]
newPairDic[eachPair]=ln
outfile.write("\t".join(ln)+"\n")
print "total pair skipped are: ",count
outfile.close()
return newPairDic,newheader<file_sep>/sourceCode/Analysis/DetermineCorrelation.py
__author__ = 'surya'
## find of the common peptide between both proteins in the exp is same
def OnlyReturnNotCommonPepCount(assay1D,assay2D,commonD,minComAssay,minpep):
ass1={}
ass2={}
commonGood=False
for assName1 in assay1D:
if assName1 in commonD:
commonpep=list(set(assay2D[assName1]).intersection(assay1D[assName1]))
remain1=len(assay1D[assName1])-len(commonpep)
remain2=len(assay2D[assName1])-len(commonpep)
if remain1>=minpep:
ass1[assName1] = remain1
if remain2>=minpep:
ass2[assName1] = len(assay2D[assName1])-len(commonpep)
newcommon=list(set(ass2.keys()).intersection(ass1.keys()))
if len(newcommon)>minComAssay:
commonGood=True
ass1.update({a1:len(assay1D[a1]) for a1 in assay1D if a1 not in commonD})
ass2.update({a2:len(assay2D[a2]) for a2 in assay2D if a2 not in commonD})
return commonGood,ass1,ass2,newcommon
## calculate the p value, k and n for the bionomial
## take two proteins, determine the assay they are involve in, if assay is not present in other protein than assign it zero
def createArrays(AssayDic1,AssayDic2,CommAssayList):#,p1,p2): ## val is assay:pepcount
allAssay1=[]
allAssay2=[]
AllAssayList=list(set(AssayDic1.keys()+AssayDic2.keys()))
for eachAss in AllAssayList:
if eachAss in AssayDic1:
allAssay1+=[AssayDic1[eachAss]]
else:
allAssay1+=[0]
if eachAss in AssayDic2:
allAssay2+=[AssayDic2[eachAss]]
else:
allAssay2+=[0]
return allAssay1,allAssay2#,total1,total2,commonSum1,commonSum2
<file_sep>/sourceCode/DatabaseAnnotation/RemovePairHavingCrapProteins.py
__author__ = 'surya'
def tagCraps(crapdic,pairdic,outputName,header):
crapPairDic={}
output=open(outputName,"w")
header=header+"\tCrap"
output.write(header+"\n")
found=0
for eachPair in pairdic:
p1=pairdic[eachPair][0]
p2=pairdic[eachPair][1]
if p1 in crapdic or p2 in crapdic:
crap="Yes"
found+=1
else:
crap="No"
wline=pairdic[eachPair]+[crap]
crapPairDic[eachPair]=wline
output.write("\t".join(wline)+"\n")
print "total crap proteins found as pair are ",found
output.close()
return crapPairDic,header
<file_sep>/sourceCode/PreProcessing/filterings.py
__author__ = 'surya'
from Analysis import GetAssayCount
def preFiltrationWithHighlyOCcuringProteins(MSFile,uniprotProteinList,out):
assCountList=[]
with open(MSFile) as OpenedMSFile:
next(OpenedMSFile)
for line in OpenedMSFile:
colList=line.split("\t")
assCount = int(colList[1].strip())
if colList[0].strip() in uniprotProteinList:
out.write(line)
assCountList.append(assCount)
assCountList.sort()
maxCutoff=assCountList[-10]
print "the maximum cutoff is ",maxCutoff
out.close()
return maxCutoff
def CheckAssayWithPeptideIds(MSFile,AssayLen,assayCheck=False,PhosList=[],proteincheck=False,proteinList=[],
MinPep=0,SelectedAssayList=[],selectedProteinFile=""):#,crap=[]):
maxAssayLen=preFiltrationWithHighlyOCcuringProteins(MSFile,proteinList,selectedProteinFile)
proteinSkiped=0
protein2Assay={}
protein2AssayPepString={}
count=0
assayList=[]
check=False
totalProt=0
with open(MSFile) as OpenedMSFile:
next(OpenedMSFile)
for line in OpenedMSFile:
colList=line.split("\t")
totalProt+=1
assCount = int(colList[1].strip())
if assCount>=maxAssayLen:
print colList[0].strip(),assCount
if assCount > AssayLen and assCount<maxAssayLen:
##first select the threshold
if proteincheck:
if colList[0].strip() in proteinList:# and colList[0].strip() not in crap:
check=True
else:
proteinSkiped+=1
check=False
else:
check=True
if check:
AssayDic=GetAssayCount.createAssayDicWithPepName(colList[2].strip(),MinPep=MinPep,
AssayCheckList=SelectedAssayList,AssCheck=assayCheck)
if len(AssayDic)<=AssayLen: #and AssayDic[AssayDic.keys()[0]]==1:
count+=1
# print(AssayDic)
elif len(AssayDic)>AssayLen:
# if len(protein2Assay)==50:
# break
protein2Assay[colList[0].strip()]=AssayDic
protein2AssayPepString[colList[0].strip()] = colList[2].strip()
# print colList[2].strip()
for each in AssayDic:
if each not in assayList:
assayList.append(each)
# for pro in protein2Assay:
# selectedProteinFile.write(pro+"\n")
# selectedProteinFile.close()
ln="total removed assays are "+str(count)+"\n"+"total assay found are "+str(len(assayList))+"\n"+\
"total proteins remaining are "+str(len(protein2Assay))+" out of total proteins "+str(totalProt)+"\n"+\
"total protein skipped because they are not present in pathway/uniprot are "+str(proteinSkiped)+"\n"
print ln
return protein2Assay,assayList,protein2AssayPepString,ln
<file_sep>/sourceCode/GeneralMethods/Generalmethods.py
__author__ = 'surya'
### create dictionary
# with more than one val
## make dictionary
def createDic(file1,key,val_list,header,multiple=True,addDublicate=False,sep="\t",checkCol=False,CheckcolNumValue=[0,0],checkList=False):
if multiple:
if addDublicate:
print("select only one of multiple or adddublicate, both cannot be used")
return {}
else:
if isinstance(val_list,list):
print ("with sigle entry please provide only one value not list")
return {}
dic={}
with open(file1) as filename:
if header:
next(filename)
for line in filename:
if line!="\n":
splits=line.split(sep)
name=splits[key].strip()
columnChecked=False
if checkCol:
if checkList:
if splits[CheckcolNumValue[0]].strip() in CheckcolNumValue[1]:
columnChecked=True
else:
if splits[CheckcolNumValue[0]].strip() == CheckcolNumValue[1]:
columnChecked=True
else:
columnChecked=True
if columnChecked:
if name not in dic:
if multiple:
dic[name]=[]
for index in val_list:
dic[name].append(splits[index].strip())
else:
if addDublicate:
dic[name]=[splits[val_list].strip()]
else:
dic[name]=splits[val_list].strip()
else:
if addDublicate:
if splits[val_list].strip() not in dic[name]:
dic[name].append(splits[val_list].strip())
return dic
## create a dic with two columns as the key rather than one
def createDicWith2Col(file1,key1,key2,val_list,header,multiple=True,addDublicate=False,sep="\t",
lineVal=False,checkCol=False,CheckcolNumValue=[0,0],checkList=False):
"""
:param file1:
:param key1:
:param key2:
:param val_list:
:param header:
:param multiple:
:param addDublicate:
:param sep:
:param lineVal:
:param checkCol:
:param CheckcolNumValue: [columnNumber,ValueOfColumn]
:return:
"""
if multiple:
if addDublicate:
print("select only one of multiple or adddublicate, both cannot be used")
return {}
else:
if isinstance(val_list,list):
print ("with sigle entry please provide only one value not list")
return {}
dic={}
with open(file1) as filename:
if header:
next(filename)
for line in filename:
splits=line.strip().split(sep)
name=splits[key1].strip()+"_"+splits[key2].strip()
columnChecked=False
if checkCol:
if checkList:
if splits[CheckcolNumValue[0]].strip() in CheckcolNumValue[1]:
columnChecked=True
else:
if splits[CheckcolNumValue[0]].strip() == CheckcolNumValue[1]:
columnChecked=True
else:
columnChecked=True
if columnChecked:
if name not in dic:
if lineVal:
dic[name]=line.strip().split(sep)
else:
if multiple:
dic[name]=[]
for index in val_list:
dic[name].append(splits[index].strip())
else:
if addDublicate:
dic[name]=[splits[val_list].strip()]
else:
dic[name]=splits[val_list].strip()
else:
if addDublicate and not lineVal:
if splits[val_list].strip() not in dic[name]:
dic[name].append(splits[val_list].strip())
# else:
# print (name,"is a duplicate entry")
return dic
def CreateDicWithAllColAsVal(file1,key,header,sep="\t",checkCol=False,CheckcolNumValue=[0,0],checkList=False):
dic={}
dublicate=0
notfoundColumn=0
columnChecked=False
with open(file1) as filename:
if header:
next(filename)
for line in filename:
splits=line.strip().split(sep)
name=splits[key].strip()
if checkCol:
if checkList:
if splits[CheckcolNumValue[0]].strip() in CheckcolNumValue[1]:
columnChecked=True
else:
if splits[CheckcolNumValue[0]].strip() == CheckcolNumValue[1]:
columnChecked=True
else:
columnChecked=True
if columnChecked:
if name not in dic:
dic[name]=[]
for index in range(0,len(splits)):
if index!=key:
dic[name].append(splits[index].strip())
else:
dublicate+=1
else:
notfoundColumn+=1
print "total dublicate keys found are ",dublicate
if checkCol:
print "total lines where ",CheckcolNumValue[1], " was not found are ", notfoundColumn
print
return dic
<file_sep>/sourceCode/Analysis/GetAssayCount.py
__author__ = 'surya'
from GeneralMethods import GeneralStat
def createAssayDic(line,check=False,checkList=[],MinPep=1):
dic={}
for each in line.strip("|").split("|"):
eachList=each.split(":")
if check:
if eachList[0] in checkList:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=int(eachList[1])
else:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=int(eachList[1])
# if len(dic)>50
return dic
def createAssayDicWithPepName(line,MinPep=1,AssayCheckList=[],AssCheck=False):
dic={}
for each in line.strip("|").split("|"):
eachList=each.split(":")
assay=eachList[0]
if AssCheck:
if assay in AssayCheckList:
peptideList=list(set(eachList[1].strip(";").split(";")))
if len(peptideList)>=MinPep:
dic[assay]=peptideList
else:
peptideList = list(set(eachList[1].strip(";").split(";")))
if len(peptideList) >= MinPep:
dic[assay] = peptideList
# if len(dic)>50
return dic
def compare2Dic(dic1,dic2):
assList=[]
com=0
assay1=dic1.keys()
assay2=dic2.keys()
totalAss=assay1+assay2
for each in totalAss:
if each not in assList:
assList.append(each)
if each in assay1 and each in assay2:
com+=1
return com,assList
def createAssayDicWithPresentOrNot(line,check=False,checkList=[],MinPep=0):
dic={}
for each in line.strip("|").split("|"):
eachList=each.split(":")
if check:
if eachList[0] in checkList:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=1
else:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=1
# if len(dic)>50
return dic
def createAssayDicWithNormPSM(line,check=False,checkList=[],MinPep=0,protLength=1):
dic={}
for each in line.strip("|").split("|"):
eachList=each.split(":")
if check:
if eachList[0] in checkList:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=float(eachList[1])/protLength
else:
if int(eachList[1])>=MinPep:
dic[eachList[0]]=float(eachList[1])/protLength
# if len(dic)>50
return dic
<file_sep>/sourceCode/DatabasePreprocessing/protein2pathway.py
__author__ = 'surya'
def createProtein2Path(proteinList,file):
prot2path={}
for line in open(file):
splits=line.strip().split("\t")
reactomeId=splits[0].strip()
proteins=splits[1:len(splits)]
for each in proteins:
if each in proteinList:
if each not in prot2path:
prot2path[each]=[reactomeId]
else:
prot2path[each].append(reactomeId)
return prot2path
## make a dic for protein2pathway
def dicFromProtein2Pathway(prot2pathwayFile):#,leafPathways,leafCheck=True):
ReactomeDic={}
prot2path={}
for line in open(prot2pathwayFile):
splits=line.strip().split("\t")
proteinId=splits[0].strip().split("-")[0] ## as most of the protein have uniprot id "-" number
if splits[5].strip()=="Homo sapiens":
reactomeId=splits[1].strip()
if proteinId not in prot2path:
prot2path[proteinId]=[reactomeId]
else:
prot2path[proteinId].append(reactomeId)
if reactomeId not in ReactomeDic:
ReactomeDic[reactomeId]=[proteinId]
else:
ReactomeDic[reactomeId].append(proteinId)
return prot2path,ReactomeDic
<file_sep>/sourceCode/DatabaseAnnotation/CheckPairForComplex.py
__author__ = 'surya'
def ParseCorumComplexFile(file1,CheckcolNumValue=[0,[0]]):
Complex2Protdic={}
prot2complex={}
with open(file1) as filename:
next(filename)
for line in filename:
splits=line.split("\t")
complex=splits[0].strip()+"_"+splits[1].strip() #id+name
proteinsList=splits[5].strip().split(";")
if splits[CheckcolNumValue[0]].strip() in CheckcolNumValue[1]:
if complex not in Complex2Protdic:
Complex2Protdic[complex]=splits[4].strip()
else:
print " more than one complex are present for ", complex
for prot in proteinsList:
if prot not in prot2complex:
prot2complex[prot]=[complex]
else:
prot2complex[prot].append(complex)
return Complex2Protdic,prot2complex
def tagComplexPair(complexFile,pairDic,outname,header):
complexDic={}
output=open(outname,"w")
header=header+"\tComplexFound\tProtComplex\tProtCompCount"
output.write(header+"\n")
complex2protDic,prot2ComplexDic=ParseCorumComplexFile(complexFile,CheckcolNumValue=[2,["Human"]])
print "total complexes found for human are ",len(complex2protDic)
print " total proteins present are ",len(prot2ComplexDic)
found,total=0,0
for eachPair in pairDic:
p1=pairDic[eachPair][0]
p2=pairDic[eachPair][1]
total+=1
if p1 in prot2ComplexDic and p2 in prot2ComplexDic:
commonComplex=list(set(prot2ComplexDic[p1]).intersection(prot2ComplexDic[p2]))
if len(commonComplex)!=0:
found+=1
AllComplex=";".join(commonComplex)
allComplexProt=""
allCompProtCount=""
for comp in commonComplex:
allComplexProt+=complex2protDic[comp]+";"
allCompProtCount+=str(len(complex2protDic[comp].split(",")))+";"
else:
AllComplex="NF"
allComplexProt="NF"
allCompProtCount="NF"
else:
AllComplex="NA"
allComplexProt="NA"
allCompProtCount="NA"
wline=pairDic[eachPair]+[AllComplex,allComplexProt,allCompProtCount]
output.write("\t".join(wline)+"\n")
complexDic[eachPair]=wline
output.close()
print " total pairs found as complex are ",found, " from total ",total
return complexDic,header
<file_sep>/sourceCode/DatabaseAnnotation/GetDistinctivePeptidesNames.py
__author__ = 'surya'
from GeneralMethods import Generalmethods
def tagPeptideCount(pairDic,prot2peptideFile,outName,header):
peptideDic={}
prot2peptideDic=Generalmethods.createDic(prot2peptideFile,0,[1,2],header=True)
header=header+"\tCommonCount\tpep1Count\tpep2Count"
output=open(outName,"w")
output.write(header+"\n")
for eachpair in pairDic:
p1=pairDic[eachpair][0]
p2=pairDic[eachpair][1]
if p1 in prot2peptideDic and p2 in prot2peptideDic:
pep1=prot2peptideDic[p1][0].split(";")
pep2=prot2peptideDic[p2][0].split(";")
commonPeptide=list(set(pep1).intersection(pep2))
wline=pairDic[eachpair]+[str(len(commonPeptide)),str(len(pep1)),str(len(pep2))]
else:
print " one of the protein is not found ",p1, p2
output.write("\t".join(wline)+"\n")
peptideDic[eachpair]=wline
output.close()
return peptideDic,header
<file_sep>/sourceCode/DatabaseAnnotation/checkForBioGridInteraction.py
__author__ = 'surya'
def ParseBioGrid(BiogridPairFile):
genePairDic={}
with open(BiogridPairFile) as BPFile:
next(BPFile)
for line in BPFile:
splits=line.strip().split("\t")
p1=splits[1]
p2=splits[2]
pair1=p1+"_"+p2
pair2=p2+"_"+p1
if pair1 not in genePairDic and pair2 not in genePairDic:
genePairDic[pair1]=line.strip()
print "total geneID interacting pairs found are ",len(genePairDic)," for human only.."
# outfile.close()
return genePairDic
def checkForProteinList(pairdic,outputfilename,protein2GeneID,BiogridPairsFile,header):
protDic = {}
geneIDPairs = ParseBioGrid(BiogridPairsFile)
totalFound=0
new=0
outfile=open(outputfilename,"w")
headerList=header.split("\t")
newheader="\t".join(headerList[0:9] + ["geneIds1", "geneIds2","ComGene","ComGeneCount","BiogridInt"] +
headerList[9:])
outfile.write( newheader+ "\n")
for eachPair in pairdic:
p1 = pairdic[eachPair][0]
p2 = pairdic[eachPair][1]
found=0
if p1 in protein2GeneID and protein2GeneID[p1][3].strip()!="":
geneidList1=protein2GeneID[p1][3].strip(";").split(";")
geneIds1="_".join(geneidList1)
else:
geneidList1=[]
geneIds1="NF"
if p2 in protein2GeneID and protein2GeneID[p2][3].strip()!="":
geneidList2 = protein2GeneID[p2][3].strip(";").split(";")
geneIds2 = "_".join(geneidList2)
else:
geneidList2=[]
geneIds2="NF"
if len(geneidList1)>0 and len(geneidList2)>0:
commonGene=list(set(geneidList1).intersection(geneidList2))
comGeneCount=str(len(commonGene))
if len(commonGene)==0:
comGenName="NF"
else:
comGenName="_".join(commonGene)
else:
comGenName="NA"
comGeneCount="0"
if p1 in protein2GeneID and p2 in protein2GeneID:
for eachp1 in protein2GeneID[p1][3].strip(";").split(";"):
for eachp2 in protein2GeneID[p2][3].strip(";").split(";"):
genePair1=eachp1+"_"+eachp2
genePair2=eachp2+"_"+eachp1
if genePair1 in geneIDPairs or genePair2 in geneIDPairs:
found+=1
if found>=1:
interact="yes"
totalFound += 1
if int(pairdic[eachPair][8])==0:
new+=1
else:
interact="no"
else:
interact="NA"
wline=pairdic[eachPair][0:9]+[geneIds1,geneIds2,comGenName,comGeneCount,interact]+pairdic[eachPair][9:]
protDic[eachPair] = wline
outfile.write("\t".join(wline)+"\n")
outfile.close()
print "total pairs found to be interacting ",totalFound," but new pairs found interacting are ",new
return protDic,newheader
|
475efa36e927247ff64677e60f4d0cfbec8f471e
|
[
"Markdown",
"Python"
] | 19
|
Python
|
compomics/ProteinAssociationPair
|
85aee777935477a55e7d2089c671433220e04d84
|
19f8b000c457af6adea8220feb04de9fdbf45f8f
|
refs/heads/master
|
<file_sep># include <stdio.h>
#include <cs50.h>
int main (void)
{
int a= 500;
int b=250;
int c=200;
int d=100;
int e=50;
int f=25;
int g=10;
int h=5;
int r=1;
int i=0;
int amount;
amount= get_int ("amount:");
while (amount>= a)
{
amount= amount-a;
i++;
}
while (amount>= b)
{
amount= amount-b;
i++;
}
while (amount>= c)
{
amount= amount-c;
i++;
}
while (amount>= d)
{
amount= amount-d;
i++;
}
while (amount>= e)
{
amount= amount-e;
i++;
}
while (amount>= f)
{
amount= amount-f;
i++;
}
while (amount>= g)
{
amount= amount-g;
i++;
}
while (amount>= h)
{
amount= amount-h;
i++;
}
while (amount>= r)
{
amount= amount-r;
i++;
}
printf(" the result is %i", i);
}
<file_sep>#include<stdio.h>
#include<cs50.h>
int main (void)
{
// the user input
long long card1;
long long card2;
long long ccard= 0;
int counter =0;
int sum;
int mult;
long long r;
long long card;
do
{
card= get_long_long("card number:");
}
while (card<=0);
card1 = card;
card2 = card;
while(card1>0)
{
card1 = card1 /10;
counter++;
}
if (counter == 13 || counter == 15 || counter == 16)
{
for(int i =1;i<=counter; i++)
{
if(i%2==0)
{
ccard = card %10;
mult= ccard*2;
}
if (i%2 !=0)
{
ccard=card%10;
mult=ccard * 1;
}
if(mult>9)
{
mult=mult-9;
}
sum = sum +mult;
card = card / 10;
}
//check wether the card are valid or not
if(sum % 10==0)
{
while(card2>100)
{
card2=card2 /10;
r=card2;
}
if ((counter ==13||counter== 16)&&(r==40))
{
printf ("Visa card valid\n");
}
if((counter == 15)&&(r==34||r==37))
{
printf("AMEX\n");
}
if ((counter==16)&&(r==52|| r==53|| r==54 || r==55))
{
printf("Master Card\n");
}
}
else
{
printf("your card is invalid");
}
}
}
|
79946dc5745635d22a8c4411884a3e4583335851
|
[
"C"
] | 2
|
C
|
Farka2674/homework
|
02ce4707f7ae4fa42ffe702ac4abd8e66da8682a
|
37b9fa3d94e0a700ff40cbc210e854ae62f8178a
|
refs/heads/master
|
<repo_name>zjucsxxd/SeamCarving-4<file_sep>/Lab01-ImplementHere.cpp
//--------------------------------------------------------------------------------------
// File: Lab01-ImplementHere.cpp
//
// DV1212 Lab01: RayTracing
//
// Copyright (c) <NAME> 2010. All rights reserved.
//--------------------------------------------------------------------------------------
#include "stdafx.h"
#include "ToScreen.h"
extern ToScreen* g_ToScreen;
//simple math vector-class
struct Vec
{
float x, y, z;
Vec() {};
Vec(float _x, float _y, float _z)
{
x = _x;
y = _y;
z = _z;
}
float Length()
{
return sqrt(x*x + y*y + z*z);
}
void Normalize()
{
float l = Length();
x /= l;
y /= l;
z /= l;
}
};
struct Ray
{
Vec o;
Vec d;
Ray(Vec origin, Vec direction)
{
o = origin;
d = direction;
}
};
struct Color
{
BYTE r;
BYTE g;
BYTE b;
Color() { memset(&r, 0, 3); }
Color(BYTE red, BYTE green, BYTE blue)
{
r = red;
g = green;
b = blue;
}
};
void Update(float deltaTime)
{
//loop through every screen pixel from top to botttom
for(unsigned int y = 0; y < SCREEN_HEIGHT; y++)
{
for(unsigned int x = 0; x < SCREEN_WIDTH; x++)
{
g_ToScreen->SetPixelColor(x, y, 255, 255, x+y);
}
}
for (unsigned int x = 0; x < 150; x++)
for (unsigned int y = 0; y < 20; y++)
g_ToScreen->SetPixelColor(x, y, 0, 0, 0);
//update DX10-surface with new pixel data
g_ToScreen->Update(deltaTime);
}
|
3277c70cf9795bf9f799b32767a3715bec6ebfd5
|
[
"C++"
] | 1
|
C++
|
zjucsxxd/SeamCarving-4
|
a2557704b4029f90fb5be86ff76a22238d23e824
|
82026cf183f499e8c0d54602e961d27d90321eaf
|
refs/heads/master
|
<file_sep>72 path=dashboard/front/graficos/inc/grafbar_grupo_mes.inc (cópia).php
27 mtime=1472213540.591005
26 atime=1472231792.49111
<file_sep><?php
function plugin_dashboard_install(){
global $DB, $LANG;
if (! TableExists("glpi_plugin_dashboard_count")) {
$query = "CREATE TABLE `glpi_plugin_dashboard_count`
(`type` INTEGER , `id` INTEGER, `quant` INTEGER, PRIMARY KEY (`id`))
ENGINE = InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; ";
$DB->query($query) or die("error creating glpi_plugin_dashboard_count " . $DB->error());
$insert = "INSERT INTO glpi_plugin_dashboard_count (type,quant) VALUES ('1','1')";
$DB->query($insert);
}
//map
if (! TableExists("glpi_plugin_dashboard_map")) {
$query_map = "CREATE TABLE IF NOT EXISTS `glpi_plugin_dashboard_map` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`entities_id` int(4) NOT NULL,
`location` varchar(50) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL,
`lat` float NOT NULL,
`lng` float NOT NULL,
PRIMARY KEY (`id`,`entities_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1;";
$DB->query($query_map) or die("error creating table glpi_plugin_dashboard_map " . $DB->error());
}
//configs
if (! TableExists("glpi_plugin_dashboard_config")) {
$query_conf = "CREATE TABLE IF NOT EXISTS `glpi_plugin_dashboard_config` (
`id` int(4) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,
`value` varchar(25) NOT NULL,
`users_id` varchar(25) NOT NULL DEFAULT '',
PRIMARY KEY (`id`,`name`,`value`,`users_id`),
UNIQUE KEY `name` (`name`,`users_id`),
KEY `name_2` (`name`,`users_id`))
ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ; ";
$DB->query($query_conf) or die("error creating table glpi_plugin_dashboard_config " . $DB->error());
}
if (TableExists("glpi_plugin_dashboard_count")) {
$query_alt = "ALTER TABLE `glpi_plugin_dashboard_count` DROP PRIMARY KEY, ADD PRIMARY KEY(`type`,`id`); ";
$DB->query($query_alt) or die("error update table glpi_plugin_dashboard_count primary key " . $DB->error());
}
if (TableExists("glpi_plugin_dashboard_config")) {
$query_alt = "ALTER TABLE glpi_plugin_dashboard_config MODIFY value varchar(125); ";
$DB->query($query_alt) or die("error alter table glpi_plugin_dashboard_config value size" . $DB->error());
//Config entities
$query_ent = "SELECT users_id FROM glpi_plugin_dashboard_config WHERE name = 'entity' AND value = '-1' ";
$result = $DB->query($query_ent) or die("error alter table glpi_plugin_dashboard_config value size" . $DB->error());
//$sel_ent = $DB->result($result_e,0,'value');
while ($row = $DB->fetch_assoc($result)) {
$query = "UPDATE glpi_plugin_dashboard_config SET value = '' WHERE name = 'entity' AND users_id = ".$row['users_id']." ";
$DB->query($query) or die("error updating table glpi_plugin_dashboard_config entity value" . $DB->error());
}
//$query_pop = "INSERT INTO glpi_plugin_dashboard_config WHERE name = 'entity' AND value = '-1' ";
//$result_pop = $DB->query($query_pop) or die("error alter table glpi_plugin_dashboard_config value size" . $DB->error());
}
//SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));
//SET sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'));
//set session sql_mode='STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';
/*
//notifications
if (! TableExists("glpi_plugin_dashboard_notify")) {
$query_notify = "CREATE TABLE IF NOT EXISTS `glpi_plugin_dashboard_notify` (
`users_id` varchar(50) NOT NULL,
`quant` int(6) NOT NULL,
`type` int(2) NOT NULL,
PRIMARY KEY (`users_id`,`type`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1; ";
$DB->query($query_notify) or die("error creating table glpi_plugin_dashboard_notify " . $DB->error());
}
*/
return true;
}
function plugin_dashboard_uninstall(){
global $DB;
$drop_count = "DROP TABLE glpi_plugin_dashboard_count";
$DB->query($drop_count);
$drop_map = "DROP TABLE glpi_plugin_dashboard_map";
$DB->query($drop_map);
$drop_config = "DROP TABLE glpi_plugin_dashboard_config";
$DB->query($drop_config);
$restore_mode = "SET sql_mode=(SELECT CONCAT(@@sql_mode,',ONLY_FULL_GROUP_BY'));";
$DB->query($restore_mode);
/*
$drop_notify = "DROP TABLE glpi_plugin_dashboard_notify";
$DB->query($drop_notify);
*/
return true;
}
?>
<file_sep><?php
include ("../../../../inc/includes.php");
global $DB, $CFG_GLPI;
Session::checkLoginUser();
Session::checkRight("profile", READ);
?>
<html>
<head>
<title> GLPI - <?php echo __('Open Tickets','dashboard'); ?> </title>
<!-- <base href= "<?php $_SERVER['SERVER_NAME'] ?>" > -->
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="content-language" content="en-us" />
<link href="../css/styles.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
<link href="../css/font-awesome.css" type="text/css" rel="stylesheet" />
<script src="../js/jquery.min.js" type="text/javascript" ></script>
<script src="../js/jquery.jclock.js"></script>
<link href="../inc/select2/select2.css" rel="stylesheet" type="text/css">
<script src="../inc/select2/select2.js" type="text/javascript" language="javascript"></script>
<?php echo '<link rel="stylesheet" type="text/css" href="../css/style-'.$_SESSION['style'].'">'; ?>
</head>
<body style="background-color: #e5e5e5; margin-left:0%;">
<?php
$status = "('5','6')" ;
$sql = "SELECT COUNT( * ) AS total
FROM glpi_tickets
WHERE glpi_tickets.status NOT IN ".$status."
AND glpi_tickets.is_deleted = 0" ;
$result = $DB->query($sql);
$data = $DB->fetch_assoc($result);
$abertos = $data['total'];
function dropdown( $name, array $options, $selected=null )
{
/*** begin the select ***/
$dropdown = '<select style="width: 300px; height: 27px;" autofocus onChange="javascript: document.form1.submit.focus()" name="'.$name.'" id="'.$name.'">'."\n";
$selected = $selected;
/*** loop over the options ***/
foreach( $options as $key=>$option )
{
/*** assign a selected value ***/
$select = $selected==$key ? ' selected' : null;
/*** add each option to the dropdown ***/
$dropdown .= '<option value="'.$key.'"'.$select.'>'.$option.'</option>'."\n";
}
/*** close the select ***/
$dropdown .= '</select>'."\n";
/*** and return the completed dropdown ***/
return $dropdown;
}
//select user entities
$sql_e = "SELECT value FROM glpi_plugin_dashboard_config WHERE name = 'entity' AND users_id = ".$_SESSION['glpiID']."";
$result_e = $DB->query($sql_e);
$sel_ent = $DB->result($result_e,0,'value');
if($sel_ent == '' || $sel_ent == -1) {
$entities = $_SESSION['glpiactiveentities'];
$ents = implode(",",$entities);
}
else {
$ents = $sel_ent;
}
$sql_ent = "
SELECT id, name
FROM `glpi_entities`
WHERE id IN (".$ents.")
ORDER BY `name` ASC ";
$result_ent = $DB->query($sql_ent);
$ent = $DB->fetch_assoc($result_ent);
$res_ent = $DB->query($sql_ent);
$arr_ent = array();
$arr_ent[0] = "-- ". __('Select a entity', 'dashboard') . " --" ;
$DB->data_seek($result_ent, 0) ;
while ($row_result = $DB->fetch_assoc($result_ent))
{
$v_row_result = $row_result['id'];
$arr_ent[$v_row_result] = $row_result['name'] ;
}
$name = 'sel_ent';
$options = $arr_ent;
$selected = "0";
?>
<div id='content' >
<div id='container-fluid' style="margin: 0px 5% 0px 5%;">
<div id="charts" class="fluid chart">
<div id="head" class="fluid">
<a href="../index.php"><i class="fa fa-home" style="font-size:14pt; margin-left:25px;"></i><span></span></a>
<div id="titulo_graf"> <?php echo __('Tickets', 'dashboard') .' '. __('by Entity', 'dashboard') ?> </div>
<div id="datas-cham" class="col-md-12 fluid" >
<form id="form1" name="form1" class="form_rel" method="post" action="select_ent.php?sel=1">
<table border="0" cellspacing="0" cellpadding="1" bgcolor="#efefef" width="300px">
<tr>
<td>
<?php echo dropdown( $name, $options, $selected ); ?>
</td>
</tr>
<tr style="height:12px;"><td> </td></tr>
<tr>
<td align="center" >
<button class="btn btn-primary btn-sm" type="submit" name="submit" value="Atualizar" ><i class="fa fa-search"></i> <?php echo __('Consult', 'dashboard'); ?></button>
<button class="btn btn-primary btn-sm" type="button" name="Limpar" value="Limpar" onclick="location.href='select_ent.php'" > <i class="fa fa-trash-o"></i> <?php echo __('Clean', 'dashboard'); ?> </button></td>
</td>
</tr>
</table>
<?php Html::closeForm(); ?>
<!-- </form> -->
</div>
</div>
<script type="text/javascript" >
$(document).ready(function() { $("#sel_ent").select2(); });
</script>
<?php
$sel = $_GET['sel'];
if($sel == "1") {
if(!isset($_POST["sel_ent"])) {
$id_ent = $_GET["ent"];
}
else {
$id_ent = $_POST["sel_ent"];
}
if($id_ent == " ") {
echo '<script language="javascript"> alert(" ' . __('Select a entity', 'dashboard') . ' "); </script>';
echo '<script language="javascript"> location.href="select_ent.php"; </script>';
}
?>
<script type="text/javascript" >
location.href="cham_entidades.php?ent=<?php echo $id_ent; ?>";
</script>
</div>
</div>
</div>
</body>
</html>
<?php } ?>
<file_sep><?php
include ("../../../../inc/includes.php");
include ("../../../../config/config.php");
include "../inc/functions.php";
global $DB;
Session::checkLoginUser();
Session::checkRight("profile", READ);
if(!empty($_REQUEST['submit']))
{
$data_ini = $_REQUEST['date1'];
$data_fin = $_REQUEST['date2'];
}
else {
$data_ini = date("Y-m-01");
$data_fin = date("Y-m-d");
}
if(!isset($_REQUEST["sel_date"])) {
$id_date = $_REQUEST["date"];
}
else {
$id_date = $_REQUEST["sel_date"];
}
?>
<head>
<title> GLPI - <?php echo __('Summary Report','dashboard')." - ". __('Entity') ?> </title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />
<meta http-equiv="content-language" content="en-us" />
<meta charset="utf-8">
<link rel="icon" href="../img/dash.ico" type="image/x-icon" />
<link rel="shortcut icon" href="../img/dash.ico" type="image/x-icon" />
<link href="../css/styles.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap.css" rel="stylesheet" type="text/css" />
<link href="../css/bootstrap-responsive.css" rel="stylesheet" type="text/css" />
<link href="../css/font-awesome.css" type="text/css" rel="stylesheet" />
<script language="javascript" src="../js/jquery.js"></script>
<script src="../js/bootstrap.min.js"></script>
<style type="text/css">
select { width: 60px; }
table.dataTable { empty-cells: show; }
a:link, a:visited, a:active { text-decoration: none;}
</style>
<?php echo '<link rel="stylesheet" type="text/css" href="../css/style-'.$_SESSION['style'].'">'; ?>
</head>
<body style="background-color: #fff !important;">
<?php
$con = $_REQUEST['con'];
if($con == "1") {
if(!isset($_REQUEST['date1']))
{
$data_ini2 = $_REQUEST['date1'];
$data_fin2 = $_REQUEST['date2'];
}
else {
$data_ini2 = $_REQUEST['date1'];
$data_fin2 = $_REQUEST['date2'];
}
if($data_ini2 == $data_fin2) {
$datas2 = "LIKE '".$data_ini2."%'";
}
else {
$datas2 = "BETWEEN '".$data_ini2." 00:00:00' AND '".$data_fin2." 23:59:59'";
}
// do select
$post_date = $_REQUEST["sel_date"];
if(!isset($post_date) or $post_date == "0") {
$sel_date = $datas2;
}
else {
$sel_date = $_REQUEST["sel_date"];
}
switch($post_date) {
case ("1") :
$data_ini2 = date('Y-m-01');
$data_fin2 = date('Y-m-d');
$sel_date = "BETWEEN '" . $data_ini2 ." 00:00:00' AND '". $data_fin2 ." 23:59:59'";
break;
case ("2") :
$data_ini2 = date('Y-m-d', strtotime('-1 week'));
$sel_date = "BETWEEN '" . $data_ini2 ." 00:00:00' AND '".$data_fin2." 23:59:59'";
break;
case ("3") :
$data_ini2 = date('Y-m-d', strtotime('-15 day'));
$sel_date = "BETWEEN '" . $data_ini2 ." 00:00:00' AND '".$data_fin2." 23:59:59'";
break;
case ("4") :
$data_ini2 = date('Y-m-d', strtotime('-1 month'));
$sel_date = "BETWEEN '" . $data_ini2 ." 00:00:00' AND '".$data_fin2." 23:59:59'";
break;
case ("5") :
$data_ini2 = date('Y-m-d', strtotime('-3 month'));
$sel_date = "BETWEEN '" . $data_ini2 ." 00:00:00' AND '".$data_fin2." 23:59:59'";
break;
}
//selected entity
$id_ent = $_REQUEST["sel_ent"];
$entidade = "AND glpi_tickets.entities_id = ".$id_ent."";
//entity name
$sql_entname = "
SELECT id, name
FROM `glpi_entities`
WHERE id = ".$id_ent."
ORDER BY `name` ASC ";
$result_entname = $DB->query($sql_entname);
$entname = $DB->result($result_entname,0,'name');
// Chamados
$sql_cham = "SELECT glpi_tickets.id AS id, glpi_tickets.name AS descr, glpi_tickets.date AS date,
glpi_tickets.solvedate AS solvedate, glpi_tickets.status AS status
FROM glpi_tickets
WHERE glpi_tickets.date ".$sel_date."
AND glpi_tickets.is_deleted = 0
".$entidade."
ORDER BY id DESC ";
$result_cham = $DB->query($sql_cham);
$chamados = $DB->fetch_assoc($result_cham) ;
//quant de chamados
$sql_cham2 =
"SELECT count(id) AS total, count(date) AS numdias, AVG(close_delay_stat) AS avgtime
FROM glpi_tickets
WHERE date ".$sel_date."
AND glpi_tickets.is_deleted = 0
".$entidade." ";
$result_cham2 = $DB->query($sql_cham2);
$conta_cham = $DB->fetch_assoc($result_cham2);
$total_cham = $conta_cham['total'];
if($total_cham > 0) {
//date diff
$numdias = round(abs(strtotime($data_fin2) - strtotime($data_ini2)) / 86400,0);
//tecnico
$sql_tec = "SELECT count(glpi_tickets.id) AS conta, glpi_users.firstname AS name, glpi_users.realname AS sname
FROM `glpi_tickets_users` , glpi_tickets, glpi_users
WHERE glpi_tickets.id = glpi_tickets_users.`tickets_id`
AND glpi_tickets.date ".$sel_date."
AND glpi_tickets_users.`users_id` = glpi_users.id
AND glpi_tickets_users.type = 2
".$entidade."
GROUP BY name
ORDER BY conta DESC
LIMIT 5";
$result_tec = $DB->query($sql_tec);
//requester
$sql_req = "SELECT count(glpi_tickets.id) AS conta, glpi_users.firstname AS name, glpi_users.realname AS sname
FROM `glpi_tickets_users` , glpi_tickets, glpi_users
WHERE glpi_tickets.id = glpi_tickets_users.`tickets_id`
AND glpi_tickets.date ".$sel_date."
AND glpi_tickets_users.`users_id` = glpi_users.id
AND glpi_tickets_users.type = 1
".$entidade."
GROUP BY name
ORDER BY conta DESC
LIMIT 5";
$result_req = $DB->query($sql_req);
//avg time
$sql_time =
"SELECT count(id) AS total, AVG(close_delay_stat) AS avgtime
FROM glpi_tickets
WHERE date ".$sel_date."
AND glpi_tickets.is_deleted = 0
".$entidade." ";
$result_time = $DB->query($sql_time);
$time_cham = $DB->fetch_assoc($result_time);
$avgtime = $time_cham['avgtime'];
//count by status
$query_stat = "
SELECT
SUM(case when glpi_tickets.status = 1 then 1 else 0 end) AS new,
SUM(case when glpi_tickets.status = 2 then 1 else 0 end) AS assig,
SUM(case when glpi_tickets.status = 3 then 1 else 0 end) AS plan,
SUM(case when glpi_tickets.status = 4 then 1 else 0 end) AS pend,
SUM(case when glpi_tickets.status = 5 then 1 else 0 end) AS solve,
SUM(case when glpi_tickets.status = 6 then 1 else 0 end) AS close
FROM glpi_tickets
WHERE glpi_tickets.is_deleted = '0'
AND glpi_tickets.date ".$sel_date."
".$entidade."";
$result_stat = $DB->query($query_stat);
$new = $DB->result($result_stat,0,'new');
$assig = $DB->result($result_stat,0,'assig');
$plan = $DB->result($result_stat,0,'plan');
$pend = $DB->result($result_stat,0,'pend');
$solve = $DB->result($result_stat,0,'solve');
$close = $DB->result($result_stat,0,'close');
//count by type
$query_type = "
SELECT
SUM(case when glpi_tickets.type = 1 then 1 else 0 end) AS incident,
SUM(case when glpi_tickets.type = 2 then 1 else 0 end) AS request
FROM glpi_tickets
WHERE glpi_tickets.is_deleted = '0'
AND glpi_tickets.date ".$sel_date."
".$entidade."";
$result_type = $DB->query($query_type);
$incident = $DB->result($result_type,0,'incident');
$request = $DB->result($result_type,0,'request');
//select groups
$sql_grp =
"SELECT count(glpi_tickets.id) AS conta, glpi_groups.name AS name
FROM `glpi_groups_tickets`, glpi_tickets, glpi_groups
WHERE glpi_groups_tickets.`groups_id` = glpi_groups.id
AND glpi_groups_tickets.`tickets_id` = glpi_tickets.id
AND glpi_tickets.is_deleted = 0
AND glpi_tickets.date ".$sel_date."
".$entidade."
GROUP BY name
ORDER BY conta DESC
LIMIT 5 ";
$result_grp = $DB->query($sql_grp);
//logo
if (file_exists('../../../../pics/logo_big.png')) {
$logo = "../../../../pics/logo_big.png";
$imgsize = "width:100px; height:100px;";
}
else {
if ($CFG_GLPI['version'] >= 0.90){
$logo = "../../../../pics/logo-glpi-login.png";
$imgsize = "background-color:#000;";
}
else {
$logo = "../../../../pics/logo-glpi-login.png";
$imgsize = "";
}
}
$content = "
<page backtop='5mm' backbottom='5mm' backleft='15mm' backright='10mm'>
<page_header>
</page_header>
<page_footer align='center'>
[[page_cu]]/[[page_nb]]
</page_footer>
<!-- <div class='fluid col-md-12 report' style='margin-left: 0px; margin-top: -8px;'> -->
<div id='logo' class='fluid'>
<span class='col-md-2' ><img src='".$logo."' alt='GLPI' style='".$imgsize."'> </span>
<span class='col-md-8' style='margin-top:-80px; height:60px; text-align:center; margin:auto;'><h3 style='vertical-align:top;'>". __('Summary Report','dashboard')." - " .__('Entity')." </h3></span>
</div>
<table id='data' class='table table-condensed table-striped' style='font-size: 16px; width:55%; margin:auto; margin-top:35px; margin-bottom:20px;'>
<tbody>
<tr>
<td>" .__('Entity')."</td>
<td align='right'>".$entname ."</td>
</tr>
<tr>
<td width='300'>". __('Period','dashboard').": </td>";
if($data_ini2 == $data_fin2) {
$content .= "<td width='200' align='right'>".conv_data($data_ini2)."</td>";
}
else {
$content .= "<td width='200' align='right'>".conv_data($data_ini2)." to ".conv_data($data_fin2)."</td>";
}
$content .= "
</tr>
<tr>
<td>". __('Date').": </td>
<td align='right'>".conv_data_hora(date("Y-m-d H:i"))."</td>
</tr>
<tr><td> </td></tr>
</tbody>
</table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; width:85%; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;' >". __('Tickets','dashboard')."</th>
</tr>
</thead>
<tbody>
<tr>
<td width='300'>". __('Tickets Total','dashboard')."</td>
<td width='200' align='right'>".$total_cham."</td>
</tr>
<tr>
<td>". _n('Day','Days',2)."</td>
<td align='right'>".$numdias."</td>
</tr>
<tr>
<td>". __('Tickets','dashboard')." ". __('By day')." - ". __('Average')."</td>
<td align='right'>".round($total_cham / $numdias,1)."</td>
</tr>
<tr>
<td>". __('Average time to closure')."</td>
<td align='right'>". time_hrs($avgtime )."</td>
</tr>
<tr><td> </td></tr>
</tbody>
</table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; width:55%; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;'>". __('Tickets by Status','dashboard')."</th>
</tr>
</thead>
<tbody>
<tr>
<td width='300'>". _x('status','New')."</td>
<td width='200' align='right'>".$new."</td>
</tr>
<tr>
<td>". __('Assigned')."</td>
<td align='right'>".$assig."</td>
</tr>
<tr>
<td>". __('Planned')."</td>
<td align='right'>".$plan."</td>
</tr>
<tr>
<td>". __('Pending')."</td>
<td align='right'>".$pend."</td>
</tr>
<tr>
<td>". __('Solved','dashboard')."</td>
<td align='right'>".$solve."</td>
</tr>
<tr>
<td>". __('Closed')."</td>
<td align='right'>".$close."</td>
</tr>
<tr><td> </td></tr>
</tbody>
</table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;'>". __('Tickets','dashboard')." ". __('by Type','dashboard')."</th>
</tr>
</thead>
<tbody>
<tr>
<td width='300'>". __('Incident')."</td>
<td width='200' align='right'>".$incident."</td>
</tr>
<tr>
<td>". __('Request')."</td>
<td align='right'>".$request."</td>
</tr>
<tr><td> </td></tr>
</tbody> </table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; width:55%; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;'>Top 5 - ". __('Tickets','dashboard')." ". __('by Group','dashboard')."</th>
</tr>
</thead>
<tbody>";
while($row = $DB->fetch_assoc($result_grp)) {
$content .= "<tr>
<td width='300'>".$row['name']."</td>
<td width='200' align='right'>".$row['conta']."</td>
</tr> ";
}
$content .= "
<tr><td> </td></tr>
</tbody> </table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; width:55%; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;'>Top 5 - ". __('Tickets','dashboard')." ". __('by Technician','dashboard')."</th>
</tr>
</thead>
<tbody>";
while($row_tec = $DB->fetch_assoc($result_tec)) {
$content .= "<tr>
<td width='300'>".$row_tec['name']." ".$row_tec['sname']."</td>
<td width='200' align='right'>".$row_tec['conta']."</td>
</tr> ";
}
$content .= "
<tr><td> </td></tr>
</tbody> </table>
<table class='fluid table table-striped table-condensed' style='font-size: 16px; width:55%; margin:auto;'>
<thead>
<tr>
<th colspan='2' style='text-align:center; background:#286090; color:#fff;'>Top 5 - ". __('Tickets','dashboard')." ". __('by Requester','dashboard')."</th>
</tr>
</thead>
<tbody>";
while($row = $DB->fetch_assoc($result_req)) {
$content .= "<tr>
<td width='300'>".$row['name']." ".$row['sname']."</td>
<td width='200' align='right'>".$row['conta']."</td>
</tr> ";
}
$content .= "</tbody> </table> </page> ";
}
}
require_once('../inc/html2pdf/html2pdf.class.php');
$filename = "summary_report_entity.pdf";
$html2pdf = new HTML2PDF('P', 'A4', 'en');
$html2pdf->writeHTML($content);
ob_end_clean();
$html2pdf->Output($filename,'D');
//header("Location:".$filename);
?>
</body>
</html>
|
7715e9bbcfbcab91bb763b2fde24b145d220656a
|
[
"PHP"
] | 4
|
PHP
|
orouet/GLPI-Dashboard
|
0a20fc1b73d7dbbf7979d33f7a9c5c937b80881a
|
933d515191fcb62ddd7c3a73aed51b8f0fed6207
|
refs/heads/master
|
<file_sep>$(function () {
//when document ready, init the plugin so any exisiting DOM element of this plugin inits with the plugin behaviour
$('.money').money();
//$.fn.money();
//$(".money").each(function () {
// $(this).money();
//});
//$(document).ready(function () {
// $(".money").each(function () {
// $(this).money();
// });
//});
});
(function ($) {
var origAppend = $.fn.append;
$.fn.append = function () {
//$('#log2').append( $(arguments[0]).prop('outerHTML') + ' ');
//alert($(arguments[0]).prop('outerHTML'));
if ( $(arguments[0]).prop('outerHTML').indexOf('money') > -1)
//if (arguments[0].attr('class') == 'money')
{
var event = jQuery.Event("append");
event.args = arguments;
event.code = 45;
return origAppend.apply(this, arguments).trigger(event);
}
else
{
return origAppend.apply(this, arguments);
}
};
})(jQuery);
(function ($) {
var origAddClass = $.fn.addClass;
$.fn.addClass = function () {
//$('#log').val($('#log').val() + arguments[0] + ' ');
//if (arguments[0] == 'money') {
if ($.inArray('money', arguments) > -1 ) {
return origAddClass.apply(this, arguments).trigger("append");
}
else {
return origAddClass.apply(this, arguments);
}
};
})(jQuery);
//(function ($) {
// var methods = ['addClass', 'toggleClass', 'removeClass'];
// $.map(methods, function (method) {
// // store the original handler function
// var originalMethod = $.fn[method];
// $.fn[method] = function () {
// return originalMethod.apply(this, arguments).trigger("myEvent");
// };
// });
//})(jQuery);
//(function ($) {
// var methods = ['addClass', 'toggleClass', 'removeClass'];
// $.map(methods, function (method) {
// // store the original handler function
// var originalMethod = $.fn[method];
// $.fn[method] = function () {
// // execute the original hanlder
// var oldClass = this[0].className;
// var result = originalMethod.apply(this, arguments);
// var newClass = this[0].className;
// // trigger the custom event
// this.trigger(method, [oldClass, newClass]);
// // return the original handler
// return result;
// };
// });
//}(this.jQuery || this.Zepto));
(function ($) {
$.fn.moneyHooked = function () {
return this
.each(function () {
$(this)
.EvalMoney().addClass('isHooked');
});
};
$.fn.money = function ()
{
$(".money").on("keypress.money", function (e) {
//$('#log').val($('#log').val() + 'keypress ' + e.which);
//0=48, 9= 57, - = 45, + = 43, . = 46, , = 44, $= 36
var validChars = [45,46,48,49,50,51,52,53,54,55,56,57];
var $this = $(this);
var currentValue = $this.val(); //before key pressed
//$('#log').val($('#log').val() + 'current val ' + currentValue + '\n\r');
//alert(e.which);
//( && currentValue.indexOf('.') != -1 && e.which == 46) ||
//alert(currentValue.length);
//if (e.which == 46 && currentValue.length > 0 && currentValue.indexOf('.') != -1 ) {
// return false;
//}
//doesnt match with valid chars:
//if ( $.inArray(e.which, validChars) == -1 ) {
// return false;
//}
//$('#log').val($('#log').val() + '. pos ' + currentValue.indexOf('.') + '\n\r');
$('#log').val($('#log').val() + ' press ');
});
$(".money").on("keydown.money", function (e) {
//0=48, 9= 57, - = 45, + = 43, . = 46, , = 44, $= 36
//home, end , left, right 35 36 37 38
//backspace 8, enter 13, tab 9 , esc 27, delete 46
//var validChars = [ 45, 46, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
//if ( $.inArray(e.which, validChars) == -1 ) {
// e.preventDefault();
// e.stopPropagation();
// return false;
//}
//alert(e.which);
$('#log').val($('#log').val() + e.which + ':DN ');
// alert('after return false');
//return false;
});
$(".money").on("keyup.money", function (e) {
var validControlChars = [35,36,37,38, ];
//alert(e.which);
var $this = $(this);
var pos = $this.caret();
mv = commafy2($this.val());
$this.val(mv.value);
//$this.caret(pos + mv.caret);
//$(this).EvalMoney();
//$(this).caret(pos);
$('#log').val($('#log').val() + 'Up' + '\n\r');
});
//$(".money").on("blur.money", function (e) {
// $(this).moneyHooked();
//});
$("body").on("append", function (e) {
//var arg0 = e.args[0];
//alert($(e.args[0]).prop('outerHTML'));
//alert(e.args);
alert(e.target.outerHTML )
$(".money:not(.isHooked)").moneyHooked();
});
//$(this).on("blur.money", function () {
// $(".money:not(.isHooked)").moneyHooked();
//});
return $(this).moneyHooked();
//return this
//.each(function () {
// $(this)
// .on('mouseenter',
// function () {
// $('body')
// .append(element);
// })
// .on('mouseleave',
// function () {
// element.remove();
// });
//});
//this.bind("blur.money", function () {
// //alert('clicked');
// $(this).ToMoney();
//});
//$("body").on("change", function () {
// $(this).ToMoney();
//});
//$("body").on("focus", ".money", function () {
// $(this).ToMoney();
//});
// return $(this).ToMoney().blur($.fn.money.blur).keyup($.fn.money.keyup);
}
//$.fn.money.keyup = function()
//{
// //$(this).ToMoney();
// return this;
//}
//$.fn.money.blur = function ()
//{
// $(this).ToMoney();
// return this;
//}
//$.fn.rVal = function () {
// if (this[0]) {
// var ele = $(this[0]);
// if (ele.hasClass('money')) {
// return $(this).MoneyToFloat() ;
// } else {
// return ele.val();
// }
// }
// return undefined;
//};
//jQuery.fn.xVal = jQuery.fn.val;
//jQuery.fn.val = function (value) {
// if (value != undefined) {
// return this.xVal(value);
// }
// if (this[0]) {
// var ele = $(this[0]);
// if (ele.hasClass('money')) {
// return $(this).MoneyToFloat();
// } else {
// return ele.xVal();
// }
// }
// return undefined;
//};
$.fn.EvalMoney = function () {
if ($(this).length > 0) {
var T = '';
if ($(this).val().length > 0) {
T = T + $(this).val();
}
if (T.indexOf('$') >= 0) {
T = T.replace(/\$/g, '');
}
if (T.indexOf(',') >= 0) {
T = T.replace(/\,/g, '');
}
if (!isNaN(T) && isFinite(T) & T != '' ) {
if (T >= 0) {
$(this).val('$' + parseFloat(T).toFixed(2));
$(this).commafy();
}
else {
$(this).val('-$' + parseFloat(-1 * T).toFixed(2));
$(this).commafy();
}
}
else if( T != '') {
$(this).val('$0.00');
}
}
else {
$(this).val('$0.00');
}
return this;
};
$.fn.MoneyToFloat = function () {
if ($(this).length > 0 && $(this).val().length > 0) {
T = $(this).val();
if (T.indexOf('$') >= 0) {
T = T.replace(/\$/g, '');
}
if (T.indexOf(',') >= 0) {
T = T.replace(/\,/g, '');
}
return parseFloat((!isNaN(T) && isFinite(T)) ? T : 0);
}
else {
return 0;
}
};
commafy2 = function (nStr) {
//var regex = new RegExp(/\./g)
//var count = "This is some text .".match(regex).length;
nStr += '';
origcount = nStr.replace(/\,/g, '').length;
nStr = nStr.replace(/\$/g, '');
nStr = nStr.replace(/\,/g, '');
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
var count = 0;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
count++;
}
caretmovecount= 1;
if(origcount < count) {
caretmovecount = 2;
}
return ({ "value": '$' + x1 + x2, "caret": caretmovecount });
};
$.fn.commafy = function () {
nStr = $(this).val();
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
$(this).val(x1 + x2);
};
//$.fn.AddDealer = function (update_id) {
// this.bind("click.AddDealer", function () {
// //$(update_id).html("content_upated");
// //alert("test" + this.id);
// var Data = JSON.stringify($('#aspnetForm').find("input,textarea,select,hidden").not("#AppRoot,#__EVENTTARGET,#__EVENTARGUMENT,#__VIEWSTATE,#__EVENTVALIDATION").serializeObject());
// //$('#dvSessionExpired').text(Data);
// Submit(Data);
// return false;
// });
//};
//alert('xo');
//$(".money").each(function (i) {
// $(this).ToMoney();
// $('#log').val($('#log').val() + i);
// $(this).cl();
//});
})(jQuery);
<file_sep>DOMchanged
=====================
DOMchanged is a JQUERY plug-in written in javascript to handle automatic DOM changes in HTML document.
### How does the service work?
When anything added/removed/changes to/from DOM, it fires an event.
### Template use
```
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="jquery-1.11.1.min.js"></script>
<script src="plugin.js"></script>
</head>
<body>
</body>
</html>
```
#### Installation
#### Technical documentation
This application is written by <NAME> (<EMAIL>) and uses free resources for development and hosting.
|
16111448b96204d99c42e4bb55bacc7d993fd79a
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
mehdiromi/domchanged
|
4144664da474ea552149b71d2209d03a8fe8f5cf
|
f8e24be19773737b895441a5c1bb97b189891306
|
refs/heads/main
|
<repo_name>fefe4/blog-front-end<file_sep>/src/components/newBlog.js
const NewBlog = () => {
return(
<main>
<form action="http://localhost:4000/api/blogs" method="POST">
<label for="title">Title</label>
<input name="title" type="text" />
<label for="description">Description</label>
<input name="description" type="text" />
<label for="body">Body</label>
<input name="body" type="text" />
<button>Submit</button>
</form>
</main>
)
}
export default NewBlog<file_sep>/src/components/editBlog.js
// import React, { useEffect, useState } from "react";
// const EditBlog = ({ match }) => {
// console.log(match);
// console.log(match.params.id)
// useEffect(() => {
// fetchBlog();
// }, []);
// const [blog, setBlog] = useState({});
// const fetchBlog = async () => {
// const data = await fetch(`http://localhost:4000/api/blogs/${match.params.id}`);
// console.log(data);
// const blogApi = await data.json();
// const blog = blogApi.blog_;
// console.log(blog);
// setBlog(blog);
// };
// return (
// <main>
// <form action="http://localhost:4000/api/blogs" method="POST">
// <label for="title">Title</label>
// <input name="title" type="text" value={blog.title}/>
// <label for="description">Description</label>
// <input name="description" value={blog.description} type="text" />
// <label for="body">Body</label>
// <input name="body" type="text" value={blog.body}/>
// <button>Submit</button>
// </form>
// </main>
// );
// };
// export default EditBlog;
<file_sep>/src/components/home.js
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
const Home = () => {
useEffect(()=> {
fetchBlogs();
}, [])
const [blogs, setBlogs] = useState([])
const fetchBlogs = async () => {
const data = await fetch ('http://localhost:4000/api/blogs', {mode: 'cors'})
const blogsApi = await data.json()
const blogs = blogsApi.blog_list
console.log(blogs)
setBlogs(blogs);
};
return(
<main className="">
<ul>
{blogs.map((blog) => {
return <li key={blog._id}>
<Link to={`/blogs/${blog._id}`}>
<h4>{blog.title} <span>{blog.date}</span></h4>
<h5>{blog.author}</h5>
<p>{blog.body}</p>
</Link>
</li>
})}
</ul>
</main>
)
}
export default Home<file_sep>/src/components/blog.js
import React, { useEffect, useState } from "react";
import { Link } from "react-router-dom";
const Blog = ({ match }) => {
//edit values
const [title, setTitle] = useState("");
const [body, setBody] = useState("");
const [description, setDescription] = useState("");
const updateTitle = (e) => {
setTitle(e.target.value);
};
const updateBody = (e) => {
setBody(e.target.value);
};
const updateDescription = (e) => {
setDescription(e.target.value);
};
useEffect(() => {
fetchBlog();
}, []);
const [blog, setBlog] = useState({});
const [hasEditBeenPressed, setHasEditBeenPressed] = useState(false);
const activateEditMode = () => {
hasEditBeenPressed? setHasEditBeenPressed(false) : setHasEditBeenPressed(true)
}
const fetchBlog = async () => {
const data = await fetch(
`http://localhost:4000/api/blogs/${match.params.id}`
);
const blogApi = await data.json();
const blog = blogApi.blog_;
setBlog(blog);
setDescription(blog.description);
setTitle(blog.title);
setBody(blog.body);
};
const actionForm = `http://localhost:4000/api/blogs/${match.params.id}`;
//put requests don't work for windows.
const editBlog = (e) => {
e.preventDefault();
// PUT request using fetch with async/await
async function updatePost() {
const requestOptions = {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
title: title,
body: body,
description: description,
}),
};
const response = await fetch(`${actionForm}`, requestOptions);
const data = await response.json();
console.log(data);
}
updatePost();
};
const deleteBlog = (e) => {
e.preventDefault();
// PUT request using fetch with async/await
async function updatePost() {
const requestOptions = {
method: "DELETE",
};
const response = await fetch(`${actionForm}`, requestOptions);
const data = await response.json();
console.log(data);
}
updatePost();
};
return (
<main className="">
<button onClick={activateEditMode}>Edit</button>
<button onClick={deleteBlog}>Delete Blog</button>
{hasEditBeenPressed ? (
<form onSubmit={editBlog}>
<label for="title">Title</label>
<input
onChange={updateTitle}
name="title"
type="text"
value={title}
/>
<label for="description">Description</label>
<input
onChange={updateDescription}
name="description"
value={description}
type="text"
/>
<label for="body">Body</label>
<input onChange={updateBody} name="body" type="text" value={body} />
<button>Submit</button>
</form>
) : (
<div>
<h4>
{" "}
{blog.title} <span>{blog.date}</span>
</h4>
<h5>{blog.author}</h5>
<p>{blog.body}</p>
</div>
)}
</main>
);
};
export default Blog;
|
1be861c58cec844462da4f14f2f45bc976e8c257
|
[
"JavaScript"
] | 4
|
JavaScript
|
fefe4/blog-front-end
|
8c3de94f4d8a0b1bf8bf4c6f60a30d6dab41b6bf
|
ca691412cc9ce8b2c973f4c9cb8c5e048342e019
|
refs/heads/master
|
<repo_name>jonwho/lolxin<file_sep>/lib/lolxin/dto/league_list_dto.rb
module Lolxin
class LeagueListDto
attr_accessor(*%i(
tier
queue
name
entries
data
league_id
))
def initialize(data)
@data = data
initialize_with(data)
end
private
def initialize_with(data)
@league_id = data['leagueId']
@tier = data['tier']
@queue = data['queue']
@name = data['name']
@entries = data['entries'].map { |entry| LeagueItemDto.new(entry) }
end
end
end
<file_sep>/lib/lolxin/dto/mini_series_dto.rb
module Lolxin
class MiniSeriesDto
attr_accessor(*%i(
wins
losses
target
progress
data
))
def initialize(data)
@data = data
return nil if data.nil?
initialize_with(data)
end
private
def initialize_with(data)
@wins = data['wins']
@losses = data['losses']
@target = data['target']
@progress = data['progress']
end
end
end
<file_sep>/lib/lolxin/api/third_party_code.rb
module Lolxin
class ThirdPartyCode < Api
attr_accessor :endpoint
def initialize(options = {})
super
@endpoint = "platform/%{version}" % {version: @version}
end
def by_summoner(summoner_id)
url = "#{endpoint}/by-summoner/#{summoner_id}"
conn.get(url)
end
end
end
<file_sep>/lib/lolxin/api/champion_mastery.rb
module Lolxin
class ChampionMastery < Api
attr_reader :endpoint
def initialize(options = {})
super
@endpoint = "champion-mastery/%{version}" % {version: @version}
end
def by_summoner(summoner_id)
url = "#{endpoint}/champion-masteries/by-summoner/#{summoner_id}"
res = conn.get(url)
return res if res.status != 200
champion_masteries = JSON.parse(res.body)
champion_masteries.map do |champion_mastery|
ChampionMasteryDto.new(champion_mastery)
end
end
def by_summoner_by_champion(summoner_id, champion_id)
url = "#{endpoint}/champion-masteries/by-summoner/#{summoner_id}/by-champion/#{champion_id}"
res = conn.get(url)
return res if res.status != 200
champion_mastery = JSON.parse(res.body)
ChampionMasteryDto.new(champion_mastery)
end
alias_method :by_champion, :by_summoner_by_champion
def scores(summoner_id)
res = conn.get("#{endpoint}/scores/by-summoner/#{summoner_id}")
return res if res.status != 200
res.body
end
end
end
<file_sep>/README.md
[](https://badge.fury.io/rb/lolxin)
[](https://travis-ci.org/jonwho/lolxin)
[](https://codeclimate.com/github/jonwho/lolxin)
[](https://codeclimate.com/github/jonwho/lolxin/coverage)
[](https://codeclimate.com/github/jonwho/lolxin)
# Lolxin
The not-so-smooth API wrapper for League of Legends. Pronounced lo-shin like
lotion! Too clever I know.
## Supported endpoints
| Endpoint | Version |
| ----------------- | ------- |
| CHAMPION-MASTERY | 3 |
| CHAMPION | 3 |
| LEAGUE | 3 |
| LOL-STATIC-DATA | 3 |
| LOL-STATUS | 3 |
| MATCH | 3 |
| SPECTATOR | 3 |
| SUMMONER | 3 |
| THIRD-PARTY-CODE | ? |
| TOURNAMENT-STUB | N/A |
| TOURNAMENT | N/A |
## Installation
Add this line to your application's Gemfile:
```ruby
gem 'lolxin'
```
And then execute:
$ bundle
Or install it yourself as:
$ gem install lolxin
## Usage
Refer to the source code for methods to hit the RIOT API. For the most part just set up your
environment variable API_KEY that you get from the RIOT developer [console](https://developer.riotgames.com/)
Quick example usage...
```
client = Client.new(ENV['API_KEY'], region: :na1)
client.lol_static_data.champions
```
## Development
After checking out the repo, run `bin/setup` to install dependencies. Then, run
`rake spec` to run the tests. You can also run `bin/console` for an interactive
prompt that will allow you to experiment.
For testing purposes I am using the gem
[dotenv](https://github.com/bkeepers/dotenv) to load my API key. I recommend
you do the same and not to commit your .env file to git to keep it a secret by
adding it to your .gitignore file. If you decide not to use dotenv for whatever
reason make sure to comment it out in the bin/console script. Also add/remove
any variables you see fit to speed up manual testing.
To install this gem onto your local machine, run `bundle exec rake install`.
## Release
To release a new version, update the version number in `lib/lolxin/helpers/version.rb`, and then
run `bundle exec rake release`, which will create a git tag for the version, push git commits and
tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
## Testing
Change up the regions per spec file so that you don't run into rate limiting issues often.
## TODO
- Add the remaining DTOs
- Parse API responses with DTOs
- TOURNAMENT/TOURNAMENT-STUB endpoints
- VCR record http responses?
- Make tests deterministic
## Contributing
Bug reports and pull requests are welcome on GitHub at
https://github.com/jonwho/lolxin. This project is intended to be a safe,
welcoming space for collaboration, and contributors are expected to adhere
to the [Contributor Covenant](contributor-covenant.org) code of conduct.
## License
The gem is available as open source under the terms of the
[MIT License](http://opensource.org/licenses/MIT).
<file_sep>/spec/champion_spec.rb
describe Champion do
let(:champion) { Client.new(ENV['API_KEY'], region: :na1).champion }
describe '#champions' do
it 'retrieves a list of ChampionDto' do
champs = champion.champions
expect(champs.length).to be >= 1
champs.each do |champ|
champ.instance_variables.each do |iv|
expect(champ.instance_variable_get(iv)).not_to be nil
end
end
end
it 'gets a champion by their numerical id' do
champ = champion.champions(266)
champ.instance_variables.each do |iv|
expect(champ.instance_variable_get(iv)).not_to be nil
end
end
end
end
<file_sep>/spec/api_version_spec.rb
describe ApiVersion do
versions = {
champions: 'v3',
champion_mastery: 'v3',
spectator: 'v3',
league: 'v3',
match: 'v3',
static_data: 'v3',
lol_status: 'v1.0',
stats: 'v1.3',
summoner: 'v1.4'
}
versions.each do |k, v|
describe "::#{k.to_s.upcase}" do
it 'returns most recent version' do
expect(described_class.const_get(k.to_s.upcase)).to eq(v)
end
end
end
end
<file_sep>/lib/lolxin/dto/champion_dto.rb
module Lolxin
class ChampionDto
attr_accessor(*%i(
ranked_play_enabled
bot_enabled
bot_mm_enabled
active
free_to_play
id
data
))
def initialize(data)
@data = data
initialize_with(data)
end
private
def initialize_with(data)
@ranked_play_enabled = data['rankedPlayEnabled']
@bot_enabled = data['botEnabled']
@bot_mm_enabled = data['botMmEnabled']
@active = data['active']
@free_to_play = data['freeToPlay']
@id = data['id']
end
end
end
<file_sep>/lib/lolxin/helpers/region.rb
module Lolxin
module Region
REGIONS = {
ru: 'ru',
kr: 'kr',
br1: 'br1',
oc1: 'oc1',
jp1: 'jp1',
na1: 'na1',
eun1: 'eun1',
euw1: 'euw1',
tr1: 'tr1',
la1: 'la1',
la2: 'la2'
}
def self.valid?(region)
REGIONS[region] || REGIONS.values.include?(region)
end
end
end
<file_sep>/spec/spectator_spec.rb
describe Spectator do
let(:client) { Client.new(ENV['API_KEY'], region: :kr) }
let(:spectator) { client.spectator }
let(:doublelift) { 20132258 }
describe '#by_summoner' do
it 'retrieves current game info the summoner is currently playing in' do
current_games = spectator.by_summoner(doublelift)
# NOTE: test only works if the player is in an active game
expect(current_games.values.any?(&:nil?)).to be(false)
end
end
describe '#featured_games' do
it 'retrieves a list of FeaturedGameInfo' do
featured_games = spectator.featured_games
expect(featured_games.values.any?(&:nil?)).to be(false)
end
end
end
<file_sep>/spec/lol_status_spec.rb
describe LolStatus do
let(:client) { Client.new(ENV['API_KEY'], region: :eun1) }
let(:lol_status) { client.lol_status }
describe '#shard_data' do
it 'returns 200 status' do
expect(lol_status.shard_data.status).to eq(200)
end
end
end
<file_sep>/spec/match_spec.rb
# TODO: need to find test values
describe Match do
let(:client) { Client.new(ENV['API_KEY'], region: :euw1) }
let(:match) { client.match }
describe '#matches' do
xit 'returns 200 status' do
end
end
describe '#by_account' do
xit 'returns 200 status' do
end
xit 'returns 200 status for recent' do
end
end
describe '#by_match' do
xit 'returns 200 status' do
end
end
describe '#tournament_code' do
xit 'returns 200 status' do
end
end
end
<file_sep>/spec/summoner_spec.rb
# NOTE: wouldn't bank on this always being right
# Doublelift may end up changing his name or transferring account
describe Summoner do
let(:client) { Client.new(ENV['API_KEY'], region: :na1) }
let(:summoner) { client.summoner }
let(:doublelift) { 20132258 }
let(:account_id) { 32971449 }
let(:name) { 'Doublelift' }
describe '#by_account' do
it 'returns 200 status' do
expect(summoner.by_account(account_id).status).to eq(200)
end
end
describe '#by_name' do
it 'returns 200 status' do
expect(summoner.by_name(name).status).to eq(200)
end
end
describe '#summoners' do
it 'returns 200 status' do
expect(summoner.summoners(doublelift).status).to eq(200)
end
end
end
<file_sep>/lib/lolxin/api/lol_status.rb
module Lolxin
class LolStatus < Api
def shard_data
conn.get("status/#{version}/shard-data")
end
end
end
<file_sep>/lib/lolxin/helpers/api.rb
module Lolxin
class Api
BASE_ENDPOINT = "https://%{region}.api.riotgames.com/lol/"
attr_accessor :api_key, :conn, :region, :version
def initialize(options = {})
@api_key = options[:api_key]
@region = options[:region]
@version = options[:version]
endpoint = BASE_ENDPOINT % {region: region}
@conn = Faraday.new(endpoint, options[:conn_options]) do |faraday|
faraday.request(:url_encoded)
faraday.adapter(Faraday.default_adapter)
faraday.params[:api_key] = api_key
end
end
end
end
<file_sep>/lib/lolxin/helpers/api_version.rb
module Lolxin
module ApiVersion
CHAMPION_MASTERY = 'v3'
CHAMPION = 'v3'
LEAGUE = 'v3'
LOL_STATIC_DATA = 'v3'
LOL_STATUS = 'v3'
MATCH = 'v3'
SPECTATOR = 'v3'
SUMMONER = 'v3'
THIRD_PARTY_CODE = 'v3'
#TOURNAMENT_STUB = 'v3'
#TOURNAMENT = 'v3'
end
end
<file_sep>/lib/lolxin.rb
# dependency
require 'faraday'
require 'json'
require 'lolxin/helpers/api'
require 'lolxin/helpers/api_version'
require 'lolxin/helpers/version'
require 'lolxin/helpers/region'
require 'lolxin/dto/dto'
require 'lolxin/dto/champion_dto'
require 'lolxin/dto/champion_mastery_dto'
require 'lolxin/dto/game_info_dto'
require 'lolxin/dto/league_item_dto'
require 'lolxin/dto/league_list_dto'
require 'lolxin/dto/league_position_dto'
require 'lolxin/dto/mini_series_dto'
require 'lolxin/api/champion_mastery'
require 'lolxin/api/champion'
require 'lolxin/api/league'
require 'lolxin/api/lol_static_data'
require 'lolxin/api/lol_status'
require 'lolxin/api/match'
require 'lolxin/api/spectator'
require 'lolxin/api/summoner'
require 'lolxin/api/third_party_code'
#require 'lolxin/api/tournament_stub'
#require 'lolxin/api/tournament'
require 'lolxin/client'
module Lolxin; end
<file_sep>/spec/lolxin_spec.rb
describe Lolxin do
end
<file_sep>/spec/league_spec.rb
describe League do
let(:client) { Client.new(ENV['API_KEY'], region: :na1) }
let(:league) { client.league }
let(:doublelift) { 20132258 }
let(:league_id) { "930faadc-f191-3fc0-b715-79804ef73cfc" }
describe '#challenger_by_queue' do
it 'retrieves a LeagueListDto' do
league_list = league.challenger_by_queue("RANKED_FLEX_SR")
league_list.instance_variables.each do |iv|
expect(league_list.instance_variable_get(iv)).not_to be nil
end
end
end
describe '#master_by_queue' do
it 'retrieves a LeagueListDto' do
league_list = league.master_by_queue("RANKED_FLEX_SR")
league_list.instance_variables.each do |iv|
expect(league_list.instance_variable_get(iv)).not_to be nil
end
end
end
# TODO: 3/5/18 API is broken. API spec says it returns a LeagueListDTO
# but it only returns the following:
# `["name", "<NAME>"]`
# leave untested for now
# describe '#leagues' do
# it 'retrieves a list of LeagueListDto' do
# league_lists = league.leagues(league_id)
# league_lists.each do |league_list|
# league_list.instance_variables.each do |iv|
# expect(league_list.instance_variable_get(iv)).not_to be nil
# end
# end
# end
# end
describe '#positions_by_summoner' do
it 'retrieves a list of LeaguePositionDto' do
league_positions = league.positions_by_summoner(doublelift)
league_positions.each do |league_position|
expect(league_position.rank).not_to be(nil)
expect(league_position.queue_type).not_to be(nil)
expect(league_position.hot_streak).not_to be(nil)
# mini_series not always present in a response
# expect(league_position.mini_series).not_to be(nil)
expect(league_position.wins).not_to be(nil)
expect(league_position.veteran).not_to be(nil)
expect(league_position.losses).not_to be(nil)
expect(league_position.player_or_team_id).not_to be(nil)
expect(league_position.league_name).not_to be(nil)
expect(league_position.player_or_team_name).not_to be(nil)
expect(league_position.inactive).not_to be(nil)
expect(league_position.fresh_blood).not_to be(nil)
expect(league_position.tier).not_to be(nil)
expect(league_position.league_points).not_to be(nil)
end
end
end
end
<file_sep>/lib/lolxin/api/champion.rb
module Lolxin
class Champion < Api
def champions(id = nil)
endpoint = "platform/%{version}/champions" % {version: version}
res = if id.nil?
conn.get(endpoint)
else
conn.get("#{endpoint}/#{id}")
end
return res if res.status != 200
body = JSON.parse(res.body)
if champs = body['champions']
champs.map { |champ| ChampionDto.new(champ) }
else
champ = body
ChampionDto.new(champ)
end
end
end
end
<file_sep>/lib/lolxin/dto/dto.rb
module Lolxin
class Dto
def initialize(data)
end
# TODO: make dynamic
def initialize_with(data)
end
end
end
<file_sep>/lib/lolxin/api/lol_static_data.rb
module Lolxin
class LolStaticData < Api
attr_accessor :endpoint
def initialize(options = {})
super
@endpoint = "static-data/%{version}" % {version: @version}
end
# TODO: get Faraday block to work with optional params
def champions(champion_id = nil)
url = if champion_id
"#{endpoint}/champions/#{champion_id}"
else
"#{endpoint}/champions"
end
conn.get(url)
end
def items(item_id = nil)
url = if item_id
"#{endpoint}/items/#{item_id}"
else
"#{endpoint}/items"
end
conn.get(url)
end
def language_strings
url = "#{endpoint}/language-strings"
conn.get(url)
end
def languages
url = "#{endpoint}/languages"
conn.get(url)
end
def maps
url = "#{endpoint}/maps"
conn.get(url)
end
def masteries(mastery_id = nil)
url = if mastery_id
"#{endpoint}/masteries/#{mastery_id}"
else
"#{endpoint}/masteries"
end
conn.get(url)
end
def profile_icons
url = "#{endpoint}/profile-icons"
conn.get(url)
end
def realms
url = "#{endpoint}/realms"
conn.get(url)
end
def reforged_rune_paths(path_id = nil)
url = if path_id
"#{endpoint}/reforged-rune-paths/#{path_id}"
else
"#{endpoint}/reforged-rune-paths"
end
conn.get(url)
end
def reforged_runes(reforged_rune_id = nil)
url = if reforged_rune_id
"#{endpoint}/reforged-runes/#{reforged_rune_id}"
else
"#{endpoint}/reforged-runes"
end
conn.get(url)
end
def runes(rune_id = nil)
url = if rune_id
"#{endpoint}/runes/#{rune_id}"
else
"#{endpoint}/runes"
end
conn.get(url)
end
def summoner_spells(spell_id = nil)
url = if spell_id
"#{endpoint}/summoner-spells/#{spell_id}"
else
"#{endpoint}/summoner-spells"
end
conn.get(url)
end
def tarball_links
url = "#{endpoint}/tarball-links"
conn.get(url)
end
def versions
url = "#{endpoint}/versions"
conn.get(url)
end
end
end
<file_sep>/lib/lolxin/dto/game_info_dto.rb
module Lolxin
class GameInfoDto
attr_accessor(*%i(
game_id
game_start_time
platform_id
game_mode
map_id
game_type
banned_champions
observers
participants
game_length
game_queue_config_id
data
))
def initialize(data)
@data = data
initialize_with(data)
end
private
# TODO: finish this
def initialize_with(data)
end
end
CurrentGameInfoDto = FeaturedGameInfoDto = GameInfoDto
end
<file_sep>/spec/lol_static_data_spec.rb
describe LolStaticData do
let(:client) { Client.new(ENV['API_KEY'], region: :br1) }
let(:lol_static_data) { client.lol_static_data }
let(:doublelift) { 20132258 }
let(:champion_id) { 39 }
let(:item_id) { 1001 }
let(:mastery_id) { 6111 }
let(:rune_id) { 5001 }
let(:spell_id) { 1 }
let(:path_id) { 8200 }
let(:reforged_rune_id) { 8005 }
describe '#champions' do
it 'returns 200 status for all champions' do
expect(lol_static_data.champions.status).to eq(200)
end
it 'returns 200 status for single champion_id' do
expect(lol_static_data.champions(champion_id).status).to eq(200)
end
end
describe '#items' do
it 'returns 200 status for all items' do
expect(lol_static_data.items.status).to eq(200)
end
it 'returns 200 status for single item_id' do
expect(lol_static_data.items(item_id).status).to eq(200)
end
end
describe '#masteries' do
it 'returns 200 status for all masteries' do
expect(lol_static_data.masteries.status).to eq(200)
end
it 'returns 200 status for single mastery_id' do
expect(lol_static_data.masteries(mastery_id).status).to eq(200)
end
end
describe '#runes' do
it 'returns 200 status for all runes' do
expect(lol_static_data.runes.status).to eq(200)
end
it 'returns 200 status for single rune_id' do
expect(lol_static_data.runes(rune_id).status).to eq(200)
end
end
describe '#summoner_spells' do
it 'returns 200 status for all summoner_spells' do
expect(lol_static_data.summoner_spells.status).to eq(200)
end
it 'returns 200 status for single spell_id' do
expect(lol_static_data.summoner_spells(spell_id).status).to eq(200)
end
end
describe '#reforged_rune_paths' do
it 'returns 200 status for all reforged_rune_paths' do
expect(lol_static_data.reforged_rune_paths.status).to eq(200)
end
it 'returns 200 status for single path_id' do
expect(lol_static_data.reforged_rune_paths(path_id).status).to eq(200)
end
end
describe '#reforged_runes' do
it 'returns 200 status for all reforged_runes' do
expect(lol_static_data.reforged_runes.status).to eq(200)
end
it 'returns 200 status for single reforged_rune_id' do
expect(lol_static_data.reforged_runes(reforged_rune_id).status).to eq(200)
end
end
%w[
language_strings
languages
maps
profile_icons
realms
versions
tarball_links
].each do |method|
describe "##{method}" do
it 'returns 200 status' do
expect(lol_static_data.send(method).status).to eq(200)
end
end
end
end
<file_sep>/spec/version_spec.rb
describe Lolxin::VERSION do
it 'matches version' do
expect(subject).to eq("0.12.1")
end
end
<file_sep>/lib/lolxin/dto/champion_mastery_dto.rb
module Lolxin
class ChampionMasteryDto
attr_accessor(*%i(
chest_granted
champion_level
champion_points
champion_id
player_id
champion_points_until_next_level
champion_points_since_last_level
last_play_time
data
))
def initialize(data)
@data = data
initialize_with(data)
end
private
def initialize_with(data)
@chest_granted = data['chestGranted']
@champion_level = data['championLevel']
@champion_points = data['championPoints']
@champion_id = data['championId']
@player_id = data['playerId']
@champion_points_until_next_level = data['championPointsUntilNextLevel']
@champion_points_since_last_level = data['championPointsSinceLastLevel']
@last_play_time = data['lastPlayTime']
end
end
end
<file_sep>/lib/lolxin/dto/league_item_dto.rb
module Lolxin
class LeagueItemDto
attr_accessor(*%i(
rank
hot_streak
mini_series
wins
veteran
losses
player_or_team_name
player_or_team_id
inactive
fresh_blood
league_points
))
def initialize(data)
@data = data
initialize_with(data)
end
private
def initialize_with(data)
@rank = data['rank']
@hot_streak = data['hotStreak']
@mini_series = MiniSeriesDto.new(data['miniSeries'])
@wins = data['wins']
@veteran = data['veteran']
@losses = data['losses']
@player_or_team_id = data['playerOrTeamId']
@player_or_team_name = data['playerOrTeamName']
@inactive = data['inactive']
@fresh_blood = data['freshBlood']
@league_points = data['leaguePoints']
end
end
end
<file_sep>/spec/champion_mastery_spec.rb
describe ChampionMastery do
let(:client) { Client.new(ENV['API_KEY'], region: :na1) }
let(:champion_mastery) { client.champion_mastery }
let(:doublelift) { 20132258 }
let(:champion_id) { 39 }
describe '#by-summoner' do
it 'retrieves a list of ChampionMasteryDto for a single summoner' do
masteries = champion_mastery.by_summoner(doublelift)
expect(masteries.length).to be >= 1
masteries.each do |mastery|
mastery.instance_variables.each do |iv|
expect(mastery.instance_variable_get(iv)).not_to be nil
end
end
end
end
describe '#by-champion' do
it 'gets a ChampionMasteryDto for a single summoner on a champion' do
mastery = champion_mastery.by_champion(doublelift, champion_id)
mastery.instance_variables.each do |iv|
expect(mastery.instance_variable_get(iv)).not_to be nil
end
end
end
describe '#scores' do
it 'gets the total mastery score a summoner has for all champions' do
expect(champion_mastery.scores(doublelift).to_i).to be > 0
end
end
end
<file_sep>/lib/lolxin/helpers/version.rb
module Lolxin
VERSION = '0.13.0'
end
<file_sep>/lib/lolxin/client.rb
module Lolxin
class ClientError < StandardError; end
# Client create connection clients for specific endpoints
class Client
ENDPOINTS = [
:champion_mastery,
:champion,
:league,
:lol_static_data,
:lol_status,
:match,
:spectator,
:summoner,
:third_party_code
#tournament_stub
#tournament
]
attr_reader :region, :api_key, :options
def initialize(api_key, options = {})
@api_key = api_key
@region = options[:region] if Region.valid?(options[:region])
@options = { api_key: @api_key, region: @region }
raise ClientError, "Invalid API key" if @api_key.nil? || @api_key.empty?
raise ClientError, "Invalid region" unless @region
end
ENDPOINTS.each do |ep|
define_method(ep) do |options = @options|
options[:version] = ApiVersion.const_get(ep.to_s.upcase)
name = ep.to_s.split('_').map(&:capitalize).join
klass = Object.const_get(name)
klass.new(options)
end
end
end
end
<file_sep>/lib/lolxin/api/league.rb
module Lolxin
class League < Api
attr_accessor :endpoint
def initialize(options = {})
super
@endpoint = "league/%{version}" % {version: @version}
end
%i(challenger master).each do |league|
define_method("#{league}_by_queue".to_sym) do |queue|
url = "#{endpoint}/#{league}leagues/by-queue/#{queue}"
res = conn.get(url)
return res if res.status != 200
league_list = JSON.parse(res.body)
LeagueListDto.new(league_list)
end
end
def leagues(league_id)
url = "#{endpoint}/leagues/#{league_id}"
res = conn.get(url)
return res if res.status != 200
league_lists = JSON.parse(res.body)
league_lists.map { |league_list| LeagueListDto.new(league_list) }
end
def positions_by_summoner(summoner_id)
url = "#{endpoint}/positions/by-summoner/#{summoner_id}"
res = conn.get(url)
return res if res.status != 200
league_positions = JSON.parse(res.body)
league_positions.map { |lp| LeaguePositionDto.new(lp) }
end
end
end
<file_sep>/lib/lolxin/api/spectator.rb
module Lolxin
class Spectator < Api
CurrentGameInfo = FeaturedGameInfo = Struct.new(
:game_id,
:game_start_time,
:platform_id,
:game_mode,
:map_id,
:game_type,
:banned_champions,
:observers,
:participants,
:game_length,
:game_queue_config_id
)
CurrentGameParticipant = Struct.new(
:profile_icon_id,
:champion_id,
:summoner_name,
:runes,
:bot,
:team_id,
:spell2d,
:masteries,
:spell1d,
:summoner_id
)
Rune = Struct.new(
:count,
:rune_id
)
Mastery = Struct.new(
:mastery_id,
:rank
)
FeaturedGames = Struct.new(
:client_refresh_interval,
:game_list
)
BannedChampion = Struct.new(
:pick_turn,
:champion_id,
:team_id
)
Observer = Struct.new(
:encryption_key
)
Participant = Struct.new(
:profile_icon_id,
:champion_id,
:summoner_name,
:bot,
:spell2d,
:team_id,
:spell1id
)
attr_accessor :endpoint
def initialize(options = {})
super
@endpoint = "spectator/%{version}" % {version: @version}
end
def by_summoner(summoner_id)
url = "#{endpoint}/active-games/by-summoner/#{summoner_id}"
res = conn.get(url)
return res if res.status != 200
current_game = JSON.parse(res.body)
build_current_game_info(current_game)
end
def featured_games
url = "#{endpoint}/featured-games"
res = conn.get(url)
return res if res.status != 200
featured = JSON.parse(res.body)
build_featured_games(featured)
end
private
def build_current_game_info(current_game)
CurrentGameInfo.new(
current_game['gameId'],
current_game['gameStartTime'],
current_game['platformId'],
current_game['gameMode'],
current_game['mapId'],
current_game['gameType'],
build_banned_champions(current_game['bannedChampions']),
build_observer(current_game['observers']),
build_current_game_participants(current_game['participants']),
current_game['gameLength'],
current_game['gameQueueConfigId']
)
end
def build_featured_games(featured_games)
FeaturedGames.new(
featured_games['clientRefreshInterval'],
featured_games['gameList'].map { |f| build_featured_game_info(f) }
)
end
def build_featured_game_info(feature)
FeaturedGameInfo.new(
feature['gameId'],
feature['gameStartTime'],
feature['platformId'],
feature['gameMode'],
feature['mapId'],
feature['gameType'],
build_banned_champions(feature['bannedChampions']),
build_observer(feature['observer']),
build_participants(feature['participants']),
feature['gameLength'],
feature['gameQueueConfigId']
)
end
def build_banned_champions(banned_champions)
return [] if banned_champions.nil? or banned_champions.empty?
banned_champions.map do |banned_champion|
BannedChampion.new(
banned_champion['pickTurn'],
banned_champion['championId'],
banned_champion['teamId']
)
end
end
def build_observer(observer)
return nil if observer.nil?
Observer.new(observer['encryptionKey'])
end
def build_current_game_participants(participants)
participants.map do |participant|
CurrentGameParticipant.new(
participant['profileIconId'],
participant['championId'],
participant['summonerName'],
participant['runes'],
participant['bot'],
participant['teamId'],
participant['spell2d'],
participant['masteries'],
participant['spell1id'],
participant['summonerId']
)
end
end
def build_participants(participants)
participants.map do |participant|
Participant.new(
participant['profileIconId'],
participant['championId'],
participant['summonerName'],
participant['bot'],
participant['spell2d'],
participant['teamId'],
participant['spell1id']
)
end
end
end
end
<file_sep>/spec/third_party_code_spec.rb
describe ThirdPartyCode do
let(:client) { Client.new(ENV['API_KEY'], region: :na1) }
let(:third_party_code) { client.third_party_code }
let(:doublelift) { 20132258 }
# NOTE: verification system with the game client
# doubtful to get code back unless i spin up the game again
describe '#by_summoner' do
xit 'returns 200 status' do
# expect(third_party_code.by_summoner(doublelift).status).to eq(200)
end
end
end
<file_sep>/lib/lolxin/api/match.rb
module Lolxin
class Match
attr_accessor :endpoint
# TODO: many endpoints to change and many DTOs to add
def initialize(options = {})
super
@endpoint = "match/%{version}" % {version: @version}
end
def matches(match_id)
url = "#{endpoint}/matches/#{match_id}"
conn.get(url)
end
def by_account(account_id, recent = false)
url = if recent
"#{endpoint}/matchlists/by-account/#{account_id}/recent"
else
"#{endpoint}/matchlists/by-account/#{account_id}"
end
conn.get(url)
end
def by_match(match_id)
url = "#{endpoint}/timelines/by-match/#{match_id}"
conn.get(url)
end
def tournament_code(tournament_code, match_id)
url = if tournament_code && match_id
"matches/by-tournament-code/#{tournament_code}/ids"
else
"matches/#{match_id}/by-tournament-code/#{tournament_code}"
end
conn.get(url)
end
end
end
<file_sep>/lib/lolxin/api/summoner.rb
module Lolxin
class Summoner < Api
attr_accessor :endpoint
def initialize(options = {})
super
@endpoint = "summoner/%{version}" % {version: @version}
end
def by_account(account_id)
url = "#{endpoint}/summoners/by-account/#{account_id}"
conn.get(url)
end
def by_name(summoner_name)
url = "#{endpoint}/summoners/by-name/#{summoner_name}"
conn.get(url)
end
def summoners(summoner_id)
url = "#{endpoint}/summoners/#{summoner_id}"
conn.get(url)
end
end
end
|
ae321a53cb45eb1c50edf332556af3075f8ac35d
|
[
"Markdown",
"Ruby"
] | 35
|
Ruby
|
jonwho/lolxin
|
ce6071189feb6d4dc772199118e1388e28db50e0
|
11205b4c1f2f2dc017abc38cdcd7a1e6d31a3800
|
refs/heads/master
|
<repo_name>rizafahmi/hyperapp-counter-app<file_sep>/src/lib/request.js
import axios from 'axios'
import { API_URL } from '../constants'
const getRequest = url => {
return axios
.get(url, {
headers: {
Authorization: `Token token="<KEY>"`
}
})
.catch(err => console.error(err))
}
export default {
getAll: _ => getRequest(API_URL),
getQuery: query => getRequest(`${API_URL}?filter=${query}&type=tag`)
}
<file_sep>/src/index.js
import { app } from 'hyperapp'
import actions from './actions'
import state from './state'
import view from './components/Quotes'
const { add, sub } = app(state, actions, view, document.body)
/**
* Hyperapp wires your actions so the view is re-rendered every time the state
* changes as a result of calling any action. This object is useful because it
* allows you to talk to your app from another app, framework, vanilla JS, etc.
*
* Here is an example on CodePen: https://codepen.io/selfup/pen/jLMRjO
*/
setTimeout(add, 1000)
setTimeout(sub, 2000)
|
641d9bbfbf8a855f51fa768f999c28b55647b46f
|
[
"JavaScript"
] | 2
|
JavaScript
|
rizafahmi/hyperapp-counter-app
|
45d7afe3b448eedf9f5059d3b4c440c74ba1b45b
|
7aa98b6b75b1d0b3ce3b6ed0ab3d4b02c79b1d46
|
refs/heads/master
|
<file_sep><?php
class DataLayer {
private $conn = null;
public function OpenConnection ()
{
$json = json_decode(file_get_contents('dataobjectserver/common/dbmetadata.json'), true);
$this->conn = new mysqli(trim($json['dbserver']),trim($json['dbuser']),trim($json['dbpwd']),trim($json['dbname']));
}
public function CloseConnection()
{
$this->conn->Close();
}
public function GetObjectCollection($object,$className,$classAttrValuePairs=null,$sortby=null,$getrelatedobjectcollection=0) {
$select_sql = "select id from $className";
if ($classAttrValuePairs) {
$select_sql .= ' where ';
foreach ($classAttrValuePairs as $key => $value) {
$select_sql .= "$key = '$value' and ";
}
$select_sql = rtrim($select_sql,'and '); //strip out the last appended add
}
if ($sortby) {
$select_sql .= ' order by ';
foreach ($sortby as $key => $value) {
$select_sql .= "$key $value,";
}
$select_sql = rtrim($select_sql,','); //strip out the last appended comma
}
if ($result = $this->conn->query($select_sql)){
while ($row = $result->fetch_array()){
//the object constructor also takes an argument to get the related object collections
//we can possibly create another method to get the object collection along with the related object collections
array_push($object->Items,new $className($row[0],$getrelatedobjectcollection));
}
$object->Length = sizeof($object->Items);
}
}
public function GetObjectProperties($object,$getrelatedobjectcollection = 0)
{
$id = $object->id ?: 'null'; //if else super shortcut
$select_sql = 'select * from ' . get_class($object) . ' where id = ' . $id;
if ($result = $this->conn->query($select_sql)) {
$row = $result->fetch_assoc();
while ($fieldinfo = $result->fetch_field()) {
$object->{$fieldinfo->name} = $row[$fieldinfo->name];
}
if ($getrelatedobjectcollection) {
$this->getRelatedObjectCollections($object);
}
}
}
private function getRelatedObjectCollections($object) {
$id = $object->id ?: 'null';
$this_table_name = get_class($object);
//get the mapping tables
$mapping_tables = DataLayer::getMappingTables($object,$this->conn);
foreach ($mapping_tables as $mapping_table_name) {
$this_table_fk_col_name = '';
$related_table_name = '';
$related_table_fk_col_name = '';
//from each mapping table, get the related table info
$relatedTablesInfo = DataLayer::getRelatedTablesInfo($mapping_table_name,$this->conn);
foreach ($relatedTablesInfo as $row) {
if ($row['referenced_table_name'] == $this_table_name) {
$this_table_fk_col_name = $row['column_name'];
}
else {
$related_table_name = $row['referenced_table_name'];
$related_table_fk_col_name = $row['column_name'];
}
}
//if one-to-one relationship
if ($related_table_name == '') {
$related_table_name = $mapping_table_name;
//select userreply.id from userreply, post where userreply.postid = post.id;
$select_sql = "select " . $related_table_name . ".id from " . $related_table_name . "," . $this_table_name . " where " . $related_table_name . "." . $this_table_fk_col_name . " = " . $this_table_name . ".id and " . $this_table_name . ".id = " . $id . ";";
}
//if one-to-many relationship
else {
$select_sql = "select " . $related_table_name . ".id from " . $related_table_name . "," . $this_table_name . "," . $mapping_table_name . " where " . $related_table_name . ".id = " . $mapping_table_name . "." . $related_table_fk_col_name . " and " . $this_table_name . ".id = " . $mapping_table_name . "." .$this_table_fk_col_name . " and " . $this_table_name . ".id = " . $id . " group by " . $related_table_name . ".id ;";
}
if ($related_id_result = $this->conn->query($select_sql)) {
//create the related object collection property
//even if there are not defined relateds
//this way we at leastr get an empty array
require_once 'dataobjectserver/' . $related_table_name . '.php';
$className = $related_table_name;
$object->{$className} = array();
if ($related_id_result->num_rows) {
while ($row = $related_id_result->fetch_assoc()) {
//now when we call GetObjectProperties we will not request for related objects
//this means that we will only go down one level when creating objects
//this will prevent going too t
//but more importantly, avoid going into an infinite loop for co-related objects
$instance = new $className($row['id']);
array_push($object->{$className},$instance);
}
}
}
}
}
public function SaveObjectProperties($object)
{
$id = $object->id ?: 'null'; //if else super shortcut
$this_table_name = get_class($object);
$select_sql = 'select * from ' . $this_table_name . ' where id = ' . $id;
$object->pagename = null;
if ($result = $this->conn->query($select_sql)) {
$columns = array();
while ($fieldinfo = $result->fetch_field()) {
array_push($columns, $fieldinfo);
}
$insert_update_on_duplicate = 'insert into ' . $this_table_name . '(';
for ($i=0;$i<sizeof($columns);$i++) {
$insert_update_on_duplicate .= $columns[$i]->name;
if ($i < sizeof($columns) - 1) {
$insert_update_on_duplicate .= ',';
}
}
$insert_update_on_duplicate .= ')';
$insert_update_on_duplicate .= ' values(';
for ($i=0;$i<sizeof($columns);$i++) {
$insert_update_on_duplicate .= DataLayer::prettifydatavalue($object->{$columns[$i]->name},$columns[$i]);
if ($i < sizeof($columns) - 1) {
$insert_update_on_duplicate .= ',';
}
}
$insert_update_on_duplicate .= ')';
$insert_update_on_duplicate .= ' on duplicate key update ';
for ($i=0;$i<sizeof($columns);$i++) {
$insert_update_on_duplicate .= $columns[$i]->name . ' = ' . DataLayer::prettifydatavalue($object->{$columns[$i]->name},$columns[$i]);
if ($i < sizeof($columns) - 1) {
$insert_update_on_duplicate .= ',';
}
}
$insert_update_on_duplicate .= ';';
if ($this->conn->query($insert_update_on_duplicate)) {
//$this->NewId = $this->conn->insert_id;
$object->id = $this->conn->insert_id;
}
else {
throw new Exception ($this->conn->error);
}
$this->setRelatedObjectCollections($object);
}
}
private function setRelatedObjectCollections($object) {
$this_table_name = get_class($object);
//get the mapping tables
$mapping_tables = DataLayer::getMappingTables($object,$this->conn);
foreach ($mapping_tables as $mapping_table_name) {
$this_table_fk_col_name = '';
$related_table_name = '';
$related_table_fk_col_name = '';
//from each mapping table, get the related table info
$relatedTablesInfo = DataLayer::getRelatedTablesInfo($mapping_table_name,$this->conn);
foreach ($relatedTablesInfo as $row) {
if ($row['referenced_table_name'] == $this_table_name) {
$this_table_fk_col_name = $row['column_name'];
}
else {
$related_table_name = $row['referenced_table_name'];
$related_table_fk_col_name = $row['column_name'];
}
}
//this system does not support one-to-one table relations
//but just to handle the one-off case of one-to-one relations
if ($related_table_name) {
//now there's no way to know from the current related ids if the user has deleted a related object
//so right now the only way we can think of to remove all entries for the main table id
$clear_relations = "delete from $mapping_table_name where $this_table_fk_col_name = $object->id;";
if ($this->conn->query($clear_relations)) {
//then re-insert the relations. for all relations
foreach ($object->{$related_table_name} as $relatedObject) {
$update_relations = "insert into $mapping_table_name ($this_table_fk_col_name,$related_table_fk_col_name) values($object->id,$relatedObject->id);";
if ($this->conn->query($update_relations)) {
}
else {
throw new Exception($this->conn->error,$this->conn->errno);
}
}
}
else {
throw new Exception($this->conn->error,$this->conn->errno);
}
}
}
}
public function DeleteObject($object)
{
$delete_sql = 'delete from ' . get_class($object) . ' where id = ' . $object->id;
$result = $this->conn->query($delete_sql);
}
private static function fieldisnotnumeric($fieldinfo) {
return $fieldinfo->type != 1 && $fieldinfo->type != 2 && $fieldinfo->type != 3 &&
$fieldinfo->type != 4 && $fieldinfo->type != 5 && $fieldinfo->type != 8 &&
$fieldinfo->type != 9 && $fieldinfo->type != 246;
}
private static function prettifydatavalue($value,$fieldinfo) {
$retval = $value;
if ($value) {
if (DataLayer::fieldisnotnumeric($fieldinfo)) {
if ($fieldinfo->type == 7 && $value == 'now()') {
$retval = $value;
}
else {
$retval = "'" . $value . "'";
}
}
}
else {
$retval = 'null';
}
return $retval;
}
private static function getMappingTables($object,$conn) {
$select_sql = "select table_name from information_schema.key_column_usage where referenced_table_name = '" . get_class($object) . "'";
$mapping_tables = array();
if ($result = $conn->query($select_sql)) {
while ($row = $result->fetch_assoc()) {
array_push($mapping_tables,$row['table_name']);
}
}
return $mapping_tables;
}
private static function getRelatedTablesInfo($mapping_table_name,$conn) {
$relatedTablesInfo = array();
$select_sql = "select referenced_table_name, column_name,referenced_column_name from information_schema.key_column_usage where table_name = '" . $mapping_table_name . "' and referenced_table_name is not null;";
if ($result = $conn->query($select_sql)) {
while ($row = $result->fetch_assoc()) {
array_push($relatedTablesInfo,$row);
}
}
return $relatedTablesInfo;
}
}
?>
|
6f44cfb07a6da9aa4c57df1f7b778a294ce67a68
|
[
"PHP"
] | 1
|
PHP
|
peterbarraud/dataobjectserver
|
aa081699a20ddb8ea6b41407518f4d6710475801
|
1f513bf82cbda43599cfd7157df82ad2d26e250c
|
refs/heads/master
|
<file_sep>package airfrov.com.androidhomework.ui.pets;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import airfrov.com.androidhomework.app.Constants;
import airfrov.com.androidhomework.ui.pets.cat.CatFragment;
import airfrov.com.androidhomework.ui.pets.dog.DogFragment;
import airfrov.com.androidhomework.ui.pets.fox.FoxFragment;
class PetTabAdapter extends FragmentStatePagerAdapter {
public static final String[] PET_TITLES = {"CATS", "DOGS","FOXES"};
public PetTabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new CatFragment();
case 1:
return new DogFragment();
case 2:
return new FoxFragment();
default:
return null;
}
}
@Override
public int getCount() {
return PET_TITLES.length;
}
@Override
public CharSequence getPageTitle(int position) {
return PET_TITLES[position];
}
}
<file_sep>package airfrov.com.androidhomework.ui.pets.cat;
import com.hannesdorfmann.mosby.mvp.MvpView;
import airfrov.com.androidhomework.model.data.Cat;
public interface CatView extends MvpView {
void setCatList();
void showCatDetails(Cat catDetails);
void stopRefresh();
void showError(String message);
void saveCatImages(String CatImage);
void updateName();
}
<file_sep>package airfrov.com.androidhomework.app;
public class Endpoints {
public static final String BASE_URL_FOX = "https://randomfox.ca";
static final String API_URL_FOX = BASE_URL_FOX +"/"; // + "/api/v1/";
public static final String FOX = "floof";
public static final String BASE_URL_CAT = "https://aws.random.cat";
static final String API_URL_CAT = BASE_URL_CAT +"/"; // + "/api/v1/";
public static final String CAT = "meow";
public static final String BASE_URL_DOG = "https://random.dog";
static final String API_URL_DOG = BASE_URL_DOG +"/"; // + "/api/v1/";
public static final String DOG = "woof.json";
}
<file_sep>package airfrov.com.androidhomework.ui.pets;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.ImageView;
import android.widget.TextView;
import airfrov.com.androidhomework.R;
import airfrov.com.androidhomework.databinding.ActivityPetMainBinding;
import io.realm.Realm;
public class PetActivity extends AppCompatActivity {
private Realm realm;
private ActivityPetMainBinding binding;
@SuppressWarnings("ConstantConditions")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
realm = Realm.getDefaultInstance();
binding = DataBindingUtil.setContentView(this, R.layout.activity_pet_main);
setSupportActionBar(binding.toolbar);
getSupportActionBar().setTitle("Random Pets");
PetTabAdapter mAdapter = new PetTabAdapter(getSupportFragmentManager());
binding.viewPager.setAdapter(mAdapter);
binding.tabs.setupWithViewPager(binding.viewPager, true);
//binding.tabs.setTabMode(TabLayout.MODE_SCROLLABLE);
}
@Override
protected void onDestroy() {
realm.close();
super.onDestroy();
}
}
<file_sep>package airfrov.com.androidhomework.model.data;
import com.google.gson.annotations.SerializedName;
import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
public class Dog extends RealmObject {
@SerializedName("dogId")
@PrimaryKey
private int dogId;
@SerializedName("dogName")
private String dogName;
@SerializedName("dogImage")
private String dogImage;
public Dog() {
}
public int getDogId() {
return dogId;
}
public void setDogId(int dogId) {
this.dogId = dogId;
}
public String getDogName() {
return dogName;
}
public void setDogName(String dogName) {
this.dogName = dogName;
}
public String getDogImage() {
return dogImage;
}
public void setDogImage(String dogImage) {
this.dogImage = dogImage;
}
}
<file_sep># AndroidHomework
The Airfrov product team loves their pets so below is a hi-fi design of an app that shows a variety of random cats, dogs, and foxes.
App Design :
I decided to use MVP Architecture in creating the homework so first after creating the project I usually start with creating my usual packages which compose of app, model, ui, & util. Then next is I compile/implement the libraries that I will be using on the project so after looking at sample design provided I decided to use recyclerview, cardview, glide, retrofit, realm, databinding, and MVP. I used cardview and recyclerview for displaying the pets using grid-layout manager since using recyclerview is a more flexible control for handling list data and it can also reuse the cells/cardview.
I used glide on displaying the images of pets even though it may take a while on loading the images depending on the internet connection it is much more efficient the saving all the images. Next is retrofit by utilizing this library it is much easier to retrieve or upload json via a rest based webservice.
And with that, I can easily use the provided public API no matter what design or json it will return. Next, I used is realm as a database for the pets object. I choose realm for its speed, ease of use, and it is well documented. Lastly, I used databinding to remove boilerplate, stronger readability and much faster the using findviewbyid.
For the MVP under my app is the class application where I initialized the realm and retrofit also this is where
API interface for retrofit can be found and all the constants and endpoints. Next is model my model is divided into two packages the data and response since the requirements are just 3 pets and static I only have 3 data and 3 response. Next is the ui, under ui will be all the activity first I created PetActivity and PetTabAdapater that will handle the tabs. Next is I created the Fragment, Presenter, View, and Adapter. All the process is happening on the presenter like saving the pets object, updating the name, and loading the images. Under the adapter are the List of pets and its cardview binding. For the fragment first I will check if the pet object is already existing if it is already existing I will just reload the previous data but if it's not I will load the images first then save it on the object before loading it. I also put a refresh what it will do it just simply refresh all the images and save it. For the Editing of the name I just simply use custom dialog and upon saving I just call the presenter and do the saving of the updated name.
UI/UX Improvements:
*Since the requirements are just 3 pets I use static layouts and tabs. But I think in reality it should be dynamic and can accommodate different pets.
*Also I make the number of pets dynamic but since the requirements are clear to show only 10 pets per tab I limit it to 10.
Backend Improvements:
*As I mention a while ago the model I created is static for 3 pets but I think it should be dynamic and should only be 1 model and just simply add a column type of pet to accommodate different pets.
*For the public API since it has different endpoints/url I think it is much more efficient to use rxjava.
<file_sep>package airfrov.com.androidhomework.ui.pets.fox;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.hannesdorfmann.mosby.mvp.viewstate.RestorableViewState;
class FoxViewState implements RestorableViewState<FoxView> {
@Override
public void saveInstanceState(@NonNull Bundle out) {
}
@Override
public RestorableViewState<FoxView> restoreInstanceState(Bundle in) {
return this;
}
@Override
public void apply(FoxView view, boolean retained) {
}
}
<file_sep>package airfrov.com.androidhomework.ui.pets.cat;
import android.content.Context;
import android.databinding.DataBindingUtil;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
import java.util.List;
import airfrov.com.androidhomework.R;
import airfrov.com.androidhomework.databinding.ItemPetCatBinding;
import airfrov.com.androidhomework.model.data.Cat;
public class CatAdapter extends RecyclerView.Adapter<CatAdapter.ViewHolder> {
private List<Cat> cat;
private final Context context;
private final CatView view;
private static final int VIEW_TYPE_DEFAULT = 0;
public CatAdapter(Context context, CatView view) {
this.context = context;
this.view = view;
cat = new ArrayList<>();
}
@Override
public int getItemViewType(int position) {
return VIEW_TYPE_DEFAULT;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
ItemPetCatBinding itemCatBinding = DataBindingUtil.inflate(
LayoutInflater.from(parent.getContext()),
R.layout.item_pet_cat,
parent,
false);
return new ViewHolder(itemCatBinding);
}
@Override
public void onBindViewHolder(CatAdapter.ViewHolder holder, int position) {
holder.itemCatBinding.setCat(cat.get(position));
holder.itemCatBinding.setView(view);
Glide.with(holder.itemView.getContext())
.load(cat.get(position).getCatImage())
.centerCrop()
.error(R.drawable.pet_placeholder)
.into(holder.itemCatBinding.catImage);
}
public void clear() {
cat.clear();
notifyDataSetChanged();
}
@Override
public int getItemCount() {
return cat.size();
}
public void setAttendeeResult(List<Cat> event) {
this.cat = event;
}
public class ViewHolder extends RecyclerView.ViewHolder {
private final ItemPetCatBinding itemCatBinding;
public ViewHolder(ItemPetCatBinding itemCatBinding) {
super(itemCatBinding.getRoot());
this.itemCatBinding = itemCatBinding;
}
}
}
|
b30dafb184b18c2587e8437a8c41c8d6e518befa
|
[
"Markdown",
"Java"
] | 8
|
Java
|
mudeleon/AndroidHomework
|
83e238a5fa26cdba5314c6ae46d116c9543df097
|
baf43b2404d2732eacc2b46876261803d110c5a7
|
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 test;
/**
*
* @author Administrator
*/
public class App {
public static void main (String[] args){
Plant plant1 = new Plant();
Tree tree = new Tree();
Plant plant2 = tree;
plant2.grow();
tree.shedLeaves();
}
}
|
74c039bdaa141345cee588646ffed02ab310066a
|
[
"Java"
] | 1
|
Java
|
pradeep2005s/try
|
422edb5d364b85948fd44c9e5e8d0204e9dbfb25
|
f5feb49af340dbd66dbf2beba5ac76482cbef384
|
refs/heads/main
|
<repo_name>SienaCSISAdvancedProgramming/IteratorMethod<file_sep>/README.md
# IteratorMethod
Class example of a method that operates on an Iterator
<file_sep>/IteratorMethod.java
import java.util.ArrayList;
import java.util.Iterator;
import java.util.TreeSet;
/**
Class example of a method that takes an Iterator as a parameter.
@author <NAME>
@version Spring 2021
*/
public class IteratorMethod {
/**
A method to find and return the largest value in a sequence of Integer
values produced by the given Iterator.
@param i the Iterator
@return the largest value produced by the Iterator
*/
public static int max(Iterator<Integer> i) {
// we require at least one element for this to make sense
int result = i.next();
while (i.hasNext()) {
int x = i.next();
if (x > result) {
result = x;
}
}
return result;
}
// a main method to try it out
public static void main(String args[]) {
// we can use max with an Iterator over a familiar
// structure like an ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();
a.add(0);
a.add(34);
a.add(-23);
a.add(882);
a.add(3);
a.add(-4);
a.add(123);
a.add(-2833);
a.add(234);
a.add(88);
System.out.println("a: " + a);
System.out.println("Largest: " + max(a.iterator()));
// or with any Iterator from some other structure
TreeSet<Integer> b = new TreeSet<Integer>();
b.add(892);
b.add(-33);
b.add(0);
b.add(-33);
b.add(72);
b.add(12);
b.add(-2);
b.add(-827);
b.add(256);
b.add(17);
System.out.println("b: " + b);
System.out.println("Largest: " + max(b.iterator()));
}
}
|
a23389c93bd75653d455988331952784c8e96871
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
SienaCSISAdvancedProgramming/IteratorMethod
|
1b22e229796df46af786586ceea4cbee621e6e99
|
31bf9fec27cec749329f597d1910490d90ea5f6c
|
refs/heads/master
|
<file_sep># WindowsApp
Code for Windows / Windows Phone app
This repo is intended for Visual Studio 2015; it may work with other versions though. This includes the code for both Windows desktop and phone which use some shared files as well as some independent files. In Nov 2015, both Windows desktop and phone had app packages generated and uploaded. On Dec 2016, only windows desktop had a new app package uploaded which updated it to Server v1.3, which includes segmenting on ProductId, and new UI. Windows Phone is still using the old server v1.2, which is still set up, but may be deprecated in the near future when ProductId segmentation is mandatory. Since we didn't have a working windows phone at time of update, we never tested the changes, which I'm fairly certain breaks some things, especially UI layout.
* open .sln in WearhausBluetoothApp directory. There is another project in the repo, it is a modified sample for development. Ignore it for now.
* You may have the error from a fresh git pull: "File 'Package.StoreAssociation.xml' not found"
* Go to Project -> Store -> etc. Log in with <EMAIL> into visual studio.
* if greyed out: http://stackoverflow.com/questions/25438522/unable-to-create-app-package-the-appxupload-file-in-visual-studio-2013-for-a
* just select project in the solution explorer
* The repo now includes the cert .pfx for generating app packages, this isn't insecure since you can always just generate a new one whenever. Keeping it in repo just saves a few hours of time. You can read this for more details: https://msdn.microsoft.com/en-us/library/windows/desktop/jj835832(v=vs.85).aspx
* Initially, I attempted to refactor Arc and BT into a separate ArcLink class, but somewhere an issue popped up that broke DFU, so a fresh new attempt was done leaving all ArcLink stuff just in Scenario1_DfuClient.xaml.cs and using FSMs to keep UI organized.
* in Visual Studio 2015, there is a bug with 2 monitors and the .xaml preview. If you want to switch device from desktop/phone, you must go to the .xaml.cs file in the root monitor, NOT a second one. For some reason, it only appears in the original monitor.
* Issues exist with windows 8: An exception is thrown from the "await RfcommDeviceService.FromIdAsync(chatServiceInfo.Id);" It is possibly related to "A message sent on a datagram socket was larger than the internal message before or some other network limit, or the buffer used to receive a datagram into was smaller than the datagram itself. (Exception from HRESULT: 0x80072738)".
* Sidd was investigating this a year ago and found no solution. It breaks only for windows 8, not 10, so we can't test it in the office, but it doesn't appear to be a big deal as of now.
Control Flow for Windows Desktop:
* Starts with App.xaml.cs, it calls OnLaunched(), which creates a new Frame and navigates it to MainPage.
* MainPage.xaml.cs. This has some weird boilerplate code that is moslty useless but left in since it wasn't worth removing. It just reads SampleConfiguration.cs for what page to create, which is listed as Scenario1_DfuClient. Then it navigates its Frame to it.
* Scenario1_DfuClient.xaml.cs follows the ArcConnState FSM, which displays UI textblocks/buttons/images to help user connect device. This creates the IO stream to the Arc and the parse loop. Once connected, it registers the Headphone on the server and checks the live FirmwareTable to see what the latest target Firmware Version is. This allows us to control remotely if we want to pause the update (ex/ something went wrong) or push out new version without needing to update the windows app. If allowed to start an update (or .dfu file is chosen from the advanced menu), it will follow the process exactly as the Android GAIA version does, streaming the file and following GAIA protocol. Once done, it will prompt the user with either an error, or a success, and the user closes the windows app (deadend).
<file_sep>using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
namespace GaiaDFU
{
public class DfuCRC
{
private static long[] revCrcTable = {
0x00000000, 0xDB710641, 0x6D930AC3, 0xB6E20C82, 0xDB261586, 0x005713C7, 0xB6B51F45, 0x6DC41904,
0x6D3D2D4D, 0xB64C2B0C, 0x00AE278E, 0xDBDF21CF, 0xB61B38CB, 0x6D6A3E8A, 0xDB883208, 0x00F93449,
0xDA7A5A9A, 0x010B5CDB, 0xB7E95059, 0x6C985618, 0x015C4F1C, 0xDA2D495D, 0x6CCF45DF, 0xB7BE439E,
0xB74777D7, 0x6C367196, 0xDAD47D14, 0x01A57B55, 0x6C616251, 0xB7106410, 0x01F26892, 0xDA836ED3,
0x6F85B375, 0xB4F4B534, 0x0216B9B6, 0xD967BFF7, 0xB4A3A6F3, 0x6FD2A0B2, 0xD930AC30, 0x0241AA71,
0x02B89E38, 0xD9C99879, 0x6F2B94FB, 0xB45A92BA, 0xD99E8BBE, 0x02EF8DFF, 0xB40D817D, 0x6F7C873C,
0xB5FFE9EF, 0x6E8EEFAE, 0xD86CE32C, 0x031DE56D, 0x6ED9FC69, 0xB5A8FA28, 0x034AF6AA, 0xD83BF0EB,
0xD8C2C4A2, 0x03B3C2E3, 0xB551CE61, 0x6E20C820, 0x03E4D124, 0xD895D765, 0x6E77DBE7, 0xB506DDA6,
0xDF0B66EA, 0x047A60AB, 0xB2986C29, 0x69E96A68, 0x042D736C, 0xDF5C752D, 0x69BE79AF, 0xB2CF7FEE,
0xB2364BA7, 0x69474DE6, 0xDFA54164, 0x04D44725, 0x69105E21, 0xB2615860, 0x048354E2, 0xDFF252A3,
0x05713C70, 0xDE003A31, 0x68E236B3, 0xB39330F2, 0xDE5729F6, 0x05262FB7, 0xB3C42335, 0x68B52574,
0x684C113D, 0xB33D177C, 0x05DF1BFE, 0xDEAE1DBF, 0xB36A04BB, 0x681B02FA, 0xDEF90E78, 0x05880839,
0xB08ED59F, 0x6BFFD3DE, 0xDD1DDF5C, 0x066CD91D, 0x6BA8C019, 0xB0D9C658, 0x063BCADA, 0xDD4ACC9B,
0xDDB3F8D2, 0x06C2FE93, 0xB020F211, 0x6B51F450, 0x0695ED54, 0xDDE4EB15, 0x6B06E797, 0xB077E1D6,
0x6AF48F05, 0xB1858944, 0x076785C6, 0xDC168387, 0xB1D29A83, 0x6AA39CC2, 0xDC419040, 0x07309601,
0x07C9A248, 0xDCB8A409, 0x6A5AA88B, 0xB12BAECA, 0xDCEFB7CE, 0x079EB18F, 0xB17CBD0D, 0x6A0DBB4C,
0x6567CB95, 0xBE16CDD4, 0x08F4C156, 0xD385C717, 0xBE41DE13, 0x6530D852, 0xD3D2D4D0, 0x08A3D291,
0x085AE6D8, 0xD32BE099, 0x65C9EC1B, 0xBEB8EA5A, 0xD37CF35E, 0x080DF51F, 0xBEEFF99D, 0x659EFFDC,
0xBF1D910F, 0x646C974E, 0xD28E9BCC, 0x09FF9D8D, 0x643B8489, 0xBF4A82C8, 0x09A88E4A, 0xD2D9880B,
0xD220BC42, 0x0951BA03, 0xBFB3B681, 0x64C2B0C0, 0x0906A9C4, 0xD277AF85, 0x6495A307, 0xBFE4A546,
0x0AE278E0, 0xD1937EA1, 0x67717223, 0xBC007462, 0xD1C46D66, 0x0AB56B27, 0xBC5767A5, 0x672661E4,
0x67DF55AD, 0xBCAE53EC, 0x0A4C5F6E, 0xD13D592F, 0xBCF9402B, 0x6788466A, 0xD16A4AE8, 0x0A1B4CA9,
0xD098227A, 0x0BE9243B, 0xBD0B28B9, 0x667A2EF8, 0x0BBE37FC, 0xD0CF31BD, 0x662D3D3F, 0xBD5C3B7E,
0xBDA50F37, 0x66D40976, 0xD03605F4, 0x0B4703B5, 0x66831AB1, 0xBDF21CF0, 0x0B101072, 0xD0611633,
0xBA6CAD7F, 0x611DAB3E, 0xD7FFA7BC, 0x0C8EA1FD, 0x614AB8F9, 0xBA3BBEB8, 0x0CD9B23A, 0xD7A8B47B,
0xD7518032, 0x0C208673, 0xBAC28AF1, 0x61B38CB0, 0x0C7795B4, 0xD70693F5, 0x61E49F77, 0xBA959936,
0x6016F7E5, 0xBB67F1A4, 0x0D85FD26, 0xD6F4FB67, 0xBB30E263, 0x6041E422, 0xD6A3E8A0, 0x0DD2EEE1,
0x0D2BDAA8, 0xD65ADCE9, 0x60B8D06B, 0xBBC9D62A, 0xD60DCF2E, 0x0D7CC96F, 0xBB9EC5ED, 0x60EFC3AC,
0xD5E91E0A, 0x0E98184B, 0xB87A14C9, 0x630B1288, 0x0ECF0B8C, 0xD5BE0DCD, 0x635C014F, 0xB82D070E,
0xB8D43347, 0x63A53506, 0xD5473984, 0x0E363FC5, 0x63F226C1, 0xB8832080, 0x0E612C02, 0xD5102A43,
0x0F934490, 0xD4E242D1, 0x62004E53, 0xB9714812, 0xD4B55116, 0x0FC45757, 0xB9265BD5, 0x62575D94,
0x62AE69DD, 0xB9DF6F9C, 0x0F3D631E, 0xD44C655F, 0xB9887C5B, 0x62F97A1A, 0xD41B7698, 0x0F6A70D9};
private static long revCrcUpdate(long acc, long delta)
{
long t = acc >> 24;
int lookup = (int)(t & 0xFF);
acc = ((acc) << 8) ^ revCrcTable[lookup] ^ (delta);
// Keep in 32-bits
return acc & 0x00000000FFFFFFFFL;
}
protected static long crc(byte[] data)
{
long crc = 0;
for (int i = data.Length; i > 0; i -= 2)
{
crc = revCrcUpdate(crc, data[i - 2] & 0x00000000000000FFL);
crc = revCrcUpdate(crc, data[i - 1] & 0x00000000000000FFL);
}
return crc;
}
public static long fileCrc(byte[] filebuffer)
{
return crc(filebuffer);
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace GaiaDFU
{
public class GaiaDfu
{
// GAIA FRAMING PARAMS
public const byte GAIA_FRAME_START = 0xff;
public const byte GAIA_PROTOCOL_VER = 0x01;
public const byte GAIA_FLAG_CHECK = 0x01;
public const ushort GAIA_CSR_VENDOR_ID = 0x000a;
public const ushort GAIA_WEARHAUS_VENDOR_ID = 0x0a4c;
public const byte GAIA_FRAME_LEN = 8;
private const byte CHUNK_SIZE = 240;
private byte[] FileBuffer;
private int FileChunksSent;
private ushort LastSentCommand;
public bool IsSendingFile;
public int TotalChunks;
public GaiaDfu()
{
FileBuffer = null;
FileChunksSent = 0;
LastSentCommand = 0x0000;
IsSendingFile = false;
}
public static byte Checksum(byte[] b)
{
byte checkSum = b[0];
for (int i = 1; i < b.Length; i++)
{
checkSum ^= b[i];
}
return checkSum;
}
public void SetFileBuffer(byte[] buf)
{
FileBuffer = buf;
TotalChunks = (int)Math.Ceiling((float)buf.Length / CHUNK_SIZE);
}
public int ChunksRemaining()
{
return (int)Math.Ceiling((float)FileBuffer.Length / CHUNK_SIZE) - FileChunksSent;
}
public int BytesRemaining()
{
return (int)FileBuffer.Length - (FileChunksSent * CHUNK_SIZE);
}
public byte[] GetNextFileChunk()
{
byte[] fileChunk;
if (ChunksRemaining() == 1)
{
int bytesToWrite = BytesRemaining();
fileChunk = new byte[bytesToWrite];
System.Buffer.BlockCopy(FileBuffer, FileChunksSent * CHUNK_SIZE, fileChunk, 0, bytesToWrite);
}
else
{
fileChunk = new byte[CHUNK_SIZE];
System.Buffer.BlockCopy(FileBuffer, FileChunksSent * CHUNK_SIZE, fileChunk, 0, CHUNK_SIZE);
}
FileChunksSent++;
return fileChunk;
}
public byte[] CreateGaiaCommand(ushort usrCmd, bool isAck = false)
{
return CreateGaiaCommand(usrCmd, GAIA_FLAG_CHECK, new byte[0], isAck);
}
public byte[] CreateGaiaCommand(ushort usrCmd, byte[] payload, bool isAck = false)
{
return CreateGaiaCommand(usrCmd, GAIA_FLAG_CHECK, payload, isAck);
}
public byte[] CreateGaiaCommand(ushort usrCmd, byte flag, bool isAck = false)
{
return CreateGaiaCommand(usrCmd, flag, new byte[0], isAck);
}
public byte[] CreateGaiaCommand(ushort usrCmd, byte flag, byte[] payload, bool isAck = false)
{
byte[] commandMessage;
int msgLen = GAIA_FRAME_LEN + payload.Length;
if (flag == GAIA_FLAG_CHECK) { msgLen += 1; }
commandMessage = new byte[msgLen];
commandMessage[0] = GAIA_FRAME_START;
commandMessage[1] = GAIA_PROTOCOL_VER;
commandMessage[2] = flag;
commandMessage[3] = (byte)payload.Length;
commandMessage[4] = GAIA_CSR_VENDOR_ID >> 8;
commandMessage[5] = GAIA_CSR_VENDOR_ID & 0xff;
commandMessage[6] = (byte)(usrCmd >> 8);
commandMessage[7] = (byte)(usrCmd & 0xff);
if (Enum.IsDefined(typeof(ArcCommand), usrCmd))
{
commandMessage[4] = GAIA_WEARHAUS_VENDOR_ID >> 8;
commandMessage[5] = GAIA_WEARHAUS_VENDOR_ID & 0xff;
}
System.Buffer.BlockCopy(payload, 0, commandMessage, 8, payload.Length);
if (flag == GAIA_FLAG_CHECK)
{
commandMessage[msgLen - 1] = Checksum(commandMessage);
}
if (!isAck)
{
LastSentCommand = usrCmd;
}
return commandMessage;
}
public byte[] CreateAck(ushort usrCmd)
{
byte[] ackPayload = { 0x00 };
return CreateGaiaCommand((ushort)(usrCmd | 0x8000), ackPayload, isAck: true);
}
private byte[] CreateDFUBegin()
{
if (FileBuffer == null)
{
System.Diagnostics.Debug.WriteLine("Did not specify a DFU File! Please Pick a File!");
return null;
}
// Get CRC first from File
uint fileSize = (uint)FileBuffer.Length;
byte[] crcBuffer = new byte[fileSize + 4];
System.Buffer.BlockCopy(FileBuffer, 0, crcBuffer, 4, (int)fileSize);
crcBuffer[0] = crcBuffer[1] = crcBuffer[2] = crcBuffer[3] = (byte)0xff;
long crc = DfuCRC.fileCrc(crcBuffer);
// Send DfuBegin with CRC and fileSize
uint mCrc = (uint)(((crc & 0xFFFFL) << 16) | ((crc & 0xFFFF0000L) >> 16));
byte[] beginPayload = new byte[8];
beginPayload[0] = (byte)(fileSize >> 24);
beginPayload[1] = (byte)(fileSize >> 16);
beginPayload[2] = (byte)(fileSize >> 8);
beginPayload[3] = (byte)(fileSize);
beginPayload[4] = (byte)(mCrc >> 24);
beginPayload[5] = (byte)(mCrc >> 16);
beginPayload[6] = (byte)(mCrc >> 8);
beginPayload[7] = (byte)(mCrc);
return CreateGaiaCommand((ushort)GaiaCommand.DFUBegin, beginPayload);
}
public static ushort CombineBytes(byte upper, byte lower)
{
return ((ushort)((((ushort)upper) << 8) | ((ushort)lower)));
}
public byte[] CreateResponseToMessage(byte[] receivedFrame, byte[] receivedPayload, byte checkSum = 0x00)
{
// Check if the Response is a command or an ACK
byte commandUpperByte = receivedFrame[6];
ushort command = CombineBytes(receivedFrame[6], receivedFrame[7]);
byte[] resp = null;
if (commandUpperByte >> 4 == ((LastSentCommand >> 12) | 0x8)) // ACK is always the command id (16 bits) masked with 0x8000 so upper byte must start with 0x8_
{
switch (command)
{
case (ushort)GaiaDfu.ArcCommand.StartDfu | 0x8000:
resp = CreateDFUBegin();
break;
default:
break;
}
}
else // otherwise, this is an actual command! We must respond to it
{
switch (command)
{
case (ushort)GaiaDfu.GaiaNotification.Event:
if (receivedPayload[0] == 0x10 && receivedPayload[1] == 0x00)
{
// WE NEED TO LOOP SENDING CHUNKS
// Sending Logic in MainWindow.xaml.cs
IsSendingFile = true;
}
break;
case (ushort)GaiaDfu.GaiaCommand.DFURequest:
resp = CreateAck(command);
break;
default:
resp = CreateAck(command);
break;
}
}
return resp;
}
public enum GaiaCommand : ushort
{
GetAppVersion = 0x0304,
GetRssi = 0x0301,
SetLED = 0x0101,
GetLED = 0x0181,
SetTone = 0x0102,
GetTone = 0x0182,
SetDefaultVolume = 0x0103,
GetDefaultVolume = 0x0183,
ChangeVolume = 0x0201,
ToggleBassBoost = 0x0218,
Toggle3DEnhancement = 0x0219,
SetLEDControl = 0x0207,
GetLEDControl = 0x0287,
DeviceReset = 0x0202,
PowerOff = 0x0204,
GetBattery = 0x0302,
GetModuleID = 0x0303,
DFURequest = 0x0630,
DFUBegin = 0x0631,
NoOp = 0x0700
}
public enum GaiaNotification : ushort
{
Register = 0x4001,
Get = 0x4081,
Cancel = 0x4002,
Event = 0x4003
}
public enum ArcCommand : ushort
{
GetColor = 0x6743,
SetColor = 0x7343,
GetHeadphoneID = 0x6749,
GetHeadphoneState = 0x6753,
GetBattery = 0x6742,
SetPulse = 0x7350,
GetPulse = 0x6750,
SetTouch = 0x7347,
GetTouch = 0x6747,
VolumeUp = 0x7655,
VolumeDown = 0x7644,
StartDfu = 0x6346,
StartScan = 0x6353,
StartBroadcast = 0x6342,
JoinStation = 0x634C,
GoIdle = 0x6349,
TurnOnMultipoint = 0x634D,
JoinNearestStation = 0x634E
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.IO;
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 System.Net.Sockets;
using GaiaDFU;
using InTheHand;
using InTheHand.Net;
using InTheHand.Net.Bluetooth;
using InTheHand.Net.Sockets;
using InTheHand.Net.Ports;
namespace DesktopDfu
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
Guid GaiaServiceID;
BluetoothClient BluetoothClient;
BluetoothDeviceInfo[] Devices;
BluetoothDeviceInfo ArcDev;
NetworkStream BluetoothStream;
GaiaDfu DFUHandler;
public MainWindow()
{
InitializeComponent();
GaiaServiceID = new Guid("00001107-D102-11E1-9B23-00025B00A5A5");
ArcDev = null;
BluetoothStream = null;
DFUHandler = new GaiaDfu();
}
private async void RunButton_Click(object sender, RoutedEventArgs e)
{
BluetoothClient = new BluetoothClient();
Devices = BluetoothClient.DiscoverDevices();
for (var i = 0; i < Devices.Length; i++)
{
Console.WriteLine(Devices[i].DeviceName);
if (Devices[i].DeviceName == "Wearhaus Arc Devboard 1")
{
Console.WriteLine("Found Wearhaus!");
}
ListBoxItem itm = new ListBoxItem();
itm.Content = Devices[i].DeviceName;
ServiceList.Items.Add(itm);
}
ServiceSelector.Visibility = System.Windows.Visibility.Visible;
}
private async void ServiceList_Tapped(object sender, MouseButtonEventArgs e)
{
try
{
RunButton.IsEnabled = false;
ServiceSelector.Visibility = System.Windows.Visibility.Collapsed;
ArcDev = Devices[ServiceList.SelectedIndex];
if (ArcDev != null)
{
var ep = new BluetoothEndPoint(ArcDev.DeviceAddress, GaiaServiceID);
if (BluetoothClient.Connected == false)
{
lock (this)
{
BluetoothClient.Connect(ep);
BluetoothStream = BluetoothClient.GetStream();
}
}
if (BluetoothClient.Connected && BluetoothStream != null)
{
Console.WriteLine("Connected!");
ChatBox.Visibility = System.Windows.Visibility.Visible;
ReceiveStringLoop(BluetoothStream);
}
}
else
{
Console.WriteLine("No Wearhaus Found! Exiting!");
}
}
catch (Exception ex)
{
ServiceList.Items.Clear();
ConversationList.Items.Clear();
RunButton.IsEnabled = true;
}
}
private void Disconnect()
{
try
{
if (BluetoothStream != null)
{
System.Diagnostics.Debug.WriteLine("DISCONNECTING AND CLOSING THE STREAM!");
BluetoothStream.Dispose();
BluetoothStream = null;
}
if (BluetoothClient != null)
{
System.Diagnostics.Debug.WriteLine("DISCONNECTING BLUETOOTH CLIENT!");
BluetoothClient.Dispose();
BluetoothClient = null;
}
RunButton.IsEnabled = true;
ServiceSelector.Visibility = System.Windows.Visibility.Collapsed;
ChatBox.Visibility = System.Windows.Visibility.Collapsed;
ServiceList.Items.Clear();
ConversationList.Items.Clear();
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error on Disconnect: " + ex.HResult.ToString() + " - " + ex.Message);
}
}
private async void DisconnectButton_Click(object sender, RoutedEventArgs e)
{
Disconnect();
}
private async void PickFileButton_Click(object sender, RoutedEventArgs e)
{
System.Diagnostics.Debug.WriteLine("TRYING TO PICK A FILE!!");
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
dlg.DefaultExt = ".dfu";
var result = dlg.ShowDialog();
if (result == true)
{
byte[] fileBuffer = File.ReadAllBytes(dlg.FileName);
DFUHandler.SetFileBuffer(fileBuffer);
System.Diagnostics.Debug.WriteLine("Picked File: " + dlg.FileName);
}
}
private async void SendDFUButton_Click(object sender, RoutedEventArgs e)
{
//if (DfuHandler.DfuFileName == null)
//{
// System.Diagnostics.Debug.WriteLine("No DFU File Picked. Please Pick a DFU File!");
// return;
//}
// Send DFU!
SendRawBytes(DFUHandler.CreateGaiaCommand((ushort)GaiaDfu.ArcCommand.StartDfu));
}
private async void SendButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (MessageTextBox.Text == "") { return; }
ushort usrCmd = Convert.ToUInt16(MessageTextBox.Text, 16);
byte[] msg = DFUHandler.CreateGaiaCommand(usrCmd);
SendRawBytes(msg);
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine("Error: " + ex.HResult.ToString() + " - " + ex.Message);
}
}
private async void SendRawBytes(byte[] msg, bool print = true)
{
BluetoothStream.Write(msg, 0, msg.Length);
string sendStr = BitConverter.ToString(msg);
if (print)
{
ConversationList.Items.Add("Sent: " + sendStr);
}
MessageTextBox.Text = "";
}
private async void ReceiveStringLoop(NetworkStream netSocket)
{
try
{
byte frameLen = GaiaDfu.GAIA_FRAME_LEN;
string receivedStr = "";
byte[] receivedFrame = new byte[frameLen];
// Frame is always FRAME_LEN long at least, so load that many bytes and process the frame
int size = await netSocket.ReadAsync(receivedFrame, 0, frameLen);
// Buffer / Stream is closed
if (size < frameLen)
{
Console.WriteLine("Disconnected from Stream!");
return;
}
receivedStr += BitConverter.ToString(receivedFrame);
byte payloadLen = receivedFrame[3];
byte[] payload = new byte[payloadLen];
if (payloadLen > 0)
{
int receivedPayloadLen = await netSocket.ReadAsync(payload, 0, payloadLen);
receivedStr += " Payload: " + BitConverter.ToString(payload);
}
byte[] resp;
// If we get 0x01 in the Flags, we received a CRC (also we should check it probably)
if (receivedFrame[2] == GaiaDfu.GAIA_FLAG_CHECK)
{
byte checksum = (byte)netSocket.ReadByte();
receivedStr += " CRC: " + checksum.ToString("X2");
// Now we should have all the bytes, lets process the whole thing!
resp = DFUHandler.CreateResponseToMessage(receivedFrame, payload, checksum);
}
else
{
// Now we should have all the bytes, lets process the whole thing!
resp = DFUHandler.CreateResponseToMessage(receivedFrame, payload);
}
ConversationList.Items.Add("Received: " + receivedStr);
if (DFUHandler.IsSendingFile)
{
ConversationList.Items.Add("Receieved Go Ahead for DFU! Starting DFU now!");
int chunksRemaining = DFUHandler.ChunksRemaining();
ConversationList.Items.Add("DFU Progress | Chunks Remaining: " + chunksRemaining);
while (chunksRemaining > 0)
{
byte[] msg = DFUHandler.GetNextFileChunk();
await netSocket.WriteAsync(msg, 0, msg.Length);
if (chunksRemaining % 1000 == 0)
{
ConversationList.Items.Add("DFU Progress | Chunks Remaining: " + chunksRemaining);
}
System.Diagnostics.Debug.WriteLine("Chunks Remaining: " + chunksRemaining);
SendRawBytes(DFUHandler.GetNextFileChunk(), false);
chunksRemaining = DFUHandler.ChunksRemaining();
}
ConversationList.Items.Add("Finished Sending DFU! Verifying...");
DFUHandler.IsSendingFile = false;
}
if(resp != null) SendRawBytes(resp);
ReceiveStringLoop(netSocket);
}
catch (Exception ex)
{
lock (this)
{
if (netSocket == null)
{
// Do not print anything here - the user closed the socket.
}
else
{
Console.WriteLine("Read stream failed with error: " + ex.Message);
Disconnect();
}
}
}
}
}
}
|
77b277e57107a0e889298f72310f90cbdb3c761c
|
[
"Markdown",
"C#"
] | 4
|
Markdown
|
wearhaus/WindowsApp
|
8763bec57b38e7fbe5d5095a1aaa744b1098a493
|
8476eaaa4b6a4b184c34d224423fee674b8ed89b
|
refs/heads/master
|
<file_sep>import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import TextField from "@material-ui/core/TextField";
import SendIcon from '@material-ui/icons/Send';
import ChatBubbleOutlineIcon from '@material-ui/icons/ChatBubbleOutline';
import PhoneInTalkIcon from '@material-ui/icons/PhoneInTalk';
import Peer from 'peerjs';
import "../App.css";
const useStyles = makeStyles((theme) => ({
root: {
flexGrow: 1,
},
paper: {
padding: theme.spacing(2),
textAlign: 'center',
color: theme.palette.text.secondary,
},
}));
let peer;
let connection;
const start = (localId, remoteId) => {
peer = new Peer(localId, {
host: 'localhost',
port: 3000,
path: '/mypeer'
});
peer.on('open', function(localId) {
console.log('My peer ID is: ' + localId);
});
connection = peer.connect(remoteId);
peer.on('connection', function(connection) {
connection.on('data', function(data) {
console.log('Received', data);
let chat = document.getElementById("chat");
chat.value = [chat.value + "\n" + data + "\n"];
});
});
}
function DataChat() {
//State
const [localId, setLocalId] = React.useState(0);
const [remoteId, setRemoteId] = React.useState(0);
const [message, setMessage] = React.useState(0);
const [messages, setMessages] = React.useState("");
//Logic
const initStart = () => {
console.log("start ", localId, remoteId);
start(localId, remoteId);
};
//Send avec ajout d'en-tête
const send = () => {
connection.send(localId + ": " + message + "\n");
setMessages([...messages, localId + ": " + message]);
let chat = document.getElementById("chat");
chat.value = [chat.value + "\n" + localId + ": " + message + "\n"];
}
const classes = useStyles();
return (
<div className={classes.root} id="App">
<Grid container spacing={3}>
<Grid item xs={4}>
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Local id" onChange={(event) => setLocalId(event.target.value)} /> <br/>
<Button onClick={initStart}>Start <ChatBubbleOutlineIcon fontSize="small"/> </Button>
</form>
</Grid>
<Grid item xs={4}>
<form className={classes.root} noValidate autoComplete="off">
<TextField id="standard-basic" label="Remote chat id" onChange={(event) => setRemoteId(event.target.value)} /> <br/>
<Button>Call <PhoneInTalkIcon/> </Button>
</form>
</Grid>
{/* <Grid item xs={3}>
<Button>Hang up</Button>
</Grid> */}
<Grid item xs={4}>
<TextField id="standard-basic" label="Message" onChange={(event) => setMessage(event.target.value)} /> <br/>
<Button onClick={send}>Send <SendIcon/> </Button>
</Grid>
<Grid item xs={12}>
<h3> Chat : </h3>
<textarea id={"chat"} rows={32} readOnly/>
</Grid>
</Grid>
</div>
)
}
export default DataChat<file_sep># TP3-Multi-Lyon
# Scripts
## Build
> *npm run build*
Ce script exécute le build du projet en mode "production", via la commande > *webpack --mode production*
## Dev
> *npm run dev*
Ce script exécute le build du projet en mode "dev", via la commande > *webpack --mode development && node server/index.js"*
# Déploiement sur Heroku
## Création du repo Heroku
> *heroku create*
Cette commande permet de créer un nouveau projet heroku
## Déploiement
> *git push heroku master*
Cette commande permet de déployer notre projet nommé "Heroku" sur heroku.
# Additional notes<file_sep>import {Component } from "react";
import * as React from "react";
import LOGO from '/logo/logo.png';
export default class Content extends Component {
constructor(props){
super(props);
}
render(){
return(
<div id="container">
<img src={LOGO} alt="Logo" />
</div>
);
}
}
|
fc02b7746b3d8c2e9f193a6036aea56cd5d4670e
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
Justsecret123/TP3-Multi-Lyon
|
9535b96717612fb4fa1d2cdd60396e65a4cec69a
|
a6024f4c5bcbfccc0838dd7d2c647aac83c3e4f1
|
refs/heads/master
|
<repo_name>lufe089/rubySample<file_sep>/README.rdoc
== README
Ejemplo de aplicación Ruby usando Scaffolding
Prueba de versiones
<file_sep>/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file.
ProyectoRailsLuisa::Application.config.session_store :cookie_store, key: '_proyectoRailsLuisa_session'
<file_sep>/app/views/cursos/index.json.jbuilder
json.array!(@cursos) do |curso|
json.extract! curso, :id, :nombreCurso, :nombreDocente, :fechaCreacionCurso
json.url curso_url(curso, format: :json)
end
|
a24d54687ba7eb45f777b13f595bed852aea9806
|
[
"RDoc",
"Ruby"
] | 3
|
RDoc
|
lufe089/rubySample
|
164910a10a1ca5da0b7fe3d2ef7203f30e357817
|
1490b6f1ea3db74641a55bc985b73aae9e9a653e
|
refs/heads/main
|
<repo_name>G-Lan/CS4156TeamProject<file_sep>/src/test/java/InfluencerProfileTest.java
import static org.junit.Assert.assertEquals;
public class InfluencerProfileTest {
/* //@Test
public void getInfluencerProfile() throws GeneralSecurityException, IOException {
InfluencerBoardResource resource = new InfluencerBoardResource(userProfileDAO);
InfluencerProfileView view = resource.getInfluencerForUser("UCw8ZhLPdQ0u_Y-TLKd61hGA");
InfluencerProfile profile = view.getInfluencerProfile();
assertEquals(profile.getChannelId(), "UCw8ZhLPdQ0u_Y-TLKd61hGA");
assertEquals(profile.getChannelName(), "1MILLION Dance Studio");
assertEquals(profile.getCountryCode(), "KR");
YoutubeAPI api = new YoutubeAPI("UC_x5XG1OV2P6uZZ5FSM9Ttw");
api.getVideoID();
}*/
}
<file_sep>/src/test/java/GetChannelAnalyticsTaskTest.java
import models.InfluencerProfile;
import org.junit.Test;
import tasks.GetChannelAnalyticsTask;
import java.io.IOException;
import java.util.ArrayList;
import static org.junit.Assert.assertEquals;
public class GetChannelAnalyticsTaskTest {
@Test
public void getInfluencersTestA() throws IOException {
String projDir = System.getProperty("user.dir");
GetChannelAnalyticsTask task = new GetChannelAnalyticsTask(projDir+"/channelAnalytics.csv");
ArrayList<InfluencerProfile> influencers = task.getInfluencers(-1);
assertEquals(influencers.size(), 0);
}
@Test
public void getInfluencersTestB() throws IOException {
String projDir = System.getProperty("user.dir");
GetChannelAnalyticsTask task = new GetChannelAnalyticsTask(projDir+"/channelAnalytics.csv");
ArrayList<InfluencerProfile> influencers = task.getInfluencers(6);
assertEquals(influencers.size(), 6);
influencers = task.getInfluencers(0);
assertEquals(influencers.size(), 0);
}
@Test
public void getInfluencersTestC() throws IOException {
String projDir = System.getProperty("user.dir");
GetChannelAnalyticsTask task = new GetChannelAnalyticsTask(projDir+"/channelAnalytics.csv");
ArrayList<InfluencerProfile> influencers = task.getInfluencers(0);
assertEquals(influencers.size(), 0);
}
}
<file_sep>/src/main/java/db/UserProfileDAO.java
package db;
import io.dropwizard.hibernate.AbstractDAO;
import models.UserProfile;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import java.util.List;
public class UserProfileDAO extends AbstractDAO<UserProfile> {
public UserProfileDAO(SessionFactory sessionFactory) {
super(sessionFactory);
}
/**
* create a user profile entry in db
*
* @param profile
* @return an UserProfile object being added to db
*/
public UserProfile createUser(UserProfile profile) {
if (profile.getEmail() == null || profile.getName() == null) {
return null;
}
return persist(profile);
}
public List<UserProfile> getAllUsers() {
return list((Query<UserProfile>) namedQuery("getAllUsers"));
}
public List<UserProfile> getUserProfile(String email) {
return list((Query<UserProfile>) namedQuery("getUserProfile")
.setParameter("userEmail", email));
}
public int deleteUserProfile(String email) {
Query query = namedQuery("deleteUserProfile").
setParameter("userEmail", email);
return query.executeUpdate();
}
public int updateUserProfile(String email, String newInterests) {
Query query = namedQuery("updateUserProfile")
.setParameter("userEmail", email)
.setParameter("interestsString", newInterests);
return query.executeUpdate();
}
}
<file_sep>/src/main/java/db/CommentRecordDAO.java
package db;
import io.dropwizard.hibernate.AbstractDAO;
import models.CommentRecord;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import java.util.List;
public class CommentRecordDAO extends AbstractDAO<CommentRecord> {
public CommentRecordDAO(SessionFactory factory) {
super(factory);
}
public CommentRecord create(CommentRecord record) {
return persist(record);
}
public List<CommentRecord> getComments( String channelId) {
return list((Query<CommentRecord>) namedQuery("getComments")
.setParameter("channelId", channelId));
}
}
<file_sep>/src/main/java/tasks/GetChannelAnalyticsTask.java
package tasks;
import models.InfluencerProfile;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
public class GetChannelAnalyticsTask {
private final String srcFile;
/**
* Constructor.
*
* @param srcFile
* the source file
*/
public GetChannelAnalyticsTask(String srcFile) {
this.srcFile = srcFile;
}
/**
* Get an array of influencers.
* @param num an int number
* @return ArrayList<> influencers
*/
public ArrayList<InfluencerProfile> getInfluencers(int num) throws IOException {
ArrayList<InfluencerProfile> influencers = new ArrayList<>();
if (num < 0) {
return influencers;
}
try {
InputStream inputStream = new FileInputStream(srcFile);
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
int i = 0;
while (i <= num) {
i += 1;
line = br.readLine();
if (line != null) {
String[] values = line.split("\t");
String channelId = values[0];
String channelName = values[1];
String type = "YouTube";
String countryCode = values[3];
String numOfSubscribers = values[7];
String averagePostViews = values[6];
String[] preTags = values[2].substring(1, values[2].length() - 1).split(",");
ArrayList<String> tags = new ArrayList<>();
for (String tag : preTags) {
tag = tag.replaceAll("[ ']", "");
tags.add(tag);
}
String photoLink = values[8];
InfluencerProfile influencer = new InfluencerProfile(channelId, channelName, type, countryCode, numOfSubscribers, averagePostViews, tags, photoLink);
influencers.add(influencer);
} else {
break;
}
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
influencers.remove(0);
return influencers;
}
}
<file_sep>/src/test/java/LikeRecordDAOTest.java
import db.LikeRecordDAO;
import io.dropwizard.testing.junit5.DAOTestExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import models.LikeRecord;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(DropwizardExtensionsSupport.class)
public class LikeRecordDAOTest {
public DAOTestExtension daoTestRule = DAOTestExtension.newBuilder()
.addEntityClass(LikeRecord.class)
.build();
private LikeRecordDAO likeRecordDAO;
@BeforeEach
public void setUp() throws Exception {
likeRecordDAO = new LikeRecordDAO(daoTestRule.getSessionFactory());
}
@Test
public void createLikeRecordTestA() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
assertThat(record1.getChannelID()).isEqualTo(channelId1);
assertThat(record1.getEmail()).isEqualTo(email1);
assertThat(likeRecordDAO.findAll("<EMAIL>").size()).isEqualTo(1);
final LikeRecord record12 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
assertThat(likeRecordDAO.findAll("<EMAIL>").size()).isEqualTo(1);
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
assertThat(likeRecordDAO.findAll("<EMAIL>").size()).isEqualTo(2);
}
@Test
public void createLikeRecordTestB() throws Exception {
String email = "<EMAIL>";
String channelId = "1";
final LikeRecord record = daoTestRule.inTransaction(() -> likeRecordDAO.create(new LikeRecord(email, channelId)));
assertThat(record.getChannelID()).isEqualTo(channelId);
assertThat(record.getEmail()).isEqualTo(email);
assertThat(likeRecordDAO.findAll("<EMAIL>").size()).isEqualTo(1);
}
@Test
public void findAllTestA() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
List<LikeRecord> list1 = daoTestRule.inTransaction(() -> likeRecordDAO.findAll(null));
assertThat(list1.size()).isEqualTo(0);
}
@Test
public void findAllTestB() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
List<LikeRecord> list1 = daoTestRule.inTransaction(() -> likeRecordDAO.findAll("<EMAIL>"));
assertThat(list1.size()).isEqualTo(0);
}
@Test
public void findAllTestC() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
List<LikeRecord> list1 = daoTestRule.inTransaction(() -> likeRecordDAO.findAll(email1));
assertThat(list1.size()).isEqualTo(2);
}
@Test
public void deleteRecordTestA() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(2);
int itemDeleted = daoTestRule.inTransaction(() -> likeRecordDAO.deleteRecord(null, channelId1));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(2);
assertThat(itemDeleted).isEqualTo(0);
}
@Test
public void deleteRecordTestB() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(2);
int itemDeleted = daoTestRule.inTransaction(() -> likeRecordDAO.deleteRecord(email1, "3"));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(2);
assertThat(itemDeleted).isEqualTo(0);
}
@Test
public void deleteRecordTestC() {
String email1 = "<EMAIL>";
String channelId1 = "1";
LikeRecord record1 = new LikeRecord(email1, channelId1);
String email2 = "<EMAIL>";
String channelId2 = "2";
LikeRecord record2 = new LikeRecord(email2, channelId2);
final LikeRecord record11 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record1));
final LikeRecord record22 = daoTestRule.inTransaction(() -> likeRecordDAO.create(record2));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(2);
int itemDeleted = daoTestRule.inTransaction(() -> likeRecordDAO.deleteRecord(email1, channelId1));
assertThat(likeRecordDAO.findAll(email1).size()).isEqualTo(1);
assertThat(itemDeleted).isEqualTo(1);
}
}
<file_sep>/spotbugs-result-InfluencerBoard[InfluencerBoard]_2020_11_15_20_12_03.html
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>SpotBugs Report</title>
<style type="text/css">
.tablerow0 {
background: #EEEEEE;
}
.tablerow1 {
background: white;
}
.detailrow0 {
background: #EEEEEE;
}
.detailrow1 {
background: white;
}
.tableheader {
background: #b9b9fe;
font-size: larger;
}
</style>
</head>
<body>
<h1>SpotBugs Report</h1>
<p>Produced using <a href="https://spotbugs.github.io">SpotBugs</a>4.1.3.</p>
<p>Project:
InfluencerBoard[InfluencerBoard]</p>
<h2>Metrics</h2>
<p>202 lines of code analyzed,
in 11 classes,
in 5 packages.</p>
<table width="500" cellpadding="5" cellspacing="2">
<tr class="tableheader">
<th align="left">Metric</th>
<th align="right">Total</th>
<th align="right">Density*</th>
</tr>
<tr class="tablerow0">
<td>High Priority Warnings</td>
<td align="right">2</td>
<td align="right">9.90</td>
</tr>
<tr class="tablerow1">
<td>Medium Priority Warnings</td>
<td align="right">1</td>
<td align="right">4.95</td>
</tr>
<tr class="$totalClass">
<td>
<b>Total Warnings</b>
</td>
<td align="right">
<b>3</b>
</td>
<td align="right">
<b>14.85</b>
</td>
</tr>
</table>
<p>
<i>(* Defects per Thousand lines of non-commenting source statements)</i>
</p>
<p>
<br/>
<br/>
</p>
<h2>Summary</h2>
<table width="500" cellpadding="5" cellspacing="2">
<tr class="tableheader">
<th align="left">Warning Type</th>
<th align="right">Number</th>
</tr>
<tr class="tablerow0">
<td>
<a href="#Warnings_I18N">Internationalization Warnings</a>
</td>
<td align="right">1</td>
</tr>
<tr class="tablerow1">
<td>
<a href="#Warnings_STYLE">Dodgy code Warnings</a>
</td>
<td align="right">2</td>
</tr>
<tr class="tablerow0">
<td>
<b>Total</b>
</td>
<td align="right">
<b>3</b>
</td>
</tr>
</table>
<p>
<br/>
<br/>
</p>
<h1>Warnings</h1>
<p>Click on each warning link to see a full description of the issue, and
details of how to resolve it.</p>
<h2>
<a name="Warnings_I18N">Internationalization Warnings</a>
</h2>
<table class="warningtable"
width="100%"
cellspacing="2"
cellpadding="5">
<tr class="tableheader">
<th align="left">Warning</th>
<th align="left">Priority</th>
<th align="left">Details</th>
</tr>
<tr class="tablerow1">
<td width="20%" valign="top">
<a href="#DM_DEFAULT_ENCODING">Reliance on default encoding</a>
</td>
<td width="10%" valign="top">High</td>
<td width="70%">
<p>Found reliance on default encoding in tasks.GetChannelAnalyticsTask.getInfluencers(int): new java.io.FileReader(String)<br/>
<br/>
<br/>In file GetChannelAnalyticsTask.java GetChannelAnalyticsTask.java,
line 22 22<br/>In class tasks.GetChannelAnalyticsTask<br/>In method tasks.GetChannelAnalyticsTask.getInfluencers(int)<br/>Called method new java.io.FileReader(String)<br/>At GetChannelAnalyticsTask.java:[line 22]<br/>At GetChannelAnalyticsTask.java:[line 22]</p>
</td>
</tr>
</table>
<p>
<br/>
<br/>
</p>
<h2>
<a name="Warnings_STYLE">Dodgy code Warnings</a>
</h2>
<table class="warningtable"
width="100%"
cellspacing="2"
cellpadding="5">
<tr class="tableheader">
<th align="left">Warning</th>
<th align="left">Priority</th>
<th align="left">Details</th>
</tr>
<tr class="tablerow1">
<td width="20%" valign="top">
<a href="#DLS_DEAD_LOCAL_STORE">Dead store to local variable</a>
</td>
<td width="10%" valign="top">High</td>
<td width="70%">
<p>Dead store to tags in resources.InfluencerBoardResource.getInfluencerForUser(String)<br/>
<br/>
<br/>In file InfluencerBoardResource.java InfluencerBoardResource.java,
line 44 44<br/>In class resources.InfluencerBoardResource<br/>In method resources.InfluencerBoardResource.getInfluencerForUser(String)<br/>Local variable named tags<br/>At InfluencerBoardResource.java:[line 44]<br/>At InfluencerBoardResource.java:[line 44]</p>
</td>
</tr>
<tr class="tablerow0">
<td width="20%" valign="top">
<a href="#NP_DEREFERENCE_OF_READLINE_VALUE">Dereference of the result of readLine() without nullcheck</a>
</td>
<td width="10%" valign="top">Medium</td>
<td width="70%">
<p>Dereference of the result of readLine() without nullcheck in tasks.GetChannelAnalyticsTask.getInfluencers(int)<br/>
<br/>
<br/>In file GetChannelAnalyticsTask.java GetChannelAnalyticsTask.java,
line 28 28<br/>In class tasks.GetChannelAnalyticsTask<br/>In method tasks.GetChannelAnalyticsTask.getInfluencers(int)<br/>Value loaded from line<br/>At GetChannelAnalyticsTask.java:[line 28]<br/>At GetChannelAnalyticsTask.java:[line 28]</p>
</td>
</tr>
</table>
<p>
<br/>
<br/>
</p>
<p>
<br/>
<br/>
</p>
<h1>
<a name="Details">Warning Types</a>
</h1>
<h2>
<a name="DLS_DEAD_LOCAL_STORE">Dead store to local variable</a>
</h2>
<p>
This instruction assigns a value to a local variable,
but the value is not read or used in any subsequent instruction.
Often, this indicates an error, because the value computed is never
used.
</p>
<p>
Note that Sun's javac compiler often generates dead stores for
final local variables. Because SpotBugs is a bytecode-based tool,
there is no easy way to eliminate these false positives.
</p>
<p>
<br/>
<br/>
</p>
<h2>
<a name="DM_DEFAULT_ENCODING">Reliance on default encoding</a>
</h2>
<p> Found a call to a method which will perform a byte to String (or String to byte) conversion, and will assume that the default platform encoding is suitable. This will cause the application behaviour to vary between platforms. Use an alternative API and specify a charset name or Charset object explicitly. </p>
<p>
<br/>
<br/>
</p>
<h2>
<a name="NP_DEREFERENCE_OF_READLINE_VALUE">Dereference of the result of readLine() without nullcheck</a>
</h2>
<p> The result of invoking readLine() is dereferenced without checking to see if the result is null. If there are no more lines of text
to read, readLine() will return null and dereferencing that will generate a null pointer exception.
</p>
<p>
<br/>
<br/>
</p>
</body>
</html>
<file_sep>/src/test/java/UserProfileDAOTest.java
import db.UserProfileDAO;
import io.dropwizard.testing.junit5.DAOTestExtension;
import io.dropwizard.testing.junit5.DropwizardExtensionsSupport;
import models.InfluencerProfile;
import models.UserProfile;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtendWith;
import java.util.ArrayList;
import static org.assertj.core.api.Assertions.assertThat;
@ExtendWith(DropwizardExtensionsSupport.class)
public class UserProfileDAOTest {
public DAOTestExtension daoTestRule = DAOTestExtension.newBuilder()
.addEntityClass(UserProfile.class)
.build();
private UserProfileDAO userProfileDAO;
@BeforeEach
public void setUp() throws Exception {
userProfileDAO = new UserProfileDAO(daoTestRule.getSessionFactory());
}
@Test
public void createUserTestA() {
UserProfile record1 = new UserProfile(null, "<EMAIL>");
final UserProfile record11 = daoTestRule.inTransaction(() -> userProfileDAO.createUser(record1));
assertThat(userProfileDAO.getAllUsers().size()).isEqualTo(0);
assertThat(record11).isEqualTo(null);
}
@Test
public void createUserTestB() {
UserProfile record1 = new UserProfile("April", "<EMAIL>");
final UserProfile record11 = daoTestRule.inTransaction(() -> userProfileDAO.createUser(record1));
assertThat(userProfileDAO.getAllUsers().size()).isEqualTo(1);
assertThat(record11.getEmail()).isEqualTo(record1.getEmail());
assertThat(record11.getName()).isEqualTo(record1.getName());
}
@Test
public void getAllUsersTest() {
UserProfile record1 = new UserProfile("April", "<EMAIL>");
final UserProfile record11 = daoTestRule.inTransaction(() -> userProfileDAO.createUser(record1));
UserProfile record2 = new UserProfile("Sicily", "<EMAIL>");
final UserProfile record22 = daoTestRule.inTransaction(() -> userProfileDAO.createUser(record2));
assertThat(userProfileDAO.getAllUsers().size()).isEqualTo(2);
}
}
<file_sep>/popularVideosRepository.py
import os
import csv
import cv2
import requests
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from PIL import Image
from io import BytesIO
from wordcloud import WordCloud, STOPWORDS
from nltk import sent_tokenize, word_tokenize, pos_tag
from nltk.corpus import stopwords, wordnet
from nltk.tokenize import RegexpTokenizer
from googleapiclient.discovery import build
CHANNEL_ANALYTICS_FILE = 'channelAnalytics.csv'
CHANNEL_KEYWORDS_FILE = 'channelKeywords.csv'
def readFromChannelCSV():
channels = pd.read_csv(CHANNEL_ANALYTICS_FILE,sep='\t',engine='python',encoding='latin-1',
names=['channel_id','title','tags','country','default_language','videoCount','viewCount',
'subscriberCount','thumbnail'])
return channels
def kMostPopularVideos(server, channelId, videoCount, k):
popularVideos = []
k = min(k, videoCount)
request = server.search().list(part='snippet',type='video',order='viewCount',safeSearch='strict',
channelId=channelId, maxResults=k)
response = request.execute()
for item in response['items']:
popularVideos.append(item['id']['videoId'])
return popularVideos
def avgRatingAndViewCount(videos):
avg_viewCount = 0
avg_rating = 0
comment_count = []
for videoId in videos:
request = server.videos().list(part='statistics',id=videoId)
response = request.execute()
# Average View Count
avg_viewCount += int(response['items'][0]['statistics']['viewCount'])
# Average Rating
likesCount = int(response['items'][0]['statistics']['likeCount'])
dislikesCount = int(response['items'][0]['statistics']['dislikeCount'])
if likesCount == 0 and dislikesCount == 0:
avg_rating += 0
else:
avg_rating += likesCount/(likesCount + dislikesCount)
if 'commentCount' in response['items'][0]['statistics']:
commentCount = response['items'][0]['statistics']['commentCount']
else:
commentCount = 0
comment_count.append(commentCount)
avg_viewCount /= len(videos)
avg_rating /= len(videos)
return avg_viewCount, avg_rating, comment_count
def commentsWordList(videos, comment_count):
comments = []
keywords = []
tokenizer = RegexpTokenizer(r'\w+')
for i in range(len(videos)):
videoId = videos[i]
commentCount = min(1000, int(comment_count[i]))
request = server.commentThreads().list(part='snippet',videoId=videoId,order='relevance',
textFormat='plainText',maxResults=1000)
response = request.execute()
for item in response['items']:
reply = item['snippet']['topLevelComment']['snippet']['textOriginal']
comments += [word.lower() for word in tokenizer.tokenize(reply) if not word.lower() in stopwords.words('english')]
valid_tags = ['JJ', 'JJR', 'JJS', 'NN', 'NNP', 'NNS', 'RB', 'RNR', 'RNS']
for word, tag in pos_tag(comments):
if tag in valid_tags and len(word) > 1:
keywords.append(word)
print('Extracted {0} keywords in the combination of all popular reviews'.format(len(keywords)))
return keywords
def thumbnailsProcessor(channelId, thumbnail_url):
threshold = 128
response = requests.get(thumbnail_url)
img = Image.open(BytesIO(response.content))
image_name = channelId + '.png'
img.save(image_name)
img_grey = cv2.imread(image_name, cv2.IMREAD_GRAYSCALE)
img_binary = cv2.threshold(img_grey, threshold, 255, cv2.THRESH_BINARY)[1]
image_name = channelId + '_mask.png'
cv2.imwrite(image_name,img_binary)
def wordCloudGenerator(channelId, keywords):
text = " ".join(word for word in keywords)
image_name = channelId + '_mask.png'
mask = np.array(Image.open(image_name))
wordcloud = WordCloud(width = 800, height = 800,
mask=mask,contour_width=2, contour_color='black',
background_color ='white',
stopwords = set(STOPWORDS),
min_font_size = 10).generate(text)
image_name = channelId + '_wordcloud.png'
wordcloud.to_file(image_name)
def main():
if len(sys.argv) < 2:
print('Valid command : python3 popularVideosRepository.py API_KEY')
else:
API_KEY = str(sys.argv[1])
server = build('youtube', 'v3', developerKey=API_KEY)
channels = readFromChannelCSV()
k = 10
avgViewCount = []
avgRating = []
commentKeywords = []
for i in range(1, len(channels)):
channelId = channels['channel_id'][i]
videoCount = channels['videoCount'][i]
videos = kMostPopularVideos(server, channelId, int(videoCount), k)
avg_viewCount, avg_rating, comment_count = avgRatingAndViewCount(videos)
avgViewCount.append(avg_viewCount)
avgRating.append(avg_rating)
keywords = commentsWordList(videos, comment_count)
commentKeywords.append(keywords)
#thumbnail_url = channels['thumbnail'][i]
#thumbnailsProcessor(channelId, thumbnail_url)
#wordCloudGenerator(channelId, keywords)
with open(CHANNEL_ANALYTICS_FILE, mode='w') as output_file:
writer = csv.writer(output_file, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['channel_id','title','tags','country','default_language','videoCount','viewCount',
'subscriberCount','avg_viewCount','avg_Rating','thumbnail'])
for i in range(len(channels)):
writer.writerow([channels['channel_id'][i + 1], channels['title'][i + 1],
channels['tags'][i + 1],channels['country'][i + 1],
channels['default_language'][i + 1],
channels['videoCount'][i + 1], channels['viewCount'][i + 1],
channels['subscriberCount'][i + 1], avgViewCount[i], avgRating[i],
channels['thumbnail'][i + 1]])
with open(CHANNEL_KEYWORDS_FILE, mode='w') as output_file:
writer = csv.writer(output_file, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['channel_id','keywords'])
for i in range(len(titles)):
writer.writerow([channels['channel_id'][i + 1], commentKeywords[i]])
if __name__ == "__main__":
main()<file_sep>/src/main/java/views/FollowingView.java
package views;
import io.dropwizard.views.View;
import models.UserProfile;
public class FollowingView extends View {
private final UserProfile user;
public FollowingView(UserProfile user) {
super("following.ftl");
this.user = user;
}
public UserProfile getUser() { return user; }
}
<file_sep>/channelAnalyticsRepository.py
import sys
import csv
import pandas as pd
from googleapiclient.discovery import build
CHANNEL_ID_FILE = 'channelIDs.csv'
CHANNEL_ANALYTICS_FILE = 'channelAnalytics.csv'
CHANNEL_DESCRIPTION_FILE = 'channelDescriptions.csv'
titles = []
descriptions = []
thumbnails = []
countries = []
defaultLanguages = []
tags = []
videoCount = []
viewCount = []
subscriberCount = []
def readFromChannelCSV():
channels = pd.read_csv(CHANNEL_ID_FILE,sep=',',engine='python',encoding='latin-1',
names=['channel_id','subcategory','category'])
print("Loaded {0} channels of {1} topics".format(len(channels['channel_id'][1:]),
len(set(channels['subcategory'][1:]))))
return channels
def channelDataAnalytics(channels):
for i in range(1, len(channels)):
channelId = channels['channel_id'][i]
request = server.channels().list(part='snippet', id=channelId)
response = request.execute()
# Title
titles.append(response['items'][0]['snippet']['title'])
# Description
if 'description' in response['items'][0]['snippet']:
descriptions.append(response['items'][0]['snippet']['description'])
else:
descriptions.append('')
# Rhumbnails
thumbnails.append(response['items'][0]['snippet']['thumbnails']['high']['url'])
request = server.channels().list(part='brandingSettings', id=channelId)
response = request.execute()
# Country
if 'country' in response['items'][0]['brandingSettings']['channel']:
countries.append(response['items'][0]['brandingSettings']['channel']['country'])
else:
countries.append('NA')
# Default Language
if 'defaultLanguage' in response['items'][0]['brandingSettings']['channel']:
defaultLanguages.append(response['items'][0]['brandingSettings']['channel']['defaultLanguage'])
else:
defaultLanguages.append('NA')
request = server.channels().list(part='topicDetails', id=channelId)
response = request.execute()
# Tags
channel_tags = []
topicCategories = response['items'][0]['topicDetails']['topicCategories']
for category in topicCategories:
idx = category.rfind('/')
channel_tags.append(category[idx + 1:].replace('_', ' '))
tags.append(channel_tags)
request = server.channels().list(part='statistics', id=channelId)
response = request.execute()
videoCount.append(response['items'][0]['statistics']['videoCount'])
viewCount.append(response['items'][0]['statistics']['viewCount'])
if response['items'][0]['statistics']['hiddenSubscriberCount'] == False:
subscriberCount.append(response['items'][0]['statistics']['subscriberCount'])
else:
subscriberCount.append('NA')
def main():
if len(sys.argv) < 2:
print('Valid command : python3 channelAnalyticsRepository.py API_KEY')
else:
API_KEY = str(sys.argv[1])
server = build('youtube', 'v3', developerKey=API_KEY)
channels = readFromChannelCSV()
channelDataAnalytics(channels)
with open(CHANNEL_ANALYTICS_FILE, mode='w') as output_file:
writer = csv.writer(output_file, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['channel_id','title','tags','country','default_language','videoCount','viewCount',
'subscriberCount','thumbnail'])
for i in range(len(titles)):
writer.writerow([channels['channel_id'][i + 1], titles[i], tags[i], countries[i],
defaultLanguages[i],videoCount[i],viewCount[i],subscriberCount[i],thumbnails[i]])
with open(CHANNEL_DESCRIPTION_FILE, mode='w') as output_file:
writer = csv.writer(output_file, delimiter='\t', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['channel_id','description'])
for i in range(len(titles)):
writer.writerow([channels['channel_id'][i + 1], descriptions[i]])
if __name__ == "__main__":
main()<file_sep>/popularChannelsRepository.py
import sys
import csv
import pandas as pd
from googleapiclient.discovery import build
TOPIC_ID_FILE = 'topicIDs.csv'
CHANNEL_ID_FILE = 'channelIDs.csv'
def readTopicIdFromCSV():
topics = pd.read_csv(TOPIC_ID_FILE,
sep=',',
engine='python',
encoding='latin-1',
names=['topic_id', 'subcategory', 'category'])
return topics
def generateKMostPopularChannels(server, topics, k):
channel_id = []
channel_subcategory = []
channel_category = []
for i in range(1, len(topics)):
request = server.search().list(part='snippet',type='channel',order='viewCount',safeSearch='strict',
topicId=topics['topic_id'][i],maxResults=k)
response = request.execute()
for item in response['items']:
channelId = item['id']['channelId']
request = server.channels().list(part='status', id=channelId)
response = request.execute()
if 'isLinked' in response['items'][0]['status']:
isLinked = response['items'][0]['status']['isLinked']
else:
isLinked = False
if 'privacyStatus' in response['items'][0]['status'] and response['items'][0]['status']['privacyStatus'] == 'public':
isPublic = True
else:
isPublic = False
if isLinked == True and isPublic == True:
channel_id.append(channelId)
channel_subcategory.append(topics['subcategory'][i])
channel_category.append(topics['category'][i])
print("Generated at total {0} most popular channels for {1} topics".format(len(channel_id),len(topics) - 1))
return channel_id, channel_subcategory, channel_category
def printPopularChannelsRepository(channel_id, channel_subcategory, channel_category, n):
data = {'channel_id':channel_id,'subcategory':channel_subcategory,'category':channel_category}
df = pd.DataFrame(data)
df.head(n)
def main():
if len(sys.argv) < 3:
print('Valid command : python3 popularChannelsRepository.py API_KEY NUM_CHANNELS_PER_TOPIC')
else:
API_KEY = str(sys.argv[1])
k = int(sys.argv[2])
server = build('youtube', 'v3', developerKey=API_KEY)
topics = readTopicIdFromCSV()
channel_id, channel_subcategory, channel_category = generateKMostPopularChannels(server, topics, k)
with open(CHANNEL_ID_FILE, mode='w') as output_file:
writer = csv.writer(output_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
writer.writerow(['channel_id','subcategory','category'])
for i in range(len(channel_id)):
writer.writerow([channel_id[i], channel_subcategory[i], channel_category[i]])
if __name__ == "__main__":
main()<file_sep>/src/main/java/tasks/Search.java
package tasks;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.http.HttpRequest;
import com.google.api.client.http.HttpRequestInitializer;
import com.google.api.services.youtube.YouTube;
import com.google.api.services.youtube.model.*;
import models.InfluencerProfile;
import java.awt.image.AreaAveragingScaleFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Print a list of videos matching a search term.
*/
public class Search {
/**
* Define a global variable that identifies the name of a file that
* contains the developer's API key.
*/
private static final long NUMBER_OF_VIDEOS_RETURNED = 25;
/**
* Define a global instance of a Youtube object, which will be used
* to make YouTube Data API requests.
*/
private YouTube youtube;
private final String apiKey = "<KEY>";
private final String channelID;
/**
* Constructor.
*
* @param channelID
* the id of the channel
*/
public Search(String channelID) {
this.channelID = channelID;
}
public InfluencerProfile getInfluencerProfileByID() {
try {
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
YouTube.Channels.List request = youtube.channels()
.list("snippet,contentDetails,statistics");
request.setKey(apiKey);
ChannelListResponse response = request.setId(this.channelID).execute();
InfluencerProfile influencerProfile;
ArrayList<String> tags = new ArrayList<>();
if(response.getPageInfo().getTotalResults() == 0){
ArrayList<String> dummyTags = new ArrayList<>();
InfluencerProfile dummy = new InfluencerProfile("N/A", "N/A",
"N/A", "N/A", "N/A", "N/A", dummyTags,
"N/A");
return dummy;
}
Channel item = response.getItems().get(0);
ChannelSnippet snippet = item.getSnippet();
influencerProfile = new InfluencerProfile(item.getId(), snippet.getTitle(),
"No Type", snippet.getCountry(),
String.valueOf(item.getStatistics().getSubscriberCount()),
String.valueOf(item.getStatistics().getVideoCount()), tags,
String.valueOf(snippet.getThumbnails().getHigh().getUrl()),
snippet.getDescription());
return influencerProfile;
} catch (Throwable t) {
ArrayList<String> dummyTags = new ArrayList<>();
InfluencerProfile dummy = new InfluencerProfile("N/A", "N/A", "N/A", "N/A", "N/A", "N/A", dummyTags, "N/A");
return dummy;
}
}
/**
* Initialize a YouTube object to search for videos on YouTube. Then
* display the name and thumbnail image of each video in the result set.
*/
// public ArrayList<String> getVideoList() {
// // Read the developer key from the properties file.
// try {
// // This objecjat is used to make YouTube Data API requests. The last
// // argument is required, but since we don't need anything
// // initialized when the HttpRequest is initialized, we override
// // the interface and provide a no-op function.
// youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
// public void initialize(HttpRequest request) throws IOException {
// }
// }).setApplicationName("youtube-cmdline-search-sample").build();
//
// // Prompt the user to enter a query term.
//
// YouTube.Playlists.List request = youtube.playlists()
// .list("snippet,contentDetails");
// request.setKey(apiKey);
// PlaylistListResponse response = request.setChannelId(this.channelID)
// .setMaxResults(25L)
// .execute();
// String playListID = response.getItems().get(0).getId();
//
// YouTube.PlaylistItems.List requestVideos = youtube.playlistItems()
// .list("snippet,contentDetails");
// requestVideos.setKey(apiKey);
// PlaylistItemListResponse responseVideos = requestVideos.setPlaylistId(playListID)
// .execute();
// ArrayList<String> videoList = new ArrayList<>();
// List<PlaylistItem> items = responseVideos.getItems();
// for (int i = 0; i < items.size() && i < 6; ++i) {
// videoList.add(items.get(i).getSnippet().getResourceId().getVideoId());
// }
//// for(int i=0; i<videoList.size(); ++i){
//// System.out.println("video id is " + videoList.get(i));
//// }
// return videoList;
//
// } catch (GoogleJsonResponseException e) {
// System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
// + e.getDetails().getMessage());
// } catch (IOException e) {
// System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
// } catch (Throwable t) {
// t.printStackTrace();
// }
// ArrayList<String> empty = new ArrayList<>();
// return empty;
// }
// public ArrayList<String> getRandomChannelID(){
// try {
// // This objecjat is used to make YouTube Data API requests. The last
// // argument is required, but since we don't need anything
// // initialized when the HttpRequest is initialized, we override
// // the interface and provide a no-op function.
// youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
// public void initialize(HttpRequest request) throws IOException {
// }
// }).setApplicationName("youtube-cmdline-search-sample").build();
//
// // Prompt the user to enter a query term.
//
// YouTube.Search.List request = youtube.search()
// .list("snippet");
//
// request.setKey(apiKey);
// SearchListResponse response = request.setMaxResults(100L)
// .setOrder("viewCount")
// .setType("channel")
// .execute();
//
// ArrayList<String> channelID = new ArrayList<>();
// for(SearchResult item : response.getItems()){
// channelID.add(item.getId().getChannelId());
// }
// Collections.shuffle(channelID);
//
// ArrayList<String> eightRandom = new ArrayList<>();
// for(int i=0; i<8; ++i){
// eightRandom.add(channelID.get(i));
// }
//
// return eightRandom;
//
// } catch (GoogleJsonResponseException e) {
// System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
// + e.getDetails().getMessage());
// } catch (IOException e) {
// System.err.println("There was an IO error: " + e.getCause() + " : " + e.getMessage());
// } catch (Throwable t) {
// t.printStackTrace();
// }
// ArrayList<String> empty = new ArrayList<>();
// return empty;
// }
public ArrayList<String> getPopularVideoList() {
// Read the developer key from the properties file.
try {
// This objecjat is used to make YouTube Data API requests. The last
// argument is required, but since we don't need anything
// initialized when the HttpRequest is initialized, we override
// the interface and provide a no-op function.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
ArrayList<String> videos = new ArrayList<>();
YouTube.Search.List request = youtube.search()
.list("snippet");
request.setKey(apiKey);
SearchListResponse response = request.setMaxResults(25L)
.setChannelId(this.channelID)
.setOrder("viewCount")
.setType("video")
.execute();
List<SearchResult> items = response.getItems();
for(SearchResult res : items){
videos.add(res.getId().getVideoId());
}
return videos;
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
ArrayList<String> empty = new ArrayList<>();
return empty;
}
public ArrayList<String> getRecommendedChannelID(ArrayList<String> interests) {
// Read the developer key from the properties file.
try {
// This objecjat is used to make YouTube Data API requests. The last
// argument is required, but since we don't need anything
// initialized when the HttpRequest is initialized, we override
// the interface and provide a no-op function.
youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, new HttpRequestInitializer() {
public void initialize(HttpRequest request) throws IOException {
}
}).setApplicationName("youtube-cmdline-search-sample").build();
String interestString = "";
Collections.shuffle(interests);
ArrayList<String> checkDuplicate = new ArrayList<>();
for(int i=0; i<interests.size() && i<7; ++i){
boolean skip = false;
for(int j=0; j<interests.get(i).length(); ++j){
char c = interests.get(i).charAt(j);
if(!Character.isAlphabetic(c)){
skip = true;
break;
}
}
if(skip || checkDuplicate.contains(interests.get(i))) continue;
interestString += interests.get(i);
//if(i == interests.size()-1 || i == 2) break;
interestString += "|";
checkDuplicate.add(interests.get(i));
}
System.out.println("youtube search string is " + interestString);
ArrayList<String> channels = new ArrayList<>();
YouTube.Search.List request = youtube.search()
.list("snippet");
request.setKey(apiKey);
SearchListResponse response = request.setMaxResults(1000L)
.setOrder("viewCount")
.setType("channel")
.setQ(interestString)
.execute();
List<SearchResult> items = response.getItems();
Collections.shuffle(items);
for(int i=0; i<8 && i<items.size(); ++i){
channels.add(items.get(i).getId().getChannelId());
}
return channels;
} catch (GoogleJsonResponseException e) {
System.err.println("There was a service error: " + e.getDetails().getCode() + " : "
+ e.getDetails().getMessage());
} catch (Throwable t) {
t.printStackTrace();
}
ArrayList<String> empty = new ArrayList<>();
return empty;
}
}
|
985254622fb9b721ae9f454d61870723d52d4177
|
[
"Java",
"Python",
"HTML"
] | 13
|
Java
|
G-Lan/CS4156TeamProject
|
2bdf8e98fe2d80b46db2cd0e8bcf217e093f9600
|
3dc2ae4c9622dc95e28f1281efbf753fad876624
|
refs/heads/master
|
<file_sep>from flask import render_template
from app import appName, db
@appName.errorhandler(404)
def not_found_error(error):
return render_template('404.html'), 404
@appName.errorhandler(500)
def internal_error(error):
db.session.rollback()
return render_template('500.html'), 500
<file_sep># FlaskSandbox
Test repository for understanding Flask framework fro Python
Source: https://habr.com/ru/post/346306/
<file_sep>from flask import Flask
from config import Config
from flask_mail import Mail
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
import logging
from logging.handlers import SMTPHandler
from logging.handlers import RotatingFileHandler
import os
from flask_moment import Moment
appName = Flask(__name__)
appName.config.from_object(Config)
db = SQLAlchemy(appName)
mail = Mail(appName)
login = LoginManager(appName)
login.login_view = 'login'
login.login_message = "Пожалуйста, войдите, чтобы открыть эту страницу."
appName.config.from_object(Config)
migrate = Migrate(appName, db)
bootstrap = Bootstrap(appName)
moment = Moment(appName)
if not appName.debug:
if appName.config['MAIL_SERVER']:
auth = None
if appName.config['MAIL_USERNAME'] or appName.config['MAIL_PASSWORD']:
auth = (appName.config['MAIL_USERNAME'], appName.config['MAIL_PASSWORD'])
secure = None
if appName.config['MAIL_USE_TLS']:
secure = ()
mail_handler = SMTPHandler(
mailhost=(appName.config['MAIL_SERVER'], appName.config['MAIL_PORT']),
fromaddr='no-reply@' + appName.config['MAIL_SERVER'],
toaddrs=appName.config['ADMINS'], subject='Microblog Failure',
credentials=auth, secure=secure)
mail_handler.setLevel(logging.ERROR)
appName.logger.addHandler(mail_handler)
if not os.path.exists('logs'):
os.mkdir('logs')
file_handler = RotatingFileHandler('logs/microblog.log', maxBytes=10240,
backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
file_handler.setLevel(logging.INFO)
appName.logger.addHandler(file_handler)
appName.logger.setLevel(logging.INFO)
appName.logger.info('Microblog startup')
from app import routes, models, errors
|
0c1cddf32f488f72c202c38552511e7cc4c2bbc9
|
[
"Markdown",
"Python"
] | 3
|
Python
|
grigorevmp/FlaskSandbox
|
8337d414d54f3d3b8f45e1b8cdea549513a74f60
|
458b3fa77b33442a217bd1e92d433faa4e3a92e6
|
refs/heads/master
|
<repo_name>ityyc/MyOkhttp<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/JsonResponse.java
package com.tuba.yuanyc.myokhttp.http;
import org.json.JSONObject;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public class JsonResponse extends DefaultHttpResponse {
private JSONObject jsonObject;
public JsonResponse(HttpResponse response) {
super(response);
}
@Override
protected void process() throws Throwable {
String body = response.getString();
jsonObject = new JSONObject(body);
}
/**
* 获取返回的JSONObject数据
* @return
*/
public JSONObject getJson() {
return jsonObject;
}
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/HttpErrorImpl.java
package com.tuba.yuanyc.myokhttp.http;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :HttpError异常错误的实现类
*/
public class HttpErrorImpl implements HttpError{
private Handle handle;
private Throwable throwable;
public HttpErrorImpl(Handle handle, Throwable throwable) {
this.handle = handle;
this.throwable = throwable;
}
@Override
public Handle getHandle() {
return handle;
}
@Override
public Throwable getThrowable() {
return throwable;
}
}
<file_sep>/README.md
# MyOkhttp
外部封装Okhttp,隐藏内部实现,下层变动上层无感知,简化开发,提高效率
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/HttpMethod.java
package com.tuba.yuanyc.myokhttp.http;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public enum HttpMethod {
POST,GET
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/BaseHttpResponse.java
package com.tuba.yuanyc.myokhttp.http;
import java.util.HashMap;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public interface BaseHttpResponse {
/**
* 获取http响应码
* @return
*/
int getCode();
/**
* 获取响应头信息
* @return
*/
HashMap<String,String> getHeaders();
/**
* 获取控制句柄
* @return
*/
Handle getHandle();
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/HttpRequest.java
package com.tuba.yuanyc.myokhttp.http;
import com.tuba.yuanyc.myokhttp.config.Configuration;
import java.util.Map;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public interface HttpRequest {
/**
* @param url 设置请求的url
*/
void setUrl(String url);
/**
* @param method 设置请求方式
*/
void setMethod(HttpMethod method);
/**
* 设置请求的参数
*
* @param key 请求参数的Key
* @param value 请求参数的value
*/
void putParam(String key, String value);
/**
* 请求头的信息参数
*
* @param key 请求头的Key
* @param value 请求头的Value
*/
void putHeader(String key, String value);
/**
* 设置网络请求的配置
*
* @param configuration
*/
void setConfiguration(Configuration configuration);
Configuration getConfiguration();
/**
* 得到请求的Url
*
* @return
*/
String getUrl();
/**
* 得到请求方式
*
* @return
*/
HttpMethod getMethod();
/**
* 得到请求头的信息参数
*
* @return
*/
Map<String, String> getHeaders();
/**
* 得到请求的参数
*
* @return
*/
Map<String, String> getParams();
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/rule/RuleManager.java
package com.tuba.yuanyc.myokhttp.rule;
import com.tuba.yuanyc.myokhttp.config.Configuration;
import com.tuba.yuanyc.myokhttp.http.HttpRequest;
import java.util.concurrent.CopyOnWriteArrayList;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public class RuleManager {
private final static CopyOnWriteArrayList<Rule> rules = new CopyOnWriteArrayList<>();
public RuleManager() {
}
public void addRule(Rule rule) {
if (rule != null && !rules.contains(rule)) {
rules.add(rule);
}
}
public Configuration getConfiguration(HttpRequest request) {
Configuration returnConfigure = null;
Configuration configuration;
for (Rule rule : rules) {
configuration = rule.getConfiguration(request);
if (configuration != null) {
returnConfigure = configuration;
break;
}
}
return returnConfigure;
}
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/HttpListener.java
package com.tuba.yuanyc.myokhttp.http;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public interface HttpListener {
/**
* 请求回调
* @param request
*/
void onRequest(HttpRequest request);
/**
* 响应回调
* @param response
*/
void onResponse(HttpResponse response);
/**
* 异常出错回调
* @param error
*/
void onError(HttpError error);
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/HttpResponseImp.java
package com.tuba.yuanyc.myokhttp.http;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Set;
import okhttp3.Headers;
import okhttp3.Response;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :HttpResponse的实现类
*/
public class HttpResponseImp implements HttpResponse {
private Handle handle;
private Response okHttpResponse;
private HashMap<String, String> headers;
public HttpResponseImp(Handle handle, Response okHttpResponse) {
this.handle = handle;
this.okHttpResponse = okHttpResponse;
}
@Override
public int getCode() {
return okHttpResponse.code();
}
@Override
public HashMap<String, String> getHeaders() {
if (null != headers) {
return headers;
}
headers = new HashMap<>();
Headers okHttpHeaders = okHttpResponse.headers();
if (okHttpHeaders == null || okHttpHeaders.size() < 0) {
return headers;
}
Set<String> keySet = okHttpHeaders.names();
for (String key : keySet) {
headers.put(key, okHttpHeaders.get(key));
}
return headers;
}
@Override
public Handle getHandle() {
return handle;
}
@Override
public String getString() throws IOException {
return okHttpResponse.body().toString();
}
@Override
public byte[] getBytes() throws IOException {
return okHttpResponse.body().bytes();
}
@Override
public InputStream getInputStream() {
return okHttpResponse.body().byteStream();
}
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/http/DefaultHttpListener.java
package com.tuba.yuanyc.myokhttp.http;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
abstract class DefaultHttpListener<T extends DefaultHttpResponse> implements HttpListener {
@Override
public void onResponse(HttpResponse response) {
T httpResponse = createHttpResponse(response);
try {
httpResponse.process();
doResponse(httpResponse);
} catch (Throwable t) {
onError(new HttpErrorImpl(httpResponse.getHandle(),t));
}
}
protected abstract T createHttpResponse(HttpResponse response);
/**
* 当请求成功并解析成功以后,要做的处理
*
* @param response 成功以后返回的数据
*/
protected abstract void doResponse(T response);
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/config/ConfigurationConst.java
package com.tuba.yuanyc.myokhttp.config;
import java.util.HashMap;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :
*/
public class ConfigurationConst {
private static HashMap<String, Configuration> configurationHashMap = new HashMap<>();
static {
configurationHashMap.put("default", new DefaultConfiguration());
configurationHashMap.put("urlRule", new UrlRuleConfiguration());
}
public static Configuration DEFAULT_CONFIGURATION = configurationHashMap.get("default");
public static Configuration ULR_RULE_CONFIGURATION = configurationHashMap.get("default");
}
<file_sep>/app/src/main/java/com/tuba/yuanyc/myokhttp/rule/UrlRule.java
package com.tuba.yuanyc.myokhttp.rule;
import com.tuba.yuanyc.myokhttp.config.Configuration;
import com.tuba.yuanyc.myokhttp.config.ConfigurationConst;
import com.tuba.yuanyc.myokhttp.http.HttpRequest;
import java.util.List;
/**
* Author :yuanyc
* Time :2017/6/9
* Description :根据Url得到一个配置
*/
public class UrlRule implements Rule {
private List<String> urls;
public UrlRule(List<String> urls) {
this.urls = urls;
}
@Override
public Configuration getConfiguration(HttpRequest request) {
String url = request.getUrl();
int size = urls.size();
for (int i = 0; i < size; i++) {
if (url.toLowerCase().startsWith(urls.get(i).toLowerCase())) {
return ConfigurationConst.ULR_RULE_CONFIGURATION;
}
}
return null;
}
}
|
045cbee1737630e6c7260d723c51beda2521fbe9
|
[
"Markdown",
"Java"
] | 12
|
Java
|
ityyc/MyOkhttp
|
09ec8fba1aea4ac03e137e3b949865dc71edfa8b
|
35569bb22d854af37217ae7c1ba716869121b11b
|
refs/heads/master
|
<file_sep>from django.urls import path
from apps.sab import views
app_name = 'sab'
urlpatterns = [
path(r'AddToCart/',views.VisitAddToCart),
path(r'ATResult/',views.VisitATResult),
path(r'ResetCart/',views.VisitResetCart),
path(r'CheckCart/',views.VisitCheckCart),
path(r'CheckResult/',views.VisitCheckResult),
path(r'Pay/',views.VisitPay),
#模板url
path(r'PRecharge/',views.VisitPRecharge),
path(r'Recharge-Submit/',views.ReturnPPage),
path(r'ParentPageR/',views.VisitPPageR),
path(r'view-cart/',views.VisitCart),
path(r'reset-cart/',views.ResetCart),
path(r'pay-cart/',views.PayForCart),
]
<file_sep>from django.db import models
from apps.fundamental.article.models import News
from apps.fundamental.storage.models import Image,Video
from apps.User.models import Institution,Teacher
from apps.course.models import Course_Base
# Create your models here.
#新闻顺序表
class News_Order(models.Model):
NO=models.ForeignKey(News,on_delete=models.CASCADE)
Order=models.IntegerField()
class Video_Order(models.Model):
VO=models.ForeignKey(Video,on_delete=models.CASCADE)
Order=models.IntegerField()
class Teacher_Order(models.Model):
TO=models.ForeignKey(Teacher,on_delete=models.CASCADE)
Order=models.IntegerField()
class Insti_Order(models.Model):
IO=models.ForeignKey(Institution,on_delete=models.CASCADE)
Order=models.IntegerField()
class Course_Order(models.Model):
CO=models.ForeignKey(Course_Base,on_delete=models.CASCADE)
Order=models.IntegerField()
<file_sep>from django.shortcuts import render
# Create your views here.
def VisitHomePage(request):
return render(request,'HomePage.html')
def VisitIndex(request):
return render(request,'index.html')
<file_sep># Generated by Django 2.2.2 on 2019-06-27 11:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('User', '0002_auto_20190627_0226'),
]
operations = [
migrations.AddField(
model_name='institution',
name='name',
field=models.CharField(default='待填写', max_length=30),
),
]
<file_sep>from django.contrib import admin
from apps.homepage.models import *
# Register your models here.
admin.site.register(News_Order)
admin.site.register(Video_Order)
admin.site.register(Teacher_Order)
admin.site.register(Insti_Order)
admin.site.register(Course_Order)
<file_sep># Generated by Django 2.2.2 on 2019-06-19 05:52
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ChinaLocation',
fields=[
('id', models.SmallIntegerField(primary_key=True, serialize=False, unique=True)),
('name', models.CharField(max_length=15, verbose_name='区域名称')),
('parent_id', models.SmallIntegerField(db_column='parent_id', default=0)),
('level', models.SmallIntegerField(choices=[(1, '省/直辖市'), (2, '市'), (3, '辖区')])),
],
options={
'db_table': 'CHINA_LOCATION',
},
),
]
<file_sep>#!/bin/bash
git filter-branch --force --index-filter 'git rm --cached -r --ignore-unmatch \
document/Spring in Action' --prune-empty --tag-name-filter cat -- --all
<file_sep># Generated by Django 2.2.1 on 2019-06-17 09:16
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('article', '0003_auto_20190617_1625'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'ordering': ('-created',)},
),
migrations.RemoveField(
model_name='article',
name='content',
),
migrations.AddField(
model_name='article',
name='author',
field=models.ForeignKey(default=0, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='作者'),
preserve_default=False,
),
migrations.AddField(
model_name='article',
name='body',
field=models.TextField(default=0, verbose_name='内容'),
preserve_default=False,
),
migrations.AddField(
model_name='article',
name='created',
field=models.DateTimeField(default=django.utils.timezone.now),
),
migrations.AddField(
model_name='article',
name='updated',
field=models.DateTimeField(auto_now=True),
),
]
<file_sep>from django.apps import AppConfig
class SabConfig(AppConfig):
name = 'sab'
<file_sep>from django.contrib.auth.decorators import permission_required, login_required
from django.shortcuts import render,redirect
from django.contrib.auth.models import User
from . import trans,Transaction
import apps.User.models as Um
from apps.fundamental.article.models import Announcement
from django.http import HttpResponseRedirect
from django.contrib.auth import authenticate, login
# Create your views here.
def TeacherInfo(request):
return render(request,'userHome/TeacherInfomation.html')
def dispatch(request):
if request.method == 'POST':
username = request.POST.get('username',None)
password = request.POST.get('password',None)
user = authenticate(request,username=username,password=<PASSWORD>)
if user is not None and user.is_active:
login(request, user)
print('here')
id = request.user.id
print(id)
if Um.Teacher.objects.filter(user_id=id):
return render(request,'userHome/TeacherInfomation.html')
if Um.Parent.objects.filter(user_id=id):
print('parent')
return redirect('/userHome/ParentPage/')
if Um.Institution.objects.filter(user_id=id):
return redirect('/userHome/InstitutionInfo/0/')
if Um.Admin.objects.filter(user_id=id):
return render(request,'userHome/AdminInfomation.html')
return HttpResponseRedirect('/User/login')
def change_t_info(request):
id = request.user.id
if not Um.Teacher.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == 'POST':
dict = {}
dict['Age'] = request.POST.get('Age')
dict['Limyear'] = request.POST.get('Limyear')
dict['Fitage'] = request.POST.get('Fitage')
dict['Brief'] = request.POST.get('Brief')
dict['PhoneNumber'] = request.POST.get('PhoneNumber')
dict['LDirection'] = request.POST.get('LDirection')
trans.change_teach_info(id,dict)
dict = trans.display_Teach_info(id)
if request.method == 'POST':
dict['res'] = 'success!'
return render(request,'userHome/tChangeInfo.html',dict)
def set_course(request,bid=None):
id = request.user.id
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return render(request,'login')
if bid:
if request.method == "POST":
if request.POST.get('delete'):
c_id = request.POST.get('course_id')
trans.delete_course(c_id,id,bid)
else:
c_id = request.POST.get('id')
return HttpResponseRedirect('../UpdateCourse'+str(c_id)+'/')
dict = trans.display_all_course(id,bid)
else:
if request.method == "POST":
c_id = request.POST.get('id')
trans.delete_course(c_id,id)
dict = trans.display_all_course(id)
return render(request,'userHome/SetCourse.html',dict)
def update_course(request,cid,bid=None):
id = request.user.id
dict = {}
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == 'POST':
dict['teacher'] = request.POST.get('teacher')
dict['price'] = request.POST.get('price')
dict['Address'] = request.POST.get('Address')
dict['homework'] = request.POST.get('homework')
trans.update_course(cid,dict)
dict = trans.display_one_course(cid)
return render()
def add_course(request,bid=None):
id = request.user.id
dict = {}
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == 'POST':
dict['name'] = request.POST.get('name')
dict['location_pro'] = request.POST.get('location_pro')
dict['location_city'] = request.POST.get('location_city')
dict['location_area'] = request.POST.get('location_area')
dict['course_teacher'] = request.POST.get('course_teacher')
dict['course_subject'] = request.POST.get('course_subject')
dict['course_age'] = request.POST.get('course_age')
dict['course_contains'] = request.POST.get('course_contains')
dict['course_time'] = request.POST.get('course_time')
dict['course_duration_time'] = request.POST.get('course_duration_time')
dict['course_price'] = request.POST.get('course_price')
trans.add_course(dict,id,bid)
dict = {}
dict['res'] = 'success!'
return render(request,'userHome/AddCourse.html',dict)
def add_announcement(request,bid=None):
id = request.user.id
dict = {}
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == "POST":
dict['title'] = request.POST.get('title')
dict['body'] = request.POST.get('body')
dict['author'] = request.user
trans.add_ann(dict)
return render(request,'userHome/Addannouncement.html',dict)
def update_announcement(request,bid=None):
id = request.user.id
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
dict = {}
if request.method == "POST":
dict['id'] = request.POST.get('id')
dict['title'] = request.POST.get('title')
dict['body'] = request.POST.get("body")
trans.update_ann(dict)
dict['res'] = '修改成功'
return render(request,'userHome/Updateannouncement.html',dict)
def show_announcement(request,bid=None):
id = request.user.id
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == "POST":
aid = request.POST.get('id')
Announcement.objects.filter(id=aid).delete()
dict = trans.display_all_ann(id)
return render(request,'userHome/announcement.html',dict)
def all_tlesson(request,bid = None):
id = request.user.id
if not Um.Teacher.objects.filter(user_id=id) and not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == "POST":
if request.POST.get('deny'):
did = request.POST.get('did')
trans.deny_tl(did)
else:
tid = request.POST.get('tid')
trans.allow_tl(tid)
dict = trans.display_all_tlesson(id,bid)
return render(request,'userHome/tlesson.html',dict)
def insinfo(request,bid):
id = request.user.id
if not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
dict = {}
dict['bid'] = bid
return render(request,'userHome/InstitutionInfomation.html',dict)
def choosebranch(request,bid):
id = request.user.id
if not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
dict={}
if request.method == 'POST':
dict['bid'] = request.POST.get('bid')
print(dict['bid'])
return HttpResponseRedirect('../'+str(dict['bid'])+'/')
else:
dict['bid'] = bid
return render(request,'userHome/ChooseBranch.html',dict)
def addbranch(request,bid):
id = request.user.id
if not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
dict={}
if request.method == 'POST':
dict['branch_province'] = request.POST.get('branch_province')
dict['branch_city'] = request.POST.get('branch_city')
dict['branch_distinct'] = request.POST.get('branch_distinct')
dict['PhoneNumber'] = request.POST.get('PhoneNumber')
dict['Address'] = request.POST.get('Address')
trans.add_branch(dict,id)
dict['res'] = '添加成功'
return render(request,'userHome/AddBranch.html',dict)
def change_i_info(request,bid):
dict = {}
id = request.user.id
if not Um.Institution.objects.filter(user_id=id):
return HttpResponseRedirect('/User/login')
if request.method == 'POST':
dict={}
dict['name'] = request.POST.get('name')
dict['branch_province'] = request.POST.get('branch_province')
dict['branch_city'] = request.POST.get('branch_city')
dict['branch_distinct'] = request.POST.get('branch_distinct')
dict['Address'] = request.POST.get('Address')
dict['PhoneNumber'] = request.POST.get('PhoneNumber')
dict['LDirection'] = request.POST.get('LDirection')
dict['Fitage'] = request.POST.get('Fitage')
dict['Brief'] = request.POST.get('Brief')
trans.change_Ins_info(id,bid,dict)
dict = trans.display_Ins_info(id,bid)
if request.method == 'POST':
dict['res'] = 'success!'
return render(request,'userHome/InsChangeInfo.html',dict)
#模板views
def VisitPPage(request):
return render(request,'ParentPage.html')
def VisitPPageG(request):
rlt={}
rlt=Transaction.GetPInfo(request)
#print(rlt)
return render(request,'ParentPageG.html',rlt)
def VisitPPageC(request):
rlt={}
rlt['data']=Transaction.GetSchedule(request)
#print(rlt)
return render(request,'ParentPageC.html',rlt)
def VisitPPageA(request):
rlt={}
rlt['data']=Transaction.GetAudition(request)
#print(rlt)
return render(request,'ParentPageA.html',rlt)
def VisitUpPInfo(request):
return render(request,'updatePinfo.html')
def VisitPPageMB(request):
Transaction.UpdatePInfo(request)
return render(request,'ParentPage.html')
<file_sep>from django.urls import path
from . import views
urlpatterns=[
path('', views.fault),
path('', views.about_us),
path('', views.about_us2),
path('', views.blog),
path('',views.blog_with_sidebar),
path('', views.checkout),
path('', views.contact),
path('', views.courses),
path('', views.event),
path('', views.index),
path('', views.index2),
path('', views.index3),
path('', views.index4),
path('', views.instructor),
path('', views.login),
path('', views.login_form),
path('', views.need_login),
path('', views.next_register),
path('', views.register),
path('', views.register2),
path('', views.register3),
path('', views.register_results),
path('', views.register_results2),
path('', views.shop),
path('', views.shop_with_sidebar),
path('', views.single_blog),
path('', views.single_courses),
path('', views.single_event),
path('', views.single_shop),
path('', views.update_personalinfo),
path('', views.view_cart),
]
<file_sep># 2019年软件工程课程设计要求
按名册顺序(或自由分组)每5人分为一组,选一人为组长
以小组为单位完成题目。
各小组最终需要提交以下文档:
1. 开发计划(包括人员安排、进度计划)
2. 需求分析文档
3. 设计文档
4. 测试计划
5. (可选项)软件配置管理计划与最终配置库
6. 测试报告
7. 工作总结:小组成员每人写一份关于自己所做工作的汇报,最后由组长汇总写一份全组工作的总结报告
最后一天以小组为单位检查程序运行情况
## 评分参考方面
1. 出勤情况
2. 团队合作
3. 工作质量
* 开发计划
* 需求分析文档
* 设计文档
* 测试计划和测试报告
* 工作总结
* 程序运行检查
## 注意事项
各组长在工作总结中要明确团队成员各自的贡献度(按百分比形式)。
成员的贡献度作为各成员工作质量的调整参数。
* 举例说明:假设项目评分为80,若一个5人组中每位成员贡献度均相同,即为20%,则每人的工作质量分数都是80分。若其中一人为25%,另一人为15%,其他3人都是20%,则第一人分数最多为100,第二人分数最多为60,其他3人分数最多为80。工作质量分数最多不超过100分。
<file_sep># Generated by Django 2.2.1 on 2019-06-17 07:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('storage', '0002_video'),
]
operations = [
migrations.CreateModel(
name='Image',
fields=[
('image_id', models.IntegerField(primary_key=True, serialize=False, verbose_name='IMAGE_ID')),
('name', models.CharField(max_length=500, verbose_name='IMAGE_NAME')),
('imageFile', models.ImageField(upload_to='images/', verbose_name='IMAGE_URL')),
],
),
migrations.DeleteModel(
name='storage',
),
migrations.RemoveField(
model_name='video',
name='id',
),
migrations.RemoveField(
model_name='video',
name='videofile',
),
migrations.AddField(
model_name='video',
name='videoFile',
field=models.FileField(default=0, upload_to='videos/', verbose_name='VIDEO_URL'),
preserve_default=False,
),
migrations.AddField(
model_name='video',
name='video_id',
field=models.IntegerField(default=0, primary_key=True, serialize=False, verbose_name='video_ID'),
preserve_default=False,
),
migrations.AlterField(
model_name='video',
name='name',
field=models.CharField(max_length=500, verbose_name='VIDEO_NAME'),
),
]
<file_sep>from django.db import models
# Create your models here.
from django.db import models
# Create your models here.
class ChinaLocation(models.Model):
id = models.SmallIntegerField(primary_key=True,unique=True)
name = models.CharField(max_length=15,verbose_name="区域名称")
parent_id = models.SmallIntegerField(default=0, db_column='parent_id')
level = models.SmallIntegerField(null=False,choices=[(1,'省/直辖市'),(2,'市'),(3,'辖区')])
class Meta:
db_table = 'CHINA_LOCATION'
<file_sep># posts/urls.py
from django.urls import path
from . import views
app_name = 'storage'
urlpatterns = [
path('postimage/', views.showimage),
path('postvideo/', views.showvideo)# new
]
<file_sep>"""yjy001 URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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.urls import path,include
urlpatterns = [
path('fault/', include('basic.urls')),
path('about_us/', include('basic.urls')),
path('about_us2/', include('basic.urls')),
path('blog/', include('basic.urls')),
path('blog_with_sidebar/', include('basic.urls')),
path('checkout/', include('basic.urls')),
path('contact/', include('basic.urls')),
path('courses/', include('basic.urls')),
path('event/', include('basic.urls')),
path('index/', include('basic.urls')),
path('index2/', include('basic.urls')),
path('index3/', include('basic.urls')),
path('index4/', include('basic.urls')),
path('instructor/', include('basic.urls')),
path('login/', include('basic.urls')),
path('login_form/', include('basic.urls')),
path('need_login/', include('basic.urls')),
path('next_register/', include('basic.urls')),
path('register/', include('basic.urls')),
path('register2/', include('basic.urls')),
path('register3/', include('basic.urls')),
path('register_results/', include('basic.urls')),
path('register_results2/', include('basic.urls')),
path('shop/', include('basic.urls')),
path('shop_with_sidebar/', include('basic.urls')),
path('single_blog/', include('basic.urls')),
path('single_courses/', include('basic.urls')),
path('single_event/', include('basic.urls')),
path('single_shop/', include('basic.urls')),
path('update_personalinfo/', include('basic.urls')),
path('view_cart/', include('basic.urls')),
path('admin/', admin.site.urls),
]
<file_sep># codings: utf-8
from django.shortcuts import render
# Create your views here.
def hello(request):
return render(request, 'need-login.html')
def login(request):
return render(request, 'User/login.html')
def login_form(request):
return render(request, 'login-form.html')
def fault(request):
return render(request, '404.html')
def about_us(request):
return render(request, 'about-us.html')
def about_us2(request):
return render(request, 'about-us-2.html')
def blog(request):
return render(request, 'blog.html')
def blog_with_sidebar(request):
return render(request, 'blog-with-sidebar.html')
def checkout(request):
return render(request, 'checkout.html')
def contact(request):
return render(request, 'contact.html')
def courses(request):
return render(request, 'courses.html')
def event(request):
return render(request, 'event.html')
def index(request):
return render(request, 'index.html')
def index2(request):
return render(request, 'index-2.html')
def index3(request):
return render(request, 'index-3.html')
def index4(request):
return render(request, 'index-4.html')
def instructor(request):
return render(request, 'instructor.html')
def next_register(request):
return render(request, 'next-register.html')
def register(request):
return render(request, 'User/register.html')
def register2(request):
return render(request, 'register2.html')
def register3(request):
return render(request, 'register3.html')
def register_results(request):
return render(request, 'register-results.html')
def register_results2(request):
return render(request, 'register-results2.html')
def next_register(request):
return render(request, 'next-register.html')
def need_login(request):
return render(request, 'need-login.html')
def shop(request):
return render(request, 'shop.html')
def shop_with_sidebar(request):
return render(request, 'shop-with-sidebar.html')
def single_blog(request):
return render(request, 'single-blog.html')
def single_courses(request):
return render(request, 'single-courses.html')
def single_event(request):
return render(request, 'single-event.html')
def single_shop(request):
return render(request, 'single-shop.html')
def update_personalinfo(request):
return render(request, 'update-personalinfo.html')
def view_cart(request):
return render(request, 'view-cart.html')<file_sep>from django.contrib.auth.decorators import login_required
import apps.User.models as umodel
from apps.course.models import Course_Base,Course_Institution,Course_Teacher,Branch
from apps.fundamental.article.models import Announcement
from apps.fundamental.CHINA_LOCATION.models import ChinaLocation
from apps.userHome.models import Temp_Lesson
from django.db.models import Q
#@login_required()
def display_Teach_info(id):
dict = {}
teacher = umodel.Teacher.objects.get(user_id=id)
dict['Name'] = teacher.Name
dict['Age'] = teacher.Age
dict['Limyear'] = teacher.Limyear
dict['LDirection'] = teacher.LDirection
dict['PhoneNumber'] = teacher.PhoneNumber
dict['Fitage'] = teacher.Fitage
dict['Sex'] = teacher.Sex
dict['Wallet'] = teacher.Wallet
dict['Brief'] = teacher.Brief
dict['Id_Num'] = teacher.Id_num
return dict
#@login_required()
def change_teach_info(id,dict):
teacher = umodel.Teacher.objects.get(user_id = 2)
tc = umodel.Teacher.objects.filter(id = teacher.id)
if dict['Age'] != teacher.Age:
tc.update(Age = dict['Age'])
if dict['Limyear'] != teacher.Limyear:
tc.update(Limyear = dict['Limyear'])
if dict['Fitage'] != teacher.Fitage:
tc.update(Fitage = dict['Fitage'])
if dict['Brief'] != teacher.Brief:
tc.update(Brief = dict['Brief'])
if dict['PhoneNumber'] != teacher.PhoneNumber:
tc.update(PhoneNumber = dict['PhoneNumber'])
if dict['LDirection'] != teacher.LDirection:
tc.update(LDirection = dict['LDirection'])
return
def update_course(cid,dict):
course = Course_Base.objects.get(id = cid)
if course.course_location != dict['Address']:
course.course_location = dict['Address']
if course.course_homework !=dict['homework']:
course.course_homework =dict['homework']
if course.course_price != dict['price']:
course.course_price = dict['price']
if course.course_teacher != dict['teacher']:
course.course_teacher = dict['teacher']
course.save()
return
def display_one_course(cid):
dict = {}
course = Course_Base.objects.get(id=cid)
temp = [course,course.course_location_province.name,course.course_location_city.name,
course.course_location_distinct.name]
dict['course']=temp
return dict
#@login_required()
def add_course(dict,id,bid):
course = Course_Base(course_location_province=ChinaLocation.objects.get(name=dict['location_pro']),
course_name=dict['name'],
course_location_city=ChinaLocation.objects.get(name=dict['location_city']),
course_location_distinct=ChinaLocation.objects.get(name=dict['location_area']),
course_teacher=dict['course_teacher'],
course_subject=dict['course_subject'],course_price=dict['course_price'],
course_age=dict['course_age'],course_time=dict['course_time'],
course_contains=dict['course_contains'],course_duration_of_week=dict['course_duration_time'])
course.save()
if umodel.Teacher.objects.filter(user_id=id):
teacher = umodel.Teacher.objects.get(user_id=id)
Course_Teacher.objects.create(course_teacher=teacher,course_id=course)
else:
branch = Branch.objects.get(id=bid)
Course_Institution.objects.create(course_ins=branch,course_id=course)
return
def display_all_course(id,b_id=None):
dict = {}
dict['courses'] = []
if umodel.Teacher.objects.filter(user_id=id):
teacher = umodel.Teacher.objects.get(user_id=id)
cc = Course_Teacher.objects.filter(course_teacher=teacher.id)
i = 0
for course in cc:
course0 = Course_Base.objects.get(id=course.course_id.id)
temp = [course0,course0.course_location_province.name,course0.course_location_city.name,
course0.course_location_distinct.name]
dict['courses'].append(temp)
else:
cc = Course_Institution.objects.filter(course_ins=b_id)
i = 0
for course in cc:
course0 = Course_Base.objects.get(id=course.course_id.id)
temp = [course0,course0.course_location_province.name,course0.course_location_city.name,
course0.course_location_distinct.name]
dict['courses'].append(temp)
return dict
def display_all_ann(id):
dict = {}
dict['res'] = []
anns = Announcement.objects.filter(author_id=id)
for ann in anns:
dict['res'].append(ann)
return dict
def delete_course(c_id,id,b_id=None):
if not Course_Base.objects.filter(id=c_id):
if umodel.Teacher.objects.filter(user_id=id):
teacher = umodel.Teacher.objects.get(user_id=id)
Course_Teacher.objects.filter(course_id=c_id).filter(course_teacher=teacher.id).delete()
Course_Base.objects.filter(id=c_id).delete()
else:
Course_Institution.objects.filter(course_id=c_id).filter(course_ins=b_id).delete()
Course_Base.objects.filter(id=c_id).delete()
return
def add_ann(dict):
ann = Announcement(**dict)
ann.save()
return
def update_ann(dict):
ann = Announcement.objects.get(id=dict['id'])
if ann.title != dict['title'] and dict['title']!='':
ann.title = dict['title']
if ann.body != dict['body'] and dict['body']!='':
ann.body = dict['body']
ann.save()
return
def display_all_tlesson(id,bid=None):
dict = {}
dict['res'] = []
if umodel.Teacher.objects.filter(user_id=id):
tea = umodel.Teacher.objects.get(user_id=id)
cts = Course_Teacher.objects.filter(course_id=tea.id)
for ct in cts:
tls = Temp_Lesson.objects.filter(lesson=ct.course_id.id).filter(state='待审核')
for tl in tls:
dict['res'].append([tl.id,tl.person.PName,tl.lesson.course_name,tl.state])
else:
bs = Branch.objects.get(id = bid)
lls = Course_Institution.objects.filter(course_ins=bs.id)
for ll in lls:
course = ll.course_id
tls = Temp_Lesson.objects.filter(lesson=course.id).filter(state='待审核')
for tl in tls:
dict['res'].append([tl.id,tl.person.Pname,tl.lesson.course_name,tl.state])
return dict
def deny_tl(id):
Temp_Lesson.objects.filter(id = id).update(state = '被拒绝')
return
def allow_tl(id):
Temp_Lesson.objects.filter(id=id).update(state='已通过')
return
def add_branch(dict,id):
ins = umodel.Institution.objects.get(user_id=id)
dict['Ins'] = ins
dict['branch_province'] = ChinaLocation.objects.get(name = dict['branch_province'])
dict['branch_city'] = ChinaLocation.objects.get(name = dict['branch_city'])
dict['branch_distinct'] = ChinaLocation.objects.get(name = dict['branch_distinct'])
b = Branch(**dict)
b.save()
return
def display_Ins_info(id,bid):
dict = {}
if bid != 0:
branch = Branch.objects.get(id = bid)
ins = umodel.Institution.objects.get(user_id = id)
dict['name'] = ins.name
dict['PhoneNumber'] = branch.PhoneNumber
dict['branch_province'] = branch.branch_province.name
dict['branch_city'] = branch.branch_city.name
dict['branch_distinct'] = branch.branch_distinct.name
dict['LDirection'] = branch.LDirection
dict['Fitage'] = branch.Fitage
dict['Address'] = branch.Address
dict['Brief'] = ins.Brief
else:
ins = umodel.Institution.objects.get(user_id = id)
dict['name'] = ins.name
dict['Brief'] = ins.Brief
return dict
def change_Ins_info(id,bid,dict):
branch = Branch.objects.get(id = bid)
ins = umodel.Institution.objects.get(user_id = id)
if ins.name != dict['name']:
ins.name = dict['name']
if branch.PhoneNumber != dict['PhoneNumber']:
branch.PhoneNumber = dict['PhoneNumber']
if branch.branch_province.name != dict['branch_province']:
branch.branch_province = ChinaLocation.objects.get(name=dict['branch_province'])
if branch.branch_city.name != dict['branch_city']:
branch.branch_city = ChinaLocation.objects.get(name=dict['branch_city'])
if branch.branch_distinct.name != dict['branch_distinct']:
branch.branch_distinct = ChinaLocation.objects.get(name=dict['branch_distinct'])
if ins.Brief != dict['Brief']:
ins.Brief = dict['Brief']
if dict['LDirection'] != branch.LDirection:
branch.LDirection = dict['LDirection']
if dict['Fitage'] != branch.Fitage:
branch.Fitage = dict['Fitage']
if dict['Address'] != branch.Address:
branch.Address = dict['Address']
ins.save()
branch.save()
return<file_sep># SE PROJECT 2019
## 注意事项
1. SUPERUSER:
username : se
passwd : <PASSWORD>
2. 依赖包
django-ckeditor
pillow
markdown
(pip install 即可)
3. 文章作者始终为id = 1 的管理员!有USER之后再做更改
4. 文章测试 http://127.0.0.1:8000/article/article-list/<file_sep># Generated by Django 2.2.1 on 2019-06-28 03:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('User', '0007_auto_20190627_2206'),
('course', '0004_auto_20190627_2206'),
('userHome', '0002_auto_20190627_1213'),
]
operations = [
migrations.AlterUniqueTogether(
name='temp_lesson',
unique_together={('person', 'lesson')},
),
]
<file_sep>from django.urls import path
from . import views
app_name = 'course'
urlpatterns = [
path('', views.Course_Index, name='course_index'),
path('<int:course_id>/' , views.Single_Course_Index,name='course_single'),
path('<int:course_id>/getinfo/',views.Single_Course_Info,name = 'course_info'),
path('getAllInfo/', views.All_Course_Info, name='All_course_info'),
path('<int:course_id>/score/' , views.Scoring_Course ,name='course_score'),
path('<int:course_id>/getcomment/' , views.Single_Course_Comment ,name='course_comment'),
path('search_course',views.Search_Course,name='search'),
path('<int:course_id>/comment_submit',views.Comment_Submit,name='submit'),
path('<int:course_id>/add_to_cart',views.Add_To_Cart,name='cart'),
path('<int:course_id>/add_to_temp_lesson',views.Add_To_Temp_Lesson,name='temp_lesson'),
path('<int:course_id>/comment_del/<int:comment_id>',views.article_delete,name='del'),
]<file_sep># Generated by Django 2.2.2 on 2019-06-27 08:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('User', '0003_auto_20190627_1447'),
]
operations = [
migrations.AddField(
model_name='branch',
name='Address',
field=models.CharField(default=None, max_length=50),
),
]
<file_sep>from django.contrib import admin
from .models import ChinaLocation
#admin.site.register(ChinaLocation)
# Register your models here.
<file_sep># Generated by Django 2.2.2 on 2019-06-26 19:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('course', '0001_initial'),
('User', '0002_auto_20190627_0226'),
]
operations = [
migrations.CreateModel(
name='Temp_Lesson',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('state', models.CharField(default='未通过', max_length=8)),
('lesson', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base', verbose_name='视听课程')),
('person', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Parent', verbose_name='试听用户')),
],
),
]
<file_sep>from django.urls import path
from . import views
app_name = 'CHINA_LOCATION'
urlpatterns = [
path('test/', views.getAreas, name='loc_test'),
path('getProvince/',views.getProvince,name='loc_province'),
path('getCity/',views.getCity,name='loc_city'),
path('getDistrict/',views.getDistrict,name='loc_distinct'),
path('getAll/', views.getAll,name = 'loc_all'),
]<file_sep># Generated by Django 2.2.2 on 2019-06-26 19:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('User', '0002_auto_20190627_0226'),
('CHINA_LOCATION', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Course_Base',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_name', models.CharField(max_length=50, verbose_name='课程名称')),
('course_teacher', models.CharField(max_length=30, verbose_name='授课老师')),
('course_subject', models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], max_length=10, verbose_name='课程方向')),
('course_age', models.CharField(choices=[('All', 'All'), ('Primary', 'Pri'), ('Junior', 'Jun'), ('Senior', 'Sen')], max_length=10, verbose_name='课程适用年龄')),
('course_contains', models.CharField(blank=True, max_length=500, verbose_name='课程内容')),
('course_time', models.DateTimeField(verbose_name='首次课时间')),
('course_duration_of_week', models.IntegerField(choices=[(12, '一季'), (26, '半年'), (52, '一年'), (104, '两年')])),
('course_price', models.IntegerField(default=0, verbose_name='课程价格')),
('course_location', models.CharField(default='UNKOWN LOCATION', max_length=20, verbose_name='上课地点')),
('course_homework', models.TextField(blank=True, max_length=500, verbose_name='课程作业')),
('course_location_city', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_city', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在城市')),
('course_location_distinct', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_distinct', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在区')),
('course_location_province', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='course_province', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在省份')),
],
options={
'db_table': 'Course_Base',
},
),
migrations.CreateModel(
name='Course_Teacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Course_by_Teacher', to='course.Course_Base', verbose_name='教师所授课程')),
('course_teacher', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Teacher_for_course', to='User.Teacher', verbose_name='教师名称')),
],
options={
'db_table': 'Course_Teacher',
},
),
migrations.CreateModel(
name='Course_Score',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_score', models.SmallIntegerField(verbose_name='课程评分')),
('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Course', to='course.Course_Base', verbose_name='被评分课程')),
],
options={
'db_table': 'Course_Score',
},
),
migrations.CreateModel(
name='Course_Institution',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Course_by_Ins', to='course.Course_Base', verbose_name='机构所授课程')),
('course_ins', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='Ins_for_Course', to='User.Branch', verbose_name='机构名称')),
],
options={
'db_table': 'Course_Institution',
},
),
]
<file_sep># Generated by Django 2.2.2 on 2019-06-27 14:06
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('course', '0003_auto_20190627_2000'),
]
operations = [
migrations.AlterField(
model_name='course_comment',
name='comment_parent',
field=models.ForeignKey(db_column='parent_id', on_delete=django.db.models.deletion.CASCADE, to='User.Parent', verbose_name='评价者'),
),
]
<file_sep>
from django.shortcuts import render, redirect
from apps.User import models
from django.contrib.auth import authenticate
from django.contrib.auth.models import User
from django.contrib import auth
from django.http import HttpResponseRedirect
from functools import wraps
def check_login(f):
@wraps(f)
def inner(request,*arg,**kwargs):
if request.session.get('is_login')=='1':
return f(request,*arg,**kwargs)
else:
return redirect('User/login.html')
return inner
def logout(request):
request.session['is_login']='0'
print(request.session['is_login'])
return render(request,"User/login.html")
def login(request):
return render(request, "User/login.html", )
def Slogin(request):
#return HttpResponse("Register")
if request.method == 'POST':
username = request.POST.get('username',None)
password = request.POST.get('password',None)
user = authenticate(request,username=username,password=password)
if user is not None and user.is_active:
auth.login(request, user)
#request.session['is_login']='1'
#request.session['user_id'] = user.id
#if user.first_name == "1":"2":"3":"4"
print('there')
return HttpResponseRedirect('/userHome/')
else:
print('用户名或密码错误!')
return render(request, "User/login.html", )
def regChoice(request):
#return HttpResponse("login")
return render(request, "User/register.html", )
#家长学生注册完毕
def POSreg(request):
if request.method == "POST":
username = request.POST.get("username",None)
password = request.POST.get("password",None)
stuname = request.POST.get("stuname",None)
parname = request.POST.get("parname",None)
age = request.POST.get("age",None)
gender = request.POST.get("gender",None)
phone = request.POST.get("phone",None)
email = request.POST.get("email",None)
#print (username,password,stuname,parname,age,gender)
#print (phone,email)
authuser = User.objects.create_user(username,email,password,first_name = '1')
new_user = models.Parent.objects.create(user = authuser,Age = age)
new_user.KName = stuname
new_user.PName = parname
new_user.Sex = gender
new_user.PhoneNumber = phone
new_user.save()
return render(request, "User/login.html", )
return render(request, "User/register3.html", )
def Teareg(request):
if request.method == "POST":
username = request.POST.get("username",None)
password = request.POST.get("password",None)
name = request.POST.get("name",None)
id_num = request.POST.get("id_num",None)
age = request.POST.get("age",None)
gender = request.POST.get("gender",None)
Direction= request.POST.get("LDirection",None)
year = request.POST.get("Limyear",None)
Fitage = request.POST.get("Fitage",None)
phone = request.POST.get("phone",None)
email = request.POST.get("email",None)
Brief = request.POST.get("Brief",None)
#print(username,password,id_num,name,age,gender)
#print(Direction,Fitage,phone,email,Brief)
authuser = User.objects.create_user(username,email,password,first_name = '2')
new_user = models.Teacher.objects.create(user = authuser)
new_user.Name = name
new_user.Age = age
new_user.Sex = gender
new_user.Id_num = id_num
new_user.LDirection = Direction
new_user.Limyear = year
new_user.Fitage = Fitage
new_user.Brief = Brief
new_user.PhoneNumber = phone
new_user.save()
return render(request, "User/login.html", )
return render(request, "User/register2.html" )
#教育机构注册完毕
def Insreg(request):
if request.method == "POST":
iname = request.POST.get("iname",None)
username = request.POST.get("username",None)
password = request.POST.get("password",None)
id_num = request.POST.get("id_num",None)
address = request.POST.get("address",None)
Direction= request.POST.get("LDirection",None)
Fitage = request.POST.get("Fitage",None)
phone = request.POST.get("phone",None)
email = request.POST.get("email",None)
Brief = request.POST.get("Brief",None)
#print(username,password,iname,id_num,address)
#print(Direction,Fitage,phone,email,Brief)
authuser = User.objects.create_user(username,email,password,first_name = '3')
new_user = models.Institution.objects.create(user = authuser)
new_user.Id_num = id_num
new_user.Address = address
new_user.LDirection = Direction
new_user.Fitage = Fitage
new_user.Brief = Brief
new_user.PhoneNumber = phone
new_user.name = iname
new_user.save()
return render(request, "User/login.html", )
return render(request,"User/register1.html", )
def Admreg(request):
if request.method == "POST":
username = request.POST.get("username",None)
password = request.POST.get("password",None)
email = request.POST.get("email",None)
authuser = User.objects.create_user(username,email,password,first_name = '4')
new_user = models.Admin.objects.create(user = authuser)
return render(request, "User/login.html", )
return render(request,"User/Admreg.html",)
# Create your views here.
@check_login
def Adm(request):
Cuid = request.session.get('user_id')
Utype = User.objects.get(id = Cuid)
if Utype is not None:
print(Cuid)
if(Utype.first_name != '4'):
return render(request,"User/login.html",)
print(request.session.get('user_id'))
return render(request,"User/Adm.html")
else:
return render(request,"User/login.html",)
@check_login
def POS(request):
Cuid = request.session.get('user_id')
Utype = User.objects.get(id = Cuid)
if Utype is not None:
print(Cuid)
if(Utype.first_name != '1'):
return render(request,"User/login.html",)
print(request.session.get('user_id'))
return render(request,"User/POS.html")
else:
return render(request,"User/login.html",)
@check_login
def Tea(request):
Cuid = request.session.get('user_id')
Utype = User.objects.get(id = Cuid)
if Utype is not None:
print(Cuid)
if(Utype.first_name != '2'):
return render(request,"User/login.html",)
print(request.session.get('user_id'))
return render(request,"User/Tea.html")
else:
return render(request,"User/login.html",)
def Find(request):
if request.method == "POST":
phone = request.POST.get("phone",None)
email = request.POST.get("email",None)
password = request.POST.get("code",None)
auserl = User.objects.filter(email = email)
#print(phone,email)
if auserl is None:
return render(request,"User/find.html",)#无此用户
for au in auserl:
print(au.id)
try:
iu = models.Institution.objects.get(user_id = au.id)
except models.Institution.DoesNotExist:
iu = None
try:
tu = models.Teacher.objects.get(user_id = au.id)
except models.Teacher.DoesNotExist:
tu = None
try:
pu = models.Parent.objects.get(user_id = au.id)
except models.Parent.DoesNotExist:
pu = None
if iu is not None:
if iu.PhoneNumber == phone:
au.set_password(<PASSWORD>)
au.save()
return render(request,"User/login.html",)
if tu is not None:
if tu.PhoneNumber == phone:
au.set_password(<PASSWORD>)
au.save()
return render(request,"User/login.html",)
if pu is not None:
if pu.PhoneNumber == phone:
au.set_password(<PASSWORD>)
au.save()
return render(request,"User/login.html",)
return render(request,"User/find.html",)
<file_sep># Generated by Django 2.2.1 on 2019-06-27 12:00
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('course', '0002_course_comment'),
]
operations = [
migrations.AlterField(
model_name='course_comment',
name='comment_parent',
field=models.ForeignKey(db_column='parent_id', on_delete=django.db.models.deletion.CASCADE, to='User.Teacher', verbose_name='评价者'),
),
migrations.AlterField(
model_name='course_comment',
name='course_id',
field=models.ForeignKey(db_column='course_id', on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base', verbose_name='被评价课程'),
),
]
<file_sep>from django.contrib import admin
from django.urls import path
from apps.inspage import views
app_name = 'inspage'
urlpatterns = [
#path('admin/',admin.site.urls),
#path('home/', views.home),
path(r'inst/<int:iid>',views.Inst),
path(r'isearch/',views.isearch),
path(r'tsearch/',views.tsearch),
]
<file_sep>from django.urls import path
from apps.homepage import views
app_name = 'homepage'
urlpatterns = [
path(r'HomePage/',views.VisitHomePage),
path(r'index/',views.VisitIndex),
]
<file_sep>from django.shortcuts import render
from django.http import HttpResponse,JsonResponse,HttpResponseRedirect
from django.core import serializers
from django.forms.models import model_to_dict
from .models import Course_Base,Course_Comment,Parent
from apps.fundamental.CHINA_LOCATION.models import ChinaLocation
from apps.sab.models import Shopping_Cart
from apps.userHome.models import Temp_Lesson
import json
from django.urls import reverse
from django.shortcuts import redirect
# Create your views here.
def Course_Index(request):
return render(request,"courses.html")
def Single_Course_Index(request,course_id):
return render(request,"single_course.html")
def Search_Course(request):
print(request)
dict_arr = []
if request.method == 'GET':
txt = request.GET['search_input']
print(txt)
course_obj = Course_Base.objects.filter(course_contains__icontains=txt)
print(course_obj)
for i in course_obj:
dict_arr.append(i.to_dict())
res = {'test':1,'search_res':dict_arr}
print(res)
return render(request,"search_courses.html",res)
#todo: 时间未处理!!!
def Single_Course_Info(request,course_id):
course_obj = Course_Base.objects.get(id=course_id)
dict_obj = course_obj.to_dict()
dict_obj['province_name'] = ChinaLocation.objects.get(id=dict_obj['course_location_province']).name
dict_obj['city_name'] = ChinaLocation.objects.get(id=dict_obj['course_location_city']).name
dict_obj['distinct_name'] = ChinaLocation.objects.get(id=dict_obj['course_location_distinct']).name
#print(dict_obj)
return JsonResponse(dict_obj)
def All_Course_Info(request):
course_obj = Course_Base.objects.all()
dict_obj =[]
for i in course_obj:
dict_obj.append( i.to_dict())
return JsonResponse({'course_all':dict_obj})
def Scoring_Course(request):
pass
def Single_Course_Comment(request,course_id):
comment_set = Course_Comment.objects.filter(course_id=course_id)
dict_obj = []
for i in comment_set:
i_dict_temp = i.to_dict()
#print(i.comment_parent)
i_dict_temp['Parent_Name'] = i.comment_parent.PName
#print(i_dict_temp)
dict_obj.append(i_dict_temp)
return JsonResponse({'comment': dict_obj})
def Comment_Submit(request,course_id):
print("commet")
user_id = request.user.id
if request.user.id is not None and request.GET['comment_text'] is not None:
user_id = request.user.id
comment_text = request.GET['comment_text']
course_base_obj = Course_Base.objects.get(id=course_id)
parent_obj = Parent.objects.get(id = user_id)
comment = Course_Comment()
comment.course_id = course_base_obj
comment.body = comment_text
comment.comment_parent = parent_obj
comment.save()
return redirect(reverse('course:course_single', kwargs={'course_id':course_id}))
def Add_To_Cart(request,course_id):
uid= request.user.id
cid = course_id
amount = Course_Base.objects.get(id=course_id).course_price
if uid is not None and cid is not None:
cart = Shopping_Cart()
cart.Amount = amount
cart.C_id = cid
cart.P_id = uid
cart.save()
return redirect(reverse('course:course_single', kwargs={'course_id':course_id}))
def Add_To_Temp_Lesson(request,course_id):
uid = request.user.id
cid = course_id
obj = Temp_Lesson.objects.filter(person_id=uid,lesson_id=course_id)
if uid is not None and cid is not None and obj is None:
tl = Temp_Lesson()
tl.person_id = uid
tl.lesson_id = cid
tl.save()
return redirect(reverse('course:course_single', kwargs={'course_id':course_id}))
# 删文章
def article_delete(request, course_id,comment_id):
# 根据 id 获取需要删除的文章
article = Course_Comment.objects.get(id=comment_id)
# 调用.delete()方法删除文章
article.delete()
# 完成删除后返回文章列表
return redirect(reverse('course:course_single', kwargs={'course_id': course_id}))
<file_sep><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Alter Personal Information</title>
</head>
<body>
<form action="/sab/Pay/" method="post">
{% csrf_token %}
{% for item in data %}
{% for var in item %}
{{ var }}
{% endfor %}
<p></p>
{% endfor %}
<input type="submit" value="Pay">
</form>
</body>
</html><file_sep>from django.apps import AppConfig
class InspageConfig(AppConfig):
name = 'inspage'
<file_sep>from django.db import models
from django.db.models.fields.related import ManyToManyField
from django.db.models.fields import DateTimeField
from ..User.models import Age_Choice,Lesson_Direction,Teacher,Institution,Branch,Parent
from apps.fundamental.CHINA_LOCATION.models import ChinaLocation
class PrintableModel(models.Model):
def __repr__(self):
return str(self.to_dict())
def to_dict(self):
opts = self._meta
data = {}
for f in opts.concrete_fields + opts.many_to_many:
if isinstance(f, ManyToManyField):
if self.pk is None:
data[f.name] = []
else:
data[f.name] = list(f.value_from_object(self).values_list('pk', flat=True))
else:
data[f.name] = f.value_from_object(self)
return data
class Meta:
abstract = True
#假定所有课均是每周一次
class Course_Base(models.Model):
course_location_province = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE, \
related_name='course_province',verbose_name="所在省份")
course_location_city = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE ,\
related_name='course_city',verbose_name="所在城市")
course_location_distinct = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE, \
related_name='course_distinct',verbose_name="所在区")
course_name=models.CharField(max_length=50,null=False,verbose_name="课程名称")
course_teacher = models.CharField(max_length=30, verbose_name='授课老师')
course_subject = models.CharField(max_length=10,choices=Lesson_Direction,verbose_name="课程方向")
course_age = models.CharField(max_length=10,choices=Age_Choice,verbose_name='课程适用年龄')
course_contains = models.CharField(max_length=500, blank=True, verbose_name="课程内容")
course_time = models.DateTimeField(verbose_name="首次课时间")
weeks_choice = [(12,"一季"),(26,"半年"),(52,"一年"),(104,"两年")]
course_duration_of_week = models.IntegerField(choices=weeks_choice)
course_price = models.IntegerField(default=0,verbose_name='课程价格')
# 课程地点
course_location = models.CharField(max_length=20, default="UNKOWN LOCATION", \
null=False, verbose_name="上课地点")
course_homework = models.TextField(max_length=500,blank=True,verbose_name='课程作业')
class Meta:
db_table = 'Course_Base'
def __repr__(self):
return str(self.to_dict())
def to_dict(self, fields=None, exclude=None):
data = {}
for f in self._meta.concrete_fields + self._meta.many_to_many:
value = f.value_from_object(self)
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
if isinstance(f, ManyToManyField):
value = [i.id for i in value] if self.pk else None
if isinstance(f, DateTimeField):
print(value)
value =""
data[f.name] = value
return data
# class Course(models.Model):
# course_base_id = models.ForeignKey(Course_Base,on_delete=models.CASCADE,null=False)
#
# # 课程地点
# course_location = models.CharField(max_length=20, default="UNKOWN LOCATION", \
# null=False, verbose_name="上课地点")
#
# #本次课时间由首次课时间,一周一节推算出来
# course_time = models.DateTimeField(verbose_name="本次课时间")
#
# course_homework = models.TextField(max_length=500,verbose_name='课程作业')
#
# class Meta:
# db_table = 'Course'
# ForeignKey,ManyToManyField与OneToOneField分别在Model中定义多对一,多对多,一对一关系。
class Course_Institution(models.Model):
course_id = models.ForeignKey(Course_Base,on_delete=models.CASCADE,\
related_name='Course_by_Ins',verbose_name='机构所授课程',null=False)
course_ins = models.ForeignKey(Branch,on_delete=models.CASCADE,\
related_name='Ins_for_Course',verbose_name='机构名称')
class Meta:
db_table = 'Course_Institution'
class Course_Teacher(models.Model):
course_id = models.ForeignKey(Course_Base,on_delete=models.CASCADE,\
related_name='Course_by_Teacher',verbose_name='教师所授课程')
course_teacher = models.ForeignKey(Teacher,on_delete=models.CASCADE,\
related_name='Teacher_for_course',verbose_name='教师名称')
class Meta:
db_table = 'Course_Teacher'
#课程评分
class Course_Score(models.Model):
course_id = models.ForeignKey(Course_Base,on_delete=models.CASCADE,\
related_name='Course',verbose_name='被评分课程')
course_score = models.SmallIntegerField(verbose_name='课程评分')
class Meta:
db_table = 'Course_Score'
class Course_Comment(models.Model):
course_id = models.ForeignKey(Course_Base,on_delete=models.CASCADE,\
db_column='course_id',verbose_name='被评价课程')
comment_parent = models.ForeignKey(Parent,on_delete=models.CASCADE,\
db_column='parent_id',verbose_name='评价者')
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created',)
def __str__(self):
return self.body[:20]
def to_dict(self, fields=None, exclude=None):
data = {}
for f in self._meta.concrete_fields + self._meta.many_to_many:
value = f.value_from_object(self)
if fields and f.name not in fields:
continue
if exclude and f.name in exclude:
continue
if isinstance(f, DateTimeField):
print(value)
value = value.strftime('%Y-%m-%d %H:%M:%S') if value else None
data[f.name] = value
return data
<file_sep>from django.db import models
# Create your models here.
class Image(models.Model):
image_id = models.IntegerField(primary_key=True,serialize=False,verbose_name="IMAGE_ID")
name= models.CharField(max_length=500,verbose_name="IMAGE_NAME")
imageFile= models.ImageField(upload_to='images/', verbose_name="IMAGE_URL")
def __str__(self):
return self.name + ": " + str(self.imageFile)
class Video(models.Model):
video_id = models.IntegerField(primary_key=True,serialize=False,verbose_name="video_ID")
name= models.CharField(max_length=500,verbose_name="VIDEO_NAME")
videoFile= models.FileField(upload_to='videos/', verbose_name="VIDEO_URL")
def __str__(self):
return self.name + ": " + str(self.videoFile)
<file_sep># Generated by Django 2.2.1 on 2019-06-26 15:19
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Teacher',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Name', models.CharField(max_length=32)),
('Age', models.IntegerField(default=0)),
('Sex', models.CharField(choices=[('Male', 'M'), ('Female', 'F')], max_length=6)),
('Id_num', models.CharField(max_length=18)),
('LDirection', models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], max_length=15)),
('Limyear', models.IntegerField(default=0)),
('Fitage', models.CharField(choices=[('All', 'All'), ('Primary', 'Pri'), ('Junior', 'Jun'), ('Senior', 'Sen')], max_length=15)),
('PhoneNumber', models.CharField(max_length=20)),
('Brief', models.CharField(max_length=80)),
('Wallet', models.FloatField(default=0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='Tea', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Parent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('PName', models.CharField(max_length=30)),
('KName', models.CharField(max_length=30)),
('Age', models.IntegerField()),
('Sex', models.CharField(choices=[('Male', 'M'), ('Female', 'F')], max_length=6)),
('PhoneNumber', models.CharField(max_length=11)),
('Birthday', models.DateField()),
('LDirection', models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], max_length=15)),
('FeeRange', models.IntegerField()),
('Area', models.CharField(max_length=10)),
('Wallet', models.FloatField(default=0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='POS', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Institution',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Id_num', models.CharField(max_length=18)),
('LDirection', models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], max_length=15)),
('Fitage', models.CharField(choices=[('All', 'All'), ('Primary', 'Pri'), ('Junior', 'Jun'), ('Senior', 'Sen')], max_length=15)),
('PhoneNumber', models.CharField(max_length=20)),
('Brief', models.CharField(max_length=80)),
('Wallet', models.FloatField(default=0)),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='Ins', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Branch',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Address', models.CharField(max_length=64)),
('LDirection', models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], max_length=15)),
('Fitage', models.CharField(choices=[('All', 'All'), ('Primary', 'Pri'), ('Junior', 'Jun'), ('Senior', 'Sen')], max_length=15)),
('PhoneNumber', models.CharField(max_length=20)),
('Ins', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Institution')),
],
),
migrations.CreateModel(
name='Admin',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='Adm', to=settings.AUTH_USER_MODEL)),
],
),
]
<file_sep>from django.db import models
from django.contrib.auth.models import User
from apps.fundamental.CHINA_LOCATION.models import ChinaLocation
# Create your models here.
Gender_Choice=(
('Male','M'),
('Female','F')
)
Lesson_Direction=(
('All','All'),
('Chinese','Chin'),
('Mathematics','Math'),
('English','Eng'),
('Physics','Phy'),
('Chemistry','Chem'),
('Biology','Bio'),
('History','His'),
('Geography','Geo'),
('Politics','Poli')
)
Age_Choice=(
('All','All'),
('Primary','Pri'),
('Junior','Jun'),
('Senior','Sen'),
)
class Parent(models.Model):
#Pid = models.IntegerField(primary_key=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='POS')
PName=models.CharField(max_length=30)
KName=models.CharField(max_length=30)
Age=models.IntegerField()
Sex=models.CharField(max_length=6,choices=Gender_Choice)
PhoneNumber=models.CharField(max_length=11)
LDirection=models.CharField(max_length=15,choices=Lesson_Direction,default = "All")
FeeRange=models.IntegerField(default= 3000)
Area=models.CharField(max_length=10,default = "All")
Wallet=models.FloatField(default=0)
class Teacher(models.Model):
#Tid = models.IntegerField(primary_key=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='Tea')
Name = models.CharField(max_length = 32)
Age = models.IntegerField(default=0)
Sex = models.CharField(max_length=6, choices=Gender_Choice)
Id_num = models.CharField(max_length = 18)
LDirection = models.CharField(max_length=15,choices=Lesson_Direction)
Limyear = models.IntegerField(default=0)#从教年限
Fitage =models.CharField(max_length=15,choices=Age_Choice)
PhoneNumber = models.CharField(max_length = 20)
Brief = models.CharField(max_length = 80)
Wallet=models.FloatField(default=0)
class Institution(models.Model):
#Iid = models.IntegerField(primary_key=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='Ins')
Id_num = models.CharField(max_length = 18)
LDirection = models.CharField(max_length=15,choices=Lesson_Direction)
Fitage =models.CharField(max_length=15,choices=Age_Choice)
PhoneNumber = models.CharField(max_length = 20)
Brief = models.CharField(max_length = 80)
Wallet=models.FloatField(default=0)
name = models.CharField(max_length=30,default='待填写')
class Branch(models.Model):
Ins = models.ForeignKey(Institution,on_delete=models.CASCADE)
branch_province = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE, \
related_name='branch_province',verbose_name="所在省份")
branch_city = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE , \
related_name='branch_city',verbose_name="所在城市")
branch_distinct = models.ForeignKey(ChinaLocation,on_delete=models.CASCADE, \
related_name='branch_distinct',verbose_name="所在区")
Address = models.CharField(max_length=50,default=None)
LDirection = models.CharField(max_length=15,choices=Lesson_Direction)
Fitage =models.CharField(max_length=15,choices=Age_Choice)
PhoneNumber = models.CharField(max_length = 20)
class Admin(models.Model):
Aid = models.IntegerField(primary_key=True)
user = models.OneToOneField(User,on_delete=models.CASCADE,related_name='Adm')
<file_sep>from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from .models import ChinaLocation
# Create your views here.
# 级联菜单
def getAreas(request):
return render(request,'china_location/location_test.html')
#获得省份
def getProvince(request):
provinces = ChinaLocation.objects.filter(level=1)
res = []
for i in provinces:
res.append( [i.id , i.name] )
return JsonResponse({'provinces':res})
#获得城市
def getCity(request):
city_id = request.GET.get('city_id')
cities = ChinaLocation.objects.filter(parent_id =city_id)
res = []
for i in cities:
res.append([i.id, i.name])
return JsonResponse({'cities':res})
#获得区 县
def getDistrict(request):
district_id = request.GET.get('district_id')
cities = ChinaLocation.objects.filter(parent_id =district_id)
res = []
for i in cities:
res.append([i.id, i.name])
return JsonResponse({'district': res})
def getAll(request):
province_id = request.GET.get('province_id')
city_id = request.GET.get('city_id')
district_id = request.GET.get('district_id')
province_name = ChinaLocation.objects.get(id= province_id).name
city_name = ChinaLocation.objects.get(id=city_id).name
district_name = ChinaLocation.objects.get(id= district_id).name
res = {province_id:province_name,city_id:city_name,district_id:district_name}
print(res)
return JsonResponse(res,safe=False)
<file_sep># Generated by Django 2.2.2 on 2019-06-27 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('User', '0006_merge_20190627_2050'),
]
operations = [
migrations.AlterField(
model_name='parent',
name='Area',
field=models.CharField(default='All', max_length=10),
),
migrations.AlterField(
model_name='parent',
name='FeeRange',
field=models.IntegerField(default=3000),
),
migrations.AlterField(
model_name='parent',
name='LDirection',
field=models.CharField(choices=[('All', 'All'), ('Chinese', 'Chin'), ('Mathematics', 'Math'), ('English', 'Eng'), ('Physics', 'Phy'), ('Chemistry', 'Chem'), ('Biology', 'Bio'), ('History', 'His'), ('Geography', 'Geo'), ('Politics', 'Poli')], default='All', max_length=15),
),
]
<file_sep>from django.shortcuts import render,redirect
from apps.course import models as insmodels
from apps.User import models as usemodels
from apps.fundamental.comment import models as fmodels
from django.contrib.auth import authenticate, login
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import auth
from functools import wraps
# Create your views here.
def Inst(request,iid = None):
Iid = iid
#print(Iid)
try:
inst = usemodels.Institution.objects.get(id = Iid)
except usemodels.Institution.DoesNotExist:
inst = None
if inst is not None:
#课程信息模块
bran = usemodels.Branch.objects.filter(Ins_id = inst.id).values("id")
bral = []
for bra in bran:
bral.append(bra['id'])
print(bral)
CofI = insmodels.Course_Institution.objects.filter(course_ins__in = bral)
cosl = []
for Cof in CofI:
course = insmodels.Course_Base.objects.get(id = Cof.course_id.id)
cosl.append(course)
#机构评论
'''
ComI = insmodels.Comment_Ins.objects.filter(com_ins = inst.id)
coml = []
for Com in ComI:
com = fmodels.Commenr_Ins.objects.get(id = Com.course_id.id)
'''
res = {"inst":inst,"cou":cosl}
return render(request,"ins/Ins.html",{'data':res})
return render(request,"ins/Ins.html",)
def isearch(request):
if request.method == "POST":
age = request.POST.get('Fitage',None)
ld = request.POST.get('LDirection',None)
print(age,ld)
if age is not None and age != 'All':
if ld is not None and ld != 'All':
relist = usemodels.Institution.objects.filter(Q(Fitage = age)&Q(LDirection = ld))
else:
relist = usemodels.Institution.objects.filter(Fitage = age)
else:
if ld is not None and ld != 'All':
relist = usemodels.Institution.objects.filter(LDirection = ld)
else:
relist = usemodels.Institution.objects.all()
wanted = []
for re in relist:
print(re)
wanted.append(re)
return render(request,"ins/ires.html",{'data':wanted})
return render(request,"ins/isearch.html",)
def isearch(request):
if request.method == "POST":
age = request.POST.get('Fitage',None)
ld = request.POST.get('LDirection',None)
print(age,ld)
if age is not None and age != 'All':
if ld is not None and ld != 'All':
relist = usemodels.Institution.objects.filter(Q(Fitage = age)&Q(LDirection = ld))
else:
relist = usemodels.Institution.objects.filter(Fitage = age)
else:
if ld is not None and ld != 'All':
relist = usemodels.Institution.objects.filter(LDirection = ld)
else:
relist = usemodels.Institution.objects.all()
wanted = []
for re in relist:
print(re)
wanted.append(re)
return render(request,"ins/ires.html",{'data':wanted})
return render(request,"ins/isearch.html",)
def tsearch(request):
if request.method == "POST":
age = request.POST.get('Fitage',None)
ld = request.POST.get('LDirection',None)
print(age,ld)
if age is not None and age != 'All':
if ld is not None and ld != 'All':
relist = usemodels.Teacher.objects.filter(Q(Fitage = age)&Q(LDirection = ld))
else:
relist = usemodels.Teacher.objects.filter(Fitage = age)
else:
if ld is not None and ld != 'All':
relist = usemodels.Teacher.objects.filter(LDirection = ld)
else:
relist = usemodels.Teacher.objects.all()
wanted = []
for re in relist:
print(re)
wanted.append(re)
return render(request,"ins/tres.html",{'data':wanted})
return render(request,"ins/tsearch.html",)
<file_sep># Create your models here.
from django.db import models
from django.contrib.auth.models import User
# timezone 用于处理时间相关事务。
from django.utils import timezone
from django.urls import reverse
# 博客文章数据模型
class News(models.Model):
# 文章作者。参数 on_delete 用于指定数据删除的方式
author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='作者')
# 文章标题。models.CharField 为字符串字段,用于保存较短的字符串,比如标题
title = models.CharField(max_length=100,verbose_name='标题')
# 文章正文。保存大量文本使用 TextField
body = models.TextField(verbose_name='内容')
# 文章创建时间。参数 default=timezone.now 指定其在创建数据时将默认写入当前的时间
created = models.DateTimeField(default=timezone.now)
# 文章更新时间。参数 auto_now=True 指定每次数据更新时自动写入当前时间
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
# 获取文章地址
def get_absolute_url(self):
return reverse('article:article_detail', args=[self.id])
class Announcement(models.Model):
# 文章作者。参数 on_delete 用于指定数据删除的方式
author = models.ForeignKey(User, on_delete=models.CASCADE,verbose_name='作者')
# 文章标题。models.CharField 为字符串字段,用于保存较短的字符串,比如标题
title = models.CharField(max_length=100,verbose_name='标题')
# 文章正文。保存大量文本使用 TextField
body = models.TextField(verbose_name='内容')
# 文章创建时间。参数 default=timezone.now 指定其在创建数据时将默认写入当前的时间
created = models.DateTimeField(default=timezone.now)
# 文章更新时间。参数 auto_now=True 指定每次数据更新时自动写入当前时间
updated = models.DateTimeField(auto_now=True)
class Meta:
ordering = ('-author',)
def __str__(self):
return self.title
# 获取文章地址
def get_absolute_url(self):
return reverse('Announcement:Announcement_detail', args=[self.id])
<file_sep>from django.contrib import admin
from .models import News,Announcement
admin.site.register(News)
admin.site.register(Announcement)
# Register your models here.
<file_sep># Generated by Django 2.2.1 on 2019-06-28 02:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('course', '0004_auto_20190627_2206'),
('User', '0007_auto_20190627_2206'),
]
operations = [
migrations.CreateModel(
name='Shopping_Cart',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Amount', models.IntegerField()),
('C', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base')),
('P', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Parent')),
],
),
migrations.CreateModel(
name='Pay_Record',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('CName', models.CharField(max_length=50)),
('Amount', models.IntegerField()),
('TPrice', models.FloatField()),
('Time', models.DateTimeField()),
('C', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base')),
('P', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Parent')),
],
),
]
<file_sep>from django.apps import AppConfig
class ChinaLocationConfig(AppConfig):
name = 'CHINA_LOCATION'
<file_sep># Generated by Django 2.2.2 on 2019-06-27 12:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('User', '0004_remove_parent_birthday'),
('User', '0005_institution_name'),
]
operations = [
]
<file_sep>from django.contrib import admin
from django.urls import path,include
from . import views
app_name = 'userHome'
urlpatterns = [
path(r'',views.dispatch),
path('TeacherInformation',views.TeacherInfo),
path(r'tChangeInfo',views.change_t_info),
path(r'SetCourse',views.set_course),
path(r'tlesson',views.all_tlesson),
path(r'announcement',views.show_announcement),
path(r'Addannouncement',views.add_announcement),
path(r'Updateannouncement',views.update_announcement),
path(r'AddCourse',views.add_course),
path('UpdateCourse/<int:cid>/',views.update_course),
path('InstitutionInfo/<int:bid>/',views.insinfo),
path('InstitutionInfo/<int:bid>/ChooseBranch',views.choosebranch),
path('InstitutionInfo/<int:bid>/AddBranch',views.addbranch),
path('InstitutionInfo/<int:bid>/SetCourse',views.set_course),
path('InstitutionInfo/<int:bid>/AddCourse',views.add_course),
path('InstitutionInfo/<int:bid>/InsChangeInfo',views.change_i_info),
path('InstitutionInfo/<int:bid>/tlesson',views.all_tlesson),
path('InstitutionInfo/<int:bid>/Addannouncement',views.add_announcement),
path('InstitutionInfo/<int:bid>/announcement',views.show_announcement),
path('InstitutionInfo/<int:bid>/Updateannouncement',views.update_announcement),
path('InstitutionInfo/<int:bid>/UpdateCourse/<int:cid>/',views.update_course),
path(r'ParentPage/',views.VisitPPage),
path(r'updatePinfo/',views.VisitUpPInfo),
path(r'UpPInfo/',views.VisitUpPInfo),
path(r'UpPInfo-Submit/',views.VisitPPageMB),
path(r'ParentPageG/',views.VisitPPageG),
path(r'ParentPageC/',views.VisitPPageC),
path(r'ParentPageA/',views.VisitPPageA),
]<file_sep># Generated by Django 2.2.2 on 2019-06-27 06:47
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('CHINA_LOCATION', '0001_initial'),
('User', '0002_auto_20190627_0226'),
]
operations = [
migrations.RemoveField(
model_name='branch',
name='Address',
),
migrations.AddField(
model_name='branch',
name='branch_city',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='branch_city', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在城市'),
preserve_default=False,
),
migrations.AddField(
model_name='branch',
name='branch_distinct',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='branch_distinct', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在区'),
preserve_default=False,
),
migrations.AddField(
model_name='branch',
name='branch_province',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, related_name='branch_province', to='CHINA_LOCATION.ChinaLocation', verbose_name='所在省份'),
preserve_default=False,
),
]
<file_sep># -*- coding: utf-8 -*-
from apps.User.models import Parent
from apps.course.models import Course_Base
from apps.userHome.models import Temp_Lesson
from apps.sab.models import Pay_Record
import datetime,time
def UpdateInfo(request):
p=Parent.objects.get(id=1)
if request.POST.get('PName')!='':
p.PName=request.POST.get('PName')
if request.POST.get('KName')!='':
p.KName=request.POST.get('KName')
if request.POST.get('Age')!='':
p.Age=request.POST.get('Age')
if request.POST.get('Sex')!='':
p.Sex=request.POST.get('Sex')
if request.POST.get('PhoneNumber')!='':
p.PhoneNumber=request.POST.get('PhoneNumber')
if request.POST.get('LDirection')!='':
p.LDirection=request.POST.get('LDirection')
if request.POST.get('FeeRange')!='':
p.FeeRange=request.POST.get('FeeRange')
if request.POST.get('Area')!='':
p.Area=request.POST.get('Area')
if request.POST.get('Wallet')!='':
p.Wallet=request.POST.get('Wallet')
p.save()
def Recharge(request):
p=Parent.objects.get(id=1)
if request.POST.get('Wallet')!='':
p.Wallet+=float(request.POST.get('Wallet'))
p.save()
def ApplyAudi(request):
p=Parent.objects.get(id=1)
c=Course_Base.objects.get(id=1)
now = datetime.datetime.now()
if(c.course_time.replace(tzinfo=None)>now):
tl=Temp_Lesson(person_id=p.id,lesson_id=c.id)
tl.save()
return True
return False
def ParentPage(request):
p=Parent.objects.get(id=1)
rlt={}
rlt['name']=p.PName
rlt['money']=p.Wallet
return rlt
#模块事务
def UpdatePInfo(request):
p=Parent.objects.get(id=1)
if request.POST.get('PhoneNumber')!='':
p.PhoneNumber=request.POST.get('PhoneNumber')
if request.POST.get('LDirection')!='':
p.LDirection=request.POST.get('LDirection')
if request.POST.get('FeeRange')!='':
p.FeeRange=request.POST.get('FeeRange')
if request.POST.get('Area')!='':
p.Area=request.POST.get('Area')
p.save()
def GetPInfo(request):
rlt={}
p=Parent.objects.get(id=1)
rlt['PName']=p.PName
rlt['KName']=p.KName
rlt['Age']=p.Age
rlt['Sex']=p.Sex
rlt['PhoneNumber']=p.PhoneNumber
rlt['LDirection']=p.LDirection
rlt['FeeRange']=p.FeeRange
rlt['Area']=p.Area
rlt['Wallet']=p.Wallet
return rlt
def GetSchedule(request):
rlt=[]
p=Parent.objects.get(id=1)
py=Pay_Record.objects.filter(P_id=p.id)
for var in py:
c=Course_Base.objects.get(id=var.C_id)
temp={}
temp['name']=c.course_name
temp['time']=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(c.course_time))
temp['province']=c.course_location_province.name
temp['city']=c.course_location_city.name
temp['distinct']=c.course_location_distinct.name
temp['location']=c.course_location
rlt.append(temp)
return rlt
def GetAudition(request):
rlt=[]
p=Parent.objects.get(id=1)
tl=Temp_Lesson.objects.filter(person_id=p.id)
for var in tl:
c=Course_Base.objects.get(id=var.lesson_id)
temp={}
temp['name']=c.course_name
temp['flag']=var.state
rlt.append(temp)
return rlt
<file_sep>from django.contrib import admin
from django.urls import path
from apps.User import views
app_name = 'User'
urlpatterns = [
#path('admin/',admin.site.urls),
path(r'register/', views.regChoice),
path(r'login/', views.login),
path(r'login/login-form.html', views.Slogin),
path(r'register3/',views.POSreg),
path(r'register2/',views.Teareg),
path(r'register1/',views.Insreg),
path(r'Admreg/',views.Admreg),
path(r'POS/',views.POS),
path(r'Tea/',views.Tea),
path(r'Adm/',views.Adm),
#模板url
path(r'find/',views.Find),
path(r'logout/',views.logout)
]
<file_sep>
from django.shortcuts import render
from .models import Image,Video
from .form import ImageForm,VideoForm
def showimage(request):
lastimage = Image.objects.last()
imagefile = lastimage.imageFile
form = ImageForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context = {'imagefile': imagefile,
'form': form
}
return render(request, 'Storage/PostImage.html', context)
def showvideo(request):
lastvideo = Video.objects.last()
videofile = lastvideo.videoFile
form = VideoForm(request.POST or None, request.FILES or None)
if form.is_valid():
form.save()
context = {'videofile': videofile,
'form': form
}
return render(request, 'Storage/PostVideo.html', context)
<file_sep># Generated by Django 2.2.2 on 2019-06-26 19:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('article', '0005_auto_20190626_1447'),
('storage', '0003_auto_20190617_1555'),
('course', '0001_initial'),
('User', '0002_auto_20190627_0226'),
]
operations = [
migrations.CreateModel(
name='Video_Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order', models.IntegerField()),
('VO', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='storage.Video')),
],
),
migrations.CreateModel(
name='Teacher_Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order', models.IntegerField()),
('TO', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Teacher')),
],
),
migrations.CreateModel(
name='News_Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order', models.IntegerField()),
('NO', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='article.News')),
],
),
migrations.CreateModel(
name='Insti_Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order', models.IntegerField()),
('IO', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Institution')),
],
),
migrations.CreateModel(
name='Course_Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('Order', models.IntegerField()),
('CO', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base')),
],
),
]
<file_sep># Generated by Django 2.2.1 on 2019-06-27 11:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('User', '0005_institution_name'),
('course', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Course_Comment',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('body', models.TextField()),
('created', models.DateTimeField(auto_now_add=True)),
('comment_parent', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='User.Teacher', verbose_name='评价者')),
('course_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='course.Course_Base', verbose_name='被评价课程')),
],
options={
'ordering': ('created',),
},
),
]
<file_sep># Generated by Django 2.2.2 on 2019-06-27 04:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('userHome', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='temp_lesson',
name='lesson',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tll', to='course.Course_Base', verbose_name='视听课程'),
),
migrations.AlterField(
model_name='temp_lesson',
name='person',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tlp', to='User.Parent', verbose_name='试听用户'),
),
migrations.AlterField(
model_name='temp_lesson',
name='state',
field=models.CharField(default='待审核', max_length=8),
),
]
<file_sep>from django.db import models
# Create your models here.
from apps.User.models import Parent
from apps.course.models import Course_Base
class Temp_Lesson(models.Model):
person = models.ForeignKey(Parent,on_delete=models.CASCADE,verbose_name='试听用户',related_name='tlp')
lesson = models.ForeignKey(Course_Base,on_delete=models.CASCADE,verbose_name='视听课程',related_name='tll')
state = models.CharField(max_length=8,default='待审核')
class Meta:
unique_together = ('person', 'lesson')<file_sep>from django.db import models
from django.contrib.auth.models import User
from ..article.models import News
# 博文的评论
class Comment(models.Model):
News = models.ForeignKey(
News,
on_delete=models.CASCADE,
related_name='comments'
)
user = models.ForeignKey(
User,
on_delete=models.CASCADE,
related_name='comments'
)
body = models.TextField()
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('created',)
def __str__(self):
return self.body[:20]
<file_sep><html>
<head>
<meta charset="UTF-8">
<title>Upload Videos</title>
</head>
<body>
<h1>Video Uploader</h1>
<form enctype="multipart/form-data" method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Upload"/>
</form>
<br><br>
<video width='400' controls>
<source src='{{ MEDIA_URL }}{{ videofile }}' type='video/mp4'>
Your browser does not support the video tag.
</video>
<br><br>
</p>
</body>
</html>
<file_sep>INSERT INTO
Course_Base
(id, course_name, course_teacher, course_subject,
course_age, course_contains, course_time, course_duration_of_week,
course_price, course_location, course_homework,
course_location_city_id, course_location_province_id, course_location_distinct_id)
VALUES (1, '高等数学', '王老师', '数学', '10', '微积分1/2/3', '1561565200274', 12, 100, '2699号', '高等数学作业', 1, 1, 1),
(2, '无机化学', '张老师', '化学', '10', '无机化学1/2/3', '1561565200274', 12, 100, '2699号', '无机化学作业', 1, 1, 1);<file_sep># -*- coding: utf-8 -*-
from apps.User.models import Parent,Institution,Teacher
from apps.course.models import Course_Base,Course_Institution,Course_Teacher
from apps.sab.models import Shopping_Cart,Pay_Record
import datetime
from django.http import JsonResponse
def AddToCart(request):
p=Parent.objects.get(id=1)
c=Course_Base.objects.get(id=1)
if request.POST.get('Amount')!='':
sc=Shopping_Cart(P_id=p.id,C_id=c.id,Amount=request.POST.get('Amount'))
sc.save()
def CheckCart(request):
CourseList=[]
p=Parent.objects.get(id=1)
sc=Shopping_Cart.objects.filter(P_id=p.id)
if sc!=None:
CartList=list(sc)
for var in CartList:
temp=[]
c=Course_Base.objects.get(id=var.C_id)
temp.append(c.course_name)
temp.append(c.course_price)
temp.append(var.Amount)
CourseList.append(temp)
return CourseList
def ResetCart(request):
p=Parent.objects.get(id=1)
sc=Shopping_Cart.objects.filter(P_id=p.id)
if sc!=None:
for var in sc:
var.delete()
return True
else:
return False
def Pay(request):
total=0
p=Parent.objects.get(id=1)
response=Shopping_Cart.objects.filter(P_id=p.id)
PayList=list(response)
for var in PayList:
total+=Course_Base.objects.get(id=var.C_id).course_price*var.Amount
if p.Wallet<total:
return False
else:
for var in PayList:
c=Course_Base.objects.get(id=var.C_id)
SinglePrice=c.course_price*var.Amount
pr=Pay_Record(P_id=var.P_id,C_id=c.id,CName=c.course_name,Amount=var.Amount,TPrice=SinglePrice,Time=datetime.datetime.now())
pr.save()
p.Wallet-=SinglePrice
p.save()
ci=Course_Institution.objects.filter(course_id=var.C_id)
if ci:
i=Institution.objects.get(id=Course_Institution.objects.get(course_id=var.C_id).course_ins.id)
i.Wallet+=SinglePrice
i.save()
else:
ct=Course_Teacher.objects.get(course_id=var.C_id)
t=Teacher.objects.get(id=ct.course_teacher.id)
t.Wallet+=SinglePrice
t.save()
var.delete()
return True
#模块事务
def UpdatePWallet(request):
p=Parent.objects.get(id=1)
if request.POST.get('money')!='':
p.Wallet+=int(request.POST.get('money'))
p.save()
def GetRecord(request):
rlt=[]
p=Parent.objects.get(id=1)
py=Pay_Record.objects.filter(P_id=p.id)
for var in py:
temp={}
temp['name']=var.CName
temp['time']=var.Time.strftime("%Y-%m-%d %H:%M:%S")
temp['price']=var.TPrice
temp['amount']=var.Amount
rlt.append(temp)
return rlt
def GetCart(request):
rlt=[]
p=Parent.objects.get(id=1)
sc=Shopping_Cart.objects.filter(P_id=p.id)
for var in sc:
c=Course_Base.objects.get(id=var.C_id)
temp={}
temp['name']=c.course_name
temp['price']=c.course_price
temp['amount']=var.Amount
temp['total']=c.course_price*var.Amount
rlt.append(temp)
return rlt
<file_sep>from django.shortcuts import render
from django.http import HttpResponse
from apps.sab import Transaction
# Create your views here.
def VisitAddToCart(request):
return render(request,'AddToCart.html')
def VisitATResult(request):
Transaction.AddToCart(request)
return render(request,'ATResult.html')
def VisitResetCart(request):
Transaction.ResetCart(request)
print('Successful!')
return render(request,'AddToCart.html')
def VisitCheckCart(request):
return render(request,'CheckCart.html')
def VisitCheckResult(request):
return render(request,'CheckResult.html',{'data':Transaction.CheckCart(request)})
def VisitPay(request):
flag=Transaction.Pay(request)
if flag==False:
return HttpResponse('Fail!')
else:
return HttpResponse('Success!')
#模板views
def Visitvc(request):
return render(request,'view-cart.html')
def VisitPRecharge(request):
return render(request,'PRecharge.html')
def ReturnPPage(request):
Transaction.UpdatePWallet(request)
return render(request,'ParentPage.html')
def VisitPPageR(request):
rlt={}
rlt['data']=Transaction.GetRecord(request)
#print(rlt)
return render(request,'ParentPageR.html',rlt)
def VisitCart(request):
rlt={}
rlt['data']=Transaction.GetCart(request)
return render(request,'view-cart.html',rlt)
def ResetCart(request):
Transaction.ResetCart(request)
return VisitCart(request)
def PayForCart(request):
Transaction.Pay(request)
return VisitCart(request)
<file_sep>from django.contrib import admin
from .models import Teacher,Parent,Institution,Admin
# Register your models here.
admin.site.register(Teacher)
admin.site.register(Parent)
admin.site.register(Institution)
admin.site.register(Admin)<file_sep>from django.db import models
from apps.User.models import Parent
from apps.course.models import Course_Base
# Create your models here.
#购物车
class Shopping_Cart(models.Model):
P = models.ForeignKey(Parent,on_delete=models.CASCADE)
C = models.ForeignKey(Course_Base,on_delete=models.CASCADE)
Amount = models.IntegerField()
#付款记录
class Pay_Record(models.Model):
P = models.ForeignKey(Parent,on_delete=models.CASCADE)
C = models.ForeignKey(Course_Base,on_delete=models.CASCADE)
CName = models.CharField(max_length=50)
Amount = models.IntegerField()
TPrice = models.FloatField()
Time = models.DateTimeField()
<file_sep>from django.contrib import admin
from apps.fundamental.comment.models import Comment
# Register your models here.
admin.site.register(Comment)
|
1c603854340af284cb5bd7cc060429732211d86e
|
[
"SQL",
"HTML",
"Markdown",
"Python",
"Shell"
] | 63
|
Python
|
Gwzlchn/SE-Project-2019
|
aecb9dc6f924494f5a38716b7764e5a782260be7
|
73aae500758d4b00186b7a858f1643f5f4e4d5dc
|
refs/heads/master
|
<repo_name>frontjss/filtersv<file_sep>/filter/shop/views.py
import requests
from django.shortcuts import render, get_object_or_404, render_to_response, redirect
from django.utils.crypto import get_random_string
from .models import Category, Product
from filter.cart.forms import CartAddProductForm
from django.template.context_processors import csrf
from django.views.generic import View
from django_tinkoff_merchant.services import MerchantAPI, PaymentHTTPException
from django_tinkoff_merchant.models import Payment
from filter.orders.models import Order
from .models import Category, Product
# Страница с товарами
def ProductList(request, category_slug=None):
category = None
categories = Category.objects.all()
products = Product.objects.filter(available=True)
if category_slug:
category = get_object_or_404(Category, slug=category_slug)
products = products.filter(category=category)
return render(request, 'shop/product/list.html', {
'category': category,
'categories': categories,
'products': products
})
# Страница товара
# def ProductDetail(request, id, slug):
# product = get_object_or_404(Product, id=id, slug=slug, available=True)
# cart_product_form = CartAddProductForm()
# return render_to_response('shop/product/detail.html',
# {'product': product,
# 'cart_product_form': cart_product_form})
def ProductDetail(request, id, slug):
product = get_object_or_404(Product, id=id, slug=slug, available=True)
cart_product_form = CartAddProductForm()
context = {'product': product, 'cart_product_form': cart_product_form}
context.update(csrf(request))
return render_to_response('shop/product/detail.html', context)
telegram = {}
def teles(request):
return render(request, 'main.html')
def tele(request):
if request.POST:
if request.POST.get('name') == "<NAME>":
a = {"name": None}
telegram.update(a)
else:
a = {"name": request.POST.get('name')}
telegram.update(a)
if request.POST.get('mail') == "E-mail":
a = {"mail": None}
telegram.update(a)
else:
a = {"mail": request.POST.get('mail')}
telegram.update(a)
if request.POST.get('phone') == "Мобильный телефон":
a = {"phone": None}
telegram.update(a)
else:
a = {"phone": request.POST.get('phone')}
telegram.update(a)
if request.POST.get('street') == "Адрес доставки":
a = {"street": None}
telegram.update(a)
else:
a = {"street": request.POST.get('street')}
telegram.update(a)
if request.POST.get('comm') == "Комментарий":
a = {"comm": None}
telegram.update(a)
else:
a = {"comm": request.POST.get('comm')}
telegram.update(a)
if request.POST.get('Installments') == "РАССРОЧКА":
a = {"Installments": "Да"}
telegram.update(a)
else:
a = {"Installments": "Нет"}
telegram.update(a)
text = """
Имя: %s
Телефон: %s
Почта: %s
Адрес: %s
Комментарий: %s
Рассрочка: %s
""" % (telegram['name'], telegram['phone'], telegram['mail'], telegram['street'], telegram['comm'], telegram['Installments'])
print(text)
if telegram['name']:
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=167315364&text=%s" % (text)
requests.post(url)
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=70025022&text=%s" % (text)
requests.post(url)
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=65472004&text=%s" % (text)
requests.post(url)
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=-303230127&text=%s" % (text)
requests.post(url)
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=34436430&text=%s" % (text)
requests.post(url)
url = "https://api.telegram.org/bot674994528:AAGIH14UqG-11arwRTtFmbPhKS0wID-Xr4E/sendMessage?chat_id=27390261&text=%s" % (text)
requests.post(url)
if request.POST.get('name'):
order = Order.objects.create(
first_name=request.POST.get('name'),
phone=request.POST.get('phone'),
email=request.POST.get('mail'),
address=request.POST.get('street'),
comment=request.POST.get('comm'),
installments=not request.POST.get('Installments') is None,
)
# amount in cents, order_id must be unique
payment = Payment(amount=14980 * 100, order_id=order.id)
MerchantAPI().init(payment).save()
if payment.can_redirect():
return redirect(payment.payment_url)
return render(request, 'ok.html', {})
else:
return render(request, 'ok.html', {})
<file_sep>/filter/shop/urls.py
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^merchant/', include('django_tinkoff_merchant.urls')), # callback
url(r'^(?P<category_slug>[-\w]+)/$', views.ProductList, name='ProductListByCategory'),
url(r'^(?P<id>\d+)/(?P<slug>[-\w]+)/$', views.ProductDetail, name='ProductDetail'),
# url(r'^$', views.ProductList, name='ProductList'),
url(r'^$', views.teles, name='main'),
url(r'tele$', views.tele, name='tele'),
]
|
74bf50edb3b7bac997bd895357f65e0d3d155d9f
|
[
"Python"
] | 2
|
Python
|
frontjss/filtersv
|
379f7f3cee4c13f22a0ccde63e2eea1f85df3299
|
df0fc69ca30fea531a2af253a534783e95df6165
|
refs/heads/master
|
<repo_name>kailashpatel2006/mysamplejenkinsproj<file_sep>/file.java
modified
added new line
added cod
|
e0d631b8ed1eca50f002b40d822716b8a87fac73
|
[
"Java"
] | 1
|
Java
|
kailashpatel2006/mysamplejenkinsproj
|
96abe146fc9c714226da155637eff549e95269cc
|
0a1518827751b36d4cbbf24b4d9400a445f6c5ad
|
refs/heads/master
|
<file_sep>'use strict';
import { Message } from './data/messages'
import {EventTarget} from 'event-target-shim'
export class PolynoteMessageEvent<T extends Message> extends CustomEvent<any> {
constructor(readonly message: T) {
super('message');
Object.freeze(this);
}
}
type ListenerCallback = (...args: any[]) => void
export type MessageListener = [typeof Message, ListenerCallback, boolean?];
const mainEl = document.getElementById('Main');
const socketKey = mainEl ? mainEl.getAttribute('data-ws-key') : null;
window.addEventListener("beforeunload", evt => {
const sess = SocketSession.tryGet;
if (sess && sess.isOpen) {
sess.close();
}
});
export class SocketSession extends EventTarget {
private static inst: SocketSession;
static get tryGet(): SocketSession | null {
if (SocketSession.inst)
return SocketSession.inst;
return null;
}
static get get() {
if (!SocketSession.inst) {
SocketSession.inst = new SocketSession()
}
return SocketSession.inst
}
socket: WebSocket;
listeners: any;
private constructor(public queue: Message[] = [], public messageListeners: MessageListener[] = []) {
super();
this.mkSocket();
}
mkSocket() {
const wsUrl = new URL(`ws?key=${socketKey}`, document.baseURI);
wsUrl.protocol = wsUrl.protocol === "https:" ? 'wss:' : 'ws';
this.socket = new WebSocket(wsUrl.href);
this.socket.binaryType = 'arraybuffer';
this.listeners = {
message: this.receive.bind(this),
open: this.opened.bind(this),
close: this.close.bind(this),
error: (event: Event) => this.dispatchEvent(new CustomEvent('error', { detail: { cause: event }}))
};
this.socket.addEventListener('message', this.listeners.message);
this.socket.addEventListener('open', this.listeners.open);
this.socket.addEventListener('close', this.listeners.close);
this.socket.addEventListener('error', this.listeners.error);
}
opened(event: Event) {
while (this.queue.length) {
this.send(this.queue.pop()!);
}
this.dispatchEvent(new CustomEvent('open'));
}
get isOpen() {
return this.socket && this.socket.readyState === WebSocket.OPEN;
}
get isConnecting() {
return this.socket && this.socket.readyState === WebSocket.CONNECTING;
}
get isClosed() {
return !this.socket || this.socket.readyState >= WebSocket.CLOSING;
}
send(msg: Message) {
if (this.isOpen) {
const buf = Message.encode(msg);
this.socket.send(buf);
} else {
this.queue.unshift(msg);
}
}
receive(event: Event) {
if (event instanceof MessageEvent) {
if (event.data instanceof ArrayBuffer) {
const msg = Message.decode(event.data);
this.dispatchEvent(new PolynoteMessageEvent(msg)); // this is how `request` works.
for (const handler of this.messageListeners) {
if (msg instanceof handler[0]) { // check not redundant even though IntelliJ complains.
const result = handler[1].apply(null, handler[0].unapply(msg));
if (handler[2] && result === false) {
this.removeMessageListener(handler);
}
}
}
} else {
//console.log(event.data);
}
}
}
addMessageListener(msgType: typeof Message, fn: ListenerCallback, removeWhenFalse: boolean = false) {
const handler: MessageListener = [msgType, fn, removeWhenFalse];
this.messageListeners.push(handler);
return handler;
}
removeMessageListener(handler: MessageListener) {
const index = this.messageListeners.indexOf(handler);
if (index >= 0) {
this.messageListeners.splice(index, 1);
}
}
listenOnceFor(msgType: typeof Message, fn: ListenerCallback) {
return this.addMessageListener(msgType, fn, true);
}
/**
* Send a request and listen for the response. The message must properly implement the isResponse method.
*/
request<T extends Message>(msg: T) {
return new Promise<T>((resolve, reject) => {
this.addEventListener('message', (evt: PolynoteMessageEvent<T>) => {
if (msg.isResponse(evt.message)) {
resolve(evt.message);
return true; // so it gets removed.
} else return false;
}, /*removeWhenFalse*/ true);
this.send(msg);
});
}
close() {
if (this.socket.readyState < WebSocket.CLOSING) {
this.socket.close();
}
for (const l in this.listeners) {
if (this.listeners.hasOwnProperty(l)) {
this.socket.removeEventListener(l, this.listeners[l]);
}
}
this.listeners = {};
this.dispatchEvent(new CustomEvent('close'));
}
reconnect(onlyIfClosed: boolean) {
if (!this.socket || this.isClosed || (!onlyIfClosed && (this.socket.readyState > WebSocket.CONNECTING))) {
this.close();
this.mkSocket();
}
}
}
|
e8f55ecf4c3ee6a03628cd893a3e62eab67ffbbd
|
[
"TypeScript"
] | 1
|
TypeScript
|
garynth41/polynote
|
40a17c3b8fab4793632ad06c2c360fc592f00406
|
f69249c5b9f34960cc5c2f24661cdc30d8b28c84
|
refs/heads/master
|
<repo_name>absent1706/gae-error-reporting-demo<file_sep>/main.py
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# [START app]
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
"""Return a friendly HTTP greeting."""
return 'Hello World!'
@app.route('/500')
def err_500():
"""Return a friendly HTTP greeting."""
# return '500 page', 500
import json, os, errno, random, traceback
try:
raise ValueError('value')
except Exception as e:
data = {
"serviceContext": {
"service": "default",
"version": os.environ.get('GAE_MODULE_VERSION', 'default')
},
"message": traceback.format_exc(),
}
filename = '/var/log/app_engine/custom_logs/errors.log.json'
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename), 0777)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
with open(filename, 'a+') as file:
file.write('\n'+json.dumps(data))
raise
# raise
return '500 page', 500
if __name__ == '__main__':
# This is used when running locally. Gunicorn is used to run the
# application on Google App Engine. See entrypoint in app.yaml.
app.run(host='127.0.0.1', port=8081, debug=True)
# [END app]
<file_sep>/README.md
# gae-error-reporting-demo
Write errors to custom log file: https://cloud.google.com/error-reporting/docs/setup/app-engine-flexible-environment
```
virtualenv env
env\Scripts\activate.bat
pip install -r requirements.txt
python main.py
gcloud app deploy --project=<PROJECT> --version v1
```
|
7601518304fd82ce84934935e49fbd0c49856ae5
|
[
"Markdown",
"Python"
] | 2
|
Python
|
absent1706/gae-error-reporting-demo
|
211c36271254f2d159c59c20a26edca070df3662
|
7c9aa5e7a99135ab3f0af6d20dfa4da31d172595
|
refs/heads/master
|
<repo_name>luguotao846211/react-ts-demo<file_sep>/src/index.js
import React from 'react'
import ReactDOM from 'react-dom'
import App from 'Src/App'
import './index.less'
if (module && module.hot) {
module.hot.accept()
}
ReactDOM.render(<App name='123' />, document.querySelector('#root'))
|
97e60874f1f354285338fc1e8826562df9f6f8e7
|
[
"JavaScript"
] | 1
|
JavaScript
|
luguotao846211/react-ts-demo
|
5f529cfa168d9450d845394cf306a14eb13d3feb
|
b8654529ccfec79668272d59d0fac0dc972713d2
|
refs/heads/master
|
<repo_name>jppotess/twilio-contact-info-node<file_sep>/messaging.js
// Messaging functionality
var config = require('./config');
var client = require('twilio')(config.accountSid, config.authToken);
client.sendMessage({
to: config.testNumber,
from: config.twilioNumber,
body: "Here's Johnny!"
}, function(error, message) {
if (error) {
console.log('An error has occurred: ' + error);
} else {
console.log('Message Sent! Message:');
console.log(message.sid);
}
});
<file_sep>/README.md
# Send Contact Info with Twilio and Node
### To Do
- [ ] Handle inbound SMS
- [ ] Different inbound options
- [ ] Replies
- [ ] vCard
- [ ] portfolio links
|
59677f2c98416476c8700eef4d82cd6cfebcb348
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
jppotess/twilio-contact-info-node
|
5d9ef260bb6a7c6ca813086db7d7facd419bed38
|
10f1e0a7b6a0c6a05af9089ca51ed809b023790d
|
refs/heads/master
|
<file_sep>
const fi = (function() {
return {
libraryMethod: function() {
return 'Start by reading https://medium.com/javascript-scene/master-the-javascript-interview-what-is-functional-programming-7f218c68b3a0'
},
each: function(collection, func) {
let dataSet = (collection instanceof Array) ? collection : Object.values(collection)
for(let i = 0; i < dataSet.length; i++) {
func(dataSet[i])
};
return collection
},
map: function(collection, func) {
let dataSet = (collection instanceof Array) ? collection : Object.values(collection)
let newCollection = []
for(let i = 0; i < dataSet.length; i++) {
newCollection.push(func(dataSet[i]))
}
return newCollection
},
reduce: function(collection, func, acc) {
if (!acc) {
acc = collection[0]
collection = collection.slice(1)
}
for(let i = 0; i < collection.length; i++) {
acc = func(acc, collection[i], collection)
}
return acc
},
find: function(collection, test) {
let dataSet = (collection instanceof Array) ? collection : Object.values(collection)
for(let i = 0; i < dataSet.length; i++) {
if (test(dataSet[i])) return dataSet[i]
}
return undefined
},
filter: function(collection, test) {
let passingValues = []
for(let i = 0; i < collection.length; i++) {
if (test(collection[i])) passingValues.push(collection[i])
}
return passingValues
},
size: function(collection) {
let dataSet = (collection instanceof Array) ? collection : Object.values(collection)
return dataSet.length
},
first: function(array, n) {
if (!n) {
return array[0]
} else {
return array.slice(0, n)
}
},
last: function(array, n) {
return (!n) ? array[array.length-1] : array.slice(array.length - n, array.length)
},
compact: function(array) {
let newArray = []
for(let i = 0; i < array.length; i++) {
if (array[i]) {
newArray.push(array[i])
}
}
return newArray
},
sortBy: function(collection, func) {
let newCollection = [...collection]
return newCollection.sort(function(a,b) {
return func(a) - func(b)
})
},
flatten: function(array, bool, newArray) {
// create new array if newArray is empty
if (!newArray){newArray = []}
if(bool) {
return newArray.concat.apply(newArray, array)
}
//iterate array, if element is num push into new array/ if element is array recurse
for(let i = 0; i < array.length; i++) {
if (Array.isArray(array[i])) {
this.flatten(array[i], bool, newArray)
} else {
newArray.push(array[i])
}
}
//return new array
return newArray
},
uniq: function(arr) {
return [... new Set(arr)]
},
keys: function(object) {
return Object.keys(object)
},
values: function(object) {
return Object.values(object)
},
functions: function(object) {
let array = []
for(let key in object){
if (typeof object[key] === "function"){
array.push(object[key])
}
}
return array
},
}
})()
fi.libraryMethod()
|
2cfb0a5b39898987312c04a57c5f2b1239ee16e5
|
[
"JavaScript"
] | 1
|
JavaScript
|
JTSwisher/js-advanced-functions-functional-library-project-onl01-seng-pt-100619
|
f6fd0831ff7f71124460096900ad5b49a94381a9
|
d12f5ab3cbaadbfc30add4d8edfb70f7ebec9319
|
refs/heads/master
|
<repo_name>cmercada86/GardenBotServer<file_sep>/models/water.go
package models
type(
Water struct{
time int
delay int
}
)<file_sep>/communication/gardencomm.go
package communication
import (
"encoding/json"
)
type (
GardenBotCommunication struct{}
)
type msg struct{
msgType string
value int
}
func NewGardenBotCommuncation() *GardenBotCommunication{
return &GardenBotCommunication{}
}
func (gbc GardenBotCommunication) QueryStatus(){
}
func (gbc GardenBotCommunication) StartWater(timeMin int){
}
func (gbc GardenBotCommunication) StopWater(){
}
func (gbc GardenBotCommunication) StartPump(timeMin int){
}
func (gbc GardenBotCommunication) StopPump(timeMin int){
}
func (gbc GardenBotCommunication) sendMsg()<file_sep>/controllers/water.go
package controllers
import (
"encoding/json"
"fmt"
"net/http"
"github.com/julienschmidt/httprouter"
)
type (
WaterController struct{}
)
func NewWaterController() * WaterController{
return &WaterController{}
}
func (wc WaterController) StartWater(w http.ResponseWriter){
}
|
23dd6c0f8a9bb79faa061f9670c89a59e677c534
|
[
"Go"
] | 3
|
Go
|
cmercada86/GardenBotServer
|
e03df829ba624767350d01734cc578793d3eb28c
|
c3851c7ec1b3a700e9ef37c5b9fc507713758022
|
refs/heads/master
|
<file_sep>----- Services -----
Le Loan approval est composé de 4 services dont 3 se trouvent sur Google App Engine et 1 sur Heroku.
Sur GAE se trouvent "AppManager", "AccManager" et "CheckAccount".
Sur Heroku se trouve le service "LoanApproval".
AppManager comporte 5 méthodes:
-d'ajout d'approval (POST) : url -> https://loanapprovalproject-42.appspot.com/AppManager/approvals/add
-de suppression : url -> https://loanapprovalproject-42.appspot.com/AppManager/approvals/delete?id=2 (par exemple pour les arguments)
-de listing des approvals : url -> https://loanapprovalproject-42.appspot.com/AppManager/approvals/all
-de récupération de la réponse manuelle : url -> https://loanapprovalproject-42.appspot.com/AppManager/approvals/check
-de récupération du dernier ID dans la bdd : url -> https://loanapprovalproject-42.appspot.com/AppManager/approvals/lastId
AccManager comporte 4 méthodes:
-d'ajout d'account (POST) : url -> https://loanapprovalproject-42.appspot.com/AccManager/accounts/add
-de suppression : url -> https://loanapprovalproject-42.appspot.com/AccManager/accounts/delete?id=2 (par exemple pour les arguments)
-de listing des accounts : url -> https://loanapprovalproject-42.appspot.com/AccManager/accounts/all
-de récupération du dernier ID dans la bdd : url -> https://loanapprovalproject-42.appspot.com/AccManager/accounts/lastId
CheckAccount comporte 1 méthode:
-de récupération du risque pour un compte: url -> https://loanapprovalproject-42.appspot.com/CheckAccount/check/account?name=titi (par exemple pour les arguments)
LoanApproval est le service déployé sur Heroku qui va appeler certains services sur GAE.
Voici l'url : https://sheltered-castle-38146.herokuapp.com/loanapproval?amount=100&name=Toto (par exemple pour les arguments)
----- Client -----
Nous avons aussi un client pour pouvoir tester tous les services créés (dossier /Client dans l'archive). Il suffit juste
d'ouvrir le fichier index.html pour les tester.
----- Qui a fait quoi ? -----
Nous nous sommes chargés tous les deux du client ainsi que du service LoanApproval sur Heroku.
Dylan s'est chargé également du service AppManager.
Mikaël a fait les services AccManager et CheckAccount.
----- Tests -----
Afin de tester les différents composants, nous avons utilisé Guzzle.
En exécutant le fichier Guzzle, celui-ci affiche les codes de retour des différentes urls testées.<file_sep><?php
require 'guzzle.phar';
$client = new Guzzle\Http\Client('https://loanapprovalproject-42.appspot.com/');
// $client = new Guzzle\Http\Client('http://localhost:8888/');
//Add Account
$response = $client->post('AccManager/accounts/add',
array(),
array(
'nom'=>'Toto',
'prenom'=>'le prenom de toto',
'account'=>2000,
'risk'=>'high'
)
)->send();
echo 'Ajout d\'un Account : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
//Get Accounts
$response = $client->get('AccManager/accounts/all')->send();
echo 'Liste des Accounts : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
// LastId
$response = $client->get('AccManager/accounts/lastId')->send();
$lastId = $response->getBody();
//Delete Account
$response = $client->get('AccManager/accounts/delete?id='.$lastId,
array(),
array()
)->send();
echo 'Suppression de l\'account d\'id = '.$lastId.' : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
//Add Approval
$response = $client->post('AppManager/approvals/add',
array(),
array(
'nom' => 'Approval1'
)
)->send();
echo 'Ajout d\'un approval : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
//Get Approvals
$response = $client->get('AppManager/approvals/all')->send();
echo 'Liste des Approvals : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
// LastId
$response = $client->get('AccManager/accounts/lastId')->send();
$lastId = $response->getBody();
//Delete Approval
$response = $client->get('AppManager/approvals/delete?id='.$lastId,
array(),
array()
)->send();
echo 'Suppression de l\'approval d\'id = '.$lastId.' : '.$response->getStatusCode()."\r\n";
echo '----'."\r\n";
//Check Account
$response = $client->get('CheckAccount/check/account?name=titi',
array(),
array()
)->send();
echo 'Check account d\'id 1 : '.$response->getBody();
echo "\r\n";
|
e48e441262a3713f905f404f2b3ff42e87ec10cc
|
[
"Text",
"PHP"
] | 2
|
Text
|
mik42000/CloudProject
|
b87323b24c0c4b9f45b8c4bdf031545458ad3b47
|
08bb4f0fd7b1408f0ee754fd99e37a247043696a
|
refs/heads/master
|
<file_sep>print("123455555")
print(12344)
<file_sep>print("1234444.py")
print("new-api branch")
|
b03745b80631cbc9dd9be25e3b8cacad7fac3475
|
[
"Python"
] | 2
|
Python
|
ekh-test/test-rp
|
5e26bc9c0fd2a823a05b46cb136b71df66acf02d
|
6c8ad7a7c2cde1b0b6e62c33309c897b5c118938
|
refs/heads/master
|
<file_sep># Path settings
typeset -U path
path=(~/bin $path)
# Locale settings
export LANG="en_US.UTF-8"
export LC_MESSAGES="en_US.UTF-8"
export LC_CTYPE="de_DE.UTF-8"
export LC_COLLATE="de_DE.UTF-8"
export LC_TIME="de_DE.UTF-8"
export LC_NUMERIC="de_DE.UTF-8"
export LC_MONETARY="de_DE.UTF-8"
export LC_PAPER="de_DE.UTF-8"
export LC_TELEPHONE="de_DE.UTF-8"
export LC_ADDRESS="de_DE.UTF-8"
export LC_MEASUREMENT="de_DE.UTF-8"
export LC_NAME="de_DE.UTF-8"
export LC_IDENTIFICATION="de_DE.UTF-8"
# Other variables
export EDITOR="vim"
export PAGER="less"
# LSCOLORS for non-Linux systems
# (on Linux, this is handled via dircolors)
if [ $(uname -s) = "FreeBSD" ]; then
export LSCOLORS=ExGxFxdxCxDxDxxbxdAeAe
fi
<file_sep># Source .bashrc
[[ -f ~/.bashrc ]] && . ~/.bashrc
# User-defined script path
PATH="$HOME/bin:$PATH"
# German locale-settings with english language
export LANG="en_US.UTF-8"
export LC_MESSAGES="en_US.UTF-8"
export LC_CTYPE="de_DE.UTF-8"
export LC_COLLATE="de_DE.UTF-8"
export LC_TIME="de_DE.UTF-8"
export LC_NUMERIC="de_DE.UTF-8"
export LC_MONETARY="de_DE.UTF-8"
export LC_PAPER="de_DE.UTF-8"
export LC_TELEPHONE="de_DE.UTF-8"
export LC_ADDRESS="de_DE.UTF-8"
export LC_MEASUREMENT="de_DE.UTF-8"
export LC_NAME="de_DE.UTF-8"
export LC_IDENTIFICATION="de_DE.UTF-8"
# Other env variables
export EDITOR=vim
export PAGER=less
# If we're local and on tty1, start X
[[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && exec startx
<file_sep># Completion
autoload -U compinit
compinit
# Color support
autoload -U colors
colors
# Prompt setup
autoload -U promptinit
promptinit
if [[ -z "$SSH_CLIENT" ]]; then
PROMPT="%{%(#.$fg[red].$fg[green])%}%B%n%b %{$fg[blue]%}%~%{$reset_color%}
%# "
else
PROMPT="%{%(#.$fg[red].$fg[yellow])%}%B%n@%m%b %{$fg[blue]%}%~%{$reset_color%}
%# "
fi
RPROMPT="%(?..%{$fg[red]%}%B!%b%{$reset_color%})"
# History settings
HISTFILE=~/.zsh_history
HISTSIZE=10000
SAVEHIST=10000
setopt append_history
setopt extended_history
setopt hist_ignore_dups
setopt hist_ignore_space
setopt inc_append_history
setopt share_history
# Keybindings
bindkey -v
bindkey "^[[A" history-beginning-search-backward
bindkey "^[[B" history-beginning-search-forward
# Other options
setopt autocd
setopt extendedglob
setopt nomatch
unsetopt beep
unsetopt notify
# Import coloring for ls
if [ $(uname -s) = "Linux" ]; then
eval $(dircolors ~/.dircolors)
fi
# Disable completion of hostnames from /etc/hosts
zstyle ':completion:*' hosts off
# Source aliases
[[ -f ~/.aliases ]] && . ~/.aliases
<file_sep># If we're local and on tty1, start X
[[ -z $DISPLAY && $XDG_VTNR -eq 1 ]] && exec startx
<file_sep># If not running interactively, don't do anything
[[ $- != *i* ]] && return
# On CentOS, the system-wide bashrc must be sourced manually
if [ -z "$PROMPT_COMMAND" ]; then
if [ -f /etc/bashrc ]; then
. /etc/bashrc
fi
fi
# Set up prompt
if [ $(whoami) == "root" ]; then
COLOR_USERHOST="\[\033[1;31m\]"
else
if [[ -z "$SSH_CLIENT" ]]; then
COLOR_USERHOST="\[\033[1;32m\]"
else
COLOR_USERHOST="\[\033[1;33m\]"
fi
fi
COLOR_PATH="\[\033[0;34m\]"
COLOR_RESET="\[\033[0;m\]"
if [[ -z "$SSH_CLIENT" ]]; then
PS1="$COLOR_USERHOST\u $COLOR_PATH\w$COLOR_RESET\n\\$ "
else
PS1="$COLOR_USERHOST\u@\h $COLOR_PATH\w$COLOR_RESET\n\\$ "
fi
# History: ignore duplicates and cmds starting with spaces
export HISTCONTROL=ignoreboth
# Import coloring for ls
if [ $(uname -s) = "Linux" ]; then
eval $(dircolors ~/.dircolors)
fi
# Source aliases
[[ -f ~/.aliases ]] && . ~/.aliases
|
baa7a3cdeb0292da0ee32b293037fd1fbafae7a5
|
[
"Shell"
] | 5
|
Shell
|
cyphex/dotfiles
|
b2366b7058b3670e607a376ea2052bc7b9d43854
|
3ce5698b497b147e138eac3055f084dfcbf8a85c
|
refs/heads/master
|
<file_sep>import axios from 'axios';
const API_RESPONSE = {
name: "<NAME>",
email: "<EMAIL>",
role: "Software Engineer",
insta: "@mika_whippet",
profile_img:
"https://pbs.twimg.com/profile_images/982394336456396801/KRv7pJaI_400x400.jpg"
};
const API_COLUMNS = [
{
field: "title",
title: "Title",
width: 80,
titleAlign: "center",
columnAlign: "center",
isEdit: true,
formatter: function(rowData, rowIndex, pagingIndex, field) {
return `<span class='cell-edit-color'>${rowData[field]}</span>`;
},
isResize: true
},
{
field: "tel",
title: "Id",
width: 150,
titleAlign: "center",
columnAlign: "center",
isEdit: true,
isResize: true
},
{
field: "project",
title: "Project",
width: 150,
titleAlign: "center",
columnAlign: "center",
isEdit: true,
isResize: true
},
{
field: "address",
title: "Address",
width: 280,
titleAlign: "center",
columnAlign: "left",
isEdit: true,
isResize: true
}
];
const API_ITEMS = [
{
title: "one",
tel: "1561987",
project: "钢琴、书法、唱歌",
address: "上海市黄浦区金陵东路569号17楼"
},
{
title: "two",
tel: "1821538",
project: "钢琴、书法、唱歌",
address: "上海市奉贤区南桥镇立新路12号2楼"
},
{
title: "three",
tel: "1610097",
project: "钢琴、书法、唱歌",
address: "上海市崇明县城桥镇八一路739号"
},
{
title: "four",
tel: "1971123",
project: "钢琴、书法、唱歌",
address: "上海市青浦区青浦镇章浜路24号"
},
{
title: "five",
tel: "1836678",
project: "钢琴、书法、唱歌",
address: "上海市松江区乐都西路867-871号"
}
];
const URL = 'https://my-json-server.typicode.com/scheevel/fakedata'
const API = axios.create({
baseURL: URL
})
export const columns = {
get: params => API.get('/demo', {params})
.then( response => {
return response.data.columns}) //works
}
export const items = {
get: params => API.get('/demo', {params})
.then( response => {
return response.data.items}),
post: (data, params) => API.post('/demo/items', {data}, {params})
};
export default{
GetResponse: () => API.get('/demo'),
//getColumns: params => API.get('/columns', params)
FullResponse(){
axios.get(URL + '/demo')
.then(function (response) {
// handle success
console.log(response);
})
.catch(function (error) {
// handle error
console.log(error);
})
.then(function () {
// always executed
});
}
}
|
356eba08cc5828c58ac126a7821dad65b7e7c90e
|
[
"JavaScript"
] | 1
|
JavaScript
|
Scheevel/sb-vue-easy-table
|
9f188139ee4173b5f6a86dd7eba76a4855d744c7
|
33761a2b6855aad3c8b601b4a7f562300d9a2539
|
refs/heads/master
|
<file_sep>package com.altieri.weatherapp.data.gson;
import com.google.gson.TypeAdapterFactory;
import com.ryanharter.auto.value.gson.GsonTypeAdapterFactory;
@GsonTypeAdapterFactory
public abstract class AppAdapterFactory implements TypeAdapterFactory {
// Static factory method to access the package
// private generated implementation
public static TypeAdapterFactory create() {
return new AutoValueGson_AppAdapterFactory();
}
}<file_sep>package com.altieri.weatherapp.ui.widget.hours_forecast;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.altieri.weatherapp.R;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
class HourForecastViewHolder extends RecyclerView.ViewHolder {
private final ImageView mImage;
private final TextView mHour;
private final TextView mTemperature;
public HourForecastViewHolder(View itemView) {
super(itemView);
mImage = (ImageView) itemView.findViewById(R.id.weather_icon);
mHour = (TextView) itemView.findViewById(R.id.hour);
mTemperature = (TextView) itemView.findViewById(R.id.temperature);
}
public void setHourForecast(String icon, String time, String temperature) {
Context context = mImage.getContext();
if (icon != null) {
String url = context.getString(R.string.weather_icon_url, icon);
// I should have handled the error showing a placeholder
Glide.with(context)
.load(url)
.fitCenter()
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(mImage);
} else {
mImage.setVisibility(View.INVISIBLE);
}
mHour.setText(time);
mTemperature.setText(temperature);
}
}
<file_sep>package com.altieri.weatherapp.ui.activity.city;
import com.altieri.weatherapp.data.CityData;
import com.altieri.weatherapp.ui.activity.main.MainActivityView;
import javax.inject.Inject;
import io.reactivex.observers.DisposableObserver;
public class SelectCityPresenter {
private final CityData mCityData;
private MainActivityView mView;
@Inject
SelectCityPresenter(CityData cityData) {
mCityData = cityData;
}
public DisposableObserver showCities(String query) {
mView.clearCities();
mView.setSelectCityVisibility(true);
mView.setForecastVisibility(false);
return mCityData.filter(query).subscribeWith(new DisposableObserver<String>() {
@Override
public void onNext(String city) {
mView.addCity(city);
}
@Override
public void onError(Throwable e) {
}
@Override
public void onComplete() {
}
});
}
public void setCity(String city) {
mView.clearCities();
mView.setSelectCityVisibility(false);
mView.clearForecast();
mView.setForecastVisibility(true);
mView.setCity(city);
}
public void setView(MainActivityView view) {
mView = view;
}
}
<file_sep>package com.altieri.weatherapp.ui.widget.daily_forecast;
import com.altieri.weatherapp.bl.model.forecast.DailyForecast;
import com.altieri.weatherapp.bl.model.forecast.Weather;
import org.junit.Test;
import java.util.ArrayList;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
public class DailyForecastPresenterUnitTest {
@Test
public void show_forecast_show_correct_info() throws Exception {
DailyForecastPresenter dailyForecastPresenter = new DailyForecastPresenter();
ArrayList<Weather> weathers = new ArrayList<>();
DailyForecastPresenter.DailyForecastView view = mock(DailyForecastPresenter.DailyForecastView.class);
dailyForecastPresenter.showForecast(view, DailyForecast.create("date", weathers)); //I'm not mocking DailyForecast to keep the things simpler
verify(view, times(1)).showDate("date");
verify(view, times(1)).showHoursForecast(weathers);
}
}<file_sep>package com.altieri.weatherapp.data.model.forecast;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
@AutoValue
public abstract class City {
public abstract @SerializedName("id") Integer getId();
public abstract @SerializedName("name") String getName();
public abstract @SerializedName("country") String getCountry();
public static TypeAdapter<City> typeAdapter(Gson gson) {
return new AutoValue_City.GsonTypeAdapter(gson);
}
}
<file_sep>package com.altieri.weatherapp.data.network;
import com.altieri.weatherapp.data.model.forecast.RawForecast;
import io.reactivex.Observable;
import retrofit2.http.GET;
import retrofit2.http.Query;
public interface ServiceWeather {
@GET("/data/2.5/forecast")
Observable<RawForecast> forecast(@Query("q") String city,
@Query("appid") String appId);
}
<file_sep>apply plugin: 'com.android.application'
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.3.1'
}
}
repositories {
// Required because retrolambda is on maven central
mavenCentral()
maven { url 'https://maven.google.com' }
}
apply plugin: 'com.android.application'
apply plugin: 'realm-android'
apply plugin: 'me.tatarka.retrolambda'
android {
compileSdkVersion 25
buildToolsVersion '25.0.3'
compileOptions.incremental = false
compileOptions {
targetCompatibility JavaVersion.VERSION_1_8
sourceCompatibility JavaVersion.VERSION_1_8
}
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = ['autovaluegson.defaultCollectionsToEmpty': 'true']
}
}
multiDexEnabled true
applicationId "com.altieri.weatherapp"
minSdkVersion 17
targetSdkVersion 25
versionCode 1
versionName "0.1"
vectorDrawables.useSupportLibrary = true
jackOptions {
enabled false
}
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
dexOptions {
preDexLibraries = false
javaMaxHeapSize "4g"
}
}
compileOptions {
incremental true
}
/**
* Signing keys config.
*/
signingConfigs {
debug {
storeFile file("debug.keystore")
keyAlias "key"
storePassword "<PASSWORD>"
keyPassword "<PASSWORD>"
}
release {
storeFile file("release.keystore")
keyAlias "key"
storePassword "<PASSWORD>"
keyPassword "<PASSWORD>"
}
}
buildTypes {
release {
debuggable false
minifyEnabled true
zipAlignEnabled true
renderscriptDebuggable false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
signingConfig signingConfigs.release
}
debug {
debuggable true
signingConfig signingConfigs.debug
minifyEnabled false
versionNameSuffix "_dev"
}
}
}
def jsr250_api = '1.0'
def multidex = '1.0.1'
def supportVersion = '25.3.1'
def daggerVer = '2.11'
def rxbinding = '2.0.0'
def retrofit2 = '2.3.0'
def okhttp3 = '3.4.1'
def autovalue = '1.4'
def autovalueparcel = '0.2.5'
def autovaluegson = '0.4.5'
def auto_value_with = '1.0.0'
def glide = '3.7.0'
def hamcrestVersion = '1.3'
def espresso_core = '2.2.2'
def mockito_core = '1.10.19'
def junit = '4.12'
dependencies {
compile "com.google.dagger:dagger:$daggerVer"
compile "com.google.dagger:dagger-android-support:$daggerVer"
annotationProcessor "com.google.dagger:dagger-android-processor:$daggerVer"
annotationProcessor "com.google.dagger:dagger-compiler:$daggerVer"
compile fileTree(dir: 'libs', include: ['*.jar'])
compile "com.android.support:multidex:$multidex"
compile "com.android.support:appcompat-v7:$supportVersion"
compile "com.android.support:design:$supportVersion"
compile "com.android.support:cardview-v7:$supportVersion"
compile "com.android.support:recyclerview-v7:$supportVersion"
compile "com.android.support:support-annotations:$supportVersion"
compile "com.android.support:preference-v7:$supportVersion"
compile "com.android.support:support-v4:$supportVersion"
compile "com.android.support:support-vector-drawable:$supportVersion"
compile "com.android.support:palette-v7:$supportVersion"
compile "com.jakewharton.rxbinding2:rxbinding:$rxbinding"
compile "com.jakewharton.rxbinding2:rxbinding-support-v4:$rxbinding"
compile "com.jakewharton.rxbinding2:rxbinding-appcompat-v7:$rxbinding"
compile "com.jakewharton.rxbinding2:rxbinding-design:$rxbinding"
compile "com.jakewharton.rxbinding2:rxbinding-recyclerview-v7:$rxbinding"
compile "com.jakewharton.rxbinding2:rxbinding-leanback-v17:$rxbinding"
compile "com.squareup.retrofit2:retrofit:$retrofit2"
compile "com.squareup.retrofit2:adapter-rxjava2:$retrofit2"
compile "com.squareup.retrofit2:converter-gson:$retrofit2"
compile "com.squareup.retrofit2:converter-scalars:$retrofit2"
compile "com.squareup.okhttp3:okhttp:$okhttp3"
compile "com.squareup.okhttp3:okhttp-urlconnection:$okhttp3"
compile "com.squareup.okhttp3:logging-interceptor:$okhttp3"
provided "com.google.auto.value:auto-value:$autovalue"
annotationProcessor "com.google.auto.value:auto-value:$autovalue"
annotationProcessor "com.gabrielittner.auto.value:auto-value-with:$auto_value_with"
annotationProcessor "com.ryanharter.auto.value:auto-value-parcel:$autovalueparcel"
compile "com.ryanharter.auto.value:auto-value-parcel-adapter:$autovalueparcel"
annotationProcessor "com.ryanharter.auto.value:auto-value-gson:$autovaluegson"
provided "com.ryanharter.auto.value:auto-value-gson:$autovaluegson"
compile "com.github.bumptech.glide:glide:$glide"
provided "javax.annotation:jsr250-api:$jsr250_api"
//other dependencies for testing
testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion"
testCompile "org.hamcrest:hamcrest-library:$hamcrestVersion"
testCompile "org.hamcrest:hamcrest-integration:$hamcrestVersion"
androidTestCompile("com.android.support.test.espresso:espresso-core:$espresso_core", {
exclude group: 'com.android.support', module: 'support-annotations'
})
testCompile "org.mockito:mockito-core:$mockito_core"
testCompile "junit:junit:$junit"
compile 'com.f2prateek.rx.preferences2:rx-preferences:2.0.0-RC2'
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.support:support-v4:25.3.1'
}
android.packagingOptions {
exclude 'LICENSE.txt'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/rxjava.properties'
}
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
if (!requested.name.startsWith("multidex")) {
details.useVersion "$supportVersion"
}
}
}
}
<file_sep>package com.altieri.weatherapp.data;
import com.altieri.weatherapp.data.model.cities.Cities;
import com.google.gson.Gson;
import java.util.ArrayList;
import javax.inject.Inject;
import io.reactivex.Observable;
import io.reactivex.Single;
public class CityData {
private final AppStorage mAppStorage;
private final Gson mGson;
private String mCity = ForecastData.DEFAULT_CITY;
@Inject
CityData(AppStorage appStorage, Gson gson) {
mAppStorage = appStorage;
mGson = gson;
}
private Single<ArrayList<String>> hardcodedCities() {
Single<ArrayList<String>> single = Single.create(e -> {
ArrayList<String> item;
try {
String json = mAppStorage.fileFromAsset("uk_locations.json");
ArrayList<String> cities = mGson.fromJson(json, Cities.class).getCities();
item = cities != null ? cities : new ArrayList<>();
} catch (Exception ex) {
item = new ArrayList<>();
}
e.onSuccess(item);
});
return single.<ArrayList<String>>cache();
}
public Observable<String> filter(String query) {
return hardcodedCities()
.toObservable()
.switchMap(Observable::fromIterable)
.filter(city -> city.toLowerCase().startsWith(query.toLowerCase()));
}
public void setCity(String city) {
mCity = city;
}
public String getCity() {
return mCity;
}
}
<file_sep>package com.altieri.weatherapp.ui.activity.main;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import com.altieri.weatherapp.bl.model.forecast.DailyForecast;
import com.altieri.weatherapp.ui.widget.daily_forecast.DailyForecastWidget;
import java.util.ArrayList;
class ForecastsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private final @NonNull ArrayList<DailyForecast> mList;
ForecastsAdapter() {
mList = new ArrayList<>();
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = new DailyForecastWidget(parent.getContext());
return new DailyForecastViewHolder(itemView);
}
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
((DailyForecastViewHolder) holder).setDailyForecast(mList.get(position));
}
@Override
public int getItemCount() {
return mList.size();
}
public void add(DailyForecast dailyForecast) {
mList.add(dailyForecast);
notifyItemInserted(mList.size() - 1);
}
void clear() {
mList.clear();
notifyDataSetChanged();
}
}
<file_sep>package com.altieri.weatherapp.bl.model.forecast;
import android.support.annotation.NonNull;
import com.google.auto.value.AutoValue;
@AutoValue
public abstract class Weather {
public abstract String getIcon();
public abstract String getTime();
public abstract double getTemperature();
public static Weather create(String icon, @NonNull String time, @NonNull Double temperature) {
return new AutoValue_Weather(icon, time, temperature);
}
}
<file_sep>package com.altieri.weatherapp.data.model.forecast;
import com.google.auto.value.AutoValue;
import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.annotations.SerializedName;
@AutoValue
public abstract class RawWeatherInfo {
//http://openweathermap.org/img/w/{icon}.png
public abstract @SerializedName("icon") String getIcon();
public static TypeAdapter<RawWeatherInfo> typeAdapter(Gson gson) {
return new AutoValue_RawWeatherInfo.GsonTypeAdapter(gson);
}
}
<file_sep>package com.altieri.weatherapp;
import javax.inject.Inject;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.internal.disposables.DisposableContainer;
public class AppCompositeDisposable implements Disposable, DisposableContainer {
private CompositeDisposable mCompositeDisposable;
@Inject
public AppCompositeDisposable(CompositeDisposable compositeDisposable) {
mCompositeDisposable = compositeDisposable;
}
@Override
public void dispose() {
mCompositeDisposable.dispose();
}
@Override
public boolean isDisposed() {
return mCompositeDisposable.isDisposed();
}
@Override
public boolean add(Disposable d) {
return mCompositeDisposable.add(d);
}
@Override
public boolean remove(Disposable d) {
return mCompositeDisposable.remove(d);
}
@Override
public boolean delete(Disposable d) {
return mCompositeDisposable.delete(d);
}
public void reset() {
mCompositeDisposable = new CompositeDisposable();
}
}
|
acaf830f4fb6057aaf8c793c3914b1024349e9b4
|
[
"Java",
"Gradle"
] | 12
|
Java
|
robertoaltieri/weatherapp
|
b28f3a54f023cc07c593dd8e48094729ee3e2583
|
468b5dac4452bbad38c18d763154de0552861bf7
|
refs/heads/master
|
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
public class Wall : MonoBehaviour
{
public BasePlayer side;
public Action<Wall> onHitBall;
private void OnTriggerEnter2D(Collider2D collider)
{
if (collider.attachedRigidbody && collider.attachedRigidbody.CompareTag(Definition.BALL))
{
onHitBall?.Invoke(this);
}
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
namespace PongClone
{
public class WallGamePlay : Gameplay
{
#region Setting
public int topScore;
#endregion
[SerializeField] private WallGameplayUI _ui = null;
public override void ManualStart()
{
Debug.LogFormat("WallGamePlay: {0}", GetInstanceID());
if (rightHandedness)
{
Initialize(leftWall.gameObject, rightPlayer, typeof(WallPlayer));
rightWall.side = me;
rightWall.onHitBall = FailToReturn;
}
else
{
Initialize(leftPlayer, rightWall.gameObject, typeof(WallPlayer));
leftWall.side = me;
leftWall.onHitBall = FailToReturn;
}
me.preHitObject += AddScore;
_ui.SetHandedness(rightHandedness);
me.StartPlay();
opponent.StartPlay();
StartCoroutine(IncreaseBallSpeed());
}
protected override void Initialize(GameObject leftPlayer, GameObject rightPlayer, Type opponentType)
{
base.Initialize(leftPlayer, rightPlayer, opponentType);
me.gameObject.SetActive(true);
opponent.GetComponent<SpriteRenderer>().enabled = true;
opponent.GetComponent<Rigidbody2D>().isKinematic = true;
opponent.GetComponent<Collider2D>().isTrigger = false;
}
private IEnumerator IncreaseBallSpeed()
{
WaitForSeconds wait = new WaitForSeconds(5);
while (ball.speed < Gameplay.MAX_SPEED)
{
yield return wait;
ball.speed++;
}
}
private void AddScore(GameObject player)
{
me.Point++;
_ui.UpdatePlayerPoint(me.Point, rightHandedness);
if (me.Point > globalData.LastSessionPoint)
{
globalData.LastSessionPoint = me.Point;
}
}
private void FailToReturn(Wall wall)
{
Fail(wall.side);
_ui.EndMatch();
}
}
}<file_sep>namespace PongClone
{
public enum Direction
{
Left, Right
}
public static class Definition
{
public const string WALL = "Wall";
public const string BALL = "Ball";
public const string PLAYER = "Player";
public const float MAX_SLOPE = 1f;
}
}<file_sep>using UnityEngine;
namespace PongClone
{
public class OnTriggerEvent2D : MonoBehaviour
{
public ColliderEvent2D onEnter;
public ColliderEvent2D onStay;
public ColliderEvent2D onExit;
private void OnTriggerEnter2D(Collider2D collision)
{
onEnter?.Invoke(collision);
}
private void OnTriggerStay2D(Collider2D collision)
{
onStay?.Invoke(collision);
}
private void OnTriggerExit2D(Collider2D collision)
{
onExit?.Invoke(collision);
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
public class BaseGameplayUI : MonoBehaviour
{
[SerializeField] protected Text[] _points;
[SerializeField] protected AnimationCurve _shineCurve;
[SerializeField] protected CanvasGroup _matchEnding;
protected IEnumerator PointShine(int id, Action onComplete)
{
Color c = _points[id].color;
float alpha = _points[id].color.a;
float time = 0;
while (time < 1)
{
time += Time.deltaTime;
float a = alpha + _shineCurve.Evaluate(time);
_points[id].color = new Color(c.r, c.g, c.b, a);
yield return null;
}
_points[id].color = new Color(c.r, c.g, c.b, alpha);
onComplete?.Invoke();
}
public void EndMatch()
{
StartCoroutine(FadeInMatchEndingUI());
Debug.Log("UI EndMatch");
}
private IEnumerator FadeInMatchEndingUI()
{
yield return new WaitForSeconds(1);
_matchEnding.gameObject.SetActive(true);
float t = 0;
while (t < 1)
{
t += Time.deltaTime * 0.75f;
_matchEnding.alpha = t;
yield return null;
}
}
}
<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace PongClone
{
[RequireComponent(typeof(Rigidbody2D))]
public abstract class BasePlayer : MonoBehaviour
{
public int id;
public float speed = 1;
protected float runtimeSpeed;
public Vector3 OriginalPosition { get; private set; }
public float direction;
public Direction facing;
public BaseBall Ball { protected get; set; }
public Action<GameObject> preHitObject;
public bool myTurn;
[SerializeField] private int _point;
public int Point
{
get { return _point; }
set
{
_point = value;
onSetPoint?.Invoke(value);
}
}
public Action<int> onSetPoint;
private float _oldPositionY;
protected float deltaY;
private Rigidbody2D _rigidbody2D;
[SerializeField] private BoxCollider2D _collider;
[SerializeField] private Vector2 _colliderSize;
private RaycastHit2D[] _raycastHits = new RaycastHit2D[1];
[SerializeField] private float _bottomY;
[SerializeField] private float _topY;
[SerializeField] private SpriteRenderer _spriteRenderer;
private Color _originalColor;
protected virtual void Awake()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
_collider = GetComponent<BoxCollider2D>();
_spriteRenderer = GetComponent<SpriteRenderer>();
_originalColor = _spriteRenderer.color;
}
protected virtual void Start()
{
Debug.Log("BasePlayer Start");
enabled = false;
Initialize();
}
private void Initialize()
{
OriginalPosition = transform.position;
_oldPositionY = transform.position.y;
_colliderSize.x = _collider.size.x * transform.localScale.x;
_colliderSize.y = _collider.size.y * transform.localScale.y;
ContactFilter2D filter = new ContactFilter2D();
filter.useLayerMask = true;
filter.layerMask = LayerMask.GetMask(Definition.WALL);
filter.useDepth = true;
filter.minDepth = filter.maxDepth = 0;
int count = _collider.Raycast(Vector2.down, filter, _raycastHits);
_bottomY = _raycastHits[0].point.y;
count = _collider.Raycast(Vector2.up, filter, _raycastHits);
_topY = _raycastHits[0].point.y;
Reset();
}
public void Reset()
{
runtimeSpeed = speed;
}
public void StartPlay()
{
StopAllCoroutines();
StartCoroutine(StartPlayTask());
}
private IEnumerator StartPlayTask()
{
Reset();
yield return BeforeLaunchBall();
enabled = true;
if (myTurn)
{
ServeBall();
}
}
protected abstract IEnumerator BeforeLaunchBall();
protected virtual void FixedUpdate()
{
deltaY = transform.position.y - _oldPositionY;
_oldPositionY = transform.position.y;
Vector2 d = Vector2.up * direction * runtimeSpeed * Time.fixedDeltaTime;
MovePosition(d);
}
protected void MovePosition(Vector2 deltaMovement)
{
Vector2 destination = _rigidbody2D.position + deltaMovement;
if (deltaMovement.y > 0 && destination.y > _topY - _colliderSize.y / 2)
{
_rigidbody2D.MovePosition(new Vector2(destination.x, _topY - _colliderSize.y / 2));
}
else if (deltaMovement.y < 0 && destination.y < _bottomY + _colliderSize.y / 2)
{
_rigidbody2D.MovePosition(new Vector2(destination.x, _bottomY + _colliderSize.y / 2));
}
else
{
_rigidbody2D.MovePosition(destination);
}
}
public void HoldBall()
{
Ball.OnHeld();
Transform ball = Ball.transform;
ball.SetParent(transform);
ball.position = transform.position;
float distance = 0.5f;
if (facing == Direction.Left)
{
ball.position = transform.position + Vector3.left * distance;
}
else
{
ball.position = transform.position + Vector3.right * distance;
}
}
public void ServeBall()
{
Ball.transform.SetParent(null);
if (facing == Direction.Left)
{
Ball.SetVelocity(Vector2.left);
}
else
{
Ball.SetVelocity(Vector2.right);
}
}
public void AddImpulseToBall(BaseBall ball)
{
deltaY = (ball.transform.position - transform.position).y * 2;
Vector2 deltaV = Vector2.up * deltaY * speed * 1.5f;
ball.AddVelocity(deltaV);
}
public void Blink()
{
if (_spriteRenderer.color == _originalColor)
{
_spriteRenderer.color = _originalColor * Color.grey;
}
else
{
_spriteRenderer.color = _originalColor * Color.white;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(Definition.BALL))
{
preHitObject?.Invoke(collision.gameObject);
BaseBall ball = collision.gameObject.GetComponent<BaseBall>();
AddImpulseToBall(ball);
}
}
}
}<file_sep>using System;
using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
public enum Handedness
{
Left, Right
}
[Serializable]
public class SaveData
{
public int pointsTowin = 3;
public Handedness handedness;
public bool musicOn = true;
public bool soundOn = true;
public const int TOP_N = 10;
public List<int> localTopPoints = new List<int>(TOP_N);
//{
// 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
//};
public int lastSessionPoint = -1;
public SaveData()
{
for (int i = 0; i < TOP_N; i++)
{
localTopPoints.Add(0);
}
}
public void Save()
{
while (localTopPoints.Count > TOP_N)
{
localTopPoints.RemoveRange(TOP_N, localTopPoints.Count - TOP_N);
}
string json = JsonUtility.ToJson(this);
Debug.LogFormat("Save: {0}", json);
PlayerPrefs.SetString("SaveData", json);
}
public static SaveData Load()
{
string json = PlayerPrefs.GetString("SaveData", "{}");
SaveData instance = JsonUtility.FromJson<SaveData>(json);
return instance;
}
public static void Clear()
{
PlayerPrefs.DeleteAll();
}
public static void WriteToDisk()
{
PlayerPrefs.Save();
}
public int InsertToBillboard(int point)
{
int index = localTopPoints.Count - 1;
for (; index >= 0; index--)
{
if (point <= localTopPoints[index])
{
index++;
break;
}
}
if (index < 0)
{
index = 0;
}
if (index == localTopPoints.Count - 1 && point <= localTopPoints[index])
{
localTopPoints.Add(point);
return localTopPoints.Count - 1;
}
else
{
localTopPoints.Insert(index, point);
return index;
}
}
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace PongClone
{
public static class UIEffect
{
public static void FadeAlpha(this Graphic body, float alpha, float duration, Action onComplete = null)
{
body.StopAllCoroutines();
body.StartCoroutine(FadeAlphaTask(body, alpha, duration, onComplete));
}
private static IEnumerator FadeAlphaTask(Graphic body, float alpha, float duration, Action onComplete)
{
body.CrossFadeAlpha(alpha, duration, false);
yield return new WaitUntil(() => body.canvasRenderer.GetAlpha() == 1);
onComplete?.Invoke();
}
public static void BlinkAlpha(this Graphic body, int times, float interval, float alpha = 0.0f)
{
body.StopAllCoroutines();
body.StartCoroutine(AlphaBlinkTask(body, times, interval, alpha));
}
private static IEnumerator AlphaBlinkTask(Graphic body, int times, float interval, float alpha)
{
float a = body.color.a;
int time = 0;
WaitForSeconds wait = new WaitForSeconds(interval / 2);
while (time++ < times)
{
body.CrossFadeAlpha(alpha, 0, false);
yield return wait;
body.CrossFadeAlpha(a, 0, false);
yield return wait;
}
yield return null;
}
public static void AnchorPos(this RectTransform transform, Vector2 to, float duration, Action<RectTransform> onComplete = null)
{
MonoBehaviour behaviour = transform.GetComponent<MonoBehaviour>();
MonoBehaviour destroy = null;
if (!behaviour)
{
behaviour = transform.gameObject.AddComponent<CoroutineHost>();
destroy = behaviour;
}
behaviour.StopAllCoroutines();
behaviour.StartCoroutine(AnchorPosTask(transform, to, duration, destroy, onComplete));
}
private static IEnumerator AnchorPosTask(RectTransform transform, Vector2 to, float duration, MonoBehaviour destroy, Action<RectTransform> onComplete)
{
float time = 0;
RectTransform rt = transform;
Vector2 origin = rt.anchoredPosition;
while (time < duration)
{
time += Time.deltaTime;
rt.anchoredPosition = Vector2.Lerp(origin, to, time / duration);
yield return null;
}
rt.anchoredPosition = to;
UnityEngine.Object.Destroy(destroy);
onComplete?.Invoke(transform);
}
}
}<file_sep>using System;
using UnityEngine;
using UnityEngine.Events;
namespace PongClone
{
[Serializable]
public class ColliderEvent2D : UnityEvent<Collider2D> { }
}<file_sep>namespace PongClone
{
public interface IPause
{
void Pause();
void Play();
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
public class AudioManager : MonoBehaviour
{
[SerializeField] private AudioSource _music = null;
[SerializeField] private AudioSource _sound = null;
public bool MusicOn
{
set { _music.mute = !value; }
}
public bool SoundOn
{
set { _sound.mute = !value; }
}
public void LoadSetting(GlobalData data)
{
MusicOn = data.MusicOn;
SoundOn = data.SoundOn;
}
public void PlaySound(AudioClip clip)
{
if (!_sound.mute)
{
_sound.clip = clip;
_sound.Play();
}
}
public void PlaySoundRepeat(AudioClip clip, int times, float interval)
{
if (!_sound.mute)
{
StartCoroutine(PlaySoundRepeatTask(clip, times, interval));
}
}
private IEnumerator PlaySoundRepeatTask(AudioClip clip, int times, float interval)
{
int count = 0;
WaitForSeconds wait = new WaitForSeconds(interval);
while (count++ < times)
{
_sound.PlayOneShot(clip);
yield return wait;
}
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace PongClone
{
public abstract class Gameplay : MonoBehaviour
{
public GameObject leftPlayer, rightPlayer;
public BasePlayer me, opponent;
#region Setting
protected const int MAX_SPEED = 32;
[Range(1, MAX_SPEED)]
public float playerSpeed = 1;
[Range(1, MAX_SPEED)]
public float ballSpeed = 1;
public bool rightHandedness = true;
#endregion
public BaseBall ball;
public Wall leftWall;
public Wall rightWall;
public GameObject deathVFX;
public GlobalData globalData;
public SceneFader sceneFader;
[SerializeField] private string _mainMenu = null;
public abstract void ManualStart();
protected virtual void Initialize(GameObject leftPlayer, GameObject rightPlayer, Type opponentType)
{
if (rightHandedness)
{
InitializeForRightHandedness(leftPlayer, rightPlayer, opponentType, out me, out opponent);
}
else
{
InitializeForLeftHandedness(leftPlayer, rightPlayer, opponentType, out me, out opponent);
}
me.speed = opponent.speed = playerSpeed;
me.Ball = opponent.Ball = ball;
me.preHitObject += globalData.PlayBallHitSoundWith;
opponent.preHitObject += globalData.PlayBallHitSoundWith;
ball.speed = ballSpeed;
ball.onHitCeilingFloor = globalData.PlayBallHitSoundWith;
me.myTurn = true;
opponent.myTurn = false;
}
protected void InitializeForRightHandedness(GameObject leftPlayer, GameObject rightPlayer, Type opponentType, out BasePlayer me, out BasePlayer opponent)
{
me = rightPlayer.AddComponent<ManualPlayer>();
me.id = 1;
me.facing = Direction.Left;
opponent = leftPlayer.AddComponent(opponentType) as BasePlayer;
opponent.id = 0;
opponent.facing = Direction.Right;
}
protected void InitializeForLeftHandedness(GameObject leftPlayer, GameObject rightPlayer, Type opponentType, out BasePlayer me, out BasePlayer opponent)
{
me = leftPlayer.AddComponent<ManualPlayer>();
me.id = 0;
me.facing = Direction.Right;
opponent = rightPlayer.AddComponent(opponentType) as BasePlayer;
opponent.id = 1;
opponent.facing = Direction.Left;
}
protected void Fail(BasePlayer player)
{
Debug.Log("Fail");
((IPause)me).Pause();
((IPause)opponent).Pause();
StartCoroutine(Explode(player));
}
private IEnumerator Explode(BasePlayer player)
{
WaitForSeconds flash = new WaitForSeconds(0.1f);
int times = 0;
while (times < 7)
{
player.Blink();
times++;
yield return flash;
}
globalData.PlayDeathSound();
player.gameObject.SetActive(false);
Instantiate(deathVFX, player.transform.position, Quaternion.identity);
}
/// <summary>
/// Load current scene as a means of replay. Called by UI button.
/// </summary>
public void LoadCurrentScene()
{
Scene scene = SceneManager.GetActiveScene();
//SceneManager.LoadScene(scene.name, LoadSceneMode.Single);
sceneFader.LoadSceneAsync(scene.name);
}
public void ToMainMenu()
{
sceneFader.LoadSceneAsync(_mainMenu);
}
}
}<file_sep>using UnityEngine;
namespace PongClone
{
public class VSWallSceneTest : MonoBehaviour
{
public WallGamePlay gameplay;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Return))
{
gameplay.ManualStart();
}
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
[RequireComponent(typeof(MeshFilter))]
public class GenerateWall : MonoBehaviour
{
private MeshFilter _meshFilter;
public Rect rect;
void Awake()
{
_meshFilter = GetComponent<MeshFilter>();
_meshFilter.mesh = new Mesh();
}
void Start()
{
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
List<Vector3> vertices = new List<Vector3>();
vertices.Add(new Vector3(rect.x, rect.y, 0));
vertices.Add(new Vector3(rect.x + Random.Range(0.5f, 1.0f), rect.y + Random.Range(0.5f, 1.5f), 0));
vertices.Add(new Vector3(rect.x, vertices[vertices.Count - 1].y, 0));
Color[] colorElems = new Color[] { new Color(0.125f, 0.125f, 0.125f), new Color(0.5f, 0.5f, 0.5f), new Color(1f, 1f, 1f) };
List<Color> colors = new List<Color>();
List<int> indices = new List<int>() { 0, 2, 1 };
int i = indices.Count - 1;
while (true)
{
float y = vertices[vertices.Count - 1].y + Random.Range(0.5f, 1.5f);
if (y >= rect.height)
{
break;
}
vertices.Add(new Vector3(vertices[vertices.Count - 1].x + Random.Range(0.5f, 1.0f), y, 0));
vertices.Add(new Vector3(rect.x, vertices[vertices.Count - 1].y, 0));
indices.Add(i);
indices.Add(i + 1);
indices.Add(i - 1);
indices.Add(i);
indices.Add(i + 2);
indices.Add(i + 1);
i += 2;
}
vertices.Add(new Vector3(rect.x, rect.height, 0));
indices.Add(i);
indices.Add(i + 1);
indices.Add(i - 1);
_meshFilter.mesh.SetVertices(vertices);
_meshFilter.mesh.SetTriangles(indices, 0);
foreach (Vector3 v in vertices)
{
colors.Add(colorElems[Random.Range(0, colorElems.Length)]);
}
_meshFilter.mesh.SetColors(colors);
gameObject.AddComponent<PolygonCollider2D>();
}
}
}
}<file_sep>using UnityEngine;
namespace PongClone
{
public class DeathVFX : MonoBehaviour
{
private ParticleSystem _particleSystem;
private void Awake()
{
_particleSystem = GetComponent<ParticleSystem>();
}
private void Start()
{
_particleSystem.Play(true);
}
private void OnParticleSystemStopped()
{
Destroy(transform.parent.gameObject);
}
}
}<file_sep>using System;
using UnityEngine;
namespace PongClone
{
public class PlayerUtil
{
public static void InitializeForRightHandedness(GameObject leftPlayer, GameObject rightPlayer, Type opponentType, out BasePlayer me, out BasePlayer opponent)
{
me = rightPlayer.AddComponent<ManualPlayer>();
me.id = 1;
me.facing = Direction.Left;
opponent = leftPlayer.AddComponent(opponentType) as BasePlayer;
opponent.id = 0;
opponent.facing = Direction.Right;
}
public static void InitializeForLeftHandedness(GameObject leftPlayer, GameObject rightPlayer, Type opponentType, out BasePlayer me, out BasePlayer opponent)
{
me = leftPlayer.AddComponent<ManualPlayer>();
me.id = 0;
me.facing = Direction.Right;
opponent = rightPlayer.AddComponent(opponentType) as BasePlayer;
opponent.id = 1;
opponent.facing = Direction.Left;
}
}
}<file_sep>using System;
using UnityEngine;
namespace PongClone
{
public class ClassicGameplay : Gameplay
{
public int endingPoint = 3;
[SerializeField] private GameplayUI _ui = null;
public override void ManualStart()
{
Initialize(leftPlayer, rightPlayer, typeof(WatchDogPlayer));
_ui.PointsToWin = endingPoint = globalData.PointsToWin;
}
protected override void Initialize(GameObject leftPlayer, GameObject rightPlayer, Type opponentType)
{
base.Initialize(leftPlayer, rightPlayer, opponentType);
leftWall.side = leftPlayer.GetComponent<BasePlayer>();
rightWall.side = rightPlayer.GetComponent<BasePlayer>();
leftWall.onHitBall = rightWall.onHitBall = UpdatePlayerPoint;
if (UnityEngine.Random.Range(0, 100) > 49)
{
ToggleTurn();
}
me.StartPlay();
opponent.StartPlay();
}
private void ToggleTurn()
{
me.myTurn = !me.myTurn;
opponent.myTurn = !opponent.myTurn;
}
public void UpdatePlayerPoint(Wall wall)
{
((IPause)me).Pause();
((IPause)opponent).Pause();
if (wall.side == me)
{
opponent.Point++;
_ui.UpdatePlayerPoint(opponent, me, RestartRound, EndMatch);
}
else if (wall.side == opponent)
{
me.Point++;
_ui.UpdatePlayerPoint(me, opponent, RestartRound, EndMatch);
}
}
private void RestartRound()
{
ToggleTurn();
me.StartPlay();
opponent.StartPlay();
Debug.Log("RestartRound");
}
private void EndMatch(BasePlayer loser)
{
Fail(loser);
_ui.EndMatch();
Debug.Log("EndMatch");
}
}
}<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
public class WatchDogPlayer : BasePlayer, IPause
{
protected override IEnumerator BeforeLaunchBall()
{
if (myTurn)
{
HoldBall();
float time = 0;
WaitForFixedUpdate wait = new WaitForFixedUpdate();
while (time < 2)
{
float duration = 0.5f;
float subTime = 0;
direction = Mathf.Sign(Random.Range(-1f, 1f));
while (time < 2 && subTime < duration)
{
time += Time.deltaTime;
subTime += Time.fixedDeltaTime;
FixedUpdate();
yield return wait;
}
yield return null;
}
}
}
private void Update()
{
direction = Mathf.Clamp(Ball.transform.position.y - transform.position.y, -1, 1);
}
#region IPause
void IPause.Pause()
{
runtimeSpeed = 0;
}
void IPause.Play()
{
Reset();
}
#endregion
}
}<file_sep># Pong
A classic clone of the game of the same name published in 1972. Made with Unity.
# Credit
### Audios
* [8000__cfork__cf-fx-bloibb](https://freesound.org/people/cfork/sounds/8000/)
* [13959__adcbicycle__7](https://freesound.org/people/adcbicycle/sounds/13959/)
* [151022__bubaproducer__laser-shot-silenced](https://freesound.org/people/bubaproducer/sounds/151022/)
* [320181__dland__hint](https://freesound.org/people/dland/sounds/320181/)
* [371433__s4l4m13__reptilian-logic](https://freesound.org/people/s4l4m13/sounds/371433/)
<file_sep>using UnityEngine;
namespace PongClone
{
public class CoroutineHost : MonoBehaviour
{
}
}<file_sep>using System.Collections.Generic;
using UnityEngine;
namespace PongClone
{
public class GlobalData : MonoBehaviour
{
private static GlobalData _instance;
public static GlobalData Instance
{
get
{
if (_instance == null)
{
_instance = FindObjectOfType<GlobalData>();
if (_instance == null)
{
_instance = (new GameObject("GlobalData")).AddComponent<GlobalData>();
_instance._saveData = SaveData.Load();
DontDestroyOnLoad(_instance.gameObject);
}
}
return _instance;
}
}
#region Save Data
#if UNITY_EDITOR
public bool saveDataFromDisk = true;
#endif
[SerializeField] private SaveData _saveData;
public int PointsToWin
{
get { return _saveData.pointsTowin; }
set { _saveData.pointsTowin = value; }
}
public Handedness Handedness
{
get { return _saveData.handedness; }
set { _saveData.handedness = value; }
}
public bool MusicOn
{
get { return _saveData.musicOn; }
set { _saveData.musicOn = _audioManager.MusicOn = value; }
}
public bool SoundOn
{
get { return _saveData.soundOn; }
set { _saveData.soundOn = _audioManager.SoundOn = value; }
}
public List<int> TopPoints
{
get { return _saveData.localTopPoints; }
}
public int LastSessionPoint
{
get { return _saveData.lastSessionPoint; }
set { _saveData.lastSessionPoint = value; }
}
public int InsertToBillboard(int point)
{
return _saveData.InsertToBillboard(point);
}
#endregion
#region Audio
private AudioManager _audioManager;
[SerializeField] private List<AudioClip> _ballHit = null;
[SerializeField] private AudioClip _deathPulse = null;
[SerializeField] private AudioClip _uiClick = null;
#endregion
private void Awake()
{
if (_instance == null)
{
Debug.LogFormat("GlobalData created: {0}", GetInstanceID());
_instance = this;
#if UNITY_EDITOR
if (saveDataFromDisk)
{
_saveData = SaveData.Load();
}
#else
_saveData = SaveData.Load();
#endif
_audioManager = GetComponent<AudioManager>();
_audioManager.LoadSetting(this);
DontDestroyOnLoad(transform.root.gameObject);
}
else
{
if (_instance.gameObject != gameObject)
{
Debug.LogFormat("GlobalData destroyed: {0}", GetInstanceID());
Destroy(gameObject);
}
}
}
#region Test
private void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
_saveData.Save();
}
if (Input.GetKeyDown(KeyCode.L))
{
_saveData = SaveData.Load();
}
if (Input.GetKeyDown(KeyCode.D))
{
SaveData.Clear();
_saveData = new SaveData();
}
if (Input.GetKeyDown(KeyCode.P))
{
_audioManager.PlaySoundRepeat(_deathPulse, 5, 0.3f);
}
if (Input.GetKeyDown(KeyCode.O))
{
_audioManager.PlaySound(_ballHit[0]);
}
}
#endregion
#region Audio
public void PlayUIClickSound()
{
_audioManager.PlaySound(_uiClick);
}
public void PlayBallHitSoundWith(GameObject with)
{
int id = with.CompareTag(Definition.WALL) ? 1 : 0;
_audioManager.PlaySound(_ballHit[id]);
}
public void PlayDeathSound()
{
_audioManager.PlaySoundRepeat(_deathPulse, 5, 0.3f);
}
#endregion
#if !UNITY_EDITOR && (UNITY_ANDROID || UNITY_IOS)
private void OnApplicationPause(bool pauseStatus)
{
if (pauseStatus && _instance.gameObject == gameObject)
{
_saveData.Save();
SaveData.WriteToDisk();
}
}
#else
private void OnApplicationQuit()
{
if (_instance.gameObject == gameObject)
{
_saveData.Save();
SaveData.WriteToDisk();
_instance = null;
}
}
#endif
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
namespace PongClone
{
public class WallGameplayUI : BaseGameplayUI
{
private int _pointIndex;
public void SetHandedness(bool rightHandedness)
{
_pointIndex = rightHandedness ? 1 : 0;
_points[_pointIndex].gameObject.SetActive(true);
_points[(_pointIndex + 1) % _points.Length].gameObject.SetActive(false);
}
public void UpdatePlayerPoint(int point, bool rightHandedness)
{
_points[_pointIndex].text = point.ToString();
StartCoroutine(PointShine(_pointIndex, null));
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace PongClone
{
public class MainMenu : MonoBehaviour
{
public GlobalData globalData;
//[SerializeField] private SceneFader _screenFade;
public SceneFader sceneFader;
[SerializeField] private BillboardPage _billboard = null;
public BillboardPage Billboard
{
get { return _billboard; }
}
[SerializeField] private GameObject _billboardBack = null;
private void Awake()
{
_billboard.back = _billboardBack;
}
private void Start()
{
InitSettingPage();
}
private void OnDestroy()
{
Debug.LogFormat("MainMenu: OnDestroy");
}
public void LoadSceneAsync(string sceneName)
{
sceneFader.LoadSceneAsync(sceneName);
}
public void PlayUIClickSound()
{
globalData.PlayUIClickSound();
}
#region Setting Page
[SerializeField] private RectTransform _pointsToWinParent = null;
[SerializeField] private RectTransform _handednessParent = null;
[SerializeField] private Toggle _music = null;
[SerializeField] private Toggle _sound = null;
private void InitSettingPage()
{
// Prevent ui from makeing click sounds on initialization.
bool soundOn = globalData.SoundOn;
globalData.SoundOn = false;
// 1/3/5
for (int i = 0; i < _pointsToWinParent.childCount; i++)
{
Toggle t = _pointsToWinParent.GetChild(i).GetComponent<Toggle>();
int index = i;
t.onValueChanged.AddListener((b) =>
{
SetPointsToWin(b, 1 + 2 * index);
});
t.isOn = false;
}
_pointsToWinParent.GetChild((globalData.PointsToWin - 1) / 2).GetComponent<Toggle>().isOn = true;
_handednessParent.GetChild(0).GetComponent<Toggle>().onValueChanged.AddListener((b) =>
{
SetHandedness(b, Handedness.Left);
});
_handednessParent.GetChild(0).GetComponent<Toggle>().isOn = (globalData.Handedness == Handedness.Left);
_handednessParent.GetChild(1).GetComponent<Toggle>().onValueChanged.AddListener((b) =>
{
SetHandedness(b, Handedness.Right);
});
_handednessParent.GetChild(1).GetComponent<Toggle>().isOn = (globalData.Handedness == Handedness.Right);
// Restore data setting.
globalData.SoundOn = soundOn;
_music.isOn = globalData.MusicOn;
_sound.isOn = globalData.SoundOn;
}
public void SetPointsToWin(bool isOn, int pointToWin)
{
PlayUIClickSound();
if (isOn)
{
globalData.PointsToWin = pointToWin;
}
}
public void SetHandedness(bool isOn, Handedness handedness)
{
PlayUIClickSound();
if (isOn)
{
globalData.Handedness = handedness;
}
}
public void ToggleMusic(bool on)
{
globalData.MusicOn = on;
}
public void ToggleSound(bool on)
{
globalData.SoundOn = on;
}
#endregion
#region Billboard Page
public void PlayBillboard()
{
Billboard.PlayBillboard();
}
#endregion
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
namespace PongClone
{
public class SceneFader : MonoBehaviour
{
private static SceneFader _instance;
public static SceneFader Instance
{
get { return _instance; }
}
#region Fade
public bool FadedIn { get; private set; }
public bool FadedOut { get; private set; }
[SerializeField] Image _cover = null;
[SerializeField] private float fadeInDuration = 1;
[SerializeField] private float fadeOutDuration = 1;
#endregion
private void Awake()
{
if (_instance == null)
{
Debug.LogFormat("SceneFader Awake: {0}", GetInstanceID());
_instance = this;
SceneManager.sceneLoaded += OnSceneLoaded;
SceneManager.sceneUnloaded += ScreenFadeOut;
DontDestroyOnLoad(gameObject);
}
else
{
if (_instance.gameObject != gameObject)
{
Destroy(gameObject);
}
}
}
private void Start()
{
_cover.canvasRenderer.SetAlpha(0);
}
private void OnDestroy()
{
Debug.LogFormat("SceneFader OnDestroy: {0}", GetInstanceID());
if (_instance.gameObject == gameObject)
{
SceneManager.sceneLoaded -= OnSceneLoaded;
SceneManager.sceneUnloaded -= ScreenFadeOut;
_instance = null;
}
}
#region Scene
public void LoadSceneAsync(string sceneName)
{
StartCoroutine(LoadSceneTask(sceneName));
FadeIn();
}
private IEnumerator LoadSceneTask(string sceneName)
{
AsyncOperation asyncLoad = SceneManager.LoadSceneAsync(sceneName);
asyncLoad.allowSceneActivation = false;
while (asyncLoad.progress < 0.9f || !FadedIn)
{
yield return null;
}
asyncLoad.allowSceneActivation = true;
while (!asyncLoad.isDone)
{
Debug.LogFormat("isDone:{0}, progress:{1}", asyncLoad.isDone, asyncLoad.progress);
yield return null;
}
Debug.LogFormat("isDone:{0}, progress:{1}", asyncLoad.isDone, asyncLoad.progress);
}
private void ScreenFadeOut(Scene current)
{
FadeOut();
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
{
Debug.LogFormat("OnSceneLoaded: {0}", scene.name);
Gameplay gameplay = FindObjectOfType<Gameplay>();
if (gameplay)
{
gameplay.sceneFader = this;
gameplay.globalData = GlobalData.Instance;
gameplay.rightHandedness = (gameplay.globalData.Handedness == Handedness.Right);
gameplay.ManualStart();
}
else if (scene.buildIndex == 0)
{
MainMenu mainMenu = FindObjectOfType<MainMenu>();
mainMenu.sceneFader = this;
mainMenu.Billboard.globalData = mainMenu.globalData = GlobalData.Instance;
}
}
#endregion
#region Fade
public void FadeIn(Action onComplete = null)
{
FadedIn = false;
StartCoroutine(FadeInTask(onComplete));
}
private IEnumerator FadeInTask(Action onComplete)
{
_cover.raycastTarget = true;
_cover.CrossFadeAlpha(1, fadeInDuration, false);
yield return new WaitUntil(() => _cover.canvasRenderer.GetAlpha() == 1);
FadedIn = true;
onComplete?.Invoke();
}
public void FadeOut(Action onComplete = null)
{
FadedOut = false;
StartCoroutine(FadeOutTask(onComplete));
}
private IEnumerator FadeOutTask(Action onComplete)
{
_cover.CrossFadeAlpha(0, fadeOutDuration, false);
yield return new WaitUntil(() => _cover.canvasRenderer.GetAlpha() == 0);
_cover.raycastTarget = false;
FadedOut = true;
onComplete?.Invoke();
}
#endregion
}
}<file_sep>using System;
using UnityEngine;
namespace PongClone
{
[RequireComponent(typeof(Rigidbody2D))]
public class BaseBall : MonoBehaviour
{
public float speed;
public int Direction
{
get
{
if (_rigidbody2D.velocity.x == 0)
{
return 0;
}
return Mathf.RoundToInt(Mathf.Sign(_rigidbody2D.velocity.y / Mathf.Abs(_rigidbody2D.velocity.x)));
}
}
private Rigidbody2D _rigidbody2D;
private TrailRenderer _trail;
public Action<GameObject> onHitCeilingFloor;
private void Awake()
{
_rigidbody2D = GetComponent<Rigidbody2D>();
_trail = GetComponentInChildren<TrailRenderer>();
}
private void FixedUpdate()
{
if (_rigidbody2D.velocity.sqrMagnitude != speed * speed)
{
_rigidbody2D.velocity = _rigidbody2D.velocity.normalized * speed;
}
}
public void OnHeld()
{
_rigidbody2D.velocity = Vector2.zero;
_rigidbody2D.simulated = false;
_trail.emitting = false;
}
public void SetVelocity(Vector2 direction, float magnitude = -1)
{
float finalMagnitude = (magnitude == -1) ? speed : magnitude;
bool move = finalMagnitude > 0;
_rigidbody2D.simulated = _trail.emitting = move;
Vector2 targetVelocity = direction * finalMagnitude;
Vector2 deltaVelocity = targetVelocity - _rigidbody2D.velocity;
_rigidbody2D.AddForce(deltaVelocity * _rigidbody2D.mass, ForceMode2D.Impulse);
}
public bool TooSteep()
{
float slope = _rigidbody2D.velocity.y / Mathf.Abs(_rigidbody2D.velocity.x);
if (Mathf.Abs(slope) >= Definition.MAX_SLOPE)
{
return true;
}
return false;
}
public void AddVelocity(Vector2 deltaV)
{
_rigidbody2D.AddForce(deltaV * _rigidbody2D.mass, ForceMode2D.Impulse);
if (Mathf.Abs(_rigidbody2D.velocity.y / _rigidbody2D.velocity.x) > Definition.MAX_SLOPE)
{
_rigidbody2D.velocity = new Vector2(_rigidbody2D.velocity.x, Mathf.Sign(_rigidbody2D.velocity.y) * Mathf.Abs(_rigidbody2D.velocity.x) * Definition.MAX_SLOPE).normalized * speed;
}
else
{
_rigidbody2D.velocity = _rigidbody2D.velocity.normalized * speed;
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.CompareTag(Definition.WALL))
{
onHitCeilingFloor(collision.gameObject);
}
}
}
}<file_sep>using System.Collections;
using UnityEngine;
namespace PongClone
{
public class ManualPlayer : BasePlayer, IPause
{
private Camera _camera;
public int moveThreshold;
#if !UNITY_EDITOR && UNITY_ANDROID
private int _fingerId = -1;
#endif
protected override void Awake()
{
base.Awake();
_camera = Camera.main;
}
protected override void Start()
{
base.Start();
moveThreshold = Screen.height / 32;
}
protected override IEnumerator BeforeLaunchBall()
{
if (myTurn)
{
HoldBall();
}
yield return new WaitForSeconds(1);
}
private void Update()
{
direction = 0;
#if UNITY_EDITOR || UNITY_STANDALONE
if (Input.GetMouseButton(0))
{
Vector2 diff = Input.mousePosition - _camera.WorldToScreenPoint(transform.position);
if (Mathf.Abs(diff.y) > moveThreshold)
{
direction = Mathf.Sign(diff.y);
}
}
#elif UNITY_ANDROID
Vector2 diff = Vector2.zero;
for (int i = 0; i < Input.touchCount;)
{
Touch t = Input.GetTouch(i);
if (_fingerId == -1)
{
if (t.phase == TouchPhase.Began || t.phase == TouchPhase.Stationary || t.phase == TouchPhase.Moved)
{
_fingerId = t.fingerId;
}
}
else if (_fingerId == t.fingerId)
{
if (t.phase == TouchPhase.Ended || t.phase == TouchPhase.Canceled)
{
_fingerId = -1;
}
Vector2 v = _camera.WorldToScreenPoint(transform.position);
diff = t.position - v;
}
break;
}
if (Mathf.Abs(diff.y) > moveThreshold) {
direction = Mathf.Sign(diff.y);
}
#endif
}
#region IPause
void IPause.Pause()
{
runtimeSpeed = 0;
}
void IPause.Play()
{
Reset();
}
#endregion
}
}<file_sep>using System.Collections;
using UnityEngine;
namespace PongClone
{
public class WallPlayer : BasePlayer, IPause
{
protected override void Start()
{
preHitObject += (o) => RandomDeltaY();
}
private void RandomDeltaY()
{
if (Ball.TooSteep())
{
int d = Ball.Direction;
if (d > 0)
{
deltaY = Random.Range(-d * speed * Time.fixedDeltaTime, -d * 0.25f * speed * Time.fixedDeltaTime);
}
else
{
deltaY = Random.Range(-d * 0.25f * speed * Time.fixedDeltaTime, -d * speed * Time.fixedDeltaTime);
}
}
else
{
deltaY = Random.Range(-speed * Time.fixedDeltaTime, speed * Time.fixedDeltaTime);
}
deltaY *= 2;
}
protected override IEnumerator BeforeLaunchBall()
{
yield return null;
}
#region IPause
void IPause.Pause()
{
runtimeSpeed = 0;
}
void IPause.Play()
{
runtimeSpeed = speed;
}
#endregion
}
}<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace PongClone
{
public class BillboardPage : MonoBehaviour
{
public GlobalData globalData;
[SerializeField] RectTransform _baseRecord = null;
[SerializeField] VerticalLayoutGroup _verticalLayoutForRecords = null;
[SerializeField] Image _frame = null;
[SerializeField] RectTransform _recordParent = null;
public GameObject back;
public void PlayBillboard()
{
_frame.enabled = false;
if (_recordParent.childCount == 0)
{
InitBillboard();
}
if (globalData.LastSessionPoint != -1)
{
int p = globalData.LastSessionPoint;
globalData.LastSessionPoint = -1;
int index = globalData.InsertToBillboard(p);
if (index < SaveData.TOP_N)
{
back.GetComponent<Button>().interactable = false;
StartCoroutine(DelayInsertToPage(p, index));
}
}
}
private IEnumerator DelayInsertToPage(int point, int index)
{
yield return null;
InsertToPage(point, index);
}
private void InitBillboard()
{
List<int> points = GlobalData.Instance.TopPoints;
for (int i = 0; i < SaveData.TOP_N; i++)
{
RectTransform newOne = Instantiate(_baseRecord, _recordParent);
newOne.gameObject.SetActive(true);
newOne.name = i.ToString();
newOne.anchoredPosition = _frame.rectTransform.anchoredPosition + Vector2.right * _verticalLayoutForRecords.padding.left;
SetDataOnRecord(points[i], newOne, i);
newOne.SetSiblingIndex(i);
}
}
private void BlinkFrame()
{
_frame.BlinkAlpha(5, 0.2f);
}
private void SetDataOnRecord(int point, RectTransform transform, int index)
{
transform.GetChild(0).GetComponent<Text>().text = (index + 1).ToString() + ".";
transform.GetChild(1).GetComponent<Text>().text = point.ToString();
}
private void InsertToPage(int point, int index)
{
if (index < 0)
{
return;
}
_verticalLayoutForRecords.enabled = false;
_frame.enabled = false;
if (index < SaveData.TOP_N)
{
RectTransform rt = _recordParent.GetChild(0) as RectTransform;
RectTransform rtNext = _recordParent.GetChild(1) as RectTransform;
float yOffset = rtNext.anchoredPosition.y - rt.anchoredPosition.y;
rt = _recordParent.GetChild(_recordParent.childCount - 1) as RectTransform;
rt.AnchorPos(rt.anchoredPosition + Vector2.up * yOffset, 1, null);
_frame.rectTransform.anchoredPosition = ((RectTransform)_recordParent.GetChild(index)).anchoredPosition - Vector2.right * _verticalLayoutForRecords.padding.left;
_frame.rectTransform.SetAsLastSibling();
int i = index;
rt = _recordParent.GetChild(index) as RectTransform;
Vector2 blinkPosition = rt.anchoredPosition;
for (; i < _recordParent.childCount - 1; i++)
{
rt = _recordParent.GetChild(i) as RectTransform;
rtNext = _recordParent.GetChild(i + 1) as RectTransform;
Action<RectTransform> onComplete = null;
if (i == _recordParent.childCount - 2)
{
onComplete = (r) =>
{
OnLastAnchorMoved(r, blinkPosition, index);
};
}
rt.AnchorPos(rtNext.anchoredPosition, 1, onComplete);
rt.name = (i + 1).ToString();
SetDataOnRecord(globalData.TopPoints[i + 1], rt, i + 1);
}
}
}
private void OnLastAnchorMoved(RectTransform rt, Vector2 blinkPosition, int insertIndex)
{
Debug.LogFormat("last moved one: {0}", rt.GetInstanceID());
int index = rt.GetSiblingIndex();
RectTransform blink = rt.parent.GetChild(index + 1) as RectTransform;
Debug.LogFormat("blink: {0}", blink.GetInstanceID());
_frame.rectTransform.anchoredPosition = blinkPosition;
_frame.enabled = true;
_frame.BlinkAlpha(5, 0.2f);
rt = _recordParent.GetChild(_recordParent.childCount - 1) as RectTransform;
rt.anchoredPosition = blinkPosition;
rt.SetSiblingIndex(insertIndex);
rt.name = insertIndex.ToString();
SetDataOnRecord(globalData.TopPoints[insertIndex], rt, insertIndex);
CanvasRenderer[] cr = rt.GetComponentsInChildren<CanvasRenderer>();
int i = 0;
for (; i < cr.Length - 1; i++)
{
cr[i].SetAlpha(0);
cr[i].GetComponent<Graphic>().FadeAlpha(1, 1);
}
cr[i].SetAlpha(0);
cr[i].GetComponent<Graphic>().FadeAlpha(1, 1, EnableBack);
}
private void EnableBack()
{
back.GetComponent<Button>().interactable = true;
}
}
}<file_sep>using System;
using System.Collections;
using UnityEngine;
namespace PongClone
{
public class GameplayUI : BaseGameplayUI
{
private const float MAX_POINT_TO_WIN = 7;
private int _pointsToWin;
public int PointsToWin
{
get { return _pointsToWin; }
set
{
_pointsToWin = value;
_pointIndexInterval = MAX_POINT_TO_WIN / value;
}
}
private float _pointIndexInterval;
public Sprite[] bars;
public void UpdatePlayerPoint(BasePlayer winner, BasePlayer loser, Action onRoundComplete, Action<BasePlayer> onMatchComplete)
{
_points[winner.id].text = winner.Point.ToString();
SpriteRenderer sr = loser.GetComponent<SpriteRenderer>();
int index = Mathf.RoundToInt(winner.Point * _pointIndexInterval);
Debug.LogFormat("index: {0}", index);
if (index > 6)
{
sr.sprite = bars[(int)MAX_POINT_TO_WIN - 1];
StartCoroutine(WinLoseAnim(winner, loser, onMatchComplete));
}
else
{
StartCoroutine(PointShine(winner.id, onRoundComplete));
sr.sprite = bars[index];
}
}
private IEnumerator WinLoseAnim(BasePlayer winner, BasePlayer loser, Action<BasePlayer> onComplete)
{
yield return StartCoroutine(PointShine(winner.id, null));
onComplete(loser);
Debug.Log("WinLoseAnim");
}
}
}
|
50acae893a7b7e73af3109962318c5a018c6698d
|
[
"Markdown",
"C#"
] | 29
|
C#
|
ToyMachineGraphics/Pong-Unity-Clone
|
4918726ec43e74e462876046f089a0269f2937b3
|
eb30664daacfc879cf9444e1269041548228079e
|
refs/heads/master
|
<file_sep>#include <Arduino.h>
#include <SPI.h>
#include "Adafruit_BLE.h"
#include "Adafruit_BluefruitLE_SPI.h"
#include "Adafruit_BluefruitLE_UART.h"
#include "Adafruit_FreeTouch.h"
#include "BluefruitConfig.h"
#define FACTORYRESET_ENABLE 0
#define MINIMUM_FIRMWARE_VERSION "0.6.6"
#define MODE_LED_BEHAVIOUR "DISABLE"
#define NUM_BUTTONS 5
#define OVERSAMPLE_AMOUNT OVERSAMPLE_1
#define SERIES_RESISTOR RESISTOR_50K
#define FREQ_MODE FREQ_MODE_NONE
#define DEBOUNCE_DELAY 30
typedef struct
{
Adafruit_FreeTouch qt;
uint64_t lastDebounceTime;
int thresh;
const __FlashStringHelper* keycode;
uint8_t pressed;
uint8_t prevState;
} gameboyButton_t;
static gameboyButton_t buttons[NUM_BUTTONS];
static Adafruit_BluefruitLE_SPI ble(BLUEFRUIT_SPI_CS, BLUEFRUIT_SPI_IRQ, BLUEFRUIT_SPI_RST);
static void readButtons(void);
static void sendButtons(void);
static void error(void);
void setup(void)
{
int i;
// while (!Serial);
/* LED for blinking when there's an error */
pinMode(LED_BUILTIN, OUTPUT);
/* Button setup */
memset(buttons, 0x00, sizeof(buttons));
/* L (L) */
buttons[0].qt = Adafruit_FreeTouch(A1, OVERSAMPLE_AMOUNT, SERIES_RESISTOR, FREQ_MODE);
buttons[0].thresh = 500;
buttons[0].keycode = F("0F");
/* Left (A) */
buttons[1].qt = Adafruit_FreeTouch(A2, OVERSAMPLE_AMOUNT, SERIES_RESISTOR, FREQ_MODE);
buttons[1].thresh = 500;
buttons[1].keycode = F("04");
/* Up (W) */
buttons[2].qt = Adafruit_FreeTouch(A3, OVERSAMPLE_AMOUNT, SERIES_RESISTOR, FREQ_MODE);
buttons[2].thresh = 500;
buttons[2].keycode = F("1A");
/* Right (D) */
buttons[3].qt = Adafruit_FreeTouch(A4, OVERSAMPLE_AMOUNT, SERIES_RESISTOR, FREQ_MODE);
buttons[3].thresh = 500;
buttons[3].keycode = F("07");
/* Down (S) */
buttons[4].qt = Adafruit_FreeTouch(A5, OVERSAMPLE_AMOUNT, SERIES_RESISTOR, FREQ_MODE);
buttons[4].thresh = 500;
buttons[4].keycode = F("16");
for (i = 0; i < NUM_BUTTONS; ++i)
{
if (!buttons[i].qt.begin())
error(F("Could not initialize button"));
}
/* Serial setup */
Serial.begin(115200);
Serial.println(F("Adafruit Bluefruit HID Keyboard Example"));
Serial.println(F("---------------------------------------"));
/* Initialise the BLE module */
Serial.print(F("Initialising the Bluefruit LE module: "));
if (!ble.begin(VERBOSE_MODE))
error(F("Couldn't find Bluefruit, make sure it's in CoMmanD mode & check wiring?"));
Serial.println(F("OK!"));
if (FACTORYRESET_ENABLE)
{
/* Perform a factory reset to make sure everything is in a known state */
Serial.println(F("Performing a factory reset: "));
if (!ble.factoryReset())
error(F("Couldn't factory reset"));
}
/* Disable command echo from Bluefruit */
ble.echo(false);
/* Print Bluefruit information */
Serial.println("Requesting Bluefruit info:");
ble.info();
/* Change the device name to make it easier to find */
Serial.println(F("Setting device name to 'Bluefruit Keyboard L': "));
if (!ble.sendCommandCheckOK(F("AT+GAPDEVNAME=Bluefruit Keyboard L")))
error(F("Could not set device name?"));
/* Enable HID Service */
Serial.println(F("Enable HID Service (including Keyboard): "));
if (ble.isVersionAtLeast(MINIMUM_FIRMWARE_VERSION))
{
if (!ble.sendCommandCheckOK(F("AT+BleHIDEn=On")))
error(F("Could not enable Keyboard"));
}
else
{
if (!ble.sendCommandCheckOK(F("AT+BleKeyboardEn=On")))
error(F("Could not enable Keyboard"));
}
/* Add or remove service requires a reset */
Serial.println(F("Performing a SW reset (service changes require a reset): "));
if (!ble.reset())
error(F("Couldn't reset??"));
ble.sendCommandCheckOK("AT+HWModeLED=" MODE_LED_BEHAVIOUR);
Serial.println(F("Ready to go!"));
Serial.println();
}
void loop(void)
{
readButtons();
sendButtons();
}
static void readButtons(void)
{
int i, result;
uint8_t newState;
for (i = 0; i < NUM_BUTTONS; ++i)
{
newState = buttons[i].prevState;
result = buttons[i].qt.measure();
if (result > buttons[i].thresh)
newState = 1;
else if (result > 0)
newState = 0;
if (newState != buttons[i].prevState)
buttons[i].lastDebounceTime = millis();
if (millis() - buttons[i].lastDebounceTime > DEBOUNCE_DELAY)
buttons[i].pressed = newState;
buttons[i].prevState = newState;
}
}
static void sendButtons(void)
{
int i;
ble.print(F("AT+BleKeyboardCode=00-00"));
// Serial.print(F("AT+BleKeyboardCode=00-00"));
for (i = 0; i < NUM_BUTTONS; ++i)
{
if (buttons[i].pressed)
{
ble.print(F("-"));
ble.print(buttons[i].keycode);
// Serial.print(F("-"));
// Serial.print(buttons[i].keycode);
}
}
ble.println();
// Serial.println();
ble.waitForOK();
// Serial.println(F("OK!"));
}
static void error(const __FlashStringHelper*err)
{
while (1)
{
if (!Serial)
Serial.begin(115200);
Serial.println(err);
digitalWrite(LED_BUILTIN, HIGH);
delay(250);
digitalWrite(LED_BUILTIN, LOW);
delay(250);
}
}
|
aca25c1c8293d3325004fc2bdd09a5c21981fbb7
|
[
"C++"
] | 1
|
C++
|
CalculatorSP/gameboygloves2
|
ec8a3468ef32aea519f8c99e8870c58ea2c9a267
|
92756b2e2823c5972c8b6b96727899256ff2a9fa
|
refs/heads/master
|
<repo_name>sherbet-lily/031702303<file_sep>/partitionI.java
import java.util.ArrayList;
public class partitionI {
String name;
String telephone;
ArrayList<String> address = new ArrayList<String>();
public String getName(int ch,String ogdata) {
return ogdata.substring(2,ch);
}
public String getTelephone(int i,String ogdata) {
return ogdata.substring(i-11, i);
}
}
|
9e163065b934347d2b45bf08f0e6730ddb912e3e
|
[
"Java"
] | 1
|
Java
|
sherbet-lily/031702303
|
26396041f8188ba87ca74d742b3eab45df7469a4
|
367c6b17d07016787db39d34283cd60d5c221b45
|
refs/heads/master
|
<repo_name>mibsbalsante/spotify-wrapper-player<file_sep>/tests/intro.md
# training with unit test tools
## video 78 | skip, only, bail
```javascript
// alt: use --bail (or `npm test -- --bail`) to stop test when some case fail
describe('Main', () => {
describe('Method A', () => {
context('Case 1', () => {
it('should happen', () => {});
});
// alt: context.only('Case 2', () => {})
context('Case 2', () => {
// alt: it.skip('should happen', () => {})
it('should happen', () => {
throw new Error('it was just a little mistake');
});
it('should happen again', () => {
});
});
});
});
```
## video 79 | mocha hooks
```javascript
describe('Main', () => {
// it runs once before the test
before(() => {
console.log('before');
});
// it runs once after the test
after(() => {
console.log('after');
});
// it runs every time, before every block
beforeEach(() => {
console.log('beforeEach');
});
// it runs every time, after every block
afterEach(() => {
console.log('afterEach');
});
it('test 1', () => {
console.log('test 1');
});
it('test 2', () => {
console.log('test 2');
});
});
```
## video 80 | hooks in practice
```javascript
describe('Main', () => {
let arr;
// it runs once before the block
before(() => {
// ex: open a db connection
});
// it runs once after the block
after(() => {
// ex: close a db connection
});
// it runs every time, before every block
beforeEach(() => {
arr = [1, 2, 3];
});
// it runs every time, after every block
afterEach(() => {
});
it('should have a size of 4 when push another value to the array', () => {
arr.push(4);
console.log(arr.length); // === 4
});
it('should have a size of 2 when pop a value to the array', () => {
arr.pop();
console.log(arr.length); // === 2
});
it('should remove the value 3 when use pop in the array', () => {
console.log(arr.pop() === 3); // true
});
});
```
## video 81 | chai methods
```javascript
const { expect } = require('chai');
describe('Main', () => {
let arr;
// it runs once before the block
before(() => {
// open a db connection
});
// it runs once after the block
after(() => {
// close a db connection
});
// it runs every time, before every block
beforeEach(() => {
arr = [1, 2, 3];
});
// it runs every time, after every block
afterEach(() => {
});
// smoke test
it('should be an array', () => {
expect(arr).to.be.an('array');
});
it('should have a size of 4 when push another value to the array', () => {
arr.push(4);
expect(arr).to.have.lengthOf(4);
});
it('should have a size of 2 when pop a value to the array', () => {
arr.pop();
expect(arr).to.have.lengthOf(2);
});
it('should remove the value 3 when use pop in the array', () => {
arr.pop();
expect(arr).to.not.include(3);
});
it('should return true when pop from the array', () => (
expect(arr.pop() === 3).to.be.true
));
});
```
<file_sep>/src/main.js
import searchEnterTrigger from './SearchTrigger';
import selectAlbumTrigger from './SelectAlbumTrigger';
import playlisTrigger from './PlaylistTrigger';
searchEnterTrigger();
selectAlbumTrigger();
playlisTrigger();
|
abd8087bd542298e8bc62ee5028395dc9e9eaf6c
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
mibsbalsante/spotify-wrapper-player
|
8f93b6779df1ccd1d50975ec1e6c6c21de68a07d
|
c4731d9cfcf1bd986c8d7cdc53cf0e37217421f0
|
refs/heads/main
|
<file_sep>import React from "react";
export default function ListItemPage(props) {
const { value } = props;
return <p>{value}</p>;
}
<file_sep>import React from "react";
import { BounceLoader } from "react-spinners";
import { css } from "@emotion/core";
export default function Loader(props) {
console.log(props.loading);
return (
<div>
<BounceLoader
loading={props.loading}
// css={override}
size={150}
/>
</div>
);
}
<file_sep>import React, { useState, useEffect } from "react";
import "./App.css";
import CheckBox from "./components/CheckBox";
import DisplayResult from "./components/DisplayResult";
import Button from "./components/Button";
// import Loader from "./components/Loader";
export default function App() {
const [itemLists, setitemLists] = useState([
{ id: 1, value: "Have", isChecked: false },
{ id: 2, value: "before", isChecked: false },
{ id: 3, value: "date before", isChecked: false },
{ id: 4, value: "speak with my ex", isChecked: false },
{ id: 5, value: "speak with my e", isChecked: false },
{ id: 6, value: "speak with my", isChecked: false },
]);
const [results, setresults] = useState(0);
const [loadings, setLoadings] = useState(false);
const [resultStores, setresultStores] = useState([
{ id: 1, value: "You are still and innocent man 1", score: 1 },
{ id: 2, value: "You are still and innocent man 2", score: 2 },
{ id: 3, value: "You are still and innocent man 3", score: 3 },
{ id: 4, value: "You are still and innocent man 4", score: 4 },
{ id: 5, value: "You are still and innocent man 5", score: 5 },
{ id: 6, value: "You are still and innocent man 6", score: 6 },
]);
const totalCount = Object.keys(itemLists).length;
var textResult;
const handleInput = (event) => {
setitemLists(
itemLists.map((itemList) => {
if (itemList.id == event.target.value) {
return {
...itemList,
isChecked: !itemList.isChecked,
};
}
return itemList;
})
);
};
const handleSubmit = (event) => {
event.preventDefault();
// setLoadings(false);
setresults(
itemLists.filter((itemList) => itemList.isChecked === true).length
);
};
const handleClear = () => {
setresults(0);
};
return (
<div className="App">
Innocent Game
{results <= 0 ? (
<div>
{itemLists.map((itemList, key) => {
return (
<CheckBox handleInput={handleInput} key={key} {...itemList} />
);
})}
<Button handleSubmit={handleSubmit} />
</div>
) : (
<div>
{resultStores.map((resultStore) => {
if (results === resultStore.id) {
textResult = resultStore.value;
}
return null;
})}
<DisplayResult
textResult={textResult}
totalCount={totalCount}
results={results}
/>
;
<button type="button" onClick={handleClear}>
Go Back
</button>
</div>
)}
</div>
);
}
<file_sep>import React from "react";
export default function DisplayResult(props) {
// console.log(props);
const { results, totalCount, textResult } = props;
return (
<div>
<p>
Result: {results}/{totalCount}
</p>
<p>{textResult}</p>
</div>
);
}
|
f8ebb5040a2b0fcc5008182e5109e8e1507e587f
|
[
"JavaScript"
] | 4
|
JavaScript
|
kehinde-elelu/honestgame
|
742e3d9ec2e89dac7efde6aee68e34b50a3880be
|
733db32e7160e948c51bd461a276181c02c0d933
|
refs/heads/master
|
<repo_name>sat0yu/sandbox<file_sep>/abc/019/A.py
# coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
strlist = raw_input()
arr = [int(x) for x in strlist.split()]
print(sorted(arr)[1])
<file_sep>/arc/031/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
void swap(vector<int>& blocks, int i, int j){
int tmp = blocks[i];
blocks[i] = blocks[j];
blocks[j] = tmp;
}
int main(int argc, char** argv){
int N;
cin >> N;
vector<int> blocks(N),
copy1, copy2;
for(int i=0; i<N; i++){
cin >> blocks[i];
}
copy(blocks.begin(), blocks.end(), back_inserter(copy1));
copy(blocks.begin(), blocks.end(), back_inserter(copy2));
int ret1 = 0, ret2 = 0;
int cidx = (blocks.size()-1)/2;
for(int i=0; i<cidx; i++){
for(int j=cidx-1; j>i+1; j++){
if( copy1[j] < copy1[j-1] ){
swap(copy1, j, j-1);
printf("left swap %d,%d\n", j, j-1);
ret1++;
}
}
}
for(int i=0; i<cidx; i++){
for(int j=cidx+1; j<N-i-1; j++){
if( copy1[j] < copy1[j+1] ){
printf("right swap %d,%d\n", j, j+1);
swap(copy1, j, j+1);
ret1++;
}
}
}
for(int i=0; i<N; i++){
printf("%d ", copy1[i]);
}
cout << endl;
// cout << ret1 << "," << ret2 << endl;
return 0;
}
<file_sep>/abc/019/D.py
# coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
<file_sep>/arc/031/A.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
string name;
cin >> name;
int size = name.size();
for(int i=0; i<size/2; i++){
if(name[i] != name[size-1-i]){
cout << "NO" << endl;;
return 0;
}
}
cout << "YES" << endl;;
return 0;
}
<file_sep>/checkio/speechmodule.py
FIRST_TEN = ["one", "two", "three", "four", "five", "six", "seven",
"eight", "nine"]
SECOND_TEN = ["ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen"]
OTHER_TENS = ["twenty", "thirty", "forty", "fifty", "sixty", "seventy",
"eighty", "ninety"]
HUNDRED = "hundred"
def checkio(number):
a, b, c = "", "", ""
w, x, y, z = 0, 0, 0, 0
while number > 0:
print number
if number >= 100:
w += 1
number -= 100
elif y == 0 and 9 < number < 20:
x = number - 9
number = 0
elif number >= 10:
y += 1
number -= 10
else:
z += 1
number -= 1
print w,x,y,z
if w > 0:
a = " ".join((FIRST_TEN[w-1],HUNDRED))
if x == y == z == 0:
return a
if x > 0:
b = SECOND_TEN[x-1]
if w > 0:
print " ".join((a,b))
return " ".join((a,b))
else:
print b
return b
if y > 0:
b = OTHER_TENS[y-2]
if not z > 0:
if w > 0:
print " ".join((a,b))
return " ".join((a,b))
else:
print b
return b
if z > 0:
c = FIRST_TEN[z-1]
if w > 0 and y > 0:
print " ".join((a,b,c))
return " ".join((a,b,c))
elif w > 0:
print " ".join((a,c))
return " ".join((a,c))
elif y > 0:
print " ".join((b,c))
return " ".join((b,c))
else:
print c
return c
#Some hints
#Don't forget strip whitespaces at the end of string
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(4) == 'four', "1st example"
assert checkio(133) == 'one hundred thirty three', "2nd example"
assert checkio(12) == 'twelve', "3rd example"
assert checkio(101) == 'one hundred one', "4th example"
assert checkio(212) == 'two hundred twelve', "5th example"
assert checkio(40) == 'forty', "6th example"
<file_sep>/abc/015/B.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int cnt=0, sum=0, ai, n;
cin >> n;
for(int i=0; i<n; i++){
scanf("%d", &ai);
if(ai > 0){
cnt++;
sum += ai;
}
}
cout << (int)ceil((double)sum / (double)cnt) << endl;
return 0;
}
<file_sep>/codeiq/codeiq633.py
#coding: utf-8;
import numpy as np
#// 教科データ
category=['Ja','Ma','En','So','Sc','Mu','Ar']
#// 海平怒りのスコア初期値
#score=[35,15,20,30,25,15,25]
#// 海平怒りの倍数(7日分
#multiplier=[
# [1,1,2,3,5,8,13],
# [1,5,9,13,17,21,25],
# [1,5,8,12,15,19,22],
# [1,3,5,7,9,11,13],
# [1,2,4,6,8,10,12],
# [1,4,6,9,11,14,16],
# [1,2,2,3,5,8,11],
#]
matrix = np.array([
[35,35,70,105,175,280,455],
[15,75,135,195,255,315,375],
[20,100,160,240,300,380,440],
[30,90,150,210,270,330,390],
[25,50,100,150,200,250,300],
[15,60,90,135,165,210,240],
[25,50,50,75,125,200,275],
])
class Tree:
class node:
def __init__(self, value, indices=None, parent=None, isRoot=False):
self.__children = []
self.value = value
self.indices = indices
self.isRoot = isRoot
if parent is not None:
self.setParent(parent)
def setParent(self, n):
n.addChild(self)
self.__parent = n
def addChild(self, n):
self.__children.append(n)
def getChildren(self):
return self.__children
def getParent(self):
return self.__parent
def getAncestors(self):
p, anc = self, [self,]
while not p.isRoot:
p = p.getParent()
anc.append(p)
return anc
def __init__(self, matrix):
self.root = Tree.node(0, isRoot=True)
self.__mat = matrix
self.createFromMatrix(parent=self.root)
def createFromMatrix(self, parent=None, ancestor=[], depth=0):
for i in [i for i in range(self.__mat.shape[0]) if not i in ancestor]:
anc = ancestor[:]
anc.append(i)
indices=(i,depth)
n = Tree.node( value=self.__mat[indices], indices=indices, parent=parent)
self.createFromMatrix(parent=n, ancestor=anc, depth=depth+1)
# explorer tree in depth-first
t = Tree( np.fliplr(matrix) )
stack = [t.root,]
min_cost = sum(sum(matrix))
while len(stack) != 0:
n = stack.pop()
anc = n.getAncestors()
cost = sum([a.value for a in anc])
# cut unuseless branch
if cost < min_cost:
# update min_cost
if len(anc) == 1 + matrix.shape[1]:
min_cost = cost
order = anc
# stack child nodes in decending
chd = [ (c.value, c) for c in n.getChildren() ]
chd.sort(reverse=True)
for i,c in chd:
stack.append(c)
result = [ category[a.indices[0]] for a in order[:-1] ]
print "見せる順番:%s" % "->".join(result)
print "怒りのスコア:%d" % min_cost
<file_sep>/checkio/weekend_counter.py
from datetime import date,timedelta
def checkio(from_date, to_date):
count = 0
while (to_date - from_date).days > 7:
count += 2
to_date -= timedelta(days=7)
fDow = from_date.weekday()
tDow = to_date.weekday()
if tDow > fDow:
count += 1 if fDow >= 5 else 0
count += 1 if tDow >= 5 else 0
elif tDow < 5 and fDow < 5:
count += 2
elif tDow < 5:
count += 2 if fDow == 5 else 1
else:
count += 3 if tDow == fDow else 2
return count
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(date(2013, 9, 18), date(2013, 9, 23)) == 2, "1st example"
assert checkio(date(2013, 1, 1), date(2013, 2, 1)) == 8, "2nd example"
assert checkio(date(2013, 2, 2), date(2013, 2, 3)) == 2, "3rd example"
assert checkio(date(1999, 1, 1), date(2000, 1, 1)) == 105, "4th example"
<file_sep>/abc/015/A.cpp
// #include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
string A,B;
cin >> A >> B;
if(A.size() > B.size()){
cout << A << endl;
}else{
cout << B << endl;
}
return 0;
}
<file_sep>/checkio/spaceship_landing_strip.py
#coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
def checkio(landing_map):
map_H, map_W = len(landing_map), len(landing_map[0])
area = 0
for i in range(map_H):
for j in range(map_H - i):
x, w = 0, 1
while x + w <= map_W:
#print(i,j,x,w,area)
#raw_input()
h = i + 1
if not ( h == sum([ (landing_map[l][x+w-1] == 'G'\
or landing_map[l][x+w-1] == 'S')\
for l in range(j,j+h) ]) ):
x += w
w = 1
else:
area = w * h if w * h > area else area
w += 1
return area
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(['G']) == 1, 'One cell - one variant'
assert checkio(['GS',
'GS']) == 4, 'Four good cells'
assert checkio(['GT',
'GG']) == 2, 'Four cells, but with a tree'
assert checkio(['GGTGG',
'TGGGG',
'GSSGT',
'GGGGT',
'GWGGG',
'RGTRT',
'RTGWT',
'WTWGR']) == 9, 'Classic'
<file_sep>/abc/016/A.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int m,d;
scanf("%d %d", &m, &d);
if(d==0){
printf("NO\n");
}else if(m%d){
printf("NO\n");
}else{
printf("YES\n");
}
return 0;
}
<file_sep>/abc/017/A.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int s1,e1,s2,e2,s3,e3;
cin >> s1 >> e1 >> s2 >> e2 >> s3 >> e3;
cout << ((s1*e1)+(s2*e2)+(s3*e3))/10 << endl;
return 0;
}
<file_sep>/arc/033/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define _GLIBCXX_DEBUG
#define UINT unsigned int
#define ULL unsigned long long
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
long numLeave = (1 << 22);
int counting_tree[1 << 23] = {0};
// int numLeave = 128;
// int counting_tree[2*128] = {0};
long idx2num(long idx){
return (idx - numLeave + 1);
}
long num2idx(long num){
return (num + numLeave - 1);
}
void add(long X){
long idx = num2idx(X);
while(idx > 0){
// cout << idx << endl;
counting_tree[idx]++;
idx >>= 1;
}
}
void remove(long X){
long idx=1;
while( idx2num(idx) < 1 ){
// printf("idx2num(%ld);%ld, counting_tree[%ld];%d, X;%ld\n", idx, idx2num(idx), idx, counting_tree[idx], X);
counting_tree[idx]--;
// printf("counting_tree[idx << 1]:%d\n", counting_tree[idx << 1]);
if( X > counting_tree[idx << 1] ){
X -= counting_tree[idx << 1];
idx = (idx << 1) +1;
}else{
idx = (idx << 1);
}
}
counting_tree[idx]--;
cout << idx2num(idx) << endl;
return;
}
int main(int argc, char** argv){
long Q,T,X;
cin >> Q;
for(int i=0; i<Q; i++){
cin >> T >> X;
if(T==1){
add(X);
}else{
remove(X);
}
}
return 0;
}
<file_sep>/codeiq/codeiq646.py
# -*- coding:utf-8 -*-
import numpy as np
import codecs
import pyximport
pyximport.install(setup_args={'include_dirs':[np.get_include()]}, inplace=True)
from utils import *
fname = 'data/hyakunin.csv'
with codecs.open(fname, mode='r', encoding='shift-jis') as fp:
# skip first row
fp.readline()
# read rest of files
data = [row.split(u',')[3:5] for row in fp.readlines()]
data.sort()
N, UD, LD = 0, {}, {}
for i in data:
upper, lower = i[0], i[1]
j = 1
while UD.get(upper[:j], None) is not None:
j += 1
#print upper[:j], upper
UD[upper[:j]] = upper
N += j
j = 1
while LD.get(lower[:j], None) is not None:
j += 1
#print lower[:j], lower
LD[lower[:j]] = lower
N += j
print N
<file_sep>/arc/031/B.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
vector< vector<bool> > isVisited(12, vector<bool>(12, false));
char seamap[12][12];
pair<int,int> start(0,0);
int numCircle = 0, numCross = 0, numIsland = 0;
void dfs(int x, int y, int depth){
if( isVisited[x][y] ){ return; }
isVisited[x][y] = true;
if(seamap[x][y] == seamap[x+1][y]){
dfs(x+1, y, depth+1);
}
if(seamap[x][y] == seamap[x][y+1]){
dfs(x, y+1, depth+1);
}
if(seamap[x][y] == seamap[x-1][y]){
dfs(x-1, y, depth+1);
}
if(seamap[x][y] == seamap[x][y-1]){
dfs(x, y-1, depth+1);
}
if( (depth == 0) and (seamap[x][y] == 'o') ){
numIsland++;
}
};
int main(int argc, char** argv){
for(int i=1; i<=10; i++){
for(int j=1; j<=10; j++){
cin >> seamap[i][j];
}
}
for(int i=0; i<12; i++){
seamap[i][0] = '*';
seamap[i][11] = '*';
seamap[0][i] = '*';
seamap[11][i] = '*';
}
for(int i=1; i<=10; i++){
for(int j=1; j<=10; j++){
dfs(i,j,0);
}
}
if(numIsland == 1){
cout << "YES" << endl;
return 0;
}
for(int i=1; i<=10; i++){
for(int j=1; j<=10; j++){
if(seamap[i][j] == 'x'){
numIsland = 0;
seamap[i][j] = 'o';
isVisited = vector< vector<bool> >(12, vector<bool>(12, false));
for(int k=1; k<=10; k++){
for(int l=1; l<=10; l++){
dfs(k,l,0);
}
}
if(numIsland == 1){
cout << "YES" << endl;
return 0;
}
seamap[i][j] = 'x';
}
}
}
cout << "NO" << endl;
return 0;
}
<file_sep>/codeiq/codeiq828.py
#coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
class Queue:
def __init__(self):
self._que = []
def size(self):
return len(self._que)
def enqueue(self, i):
self._que.append(i)
def dequeue(self):
if not len(self._que) > 0:
raise IndexError("empty queue.")
ret = self._que[0]
self._que = self._que[1:]
return ret
def naive_bfs(S, T):
depth = 1
n = int(len(S) / 2)
mask = {}
que = Queue()
que.enqueue(S)
que.enqueue(False)
while que.size() > 0:
seq = que.dequeue()
if seq is False:
depth += 1
que.enqueue(False)
continue
seqs = [ seq[i:i+n]+seq[:i]+seq[i+n:] for i in range(1,n+1) ]
#print(depth,seqs)
#raw_input()
for _S in seqs:
if _S == T:
print("HIT:",depth,_S)
return depth
if not mask.has_key(_S):
print(depth,_S)
que.enqueue(_S)
mask[_S] = True
else:
print("already visited.")
def reverse_bfs(T, P):
depth = 1
n = int(len(P) / 2)
mask = {}
que = Queue()
que.enqueue(P)
que.enqueue(False)
while que.size() > 0:
seq = que.dequeue()
if seq is False:
depth += 1
que.enqueue(False)
continue
seqs = [ seq[n:n+i]+seq[:n]+seq[n+i:] for i in range(1,n+1) ]
#print(depth,seqs)
#raw_input()
for _P in seqs:
if _P == T:
print("HIT:",depth,_P)
return depth
if not mask.has_key(_P):
print(depth,_P)
que.enqueue(_P)
mask[_P] = True
else:
print("already visited.")
if __name__ == '__main__':
source = "1234567890"
target = "0987654321"
#print( naive_bfs(source, target) )
print( reverse_bfs(source, target) )
<file_sep>/topcoder/srm146.div2.large.cpp
#include<iostream>
#include<vector>
#include<iterator>
#include<numeric>
#include<algorithm>
using namespace std;
class BridgeCrossing{
private:
vector< vector<int> > combination(vector<int> target, int k){
vector< vector<int> > combs;
for(unsigned char i = (1 << target.size()) - 1; i > 0; --i){
int num=0;
for(int mask=1; mask != 0; mask = mask << 1){
if(i & mask){ ++num; }
}
if( num == k ){
vector<int> comb;
for(int j=0, size=target.size(); j<size; ++j){
if( i & (1 << j) ){ comb.push_back(j); }
}
combs.push_back(comb);
}
}
return combs;
};
int search(vector<int> S, vector<int> T, int spent_time, int lower_bound){
if(!(S.size() > 0)){
return spent_time;
}else if(S.size() == 1){
return spent_time + S[0];
}
//if(spent_time > lower_bound){ return spent_time; }
vector< vector<int> > combs = combination(S, 2);
vector< vector<int> >::iterator comb=combs.begin(), end_comb=combs.end();
vector<int> times;
for(; comb!=end_comb; ++comb){
vector<int> _T(T.size()), _S(S.size());
copy(S.begin(), S.end(), _S.begin());
copy(T.begin(), T.end(), _T.begin());
int go_way = max(_S[ (*comb)[0] ], _S[ (*comb)[1] ]);
// ADD TO 'T'
_T.push_back(_S[ (*comb)[0] ]);
_T.push_back(_S[ (*comb)[1] ]);
// REMOVE FROM 'S'
// we have to erase elements using indiced stored in (*comb) from back
// otherwise, indices get out of right posizions
for(vector<int>::reverse_iterator idx=(*comb).rbegin(); idx!=(*comb).rend(); ++idx){
vector<int>::iterator it = _S.begin();
advance(it, *idx);
_S.erase(it);
}
if(_S.size() > 0){
for(int j=0, end_j=_T.size(); j<end_j; ++j){
vector<int> __T(_T.size()), __S(_S.size());
copy(_S.begin(), _S.end(), __S.begin());
copy(_T.begin(), _T.end(), __T.begin());
__S.push_back(_T[j]);
vector<int>::iterator it = __T.begin();
advance(it, j);
__T.erase(it);
times.push_back( search(__S, __T, (spent_time + go_way + _T[j]), lower_bound) );
}
}else{
times.push_back( search(_S, _T, (spent_time + go_way), lower_bound) );
}
}
return *min_element(times.begin(), times.end());
};
public:
int minTime(vector<int> times){
int min_time;
// culc. naive case
min_time = ( *min_element(times.begin(), times.end()) ) * (times.size() - 2);
min_time += accumulate(times.begin(), times.end(), 0);
min_time -= *min_element(times.begin(), times.end());
vector<int> T;
return search(times, T, 0, min_time);
};
};
int main(){
BridgeCrossing bc = BridgeCrossing();
vector<int> times;
// case 1, ans: 17
times.clear();
times.push_back(1);
times.push_back(2);
times.push_back(5);
times.push_back(10);
cout << bc.minTime(times) << endl;
// case 2, ans: 16
times.clear();
times.push_back(1);
times.push_back(2);
times.push_back(3);
times.push_back(4);
times.push_back(5);
cout << bc.minTime(times) << endl;
// case 3, ans: 162
times.clear();
times.push_back(1);
times.push_back(2);
times.push_back(3);
times.push_back(50);
times.push_back(99);
times.push_back(100);
cout << bc.minTime(times) << endl;
// case 4, ans: 100
times.clear();
times.push_back(100);
cout << bc.minTime(times) << endl;
}
<file_sep>/poj/2010_2.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int N,C,F;
bool comp(pair<int, int>& a, pair<int, int>& b){
return a.first < b.first;
}
int main(int argc, char** argv){
cin >> N >> C >> F;
vector<pair<int, int> > cow(C+1);
for(int i=1; i<=C; i++){
cin >> cow[i].first >> cow[i].second;
}
// The main strategy;
// examine the cows from the one that has most greater CSAR
// to the one having the smaller score
// At first, sort cows in CSAT order
sort(cow.begin()+1, cow.end(), comp);
// Second; construct an array that stores the minimum value of
// summations of (N>>1) greater(or smaller) values than cow[i].second,
// ex; N=3,C=7 then, (N+1)>>1 is 2, and C-(N>>1) is 6
// ex; N=5,C=7 then, (N+1)>>1 is 3, and C-(N>>1) is 5
for(int i=(C-(N>>1)); i>=((N+1)>>1); i--){
priority_queue<int, vector<int>, greater<int> > greaters, smallers;
int sum_smallers=0, sum_greaters=0;
vector<int> temp(N>>1);
for(int j=i-1; j>=1; j--){
smallers.push(cow[j].second);
if( smallers.size() < (N>>1) ){continue;}
for(int k=0; k<(N>>1); k++){
sum_smallers += smallers.top();
temp[k] = smallers.top();
smallers.pop();
}
if(cow[i].second + sum_smallers > F){break;}
for(int k=0; k<(N>>1); k++){ smallers.push(temp[k]); }
sum_smallers = 0;
}
for(int j=i+1; j<=C; j++){
greaters.push(cow[j].second);
if( greaters.size() < (N>>1) ){continue;}
for(int k=0; k<(N>>1); k++){
sum_greaters += greaters.top();
temp[k] = greaters.top();
greaters.pop();
}
if(cow[i].second + sum_greaters > F){break;}
for(int k=0; k<(N>>1); k++){ greaters.push(temp[k]); }
sum_greaters = 0;
}
if(cow[i].second + sum_greaters + sum_smallers <= F){
cout << cow[i].first << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
<file_sep>/codeiq/codeiq684.py
#coding: utf-8;
import numpy as np
def fact(n):
if n <= 1:
return 1
else:
return f(n-1)*n
def perm(*args):
numerator = fact( sum(args) )
for a in args:
numerator /= fact(a)
return numerator
def make_count():
dictionary = {}
def count(head, args):
elems = args[:]
for i,e in enumerate(elems):
if e <= 0:
del elems[i]
key = "%r%r" % (head,args)
if dictionary.has_key(key):
return dictionary[key]
else:
if len(elems) > 0:
if elems[head] > 1:
elems[head] -= 1
else:
del elems[head]
else:
return 1
buf = 1
for i in range(len(elems)):
buf += count(i,elems)
dictionary[key] = buf
return buf
return count
count = make_count()
ans = 0
juwels = [1,4,1,4,2,1,3]
for i in range(len(["a","b","c","d"])): #(a+b+c+d).......
ans += count(i,juwels)
juwels = [0,4,1,4,1,1,3]
for i in range(len(["b","c","d","e","f"])): #ea(b+c+d+e+f).....
ans += count(i,juwels)
juwels = [0,4,0,4,1,1,2]
ans += count(i,juwels) #eagcb...
juwels = [0,4,0,3,1,1,2]
for i in range(len(["b","d","e"])): #eagcd(b+d+e)..
ans += count(i,juwels)
print ans
<file_sep>/abc/017/C2.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int N, M;
vector<int> s;
vector< pair<int,int> > lr;
vector<unsigned long long> bits;
int dfs(int i, unsigned long long b, int score){
unsigned long long mask = ( (1<<(lr[i].second - lr[i].first+1)) - 1 ) << (64-lr[i].first);
dfs(i+1, (b | mask), score + s[i]);
dfs(i+1, b, score);
}
int main(int argc, char** argv){
cin >> N >> M;
s.resize(N);
lr.resize(N);
for(int i=0; i<N; i++){
cin >> lr[i].first >> lr[i].second >> s[i];
}
sort(lr.begin(), lr.end());
cout << dfs(0, 0ULL, 0) << endl;
return 0;
}
<file_sep>/abc/019/B.py
# coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
s = raw_input()
pre = ''
count = 0
res = ''
for x in s:
if x == pre:
count += 1
else:
res += pre + str(count)
count = 1
pre = x
res += pre + str(count)
print(res[1:])
<file_sep>/abc/018/A.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
return 0;
}
<file_sep>/arc/032/A.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int n;
cin >> n;
if( n == 2 ){
cout << "WANWAN" << endl;
}else{
cout << "BOWWOW" << endl;
}
return 0;
}
<file_sep>/checkio/non_unique_elements.py
from collections import Counter
def checkio33(data):
count = Counter(data)
count.subtract(set(data))
# 3.3から単項加算(減算)をサポート
# 単項加算(減算)は空カウンタの加算(からの減算)のショートカット
return [x for x in data if x in +count]
def checkio27(data):
# リストに含まれる特定の要素数はcountメソッドで受け取れる
return [i for i in data if data.count(i) > 1]
def checkio(data):
ret = []
for e in data:
if sum([ True if e == f else False for f in data]) > 1:
ret.append(e)
return ret
if __name__ == "__main__":
assert isinstance(checkio33([1]), list)
assert checkio33([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
assert checkio33([1, 2, 3, 4, 5]) == []
assert checkio33([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
assert checkio33([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
assert isinstance(checkio27([1]), list)
assert checkio27([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
assert checkio27([1, 2, 3, 4, 5]) == []
assert checkio27([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
assert checkio27([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
assert isinstance(checkio([1]), list)
assert checkio([1, 2, 3, 1, 3]) == [1, 3, 1, 3]
assert checkio([1, 2, 3, 4, 5]) == []
assert checkio([5, 5, 5, 5, 5]) == [5, 5, 5, 5, 5]
assert checkio([10, 9, 10, 10, 9, 8]) == [10, 9, 10, 10, 9]
<file_sep>/codeiq/codeiq629.py
#coding: utf-8;
import numpy as np
fname = "data/sample.in.txt"
#fname = "data/problem.in.txt"
import pyximport
pyximport.install(setup_args={'include_dirs':[np.get_include()]}, inplace=True)
from utils import *
with open(fname, mode='r') as fp:
N = int(fp.readline())
W = int(fp.readline())
items = np.loadtxt(fname, dtype=np.int, delimiter=' ', skiprows=2)
items = np.r_[[[0,]*items.shape[1]], items]
knapsack(items, N, W)
<file_sep>/abc/019/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
vector<unsigned char> M(1<<27, 0);
int main(int argc, char** argv){
int N, res=0;
unsigned long long a;
cin >> N;
vector<int> A(N);
for(int i=0; i<N; i++){
cin >> A[i];
M[A[i]>>3] |= 1U << (A[i] & 0x07);
}
sort(A.begin(), A.end());
for(int i=0; i<N; i++){
unsigned long long a = A[i];
if( M[a>>3] & (1ULL << (a & 0x07)) ){
// cout << a << endl;
res++;
}
while( a < (1<<27) ){
M[a>>3] &= ~(1U << (a & 0x07));
a <<= 1;
}
}
cout << res << endl;
return 0;
}
<file_sep>/arc/033/C_bit.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define _GLIBCXX_DEBUG
#define UINT unsigned int
#define ULL unsigned long long
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int N=2000001;
int BIT[2000001] = {0};
// int N=8+1;
// int BIT[8+1] = {0};
void add(int X){
for(int x=X; x<=N; x += x & -x){
BIT[x] += 1;
}
// for(int i=0; i<N; i++){ printf("%d ", BIT[i]); }
// cout << endl;
}
void remove(int X){
for(int x=X; x<=N; x += x & -x){
BIT[x] -= 1;
}
// for(int i=0; i<N; i++){ printf("%d ", BIT[i]); }
// cout << endl;
}
void search(int X){
int k=1;
for(; k<N; k<<=1){}
k>>=1;
int x=0;
for(; k>0; k>>=1){
// printf("X:%d > BIT[x:%d + k:%d]:%d\n", X, x, k, BIT[x+k]);
if( (x + k <= N) and (X > BIT[x + k]) ){
X -= BIT[x + k];
x += k;
}
}
// considering the case in which binary-search gets to a leaf,
// 1 added to X; the 1 means the smallest range represented by k
// cout << "searched: " << x+1 << endl;
remove(x+1);
cout << x+1 << endl;
}
int main(int argc, char** argv){
int Q,T,X;
cin >> Q;
for(int i=0; i<Q; i++){
cin >> T >> X;
if(T==1){
add(X);
}else{
search(X);
}
}
return 0;
}
<file_sep>/abc/015/C2.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int n, k;
unsigned char T[10][10];
bool check(unsigned char uc, int i, int j){
if(i == n-1){
return (uc ^ T[i][j]);
}else if(i == 0){
for(int l=0; l<k; l++){
if( !check(T[i][j], i+1, l) ){
return false;
}
}
return true;
}else{
unsigned char xored = (uc ^ T[i][j]);
for(int l=0; l<k; l++){
if( !check(xored, i+1, l) ){
return false;
}
}
return true;
}
}
int main(int argc, char** argv){
cin >> n >> k;
for(int i=0; i<n; i++){
for(int j=0; j<k; j++){
scanf("%d", &(T[i][j]));
}
}
if( check(0, 0, 0) ){
printf("Nothing\n");
}else{
printf("Found\n");
}
return 0;
}
<file_sep>/abc/016/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int n,m,a,b;
scanf("%d %d", &n, &m);
vector< set<int> > G(n+1);
for(int i=1; i<=n; i++){
G[i].insert(i);
}
for(int i=0; i<m; i++){
scanf("%d %d", &a, &b);
G[a].insert(b);
G[b].insert(a);
}
for(int i=1; i<=n; i++){
set<int>::iterator it = G[i].begin(), it_end = G[i].end();
for(; it != it_end; it++){
cout << *it << " ";
}
cout << endl;
}
for(int i=1; i<=n; i++){
set<int>::iterator it = G[i].begin(), it_end = G[i].end();
int ret=0;
set<int> temp;
for(; it != it_end; it++){
set_intersection(
G[*it].begin(), G[*it].end(),
temp.begin(), temp.end(),
// G[i].begin(), G[i].end(),
back_inserter(temp));
}
cout << ret << endl;
}
return 0;
}
<file_sep>/arc/032/B.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<set>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
// vector< vector<bool> > G(100001, vector<bool>(100001, false));
// vector< vector<int> > G(100001);
vector< set<int> > G(100001);
vector<bool> H(100001, false);
int N,M;
void dfs(int node){
if(H[node]){
return;
}
H[node] = true;
for(int i=1; i<=N; i++){
// if( G[node][i] and (!H[i]) ){
// if( (!H[i]) and ( find( G[node].begin(), G[node].end(), i ) != G[node].end() ) ){
if( (!H[i]) and ( G[node].find(i) != G[node].end() ) ){
dfs(i);
}
}
return;
}
int main(int argc, char** argv){
cin >> N >> M;
for(int i=0; i<M; i++){
int a, b;
cin >> a >> b;
// G[a][b] = G[b][a] = true;
G[a].insert(b);
G[b].insert(a);
}
// for(int i=0; i<=N; i++){
// for(int j=0; j<=N; j++){
// cout << G[i][j] << " ";
// }
// cout << endl;
// }
int count=0;
for(int i=1; i<=N; i++){
if(!H[i]){
count++;
dfs(i);
}
};
cout << count - 1 << endl;
return 0;
}
<file_sep>/topcoder/srm249.div2.1100.cpp
#include<iostream>
#include<vector>
#include<map>
#include<string>
#include<math.h>
#define N 12
#define min(a,b) (a > b ? b : a)
using namespace std;
class TableSeating{
public:
double getExpected(int numTables, vector<int> probs){
double expect[N+1] = {0,};
int sum=0;
for(int i=0; i < probs.size(); ++i){ sum += probs[i]; }
if(sum != 100){ printf("warning: incorrect probs.\n"); }
for(int t=1; t <= numTables; ++t){
for(int c = min(t, probs.size()); c > 0; --c){
int nPat = t - c + 1;
double p = (probs[c - 1] / 100.0) * (1. / nPat);
for(int i = 0; i <= t - c; ++i){
expect[t] += p * ( expect[i] + c + expect[ t - ( i + c ) ] );
}
}
}
for(int i=1; i<=numTables; ++i) printf("%lf ", expect[i]);
cout << endl;
return expect[numTables];
};
};
int main(){
TableSeating ts = TableSeating();
vector<int> probs;
probs.clear();
probs.push_back(100);
cout << ts.getExpected(4, probs) << endl;
probs.clear();
probs.push_back(0);
probs.push_back(100);
cout << ts.getExpected(4, probs) << endl;
probs.clear();
probs.push_back(0);
probs.push_back(0);
probs.push_back(0);
probs.push_back(0);
probs.push_back(0);
probs.push_back(50);
probs.push_back(50);
cout << ts.getExpected(5, probs) << endl;
probs.clear();
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(9);
probs.push_back(10);
cout << ts.getExpected(12, probs) << endl;
}
<file_sep>/abc/015/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int n, k;
unsigned char T[10][10];
bool check(unsigned char uc, int i, int j){
unsigned char xored = uc ^ T[i][j];
if(i == n-1){
return xored;
}else{
bool tf = true;
for(int l=0; l<k; l++){
tf &= check(xored, i+1, l);
}
return tf;
}
}
int main(int argc, char** argv){
cin >> n >> k;
for(int i=0; i<n; i++){
for(int j=0; j<k; j++){
scanf("%d", &(T[i][j]));
}
}
if( check(0U, 0, 0) ){
printf("Nothing\n");
}else{
printf("Found\n");
}
return 0;
}
<file_sep>/poj/3176.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
// DFSで渡すのが面倒なのでグローバルで用意
int N;
// 350*(350+1)/2 = 61425
// スタック領域だと心配なのでヒープで確保
vector<int> T(70000);
vector<int> M(70000);
int dfs(int top, int left){
int pos = top*(top-1)/2+left;
// 最下段の場合はそのまま返す
if(top == N){
return M[pos]=T[pos];
}
// メモがあればそのまま返す
if(M[pos] >= 0){
return M[pos];
}
// なければ探索
int l = dfs(top+1, left);
int r = dfs(top+1, left+1);
if( l > r ){
M[pos] = T[pos] + l;
}else{
M[pos] = T[pos] + r;
}
return M[pos];
}
int main(int argc, char** argv){
cin >> N;
// 要素数はN(N+1)/2、1-originにするために+1
int size = N*(N+1)/2 + 1;
for(int i=1; i<size; i++){
cin >> T[i];
M[i] = -1;
}
// メモ化再帰
cout << dfs(1,1);
}
<file_sep>/arc/032/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
unsigned long long A[100001] = {0};
unsigned long long B[100001] = {0};
int main(int argc, char** argv){
int N, max=0, min=((1UL<<32)-1);
cin >> N;
for(int i=0; i<N; i++){
cin >> A[i] >> B[i];
max = (max > A[i]) ? max : A[i];
max = (max > B[i]) ? max : B[i];
min = (min > A[i]) ? A[i] : min;
min = (min > B[i]) ? B[i] : min;
}
for(int i=min; i<=max; i++){
for(int j=0; j<N; j++){
}
}
return 0;
}
<file_sep>/checkio/house_password.py
def checkio(data):
if not len(data) >= 10:
return False
alphabet = set(data)
digit = set([str(i) for i in range(10)])
lower = set(['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'])
upper = set(['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'])
if not len( alphabet.intersection(digit) ) > 0:
return False
if not len( alphabet.intersection(lower) ) > 0:
return False
if not len( alphabet.intersection(upper) ) > 0:
return False
#replace this for solution
return True
if __name__ == '__main__':
assert checkio('A1213pokl') == False, "1st example"
assert checkio('bAse730onE4') == True, "2nd example"
assert checkio('asasasasasasasaas') == False, "3rd example"
assert checkio('QWERTYqwerty') == False, "4th example"
assert checkio('123456123456') == False, "5th example"
assert checkio('QwErTy911poqqqq') == True, "6th example"
<file_sep>/topcoder/srm204.div2.900.cpp
#include<iostream>
#include<vector>
#include<map>
#include<math.h>
using namespace std;
class Apothecary{
public:
vector<int> balance(int W){
//// (1) check about how many objects are needed to measure the weight
// proposition:
// x can be represented just by {i_1, ..., i_n}
// s.t \sum_{i=1}^{n-1}3^i < x <= \sum_{i=1}^{n}3^i
int sum=0, N=0;
while(sum < W){ sum += (int)pow(3, N++); }
//// (2) create dictionary
// key: \sum_{i=0}^{n}(3^i * \delta(bits[i]=1))
// s.t. \delta takes 1 if given condition would satisfied, or takes 0.
// value: a condition of bits
map<int,int> dict;
for(int i=0; i < (1 << N); ++i){
int sum = 0;
for(int j=0; j<=N; ++j){
if( i & (1 << j) ){ sum += pow(3, j); }
}
dict[ sum ] = i;
}
//// (3) balance the apothecary
// these two variables represent the presences of items using N-bits (from right)
int pLeft = 0, pRight = 0;
// these two variables represent the weight of a side, respectivily
int wLeft = W, wRight = 0;
// using reverse_iterator,
// scan dictionary from the recode having largest key to the one having smallest key
map<int,int>::reverse_iterator i = dict.rbegin();
while( wLeft != wRight ){
if( wLeft < wRight ){
// proceeeding until left side has more weight than right side
for(; i->first + wLeft >= wRight && i != dict.rend(); ++i){}
i--;
// ##### why can we know that the bits used by i->first haven't used yet ?? #####
wLeft += i->first;
pLeft |= i->second;
}else{
for(; i->first + wRight >= wLeft && i != dict.rend(); ++i){}
i--;
// ##### why can we know that the bits used by i->first haven't used yet ?? #####
wRight += i->first;
pRight |= i->second;
}
}
//// (3) create a vector representing items
vector<int> items;
for(int i=N-1; i>=0; --i){
if( pLeft & (1<<i) ){ items.push_back( -(int)pow(3,i) ); }
}
for(int i=0; i<N; ++i){
if( pRight & (1<<i) ){ items.push_back( (int)pow(3,i) ); }
}
return items;
};
};
int main(){
Apothecary ap = Apothecary();
for(int i=0; i<100; ++i){
vector<int> items = ap.balance(i);
printf("%d:\t", i);
int right=0, left=i;
for(int j=0; j<items.size(); ++j){
printf("%d, ", items[j]);
if(items[j]>0){
right += items[j];
}else{
left -= items[j];
}
}
printf("\t::%d=%d\n", left, right);
}
}
<file_sep>/arc/033/B.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define _GLIBCXX_DEBUG
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
#define N 125000000
using namespace std;
int main(int argc, char** argv){
int NA,NB;
cin >> NA >> NB;
vector<unsigned char> bits(N, 0);
int ai,bi,numerator=0, denominator=NA;
for(int i=0; i<NA; i++){
cin >> ai;
bits[(ai >> 3)] |= (1 << (ai & 0x07));
}
for(int i=0; i<NB; i++){
cin >> bi;
if( bits[(bi >> 3)] & (1 << (bi & 0x07)) ){
numerator++;
}else{
denominator++;
};
}
printf("%.10f\n", (double)numerator / (double)denominator);
return 0;
}
<file_sep>/codeiq/codeiq669.c
#include<stdio.h>
int min(int positive_numbers[]){
int *p, res;
p = positive_numbers;
res = positive_numbers[0];
for(;*p>=0;p++){
//for(;*p>=0;){
if(res > *p){
//if(res > ++*p){
res = *p;
}
}
return res;
}
int main(){
int array[6] = {5, 2, 1, 3, 4, -1};
printf("%d\n", min(array));
return 0;
}
<file_sep>/abc/017/B.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
string S;
bool isChock(int i){
if(i>=S.size()){
return true;
}else if(S[i] == 'o'){
return isChock(i+1);
}else if(S[i] == 'k'){
return isChock(i+1);
}else if(S[i] == 'u'){
return isChock(i+1);
}else if(S[i] == 'c' and ( ( i+1 < S.size() ) and S[i+1] == 'h')){
return isChock(i+2);
}else{
return false;
}
}
int main(int argc, char** argv){
cin >> S;
if(isChock(0)){
cout << "YES" << endl;
}else{
cout << "NO" << endl;
}
return 0;
}
<file_sep>/checkio/loading_cargo.py
def checkio(data):
if len(data) == 1: return data[0]
data = [0,] + data
N = sum(data)
M = [ [False,]*len(data) for i in range(N+1) ]
M[0] = [True,]*len(data)
for i in range(1,len(M)):
for j,d in enumerate(data):
if M[i][j-1]:
M[i][j] = True
else:
M[i][j] = True if i-d >= 0 and M[i-d][j-1] else False
#for i,row in enumerate(M):
# print "%2d\t%r" % (i,row)
for i,row in enumerate(M[:N/2+1][::-1]):
print (N + N%2)/2 - i,row
if sum(row) > 0:
print "red:%d" % (2*i + N%2)
return 2*i + N%2
return -1
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
print "1st"
assert checkio([10, 10]) == 0, "1st example"
print "2nd"
assert checkio([10]) == 10, "2nd example"
print "3rd"
assert checkio([5, 8, 13, 27, 14]) == 3, "3rd example"
print "4th"
assert checkio([5, 5, 6, 5]) == 1, "4th example"
print "5th"
assert checkio([12, 30, 30, 32, 42, 49]) == 9, "5th example"
print "6th"
assert checkio([1, 1, 1, 3]) == 0, "6th example"
<file_sep>/abc/019/D.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define UINT unsigned int
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int dist(int v1, int v2){
cout << "? " << v1 << " " << v2 << endl;
int d;
cin >> d;
return d;
}
int main(int argc, char** argv){
int N;
cin >> N;
int res=dist(1,2);
int st=1, en=2;
for(int i=3; i<=N; i++){
int e_st = dist(st, i);
int e_en = dist(en, i);
if(e_st > res){
res = e_st;
en = i;
}else if(e_en > res){
res = e_en;
st = i;
}
// printf("st:%d, en:%d, res:%d\n", st, en, res);
}
cout << "! " << res << endl;
cout << flush;
return 0;
}
<file_sep>/topcoder/srm388.div2.1000.cpp
#include<iostream>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<string.h>
#include<math.h>
using namespace std;
class SmoothNumbersHard{
private:
bool isPrime(int i){
for(int j=2, j_end=(int)floor(sqrt(i)); j<=j_end; ++j){
if( !(i % j) ){ return false; }
}
return true;
};
public:
int countSmoothNumbers(int N, int k){
vector<int> primes;
for(int i=2; (i<=k) and (i<=N); ++i){
if( isPrime(i) ){ primes.push_back(i); }
}
vector<bool> memo(N+1);
int ret = 1;
queue<int> que;
que.push(1);
while( !que.empty() ){
int i = que.front();
que.pop();
for(int j=0, j_end=primes.size(); j<j_end; ++j){
unsigned int q = i * primes[j];
if( (q <= (unsigned int)N) and !memo[q] ){
++ret;
memo[q] = true;
que.push(q);
}
}
}
return ret;
};
};
int main(){
SmoothNumbersHard snh;
int N, K, ans, ret;
N = 10;
K = 3;
ret = snh.countSmoothNumbers(N,K);
ans = 7;
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 10;
K = 4;
ans = 7;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 15;
K = 3;
ans = 8;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 5;
K = 20;
ans = 5;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 123456;
K = 123;
ans = 23855;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 4000000;
K = 33;
ans = 33073;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 4123654;
K = 123;
ans = 215681;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
N = 5000000;
K = 1000;
ans = 1196525;
ret = snh.countSmoothNumbers(N,K);
printf("snk.countSmoothNumbers(%d,%d) returns %d (a correct answer is %d)\n", N, K, ret, ans);
}
<file_sep>/abc/016/D.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define UINT unsigned int
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int p[101][2];
int main(int argc, char** argv){
int ax,ay,bx,by,n,cross=0;
scanf("%d %d %d %d", &ax, &ay, &bx, &by);
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d %d", &(p[i][0]), &(p[i][1]));
}
for(int i=0; i<n; i++){
int px = p[i+1][0] - p[i][0],
py = p[i+1][1] - p[i][1];
if(i == n-1){
px = p[0][0] - p[i][0];
py = p[0][1] - p[i][1];
}
int ux = ax - p[i][0],
uy = ay - p[i][1],
vx = bx - p[i][0],
vy = by - p[i][1];
int S1 = 0.5 * (px * uy - ux * py),
S2 = 0.5 * (px * vy - vx * py);
if(S1 * S2 < 0){ cross++; }
}
cout << (cross/2 + 1) << endl;
return 0;
}
<file_sep>/codeiq/codeiq667.py
#coding: utf-8;
for i in range(1,100+1):
count = 1
for j in range(1,i/2+1):
count += 0 if (i % j) else 1
if (count % 2):
print i
<file_sep>/abc/016/A.py
m = int(raw_input())
d = int(raw_input())
if d==0:
print('NO')
elif not(m % d):
print('YES')
else:
print('NO')
<file_sep>/poj/2010.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<string.h>
#include<math.h>
#include<queue>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int N,C,F;
bool comp(pair<int, int>& a, pair<int, int>& b){
return a.first < b.first;
}
int main(int argc, char** argv){
cin >> N >> C >> F;
vector<pair<int, int> > cow(C+1);
for(int i=1; i<=C; i++){
cin >> cow[i].first >> cow[i].second;
}
// The main strategy;
// examine the cows from the one that has most greater CSAR
// to the one having the smaller score
// At first, sort cows in CSAT order
sort(cow.begin()+1, cow.end(), comp);
// Second; construct an array that stores the minimum value of
// summations of (N>>1) greater(or smaller) values than cow[i].second,
vector<int> sum_greaters(C+1), sum_smallers(C+1), temp(N>>1);
priority_queue<int, vector<int>, greater<int> > greaters, smallers;
// cout << "-----------" << endl;
for(int i=1; i<=C; i++){
smallers.push(cow[i].second);
if(smallers.size() < (N>>1)){ continue; }
for(int j=0; j<(N>>1); j++){
temp[j] = smallers.top();
sum_smallers[i] += smallers.top();
smallers.pop();
}
for(int j=0; j<(N>>1); j++){ smallers.push(temp[j]); }
// cout << sum_smallers[i] << endl;
}
// cout << "-----------" << endl;
for(int i=C; i>=1; i--){
greaters.push(cow[i].second);
if(greaters.size() < (N>>1)){ continue; }
for(int j=0; j<(N>>1); j++){
temp[j] = greaters.top();
sum_greaters[i] += greaters.top();
greaters.pop();
}
for(int j=0; j<(N>>1); j++){ greaters.push(temp[j]); }
// cout << sum_greaters[i] << endl;
}
// cout << "-----------" << endl;
// ex; N=3,C=7 then, (N+1)>>1 is 2, and C-(N>>1) is 6
// ex; N=5,C=7 then, (N+1)>>1 is 3, and C-(N>>1) is 5
for(int i=(C-(N>>1)); i>=((N+1)>>1); i--){
if(cow[i].second + sum_greaters[i+1] + sum_smallers[i-1] <= F){
cout << cow[i].first << endl;
return 0;
}
}
cout << -1 << endl;
return 0;
}
<file_sep>/abc/016/C2.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define UINT unsigned int
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int n,m,a,b;
scanf("%d %d", &n, &m);
vector<UINT> G(n+1, 0);
// for(int i=1; i<=n; i++){
// G[i] |= (1<<i);
// }
for(int i=0; i<m; i++){
scanf("%d %d", &a, &b);
G[a] |= (1<<b);
G[b] |= (1<<a);
}
// for(int i=1; i<=n; i++){
// for(int j=1; j<=n; j++){
// cout << (bool)(G[i] & (1U<<j)) << " ";
// }
// cout << endl;
// }
for(int i=1; i<=n; i++){
UINT temp=0;
for(int j=1; j<=n; j++){
if( G[i] & (1<<j) ){
temp |= G[j];
}
}
int ret=0;
temp &= ~G[i];
temp &= ~(1<<i);
for(int j=1; j<=n; j++){
if( temp & (1<<j) ){
ret++;
}
}
cout << ret << endl;
}
return 0;
}
<file_sep>/codeiq/codeiq839.py
#coding: utf-8;
from __future__ import division, print_function, unicode_literals
from future_builtins import *
import string
def toAsciiNumberFromInteger(n):
i, size = 1, len(string.ascii_lowercase)
while n > size**i: i += 1
asc = ""
for j in reversed(range(i)):
count = 0
while n >= size**j:
count += 1
n -= size**j
asc += string.ascii_lowercase[count-1]
return asc
def toIntegerFromAsciiNumber(asc):
def int(ch):
return string.ascii_lowercase.find(ch) + 1
integer = 0
size = len(string.ascii_lowercase)
for i,ch in enumerate(asc):
integer += int(ch) * size**( len(asc) - (i+1) )
return integer
def divide(sequence, n):
if not len(sequence) > 0:
return []
else:
return [sequence[:n]] + divide(sequence[n:],n)
def encode(word):
transed = ""
cur, count = word[0], 0
word.strip()
for c in word+"$":
if cur == c:
count += 1
else:
# append current symbol to transed words
for asc in toAsciiNumberFromInteger(count):
transed += ( cur + asc )
# make preparation of next symbol
cur = c
count = 1
return transed
def decode(seq):
if len(seq) % 2 > 0:
raise ValueError("Invalid Sequence.")
word = ""
for ch, cnt in divide(seq,2):
word += ch * toIntegerFromAsciiNumber(cnt)
return word
if __name__ == '__main__':
filepath = "./data/spacetalky/words.txt"
with open(filepath) as f:
words = f.readlines()
words = map(lambda x:x.strip(), words)
for w in words:
try:
X = decode(w)
except ValueError:
X = 'X'
print(':'.join([X,w]))
<file_sep>/checkio/feed_pigeons.py
def checkio(N):
return recursive(N, 0, 0)
def recursive(N, m, t):
t += 1
m += t
if N > m:
return recursive(N-m, m, t)
else:
return N if N > m - t else m - t
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(1) == 1, "1st example"
assert checkio(2) == 1, "2nd example"
assert checkio(5) == 3, "3rd example"
assert checkio(10) == 6, "4th example"
<file_sep>/codeiq/codeiq755.py
#coding: utf-8;
class Combination:
def __init__(self, items):
self.items = items
self.n = len(items)
self.bits = [0,]*self.n
def enumerate(self, k):
for i in range(2 ** self.n):
binary = [ 1 if bit == '1' else 0 for bit in format(i, '0%db' % self.n) ]
if sum(binary) == k:
yield [ self.items[p] for p,q in enumerate(binary) if q == 1 ]
def makeHashKey(list_obj):
return ''.join( [ str(i) for i in sorted(list_obj[:]) ] )
if __name__ == '__main__':
# initialize
digits = {
'0': "1111110",
'1': "0110000",
'2': "1101101",
'3': "1111001",
'4': "0110011",
'5': "1011011",
'6': "1011111",
'7': "1110000",
'8': "1111111",
'9': "1111011",
}
comb = Combination(digits.keys())
W = {}
for e in comb.enumerate(2):
W[makeHashKey(e)]\
= sum([ 1 if s != t else 0 for s,t in zip(digits[e[0]],digits[e[1]]) ])
# Dynamic Programming
B = {}
for digit in comb.enumerate(1):
B[makeHashKey(digit)] = {digit[0]:0}
for n in range(1,10):
for S_list in comb.enumerate(n):
S = set(S_list)
S_str = makeHashKey(S_list)
for i in S:
#print S,set(digits.keys()) - S
for j in (set(digits.keys()) - S):
SJ_list = S_list + [j,]
SJ = set(SJ_list)
SJ_str = makeHashKey(SJ_list)
if not B.has_key(SJ_str): B[SJ_str] = {}
cost = B[S_str][i] + W[makeHashKey([i,j])]
B[SJ_str][j] = cost if cost < B[SJ_str].get(j, float("inf")) else B[SJ_str][j]
print min(B['0123456789'].values())
<file_sep>/codeiq/codeiq618.py
#coding: utf-8;
import numpy as np
import pyximport
pyximport.install(setup_args={'include_dirs':[np.get_include()]}, inplace=True)
from utils import *
C = np.array([
[ 0, 7, 12, 8, 11, 7 ],
[ 3, 0, 10, 7, 13, 2 ],
[ 4, 8, 0, 9, 12, 3 ],
[ 6, 6, 9, 0, 10, 7 ],
[ 7, 7, 11, 10, 0, 5 ],
[ 9, 7, 8, 9, 10, 0 ],
])
min_score = 999
# consider permitation of {2,3,4,5,6} meaning visit point
N=5
for i in range(factorial(N)):
# generate permitation
d = numToFactoradic(i, N-1)
n = factoradicToNum(d)
p = factoradicToPermitation(range(2,N+2), d)
# add start/end point
p = [1,] + p + [1,]
# search the opt. route
score = sum([ C[ p[j]-1, p[j+1]-1 ] for j in range(N+1) ])
if score < min_score:
min_score, opt = score, p
print min_score
print ' -> '.join([str(i) for i in opt])
<file_sep>/poj/1742.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<string>
#include<string.h>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
#define MAXN 101
#define MAXM 100001
using namespace std;
int n, m;
int A[MAXN], C[MAXN];
// メモ配列は2*mで十分(M[0],M[1]をprev,curとして交互に使用)
// cur[j]に格納するのはコインA[i]の残り使用可能枚数(<C[i])
int M[2][MAXM];
int main(int argc, char** argv){
while(1){
cin >> n >> m;
if(!n && !m){ break; }
for(int i=1; i<=n; i++){ cin >> A[i]; }
for(int i=1; i<=n; i++){ cin >> C[i]; }
// メモ配列は負の値で初期化
memset(M, -1, sizeof(M));
// DP
for(int i=1; i<=n; i++){
int* prev = M[(i+1)%2];
int* cur = M[i%2];
// 0は0枚のコインを使って表現可能
prev[0] = 0;
cur[0] = C[i];
for(int j=1; j<=m; j++){
// 先にcur[j-A[i]]を確認して、残り利用可能枚数が正ならば
// デクリメントした値をメモ配列に代入
if( j - A[i] >= 0 && cur[j - A[i]] > 0 ){
cur[j] = cur[j -A[i]] - 1;
}
// そもそもA[i]のコインを使わなくても表現可能な場合は
// 改めてC[i]で上書き
if( prev[j] >= 0 ){
cur[j] = C[i];
}
}
}
// 回答出力
int count=0;
for(int j=1; j<=m; j++){
// 非負ならば表現可能
if(M[n%2][j] >= 0){ count++; }
}
cout << count << endl;
}
}
<file_sep>/topcoder/srm531.div2.950.cpp
#include<iostream>
#include<vector>
#include<map>
#include<set>
#include<string>
using namespace std;
typedef map<pair<int,int>,int> container;
typedef pair<pair<int,int>,int> value_type;
struct second_order {
bool operator()(const value_type& x, const value_type& y) const {
return x.second > y.second;
}
};
class KingdomReorganization{
private:
map<char,int> char2int;
public:
KingdomReorganization(){
for(int i=0; i<26; ++i){
char2int['A' + i] = i;
char2int['a' + i] = i + 26;
}
};
int getCost(vector <string> kingdom, vector <string> build, vector <string> destroy){
int N = kingdom.size();
vector< vector<int> > graph(N);
vector< vector<int> > costs(N);
map<pair<int,int>, int> edges;
// calc. costs
for(int i=0; i<N; ++i){
graph[i] = vector<int>(N);
costs[i] = vector<int>(N);
const char *i_neighbors = kingdom[i].c_str(),
*i_build = build[i].c_str(),
*i_destroy = destroy[i].c_str();
for(int j=0; j<N; ++j){
costs[i][j] = 0;
if( i != j ){
if( i_neighbors[j] == '0' ){
costs[i][j] += char2int[ i_build[j] ];
graph[i][j] = 0;
}else{
costs[i][j] += -char2int[ i_destroy[j] ];
graph[i][j] = 1;
}
}
}
}
// debug print
for(int i=0; i<N; ++i){
for(int j=0; j<N; ++j){ cout << costs[i][j] << "\t"; }
cout << endl;
}
// construct edges
for(int i=0; i<N; ++i){
for(int j=i+1; j<N; ++j){
edges[ pair<int,int>(i,j) ] = costs[i][j];
}
}
// initialize components set
set<unsigned long long> components;
for(int i=0; i<N; ++i){ components.insert( (1 << i) ); }
// calc. minimum spanning tree
int result = 0;
priority_queue<value_type, vector<value_type>, second_order> que;
for(container::iterator i = edges.begin(); i!=edges.end(); ++i){ que.push(*i); }
while ( !( que.empty() ) ){
value_type e = que.top();
que.pop();
int vi = (e.first).first, vj = (e.first).second;
unsigned long long i = (1 << vi), j = (1 << vj);
set<unsigned long long>::iterator c = components.begin(), i_comp, j_comp;
i_comp = j_comp = components.end();
bool flg=true;
for(; c!=components.end(); ++c){
if( *c & i ){ i_comp = c; }
if( *c & j ){ j_comp = c; }
if( (*c & i) and (*c & j) ){ flg=false; }
}
if( flg and (i_comp != components.end()) and (j_comp != components.end()) ){
components.insert( (*i_comp) | (*j_comp) );
components.erase(i_comp);
components.erase(j_comp);
//debug
cout << "used edge: " << vi << "-" << vj << endl;
if( graph[ vi ][ vj ] == 0 ){
result += e.second;
}
}else if( graph[ vi ][ vj ] == 1 ){
result -= e.second;
}
}
return result;
};
};
int main(){
vector<string> kingdom, build, destroy;
KingdomReorganization kr;
int ret;
kingdom.clear();
build.clear();
destroy.clear();
kingdom.push_back("000");
kingdom.push_back("000");
kingdom.push_back("000");
build.push_back("ABD");
build.push_back("BAC");
build.push_back("DCA");
destroy.push_back("ABD");
destroy.push_back("BAC");
destroy.push_back("DCA");
ret = kr.getCost(kingdom, build, destroy);
cout << "return: " << ret << endl;
kingdom.clear();
build.clear();
destroy.clear();
kingdom.push_back("011");
kingdom.push_back("101");
kingdom.push_back("110");
build.push_back("ABD");
build.push_back("BAC");
build.push_back("DCA");
destroy.push_back("ABD");
destroy.push_back("BAC");
destroy.push_back("DCA");
ret = kr.getCost(kingdom, build, destroy);
cout << "return: " << ret << endl;
kingdom.clear();
build.clear();
destroy.clear();
kingdom.push_back("011000");
kingdom.push_back("101000");
kingdom.push_back("110000");
kingdom.push_back("000011");
kingdom.push_back("000101");
kingdom.push_back("000110");
build.push_back("ABDFFF");
build.push_back("BACFFF");
build.push_back("DCAFFF");
build.push_back("FFFABD");
build.push_back("FFFBAC");
build.push_back("FFFDCA");
destroy.push_back("ABDFFF");
destroy.push_back("BACFFF");
destroy.push_back("DCAFFF");
destroy.push_back("FFFABD");
destroy.push_back("FFFBAC");
destroy.push_back("FFFDCA");
ret = kr.getCost(kingdom, build, destroy);
cout << "return: " << ret << endl;
kingdom.clear();
build.clear();
destroy.clear();
kingdom.push_back("0000000000");
kingdom.push_back("0000000011");
kingdom.push_back("0001010000");
kingdom.push_back("0010010000");
kingdom.push_back("0000001000");
kingdom.push_back("0011000000");
kingdom.push_back("0000100000");
kingdom.push_back("0000000011");
kingdom.push_back("0100000101");
kingdom.push_back("0100000110");
build.push_back("AhPEqkSFMM");
build.push_back("hAfKPtsDad");
build.push_back("PfAyGQkaqN");
build.push_back("EKyAeLpRpm");
build.push_back("qPGeASfNwo");
build.push_back("ktQLSAnCAK");
build.push_back("SskpfnAdJS");
build.push_back("FDaRNCdAZz");
build.push_back("MaqpwAJZAn");
build.push_back("MdNmoKSznA");
destroy.push_back("AgTqWWxEYH");
destroy.push_back("gAXPgjzIRA");
destroy.push_back("TXAleTmWvT");
destroy.push_back("qPlAQkwxRO");
destroy.push_back("WgeQAqgbJJ");
destroy.push_back("WjTkqAiTzl");
destroy.push_back("xzmwgiAuHb");
destroy.push_back("EIWxbTuAwk");
destroy.push_back("YRvRJzHwAn");
destroy.push_back("HATOJlbknA");
ret = kr.getCost(kingdom, build, destroy);
cout << "return: " << ret << endl;
}
<file_sep>/topcoder/srm159.div2.1000.py
#coding=utf-8
from __future__ import division, print_function, unicode_literals
from future_builtins import *
class ThePriceIsRight:
def howManyReveals(self, prices):
N = len(prices)
dp = [[0 for j in range(N)] for i in range(N)]
for i in range(N):
dp[0][i] = 0
dp[i][0] = 1
for i in range(1,N):
for j in range(1,N):
dp[i][j] = sum([ dp[k][j-1] for k in range(i) if prices[i] > prices[k] ])
for j in reversed(range(N)):
counter = sum([ dp[i][j] for i in range(N) ])
if counter > 0:
return (j+1, counter)
if __name__ == '__main__':
ins = ThePriceIsRight()
if (4,1) != ins.howManyReveals((30,10,20,40,50)): raise ValueError("Wrong Answer.")
if (10,1) != ins.howManyReveals((1,2,3,4,5,6,7,8,9,10)): raise ValueError("Wrong Answer.")
if (1,10) != ins.howManyReveals((10,9,8,7,6,5,4,3,2,1)): raise ValueError("Wrong Answer.")
if (4,2) != ins.howManyReveals((39,88,67,5,69,87,82,64,58,61)): raise ValueError("Wrong Answer.")
if (5,2) != ins.howManyReveals((29,31,73,70,14,5,6,34,53,30,15,86)): raise ValueError("Wrong Answer.")
<file_sep>/checkio/median.py
import math
def checkio(data):
data.sort()
m = len(data)//2
if len(data) % 2:
return data[m]
else:
return (data[m-1]+data[m])/2
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio([1, 2, 3, 4, 5]) == 3, "Sorted list"
assert checkio([3, 1, 2, 5, 3]) == 3, "Not sorted list"
assert checkio([1, 300, 2, 200, 1]) == 2, "It's not an average"
assert checkio([3, 6, 20, 99, 10, 15]) == 12.5, "Even length"
<file_sep>/abc/017/C.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
vector<int> s;
vector< pair<int,int> > lr;
int main(int argc, char** argv){
int N, M;
cin >> N >> M;
s.resize(N);
lr.resize(N);
for(int i=0; i<N; i++){
cin >> lr[i].first >> lr[i].second >> s[i];
}
// sort(lr.begin(), lr.end(), greater<pair<int,int> >());
sort(lr.begin(), lr.end());
vector<int> diff(M+1,0);
vector<int> height(M+1,0);
for(int i=0; i<N; i++){
diff[ lr[i].first ]++;
diff[ lr[i].second+1 ]--;
}
int minheight = (1<<20);
for(int i=1; i<=M; i++){
height[i] = height[i-1] + diff[i];
minheight = (minheight < height[i]) ? minheight : height[i];
}
for(int i=1; i<=M; i++){
cout << i << ":" << height[i] << endl;
if(height[i] == minheight){
for(int i=0;
}
}
return 0;
}
<file_sep>/topcoder/srm328.div2.medium.cpp
#include<iostream>
#include<vector>
#include<queue>
#include<string>
#include<string.h>
#include<stdlib.h>
using namespace std;
class LightsCube{
public:
struct Light{ int x, y, z, color; };
vector <int> count(int N, vector <string> lights){
vector<int> colors;
queue<Light> edge;
bool ***cube;
// initialize cube that storing the statuses of lights
cube = (bool***)malloc(sizeof(bool**) * N);
for(int i=0; i<N; ++i){
cube[i] = (bool**)malloc(sizeof(bool*) * N);
for(int j=0; j<N; ++j){
cube[i][j] = (bool*)malloc(sizeof(bool) * N);
memset(cube[i][j], false, sizeof(cube[i][j]));
}
}
// turn on the lights given as an argument,
// push them into queue named edge
// and count thiers color
for(int i=0, M=(int)lights.size(); i<M; ++i){
const char* pos = lights[i].c_str();
int x = atoi(&pos[0]),
y = atoi(&pos[2]),
z = atoi(&pos[4]);
cube[x][y][z] = true;
Light l = {x, y, z, i};
edge.push(l);
colors.push_back(1);
}
// search w/ queue
while( !edge.empty() ){
Light l = edge.front();
edge.pop();
if(l.x+1 < N && !cube[l.x+1][l.y][l.z]){
cube[l.x+1][l.y][l.z] = true;
Light nl = {l.x+1, l.y, l.z, l.color};
++colors[l.color];
edge.push(nl);
}
if(0 <= l.x-1 && !cube[l.x-1][l.y][l.z]){
cube[l.x-1][l.y][l.z] = true;
Light nl = {l.x-1, l.y, l.z, l.color};
++colors[l.color];
edge.push(nl);
}
if(l.y+1 < N && !cube[l.x][l.y+1][l.z]){
cube[l.x][l.y+1][l.z] = true;
Light nl = {l.x, l.y+1, l.z, l.color};
++colors[l.color];
edge.push(nl);
}
if(0 <= l.y-1 && !cube[l.x][l.y-1][l.z]){
cube[l.x][l.y-1][l.z] = true;
Light nl = {l.x, l.y-1, l.z, l.color};
++colors[l.color];
edge.push(nl);
}
if(l.z+1 < N && !cube[l.x][l.y][l.z+1]){
cube[l.x][l.y][l.z+1] = true;
Light nl = {l.x, l.y, l.z+1, l.color};
++colors[l.color];
edge.push(nl);
}
if(0 <= l.z-1 && !cube[l.x][l.y][l.z-1]){
cube[l.x][l.y][l.z-1] = true;
Light nl = {l.x, l.y, l.z-1, l.color};
++colors[l.color];
edge.push(nl);
}
}
return colors;
};
};
int main(){
LightsCube lb = LightsCube();
const char* pos[] = {"0 2 4", "2 0 0", "3 4 4", "4 1 2"};
vector<string> posstr(pos, pos + (int) sizeof(pos) / sizeof(char*));
vector<int> colors = lb.count(5, posstr);
for(int i=0,M=(int)colors.size(); i<M; ++i) cout << colors[i] << " ";
cout << endl;
}
<file_sep>/arc/032/B_unionFindTree.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<set>
#include<algorithm>
#include<map>
#include<string>
#include<math.h>
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int N,M;
int uf_parent[100001], uf_rank[100001];
int root(int a){
if(uf_parent[a] == a){
return a;
}else{
return ( uf_parent[a] = root(uf_parent[a]) );
}
}
void unite(int a, int b){
int root_a = root(a),
root_b = root(b);
if(uf_rank[root_a] > uf_rank[root_b]){
uf_parent[root_b] = root_a;
}else if(uf_rank[root_a] < uf_rank[root_b]){
uf_parent[root_a] = root_b;
}else{
// choose root_a as a root of root_b since both nodes can be used
uf_parent[root_a] = root_b;
// increment the rank of the tree having node 'a' as its root
uf_rank[root_a]++;
}
}
bool isSameSet(int a, int b){
return (root(a) == root(b)) ? true : false;
}
int main(int argc, char** argv){
cin >> N >> M;
for(int i=1; i<=N; i++){
uf_parent[i] = i;
uf_rank[i] = 0;
}
for(int i=0; i<M; i++){
int a, b;
cin >> a >> b;
unite(a,b);
}
int ret = 0;
for(int i=1; i<=N; i++){
// if a node is the root of it own tree
if( root(i) == i ){
ret++;
}
}
cout << ret-1 << endl;
return 0;
}
<file_sep>/checkio/most_wanted_letter.py
def checkio(text):
hashmap = {}
alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
for l in text:
a = l.lower()
if a in alphabet:
if a in hashmap:
hashmap[a] += 1
else:
hashmap[a] = 1
letter, count = None, 0
for l,c in sorted(hashmap.items()):
if c > count:
letter, count = l, c
return letter
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio("Hello World!") == "l", "Hello test"
assert checkio("How do you do?") == "o", "O is most wanted"
assert checkio("One") == "e", "All letter only once."
assert checkio("Oops!") == "o", "Don't forget about lower case."
assert checkio("AAaooo!!!!") == "a", "Only letters."
<file_sep>/abc/015/D.cpp
#include<iostream>
#include<stdio.h>
#include<vector>
#include<algorithm>
#include<map>
#include<set>
#include<string>
#include<math.h>
#define UINT unsigned int
#define MAX(x,y) ( (x)>(y) ? (x) : (y) )
#define MIN(x,y) ( (x)<(y) ? (x) : (y) )
using namespace std;
int main(int argc, char** argv){
int W, N, K;
cin >> W >> N >> K;
int SS[50][2];
for(int i=1; i<=N; i++){
cin >> SS[i][0] >> SS[i][1];
}
vector< vector< vector<int> > > DP(K+1, vector< vector<int> >(N+1, vector<int>(W+1, 0)));
for(int i=1; i<=K; i++){ // DP
for(int k=1; k<=W; k++){ // initialize the first line
if(SS[1][0] <= k){
DP[i][1][k] = SS[1][1];
}else{
DP[i][1][k] = 0;
}
}
for(int j=2; j<=N; j++){
for(int k=1; k<=W; k++){
if( ( SS[j][0] <= k ) and ( DP[i-1][j-1][k-SS[j][0]] + SS[j][1] > DP[i][j-1][k] ) ){
DP[i][j][k] = DP[i-1][j-1][k-SS[j][0]] + SS[j][1];
}else{
DP[i][j][k] = DP[i][j-1][k];
}
}
// printf("i=%d, j=%d:\t", i, j);
// for(int k=1; k<=W; k++){
// cout << DP[i][j][k] << " ";
// }
// cout << endl;
}
}
cout << DP[K][N][W] << endl;
return 0;
}
<file_sep>/checkio/striped_word.py
VOWELS = "AEIOUY"
CONSONANTS = "BCDFGHJKLMNPQRSTVWXZ"
import string
class checker:
def __init__(self, word):
self.word = word.upper()
self.next = 0 if self.word[0] in VOWELS else 1
def pop(self):
c = self.word[0]
if ( self.next == 0 and c in VOWELS ) \
or ( self.next == 1 and c in CONSONANTS ):
self.next = 1 if self.next == 0 else 0
self.word = self.word[1:]
return True
else:
return False
def isStripe(self):
if not len(self.word) > 1: return False
while len(self.word) > 0:
if not self.pop(): return False
return True
def checkio(data):
data = data\
.replace(",", " ")\
.replace(".", " ")\
.replace("!", " ")\
.replace("?", " ")
words = data.split()
return sum([checker(w).isStripe() for w in words])
#These "asserts" using only for self-checking and not necessary for auto-testing
if __name__ == '__main__':
assert checkio(u"My name is ...") == 3, "All words are striped"
assert checkio(u"Hello world") == 0, "No one"
assert checkio(u"A quantity of striped words.") == 1, "Only of"
assert checkio(u"Dog,cat,mouse,bird.Human.") == 3, "Dog, cat and human"
<file_sep>/checkio/matrix_transpose.py
def checkio(data):
m, n = len(data), len(data[0])
trans = [[n,]*m for n in range(n)]
# we cannot initialize 2-D list as following
# but I can not locate what causes the problem
#trans = [[0,]*m,]*n
for i,row in enumerate(data):
for j,col in enumerate(row):
trans[j][i] = col
return trans
# following code is posted in "clear" category
def clear(matr):
return list(map(list, zip(*matr)))
if __name__ == '__main__':
assert checkio([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]) == [[1, 4, 7],
[2, 5, 8],
[3, 6, 9]], "Square matrix"
assert checkio([[1, 4, 3],
[8, 2, 6],
[7, 8, 3],
[4, 9, 6],
[7, 8, 1]]) == [[1, 8, 7, 4, 7],
[4, 2, 8, 9, 8],
[3, 6, 3, 6, 1]], "Rectangle matrix"
|
381526e036c451f68507783f29e1bd1051fa132b
|
[
"C",
"Python",
"C++"
] | 62
|
Python
|
sat0yu/sandbox
|
aecdd28d2f585d73ec18847ddddac93ef3772371
|
9e51e78391de3ec877ab75e5bb3f354cc1813ef8
|
refs/heads/master
|
<file_sep># Bouncing Boxes
This is a simple test/demo for the Elegoo 2.8 inch TFT display (ILI9341).
<file_sep>/**
* ==========================================================================
* Elegoo ILI9341 TFT LCD test/demo: bouncing boxes
* ==========================================================================
*
* Author: <NAME> <<EMAIL>>
*
* Libraries used:
* - Elegoo_GFX (Core graphics library)
* - Elegoo_TFTLCD (Hardware-specific library)
*
* Licenses:
* This is free software and information under the GNU LPGL
* https://www.gnu.org/licenses/lgpl.html
*/
#include <Elegoo_GFX.h>
#include <Elegoo_TFTLCD.h>
// The control pins for the LCD can be assigned to any digital or
// analog pins...but we'll use the analog pins as this allows us to
// double up the pins with the touch screen (see the TFT paint example).
#define LCD_CS A3 // Chip Select goes to Analog 3
#define LCD_CD A2 // Command/Data goes to Analog 2
#define LCD_WR A1 // LCD Write goes to Analog 1
#define LCD_RD A0 // LCD Read goes to Analog 0
#define LCD_RESET A4 // Can alternately just connect to Arduino's reset pin
// Assign human-readable names to some common 16-bit color values:
#define BLACK 0x0000
#define BLUE 0x001F
#define RED 0xF800
#define GREEN 0x07E0
#define CYAN 0x07FF
#define MAGENTA 0xF81F
#define YELLOW 0xFFE0
#define WHITE 0xFFFF
// Our background color:
#define BACKGROUND BLACK
Elegoo_TFTLCD tft(LCD_CS, LCD_CD, LCD_WR, LCD_RD, LCD_RESET);
unsigned long lastms;
/**
* class Ball: model of a bouncing "ball" (a box for now…)
*
* We need to avoid redrawing the whole display to avoid flicker.
* So we're implementing an incremental scheme of…
* - moving the ball
* - erasing the old position remains
* - drawing the ball at the new position
*
* To make things easy for the test, the ball is just a filled box.
*
* Moving includes bouncing off walls and ground, with random modifications
* of the speed to include some nice variations. Gravity is also added.
*/
class Ball {
float x, y, dx, dy; // Position (x,y) and speed (dx,dy)
int ix, iy, ox, oy; // New (ix,iy) and old (ox,oy) integer position
unsigned int radius; // a random size
unsigned int color; // a random color
public:
/**
* Generate the ball:
*/
Ball() {
// init attributes:
radius = random(6, 12);
color = random(BLACK, WHITE);
// init position:
x = random(radius, tft.width()-radius);
y = random(radius, tft.height()-radius);
// init speed:
dx = random(20, 45) / 10.0;
dy = random(20, 45) / 10.0;
}
/**
* Move the ball, bounce off walls & ground, add gravity:
*/
void move() {
// remember old ball position:
ox = ix;
oy = iy;
// bounce:
if (x+dx <= radius || x+dx >= tft.width() - radius) {
// bounce from walls
dx = random(20, 45) / 10.0 * ((dx > 0) ? -1 : 1);
}
if (y+dy >= tft.height() - radius) {
// bounce from ground
dy = random(-45, -20) / 10.0;
}
else {
// add gravity
dy += 0.05;
}
// move ball:
x += dx;
y += dy;
ix = x;
iy = y;
}
/**
* Erase remains of old ball (ox,oy):
*/
void erase() {
// get movement distances old → new position:
int mx = ix - ox;
int my = iy - oy;
// erase horizontal gap:
if (mx > 0) {
tft.fillRect(ox - radius, oy - radius, mx, radius*2, BACKGROUND);
}
else if (mx < 0 ) {
tft.fillRect(ox + radius + mx, oy - radius, -mx, radius*2, BACKGROUND);
}
// erase vertical gap:
if (my > 0) {
tft.fillRect(ox - radius, oy - radius, radius*2, my, BACKGROUND);
}
else if (my < 0 ) {
tft.fillRect(ox - radius, oy + radius + my, radius*2, -my, BACKGROUND);
}
}
// Draw new ball:
void draw() {
tft.fillRect(ix - radius, iy - radius, radius*2, radius*2, color);
}
};
/**
* Create some balls:
*/
#define BALLCOUNT 5
Ball *balls[BALLCOUNT];
/**
* Arduino sketch init hook:
*/
void setup() {
randomSeed(analogRead(0));
// init display:
tft.reset();
uint16_t identifier = tft.readID();
if(identifier == 0x9325) {
Serial.println(F("Found ILI9325 LCD driver"));
} else if(identifier == 0x9328) {
Serial.println(F("Found ILI9328 LCD driver"));
} else if(identifier == 0x4535) {
Serial.println(F("Found LGDP4535 LCD driver"));
}else if(identifier == 0x7575) {
Serial.println(F("Found HX8347G LCD driver"));
} else if(identifier == 0x9341) {
Serial.println(F("Found ILI9341 LCD driver"));
} else if(identifier == 0x8357) {
Serial.println(F("Found HX8357D LCD driver"));
} else if(identifier==0x0101)
{
identifier=0x9341;
Serial.println(F("Found 0x9341 LCD driver"));
} else {
Serial.print(F("Unknown LCD driver chip: "));
Serial.println(identifier, HEX);
identifier=0x9341;
}
tft.begin(identifier);
tft.fillScreen(BACKGROUND);
tft.setRotation(3);
// create balls:
for (int i=0; i<BALLCOUNT; i++) {
balls[i] = new Ball();
}
lastms = millis();
}
/**
* Arduino sketch loop hook:
*/
void loop() {
// 5 ms time steps (200 Hz):
unsigned long ms = millis();
if (ms - lastms <= 5) {
return;
}
lastms = ms;
// Move all balls:
for (Ball *b : balls) {
b->move();
}
// Erase all old balls:
for (Ball *b : balls) {
b->erase();
}
// Draw all new balls:
for (Ball *b : balls) {
b->draw();
}
}
|
b3a17611eb73996c7e4c5841d46d64e2c6486a41
|
[
"Markdown",
"C++"
] | 2
|
Markdown
|
dexterbg/BouncingBoxes
|
030724018a7c1bcb2b06c6b038d3111842982cbc
|
62a46a9ac57b9cd16a976a471b7af57131d11d92
|
refs/heads/master
|
<repo_name>DNwin/tickets<file_sep>/app_api/models/user.js
/**
* Created by dennis on 3/5/16.
*/
"use strict";
var crypto = require('crypto');
module.exports = function(sequelize, DataTypes) {
var User = sequelize.define("User", {
userId: {
type: DataTypes.INTEGER,
primaryKey: true,
allowNull: false,
autoIncrement: true,
unique: true
},
username: {
type: DataTypes.STRING,
unique: true,
required: true,
validate: {
isLowercase: true
}
},
email: {
type: DataTypes.STRING,
unique: true,
required: true,
validate: {
isEmail: true
}
},
firstName: DataTypes.STRING,
lastName: DataTypes.STRING,
salt: DataTypes.STRING,
hash: DataTypes.STRING(1500),
status: {
type: DataTypes.ENUM,
allowNull: false,
values: ['active', 'pending', 'inactive'],
defaultValue: 'pending'
}
}, {
instanceMethods: {
setUsername: function(username) {
this.username = username.toString().toLowerCase();
},
setPassword: function(password) {
this.salt = crypto.randomBytes(16).toString('hex');
this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
},
validPassword: function(password) {
var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex');
return this.hash === hash;
}
},
classMethods: {
associate: function(models) {
}
}
});
return User;
};
<file_sep>/app_client/src/ticketboard/controllers/TicketboardController.js
/**
* Created by dennis on 3/7/16.
*/
var myModule = angular.module('Tickets.Ticketboard');
/**
* Factory: TicketsHelper
* Contains helper functions for the tickets app.
*/
myModule.factory('TicketsHelper', function() {
/**
* Function: buildIndex()
* Processes categories for usage with select boxes on the form.
* @param source - Array of a category
* @param property - Key name within object.
* @returns {Array}
*/
var buildIndex = function (source, property) {
var tempArray = [];
for (var i = 0, len = source.length; i < len; ++i) {
tempArray[source[i][property]] = source[i];
}
return tempArray;
};
return {
buildIndex: buildIndex
};
});
/**
* Service: TicketsModel
* Processes data for tickets
*/
myModule.service('TicketsModel', function() {
var service = this,
categories = [
{name: 'Development'},
{name: 'Database'},
{name: 'IT'}
],
statuses = [
{name: 'Not Completed'},
{name: 'In Progress'},
{name: 'Completed'}
],
types = [
{name: 'Request'},
{name: 'Urgent'},
{name: 'Bug'},
{name: 'Question'}
],
tickets = [
{
title: 'Setup new desktop.',
description: 'Replace Sammy\'s old desktop with a new one. Backup his files',
category: 'IT',
type: 'Urgent',
status: 'Not Completed'
},
{
title: 'Delete Invoice #18829',
description: 'It was created by mistake. Please void the invoice and corresponding task.',
category: 'Database',
type: 'Request',
status: 'Completed'
},
{
title: 'Improve Ticket Application',
description: 'Has a few bugs.',
category: 'Development',
type: 'Bug',
status: 'Not Completed'
}
];
service.getCategories = function() {
return categories
};
service.getStatuses = function () {
return statuses;
};
service.getTypes = function () {
return types;
};
service.getTickets = function () {
return tickets;
};
});
/**
* Controller: MainCtrl
* Main controller for the Tickets ViewModel
*/
myModule.controller('TicketboardCtrl', function(TicketsModel, TicketsHelper) {
var main = this;
main.categories = TicketsModel.getCategories();
main.types = TicketsModel.getTypes();
main.statuses = TicketsModel.getStatuses();
main.tickets = TicketsModel.getTickets();
main.categoriesIndex = TicketsHelper.buildIndex(main.categories, 'name');
main.typesIndex = TicketsHelper.buildIndex(main.types, 'name');
main.statusesIndex = TicketsHelper.buildIndex(main.statuses, 'name');
main.setCurrentTicket = function (ticket) {
main.currentTicket = ticket;
main.currentCategory = main.categoriesIndex[ticket.category];
main.currentType = main.typesIndex[ticket.type];
main.currentStatus = main.statusesIndex[ticket.status];
};
main.createTicket = function() {
main.tickets.push({
title: 'New Ticket',
description: 'Description pending.',
type: 'Request',
status: 'Not Completed'
});
};
main.setCurrentCategory = function(category) {
if (typeof main.currentTicket !== 'undefined') {
main.currentTicket.category = category.name;
}
};
main.setCurrentStatus = function (status) {
if (typeof main.currentTicket !== 'undefined') {
main.currentTicket.status = status.name;
}
};
main.setCurrentType = function (type) {
if (typeof main.currentTicket !== 'undefined') {
main.currentTicket.type = type.name;
}
};
});
/**
* Directive: <ticket>
* Used for an single ticket record to display on a list.
*/
myModule.directive('ticket', function() {
return {
scope: true,
replace: true,
template: '<div><h4>{{ticket.title}}</h4><p>{{ticket.description}}</p></div>'
}
});<file_sep>/app_client/src/app.js
/**
* Created by dennis on 3/9/16.
*/
var myModule = angular.module('Tickets',
[
'ngRoute',
'Tickets.Common',
'Tickets.Ticketboard'
]);
myModule.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'src/ticketboard/tpl/ticketboard.tpl.html',
controller: 'TicketboardCtrl',
controllerAs: 'ticketboard'
})
.otherwise({redirectTo: '/'});
});
<file_sep>/test/api/server.test.js
/**
* Created by dennis on 2/1/16.
*/
var app = require('../../app');
var Bluebird = require('bluebird');
var expect = require('expect.js');
var request = require('supertest');
describe('Employees REST Api', function() {
it('Should respond with index', function(done) {
request(app)
.get('/')
.expect(200, done)
});
});<file_sep>/README.md
Ticket App
=================
* Support ticket management application.
* Built on a Javascript stack: Sequelize.js, Node.js, Express.js, Angular.js
## Installation
* Clone the repository
* Install modules using `npm install`
* Build the front end using `gulp dev` or `gulp prod` within the `app_client` folder.
* Start app with `npm start`
## Tests
* You can run the tests by executing `npm test`.
### Demo
A current demo can be found at: http://bullstack.io:3000/
---
|
a9ce068739dde263854ac228aee04669bc057bf4
|
[
"JavaScript",
"Markdown"
] | 5
|
JavaScript
|
DNwin/tickets
|
ce9360f3f72caab8a57d9da984343d0256300ed5
|
217d17891fd3f77b70fa66b8afa69489b816b0dd
|
refs/heads/master
|
<repo_name>Damir2805/CalcArea<file_sep>/CalcArea/Program.cs
using System;
namespace CalcArea
{
class Program
{
static void Main(string[] args)
{
CalcTriangle(); // Here methods are called
CalcCircle();
}
/*All the methods are defined here*/
static void CalcTriangle()
{
Console.WriteLine("Введите длину первой стороны");
double a = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Введите длину второй стороны");
double b = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Введите длину третьей стороны");
double c = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Введите единицы измерения");
string mes = Console.ReadLine();
double v = (a + b + c);
double p = v / 2;
double sq = p * (p - a) * (p - b) * (p - c);
double area = Math.Sqrt(sq);
Console.WriteLine($"площадь треугольника равна {area} кв. {mes}");
}
static void CalcCircle()
{
Console.WriteLine("Введите диаметр окружности");
double d = Convert.ToDouble(Console.ReadLine());
Console.WriteLine("Введите единицы измерения");
string mes = Console.ReadLine();
double area = (3.14 * d * d) / 4;
Console.WriteLine($"площадь круга равна {area} кв. {mes}");
}
}
}
|
8f613b881ef14be1ccd78ae9b35508cf568b5056
|
[
"C#"
] | 1
|
C#
|
Damir2805/CalcArea
|
4408e746c0bc8ed0f0f4942fb4813ba73820da36
|
ba4aa2d1f4ae3905f6451ec89ce00ab7b18806ba
|
refs/heads/master
|
<file_sep>import numpy as np
def work_on_title(combine):
for dataset in combine:
dataset['Title'] = dataset.Name.str.extract(' ([A-Za-z]+)\.', expand=False)
for dataset in combine:
dataset['Title'] = dataset['Title'].replace(['Lady', 'Countess', 'Don', 'Dr', 'Rev', 'Sir', 'Jonkheer', 'Dona'], 'Rare')
dataset['Title'] = dataset['Title'].replace(['Capt', 'Col', 'Major'], 'Officer')
dataset['Title'] = dataset['Title'].replace('Mlle', 'Miss')
dataset['Title'] = dataset['Title'].replace('Ms', 'Miss')
dataset['Title'] = dataset['Title'].replace('Mme', 'Mrs')
title_mapping = {"Mr": 1, "Miss": 2, "Mrs": 3, "Master": 4, "Rare": 5, "Officer": 6}
for dataset in combine:
dataset['Title'] = dataset['Title'].map(title_mapping)
dataset['Title'] = dataset['Title'].fillna(0)
def sex_to_int(combine):
for dataset in combine:
dataset['Sex'] = dataset['Sex'].map({'female': 1, 'male': 0}).astype(int)
def fill_missed_age(combine):
guess_ages = np.zeros((2, 3))
for dataset in combine:
for i in range(0, 2):
for j in range(0, 3):
guess_df = dataset[(dataset['Sex'] == i) & (dataset['Pclass'] == j + 1)]['Age'].dropna()
# age_mean = guess_df.mean()
# age_std = guess_df.std()
# age_guess = rnd.uniform(age_mean - age_std, age_mean + age_std)
age_guess = guess_df.median()
# Convert random age float to nearest .5 age
guess_ages[i, j] = int(age_guess / 0.5 + 0.5) * 0.5
for i in range(0, 2):
for j in range(0, 3):
dataset.loc[(dataset.Age.isnull()) & (dataset.Sex == i) & (dataset.Pclass == j + 1), 'Age'] = \
guess_ages[i, j]
dataset['Age'] = dataset['Age'].astype(int)
def age_to_categories(combine):
for dataset in combine:
dataset.loc[dataset['Age'] <= 16, 'Age'] = 0
dataset.loc[(dataset['Age'] > 16) & (dataset['Age'] <= 32), 'Age'] = 1
dataset.loc[(dataset['Age'] > 32) & (dataset['Age'] <= 48), 'Age'] = 2
dataset.loc[(dataset['Age'] > 48) & (dataset['Age'] <= 64), 'Age'] = 3
dataset.loc[dataset['Age'] > 64, 'Age'] = 4
#dataset['Age'] = dataset['Age'].astype(int)
return combine
def add_family_size(combine):
for dataset in combine:
dataset['FamilySize'] = dataset['SibSp'] + dataset['Parch'] + 1
def add_is_alone(combine):
for dataset in combine:
dataset['IsAlone'] = 0
dataset.loc[dataset['FamilySize'] == 1, 'IsAlone'] = 1
def add_age_class(combine):
for dataset in combine:
dataset['Age*Class'] = dataset.Age * dataset.Pclass
def fill_missed_port(combine):
freq_port = combine[0].Embarked.dropna().mode()[0]
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].fillna(freq_port)
def port_to_int(combine):
for dataset in combine:
dataset['Embarked'] = dataset['Embarked'].map({'S': 0, 'C': 1, 'Q': 2}).astype(int)
def fill_missed_fare(combine):
for dataset in combine:
dataset['Fare'].fillna(dataset['Fare'].dropna().median(), inplace=True)
def fare_to_int(combine):
for dataset in combine:
dataset.loc[dataset['Fare'] <= 7.91, 'Fare'] = 0
dataset.loc[(dataset['Fare'] > 7.91) & (dataset['Fare'] <= 14.454), 'Fare'] = 1
dataset.loc[(dataset['Fare'] > 14.454) & (dataset['Fare'] <= 31), 'Fare'] = 2
dataset.loc[dataset['Fare'] > 31, 'Fare'] = 3
dataset['Fare'] = dataset['Fare'].astype(int)
def drop_unused_columns(combine):
combine[0] = combine[0].drop(['Ticket', 'Cabin'], axis=1)
combine[1] = combine[1].drop(['Ticket', 'Cabin'], axis=1)
combine[0] = combine[0].drop(['Title'], axis=1)
combine[1] = combine[1].drop(['Title'], axis=1)
combine[0] = combine[0].drop(['Name', 'PassengerId'], axis=1)
combine[1] = combine[1].drop(['Name'], axis=1)
combine[0] = combine[0].drop(['Parch', 'SibSp'], axis=1)
combine[1] = combine[1].drop(['Parch', 'SibSp'], axis=1)
#combine[0] = combine[0].drop(['FamilySize'], axis=1)
#combine[1] = combine[1].drop(['FamilySize'], axis=1)
return combine
<file_sep># machine-learning
Application of SVM algorithm for the task of "Titanic" passenger classification
[Kaggle](https://www.kaggle.com/c/titanic#description)<file_sep>https://www.kaggle.com/c/titanic#description
<file_sep>from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC, LinearSVC
from sklearn.ensemble import RandomForestClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.linear_model import Perceptron
from sklearn.linear_model import SGDClassifier
from sklearn.tree import DecisionTreeClassifier
def logistic_regression(X_train, Y_train, X_test):
logreg = LogisticRegression()
logreg.fit(X_train, Y_train)
Y_pred = logreg.predict(X_test)
acc_log = round(logreg.score(X_train, Y_train) * 100, 2)
return [acc_log, Y_pred]
def support_vector_machines(X_train, Y_train, X_test):
svc = SVC()
svc.fit(X_train, Y_train)
Y_pred = svc.predict(X_test)
acc_svc = round(svc.score(X_train, Y_train) * 100, 2)
return [acc_svc, Y_pred]
def KNeighbors(X_train, Y_train, X_test):
knn = KNeighborsClassifier(n_neighbors=3)
knn.fit(X_train, Y_train)
Y_pred = knn.predict(X_test)
acc_knn = round(knn.score(X_train, Y_train) * 100, 2)
return [acc_knn, Y_pred]
def gaussian_naive_bayes(X_train, Y_train, X_test):
gaussian = GaussianNB()
gaussian.fit(X_train, Y_train)
Y_pred = gaussian.predict(X_test)
acc_gaussian = round(gaussian.score(X_train, Y_train) * 100, 2)
return [acc_gaussian, Y_pred]
def perceptron(X_train, Y_train, X_test):
perceptron = Perceptron()
perceptron.fit(X_train, Y_train)
Y_pred = perceptron.predict(X_test)
acc_perceptron = round(perceptron.score(X_train, Y_train) * 100, 2)
return [acc_perceptron, Y_pred]
def linear_svm(X_train, Y_train, X_test):
linear_svc = LinearSVC()
linear_svc.fit(X_train, Y_train)
Y_pred = linear_svc.predict(X_test)
acc_linear_svc = round(linear_svc.score(X_train, Y_train) * 100, 2)
return [acc_linear_svc, Y_pred]
def stochastic_gradient_descent(X_train, Y_train, X_test):
sgd = SGDClassifier()
sgd.fit(X_train, Y_train)
Y_pred = sgd.predict(X_test)
acc_sgd = round(sgd.score(X_train, Y_train) * 100, 2)
return [acc_sgd, Y_pred]
def decision_tree(X_train, Y_train, X_test):
decision_tree = DecisionTreeClassifier()
decision_tree.fit(X_train, Y_train)
Y_pred = decision_tree.predict(X_test)
acc_decision_tree = round(decision_tree.score(X_train, Y_train) * 100, 2)
return [acc_decision_tree, Y_pred]
def random_forest(X_train, Y_train, X_test):
random_forest = RandomForestClassifier(n_estimators=100)
random_forest.fit(X_train, Y_train)
Y_pred = random_forest.predict(X_test)
random_forest.score(X_train, Y_train)
acc_random_forest = round(random_forest.score(X_train, Y_train) * 100, 2)
return [acc_random_forest, Y_pred]
<file_sep># data analysis and wrangling
import pandas as pd
import numpy as np
import random as rnd
# visualization
import seaborn as sns
import matplotlib.pyplot as plt
from common.models import *
from features import *
train_df = pd.read_csv('input/train.csv')
test_df = pd.read_csv('input/test.csv')
combine = [train_df, test_df]
def feature_extracting():
global combine
work_on_title(combine)
sex_to_int(combine)
fill_missed_age(combine)
combine = age_to_categories(combine)
add_family_size(combine)
add_is_alone(combine)
add_age_class(combine)
fill_missed_port(combine)
port_to_int(combine)
fill_missed_fare(combine)
fare_to_int(combine)
combine = drop_unused_columns(combine)
def test():
global combine
train_df = combine[0]
test_df = combine[1]
X_train = train_df.drop("Survived", axis=1)
Y_train = train_df["Survived"]
X_test = test_df.drop("PassengerId", axis=1).copy()
# Logistic Regression
acc_log, Y_log = logistic_regression(X_train, Y_train, X_test)
# Support Vector Machines
acc_svc, Y_svc = support_vector_machines(X_train, Y_train, X_test)
acc_knn, Y_knn = KNeighbors(X_train, Y_train, X_test)
# Gaussian Naive Bayes
acc_gaussian, Y_gaussian = gaussian_naive_bayes(X_train, Y_train, X_test)
# Perceptron
acc_perceptron, Y_perceptron = perceptron(X_train, Y_train, X_test)
# Linear SVC
acc_linear_svc, Y_linear_svc = linear_svm(X_train, Y_train, X_test)
# Stochastic Gradient Descent
acc_sgd, Y_sgd = stochastic_gradient_descent(X_train, Y_train, X_test)
# Decision Tree
acc_decision_tree, Y_decision_tree = decision_tree(X_train, Y_train, X_test)
# Random Forest
acc_random_forest, Y_random_forest = random_forest(X_train, Y_train, X_test)
models = pd.DataFrame({
'Model': ['Support Vector Machines', 'KNN', 'Logistic Regression',
'Random Forest', 'Naive Bayes', 'Perceptron',
'Stochastic Gradient Decent', 'Linear SVC',
'Decision Tree'],
'Score': [acc_svc, acc_knn, acc_log,
acc_random_forest, acc_gaussian, acc_perceptron,
acc_sgd, acc_linear_svc, acc_decision_tree]})
print(models.sort_values(by='Score', ascending=False))
submission = pd.DataFrame({
"PassengerId": test_df["PassengerId"],
"Survived": Y_random_forest
})
submission.to_csv('output/submission_random_forest.csv', index=False)
feature_extracting()
test()
|
9e02cebe572565f48e479396dd7550134d77ee76
|
[
"Markdown",
"Python"
] | 5
|
Python
|
vrublevskiyvitaliy/machine-learning
|
2b37d24631a08c6730fb0b0fbea56d15a7f90b85
|
537d1de993dd808048347485e938fe4b197abc01
|
refs/heads/master
|
<repo_name>stigbosmans/EscapeGameArduino<file_sep>/mol-driver.py
import serial
import time
from socketIO_client import SocketIO, LoggingNamespace
ser = serial.Serial('COM3', 9600, timeout=0)
socketIO = SocketIO('localhost', 3000, LoggingNamespace)
def process_code(code):
if code.find(';')>-1:
ar=code.split(";")
if len(ar[0])==4:
socketIO.emit("msg",ar[0])
socketIO.wait(seconds=1)
print(ar[0])
def print_state(code):
if code[0]!="0":
print(num_to_text(code[0]),"Geel")
if code[1]!="0":
print(num_to_text(code[1]),"Groen")
if code[2]!="0":
print(num_to_text(code[2]),"Oranje")
if code[3]!="0":
print(num_to_text(code[3]),"Grijs")
else:
print("CLOCK IS TICKING!")
if code=="1234":
print("CORRECT!")
elif code[0]!="0" and code[1]!="0" and code[2]!="0" and code[3]!="0":
print("EXPLODED!")
def num_to_text(num):
if num=="1":
return "eerste kabel verwijderd:"
elif num=="2":
return "tweede kabel verwijderd:"
elif num=="3":
return "derde kabel verwijderd:"
elif num=="4":
return "vierde kabel verwijderd:"
else:
return ""
while True:
bytesToRead = ser.inWaiting()
res=ser.read(bytesToRead)
process_code(str(res, 'ascii'))
time.sleep(.1)
<file_sep>/escape_mol/escape_mol.ino
const int YELLOW=0;
const int GREEN=1;
const int ORANGE=3;
const int GREY=5;
int count=0;
int cablesConnected[4]={0,0,0,0};
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
//Yellow:0, Green:1, Orange:2, Grey:3
set_state(cablesConnected,YELLOW);
set_state(cablesConnected,GREEN);
set_state(cablesConnected,ORANGE);
set_state(cablesConnected,GREY);
print_state(cablesConnected);
delay(100);
}
void print_state(int connected[4]){
Serial.println(String(connected[0])+String(connected[1])+String(connected[2])+String(connected[3])+";");
}
void set_state(int connected[4],int color){
if(is_low(color) && connected[get_color_index(color)]==0){
count++;
connected[get_color_index(color)]=count;
}
}
int get_color_index(int color){
if(color==0){
return 0;
}else if(color==1){
return 1;
}else if(color==3){
return 2;
}else if(color==5){
return 3;
}else{
return 0;
}
}
bool is_low(int color){
return analogRead(color)<1000;
}
|
55739db58945726bc36f8f68e05c0431175a9182
|
[
"Python",
"C++"
] | 2
|
Python
|
stigbosmans/EscapeGameArduino
|
cc54f6fe860a04a9b442a3aaa1e73ab3e48b4d3b
|
da2ce3a0b3fe12bb03b6a3a30ca1c7b27a00f051
|
refs/heads/master
|
<file_sep>package Crypto;
import java.awt.*;
import java.awt.event.*;
import java.math.BigInteger;
import javax.swing.*;
/**
*
* @author <NAME>
*/
public class KunciPublikDialog extends javax.swing.JDialog {
private ecdsa.Point pubKey;
/**
* Creates new form KunciPublikDialog
*/
public KunciPublikDialog(Frame parent) {
super(parent, true);
setLocation (320,100);
setTitle("Verifikasi Email");
initComponents();
pubKey = new ecdsa.Point();
}
private void actionConnect() {
if ((PublikXField.getText().trim().length() < 1) || (PublikYField.getText().trim().length() < 1)){
JOptionPane.showMessageDialog(this,
"Mohon isikan kunci publik",
"Missing Setting(s)", JOptionPane.ERROR_MESSAGE);
return;
}
pubKey.setX(new BigInteger(PublikXField.getText()));
pubKey.setY(new BigInteger(PublikYField.getText()));
// Close dialog.
dispose();
}
public ecdsa.Point getPublikKey() {
return pubKey;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
PublikXField = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
SubmitBtn = new javax.swing.JButton();
PublikYField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
jLabel1.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel1.setText("Masukkan Kunci Publik Anda:");
SubmitBtn.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
SubmitBtn.setText("Submit");
SubmitBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
SubmitBtnActionPerformed(evt);
}
});
jLabel2.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel2.setText("X");
jLabel3.setFont(new java.awt.Font("Tahoma", 0, 16)); // NOI18N
jLabel3.setText("Y");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(SubmitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel2)
.addComponent(jLabel3))
.addGap(29, 29, 29)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(PublikYField, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(PublikXField, javax.swing.GroupLayout.PREFERRED_SIZE, 342, javax.swing.GroupLayout.PREFERRED_SIZE)))))
.addContainerGap(19, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(41, 41, 41)
.addComponent(jLabel1)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PublikXField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 9, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(PublikYField, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(SubmitBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void SubmitBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubmitBtnActionPerformed
actionConnect();
}//GEN-LAST:event_SubmitBtnActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField PublikXField;
private javax.swing.JTextField PublikYField;
private javax.swing.JButton SubmitBtn;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
// End of variables declaration//GEN-END:variables
}
<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 Crypto;
import ecdsa.ECDSA;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author <NAME>
*/
public class KunciDialog extends javax.swing.JDialog {
private ECDSA ecdsa;
/**
* Creates new form KunciDialog
*/
public KunciDialog(Frame parent) throws IOException {
// Call super constructor, specifying that dialog is modal.
super(parent, true);
// Set dialog title.
setTitle("Kunci Anda");
setLocation (400,150);
initComponents();
ecdsa = new ECDSA();
File f = new File(".pri");
if(f.exists() && !f.isDirectory()) {
readPrivateKey();
KunciPrivatField.setText(ecdsa.getdA().toString());
}
File f2 = new File(".pub");
if(f2.exists() && !f2.isDirectory()) {
readPublicKey();
KunciPublikXField.setText(ecdsa.getQA().getX().toString());
KunciPublikYField.setText(ecdsa.getQA().getY().toString());
}
}
// Get private key
public BigInteger getPriKey() {
return ecdsa.getdA();
}
// Get public key
public ecdsa.Point getPubKey() {
return ecdsa.getQA();
}
//Save private key into *.pri file
private void savePrivateKey() throws FileNotFoundException, IOException{
String file = ".pri";
byte[] bytes = ecdsa.getdA().toByteArray();
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(bytes);
} finally {
stream.close();
}
}
//Save public key into *.pub file
private void savePublicKey() throws IOException{
String file = ".pub";
byte[] bytes = ecdsa.getQA().toHexString().getBytes();
FileOutputStream stream = new FileOutputStream(file);
try {
stream.write(bytes);
} finally {
stream.close();
}
}
//Read private key from .pri file
private void readPrivateKey() throws IOException{
String file = ".pri";
Path path = Paths.get(file);
byte[] bytes = Files.readAllBytes(path);
BigInteger privateKey = new BigInteger(bytes);
ecdsa.setdA(privateKey);
}
//Read public key from .pub file
private void readPublicKey() throws IOException{
String file = ".pub";
Path path = Paths.get(file);
byte[] bytes = Files.readAllBytes(path);
String str = new String(bytes);
int len = str.length();
ecdsa.Point signPoint = new ecdsa.Point();
signPoint.setX(new BigInteger(str.substring(0, len/2), 16));
signPoint.setY(new BigInteger(str.substring(len/2), 16));
ecdsa.setQA(signPoint);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
TitleLabel = new javax.swing.JLabel();
KunciPrivatLabel = new javax.swing.JLabel();
KunciPublikXLabel = new javax.swing.JLabel();
KunciPrivatField = new javax.swing.JTextField();
BangkitkanBtn = new javax.swing.JButton();
KunciPublikYLabel = new javax.swing.JLabel();
CloseBtn = new javax.swing.JButton();
KunciPublikXField = new javax.swing.JTextField();
KunciPublikYField = new javax.swing.JTextField();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
TitleLabel.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
TitleLabel.setText("Kunci Anda");
KunciPrivatLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
KunciPrivatLabel.setText("Kunci Privat");
KunciPublikXLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
KunciPublikXLabel.setText("Kunci Publik X");
KunciPrivatField.setEditable(false);
BangkitkanBtn.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
BangkitkanBtn.setText("Bangkitkan");
BangkitkanBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
BangkitkanBtnActionPerformed(evt);
}
});
KunciPublikYLabel.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
KunciPublikYLabel.setText("Kunci Publik Y");
CloseBtn.setFont(new java.awt.Font("Tahoma", 0, 15)); // NOI18N
CloseBtn.setText("Close");
CloseBtn.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
CloseBtnActionPerformed(evt);
}
});
KunciPublikXField.setEditable(false);
KunciPublikYField.setEditable(false);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(KunciPrivatLabel, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KunciPublikXLabel, javax.swing.GroupLayout.Alignment.TRAILING))
.addComponent(KunciPublikYLabel))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(KunciPublikXField)
.addComponent(KunciPrivatField, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KunciPublikYField))
.addContainerGap())
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addGap(0, 0, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(TitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 209, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(57, 57, 57))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(BangkitkanBtn)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(CloseBtn)
.addContainerGap())))))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(TitleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(KunciPrivatLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 24, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KunciPrivatField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(KunciPublikXLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KunciPublikXField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(KunciPublikYLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(KunciPublikYField, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(BangkitkanBtn)
.addComponent(CloseBtn))
.addContainerGap(13, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void BangkitkanBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BangkitkanBtnActionPerformed
ecdsa.generateKey();
KunciPrivatField.setText(ecdsa.getdA().toString());
KunciPublikXField.setText(ecdsa.getQA().getX().toString());
KunciPublikYField.setText(ecdsa.getQA().getY().toString());
try {
savePrivateKey();
savePublicKey();
} catch (IOException ex) {
Logger.getLogger(KunciDialog.class.getName()).log(Level.SEVERE, null, ex);
}
}//GEN-LAST:event_BangkitkanBtnActionPerformed
private void CloseBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_CloseBtnActionPerformed
// TODO add your handling code here:
dispose();
}//GEN-LAST:event_CloseBtnActionPerformed
/**
* @param args the command line arguments
*/
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton BangkitkanBtn;
private javax.swing.JButton CloseBtn;
private javax.swing.JTextField KunciPrivatField;
private javax.swing.JLabel KunciPrivatLabel;
private javax.swing.JTextField KunciPublikXField;
private javax.swing.JLabel KunciPublikXLabel;
private javax.swing.JTextField KunciPublikYField;
private javax.swing.JLabel KunciPublikYLabel;
private javax.swing.JLabel TitleLabel;
// End of variables declaration//GEN-END:variables
}
|
b88d4f23b51e90c6446d131c1ae4a1ec621bd2d8
|
[
"Java"
] | 2
|
Java
|
cilvia-sianora/EmailClientCrypto
|
c9e96d62ecae6a509d6c1ff3c76e0944e5087143
|
05b6c8fc192c6b001cf724e7e29e305fa8b69750
|
refs/heads/main
|
<file_sep>
import csv
def read_csv(file, mode='r'):
"""
read from csv file
:param file: csv file path
:param mode: [select] read format. defalut:r
:return: array []
"""
data = []
with open(file, mode, encoding='utf-8') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
data.extend(row)
return data
def write_csv(file, data, mode='r'):
"""
write data into csv file
:param file: save file path
:param data: data format: [[],[],[]]
:param mode: [select] save format. defalut:r
:return: None
"""
with open(file, mode, encoding='utf-8') as f:
csv_writer = csv.writer(f, lineterminator='\n')
csv_writer.writerows(data)
def read_minibatch(file):
data = read_csv(file)
arr = []
num = 1
i = 1
for line in data:
num += 1
i += 1
arr.append(line)
if num > 1000 or i > len(data):
yield arr
arr = []
num = 1
<file_sep>import os
from fileio import write_csv
def txt2ava1(txt_path, label_dict, ava_file, ava_obj_file):
"""
convert sigle txt format file to ava
surport txt format : frame#,n[id,x1,y1,x2,y2,label]
"""
annotation_person_arr = []
annotation_obj_arr = []
for root, dirs, files in os.walk(txt_path):
for file in files:
print(file)
file_path = os.path.join(txt_path, file)
video_id = file[:-4]
with open(file_path) as f:
txtes = f.readlines()
for txt in txtes:
txt = txt.strip('\n')
arr = txt.split(',')
frame = arr[0]
if int(arr[0]) % 5 == 0:
count = int(arr[1])
for num in range(count):
idx = 2 + num * 6
axis = arr[idx+1:idx+5]
str = arr[idx+5]
labels = str.split('@')
idx = labels[0]
if labels[1] == 'a':
if len(labels) > 2:
for k in labels[2:]:
action_id = label_dict[k]
re_arr = [video_id, int(frame), int(axis[0]), int(axis[1]), int(axis[2]), int(axis[3]), action_id, idx]
annotation_person_arr.append(re_arr)
# else:
# re_arr = [video_id, int(frame), int(axis[0]), int(axis[1]), int(axis[2]),
# int(axis[3]), -1, idx]
# annotation_person_arr.append(re_arr)
else:
label = label_dict[labels[1]]
annotation_obj_arr.append([video_id, int(frame), int(axis[0]), int(axis[1]), int(axis[2]), int(axis[3]), label, idx])
write_csv(annotation_person_arr, ava_file, 'a+')
write_csv(annotation_obj_arr, ava_obj_file, 'a+')
<file_sep>from .io import read_csv, write_csv
from .rename import rename2md5
__all__ = [
'read_csv', 'write_csv', 'rename2md5'
]
<file_sep>Release This Package for PIPY
create requirements.txt
`pip freeze > requirements.txt`
<file_sep>
import hashlib
import time
import os
def _createmd5():
m = hashlib.md5()
m.update(bytes(str(time.time()), encoding='utf-8'))
return m.hexdigest()
def md5rename1(org_movie_path, org_txt_path, rename_movie_path, rename_txt_path):
"""
:param org_movie_path:
:param org_txt_path:
:param rename_movie_path:
:param rename_txt_path:
:return: None
"""
for root, dirs, files in os.walk(org_txt_path):
for file in files:
dotpos = file.rfind('_')
if dotpos < 0:
file = file
else:
file = file[:dotpos]
name = file + '.mp4'
org_movie_file_path = os.path.join(org_movie_path, name)
new_name = _createmd5()
rename_movie_file_path = os.path.join(rename_movie_path, new_name + '.pm4')
org_txt_file_path = os.path.join(org_txt_path, file + '_gt.txt')
rename_txt_file_path = os.path.join(rename_txt_path, new_name + '.txt')
os.rename(org_movie_file_path, rename_movie_file_path)
os.rename(org_txt_file_path, rename_txt_file_path)
|
536aad808b209031657f20bbf7f0ecfebdacdd89
|
[
"Markdown",
"Python"
] | 5
|
Python
|
opendwlab/dwcv
|
a1dbcc486acf094e93662fbbb1438925a7e3dd69
|
cccf15bd0b69db11db3bc9214508cb77d9cafdc3
|
refs/heads/master
|
<repo_name>hyongbai/android-sdk-sample<file_sep>/Example/src/com/liquidm/sdk/example/VideoAdFromXmlActivity.java
package com.liquidm.sdk.example;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import com.liquidm.sdk.VideoAdView;
public class VideoAdFromXmlActivity extends Activity implements VideoAdViewFullscreenModeProvider.Listener {
private VideoAdView videoAdView;
private VideoAdViewFullscreenModeProvider videoAdViewFullscreenModeProvider;
private View contentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide title bar on older phones so it won't be visible in fullscreen mode
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
setContentView(R.layout.activity_video_ad_from_xml);
videoAdView = (VideoAdView) findViewById(R.id.video_ad_view);
videoAdView.setFullscreenButtonVisible(true);
videoAdViewFullscreenModeProvider = new VideoAdViewFullscreenModeProvider(this, videoAdView, 16, 9);
videoAdViewFullscreenModeProvider.setListener(this);
contentView = findViewById(R.id.content_view);
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
videoAdViewFullscreenModeProvider.update();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
videoAdViewFullscreenModeProvider.update();
}
@Override
public void onFullscreenChanged(boolean fullscreen) {
contentView.setVisibility(fullscreen ? View.GONE : View.VISIBLE);
}
}
<file_sep>/Example/src/com/liquidm/sdk/example/NativeAdFromXmlActivity.java
package com.liquidm.sdk.example;
import android.app.Activity;
import android.os.Bundle;
public class NativeAdFromXmlActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_native_ad_from_xml);
}
}
<file_sep>/Example/src/com/liquidm/sdk/example/VideoAdFromCodeActivity.java
package com.liquidm.sdk.example;
import android.app.Activity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.LinearLayout;
import com.liquidm.sdk.VideoAdView;
import com.liquidm.sdk.example.VideoAdViewFullscreenModeProvider.Listener;
public class VideoAdFromCodeActivity extends Activity implements Listener {
// Enter your site token and video path here
private static final String SITE_TOKEN = "<PASSWORD>";
private static final String VIDEO_PATH = "http://madvertise-assets-production.s3.amazonaws.com/assets/video-tests/poh.mp4";
private VideoAdView videoAdView;
private VideoAdViewFullscreenModeProvider videoAdViewFullscreenModeProvider;
private View contentView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Hide title bar on older phones so it won't be visible in fullscreen mode
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
}
setContentView(R.layout.activity_video_ad_from_code);
LinearLayout mainLayout = (LinearLayout) findViewById(R.id.main_layout);
contentView = findViewById(R.id.content_view);
videoAdView = new VideoAdView(this, SITE_TOKEN, VIDEO_PATH);
videoAdView.setFullscreenButtonVisible(true);
videoAdViewFullscreenModeProvider = new VideoAdViewFullscreenModeProvider(this, videoAdView, 16, 9);
videoAdViewFullscreenModeProvider.setListener(this);
{
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
mainLayout.addView(videoAdView, 0, params);
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
videoAdViewFullscreenModeProvider.update();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
videoAdViewFullscreenModeProvider.update();
}
@Override
public void onFullscreenChanged(boolean fullscreen) {
contentView.setVisibility(fullscreen ? View.GONE : View.VISIBLE);
}
}
<file_sep>/CHANGELOG.md
LiquidM SDK Changelog
===
5.3.1 (2014-07-24)
---
- Fixed close button showing when custom close button is used
5.3.0 (2014-06-13)
---
- Added native ads.
5.2.6 (2014-05-13)
---
- Fixed ad notifications when MRAID ad enters two-part expand.
- Fixed MRAID state handling when ad enters two-part expand.
- Fixed bug in AdActivity that sometimes led to crash.
5.2.5 (2014-04-23)
---
- ACCESS_WIFI_STATE permission is no longer required.
- Updated GooglePlayServices to 4.3.23.
- Fixed problem with keyboard that wasn't showing up on a some devices after selecting an input field in an ad.
- Fixed problem preventing to return from ad inline video.
5.2.4 (2014-04-16)
---
- VideoAdView now resumes playing from last position.
- Fixed VideoAdView resizing problem which occured on some devices.
5.2.3 (2014-04-02)
---
- Fixed banner rendering bug occuring during crossfade reload animation.
Crossfade reload animation now fades to black.
Fading to transparency was causing strange artifacts on some devices: black rectangle or doubled ad in the left bottom corner of the screen.
5.2.2 (2014-03-21)
---
- Added javadocs.
- Image interstitials will fit on the screen from now on maintaining theirs aspect ratio.
- Ads that doesn't fit on the screen won't show up and error will be logged.
5.2.1 (2014-03-12)
---
- Fixed problem with parsing MRAID calendar event json.
- Fixed mraid.useCustomClose().
- Avoid ad view zooming happening when entering text.
5.2.0 (2014-03-07)
---
- Added TestApp application.
5.1.2 (2014-03-06)
---
- Fixed problem with HD banners occuring on HDPI devices.
5.1.1 (2014-02-25)
---
- Fixed problem with multiple simultaneous ad requests.
5.1.0 (2014-02-21)
---
- Various fixes and improvements in MRAID implementation.
- Fixed mraid.createCalendarEvent() click notification.
- Fixed mraid.storePicture() on Nexus 7.
5.0.6 (2014-02-12)
---
- Support ads that open content in separate browser windows.
- Avoid scrolling in image ads.
5.0.5 (2014-02-10)
---
- Fixed fullscreen ad orientation handling.
- Fixed mediation adapter onPresentScreen, onDismissScreen, onClick notifications.
- Video pre-rolls and post rolls are now shown only once.
- Fixed video ad glitches.
- Updated example application icons.
5.0.4 (2014-02-05)
---
- Added support for HD banners.
- Fixed text overflowing in text ads.
- VideoAdView now allows to retry playing video after an error has occured.
- VideoAdView now skips to last known position after it recovered from error.
- Video ad won't show "Skip in 00 secs" ever again.
- Fixed video ad crashes on Samsung Galaxy Note.
- Fixed mediation adapter onLeaveApplicaton notification.
5.0.3 (2014-01-30)
---
- Created AdMob mediation adapter.
- Fixed MRAID initialization on Android devices with API < 11.
5.0.2 (2014-01-17)
---
- Minor fixes in SDK.
5.0.0 (2014-01-16)
---
- Added video ads support.
4.0.0 (2013-11-22)
---
- Added MRAID 2.0 support.
- Created example application.
- Added support for custom size banners.
<file_sep>/Example/src/com/liquidm/sdk/example/ActivityOrientationLocker.java
package com.liquidm.sdk.example;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
public class ActivityOrientationLocker implements SensorEventListener {
private Activity activity;
private SensorManager sensorManager;
private int lockedOrientation;
private boolean listening;
public ActivityOrientationLocker(Activity activity) {
this.activity = activity;
this.sensorManager = (SensorManager) activity.getSystemService(Activity.SENSOR_SERVICE);
}
public void lockOrientation(int orientation) {
lockedOrientation = orientation;
activity.setRequestedOrientation(orientation);
if (!listening) {
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
listening = true;
}
}
@Override
public void onSensorChanged(SensorEvent event) {
float gx = event.values[0];
float gy = event.values[1];
boolean vertical = (Math.abs(gy) > 4.0f);
boolean horizontal = (Math.abs(gx) > 4.0f);
int orientation;
if (vertical && !horizontal) {
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_PORTRAIT;
} else if (horizontal && !vertical) {
orientation = ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE;
} else {
orientation = -1;
}
if (listening) {
if (orientation == lockedOrientation) {
activity.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_USER);
sensorManager.unregisterListener(this);
listening = false;
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
<file_sep>/README.md
# LiquidM Android SDK
The LiquidM Android SDK allows you to request and present ads in your app. It includes the newest mobile ad technology and provides the following features:
- Support for banner and interstitial ads
- text, image and [MRAID 2.0](http://www.iab.net/media/file/IAB_MRAID_v2_FINAL.pdf) (interactive rich media creatives) ad formats
- industry standard banners sizes: mma, medium_rectangle, etc. and custom sized banners
- standard and HD image banners
- Support for video ads (based on [VAST](http://www.iab.net/media/file/VASTv3.0.pdf))
- pre-roll and post-roll video ads
- landscape-portrait auto adaptation
- Support for DFP mediation
- dedicated adapter for [DFP Network Mediation](https://developers.google.com/mobile-ads-sdk/docs/dfp/mediation) integrated into SDK
# Repository structure
This repository contains an example app (LiquidMSDKExample) and provides all the files to integrate the LiquidM Android SDK in your app. We suggest that you clone this repository with git (git clone https://github.com/liquidm/android-sdk-sample.git). If you're not familiar with git you can download the content of this repository as zip archive ([download](https://github.com/liquidm/android-sdk-sample/archive/master.zip)).
After you cloned this repository or unzipped the archive you'll find the following structure:
- [SDK](SDK): Actual SDK with [DFP Network Mediation](https://developers.google.com/mobile-ads-sdk/docs/dfp/mediation) adapter.
- [API](Docs/API): Documentation of the public SDK interface.
- [Example](Example): Example application.
- [GooglePlayServices](GooglePlayServices): Google Play Services library needed by example application.
- [CHANGELOG.md](CHANGELOG.md): Documentation of SDK changes.
- [README.md](README.md): This documentation.
# Try the example application
First of all you should try to open our example app which contains the LiquidM Android SDK already integrated. To do so, just import the [example project](Example) into Eclipse, attach the Android device and run it.
 
In the example application you can see how to properly integrate:
- banner ad (both in code and xml)
- interstitial ad
- video ad (both in code and xml)
# Integrate the SDK into your application
1. Copy [liquidmsdk.jar](https://github.com/liquidm/android-sdk-sample/raw/master/SDK/liquidmsdk.jar) into libs/ directory of your project.
1. Set required permissions in AndroidManifest.xml
```xml
<uses-permission android:name="android.permission.INTERNET"/>
```
1. Set optional permissions in AndroidManifest.xml
Enable ```WRITE_EXTERNAL_STORAGE``` to allow MRAID ads store pictures on the device.
```xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
```
Enable ```ACCESS_COARSE_LOCATION``` or ```ACCESS_FINE_LOCATION``` to allow SDK gather device's location passively.
```xml
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
```
```xml
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
```
1. Define AdActivity in AndroidManifest.xml
```xml
<activity
android:name="com.liquidm.sdk.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|uiMode|screenLayout|screenSize|smallestScreenSize" />
```
1. Add Google Play Services to your project
1. [Install the Google Play Services SDK](http://developer.android.com/google/play-services/setup.html#Install)
1. [Integrate your project with Google Play Services SDK](http://developer.android.com/google/play-services/setup.html#Setup)
# Use cases
This section contains some common uses and describes how to integrate different kinds of ads into your applicaiton. For banners and video ads you can choose to integrate them in layout xml files or in application code. Please make sure, that you replace the "TestTokn" with your personal token. The "TestTokn" contains example ads and allows you to test your implementation.
## Request banner ad in xml
1. Add liquidm namespace declaration to xml root element.
```xml
xmlns:liquidm="http://schemas.android.com/apk/lib/com.liquidm.sdk"
```
1. Add AdView to your layout.
```xml
<!-- Replace TestTokn with your personal token -->
<!-- For adSize use one of: mma, medium_rectangle, leaderboard, portrait, landscape, xx_large
or provide a custom size, for example: 320x50.
Note that the custom size is given in device-independent pixels. -->
<com.liquidm.sdk.AdView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|bottom"
liquidm:adSize="mma"
liquidm:autoreload="true"
liquidm:siteToken="TestTokn" />
```
See [example layout](Example/res/layout/activity_banner_ad_from_xml.xml) for more details.
See also [How to select the best fitting banner size for most android devices?](#how-to-select-the-best-fitting-banner-size-for-most-android-devices)
## Request banner ad in code
```java
// Replace TestTokn with your personal token.
String siteToken = "<PASSWORD>";
// Select desired ad size (MMA, MEDIUM_RECTANGLE, LEADERBOARD, PORTRAIT, LANDSCAPE, XX_LARGE)
AdSize adSize = AdSize.MMA;
// or request custom sized ad using:
// (note that the custom size is given in device-independent pixels)
// AdSize adSize = new AdSize(320, 50);
AdView adView = new AdView(this, siteToken, adSize);
adView.setAutoreload(true);
layout.addView(adView, new FrameLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL));
```
See [example code](Example/src/com/liquidm/sdk/example/BannerAdFromCodeActivity.java) for more details.
See also [How to select the best fitting banner size for most android devices?](#how-to-select-the-best-fitting-banner-size-for-most-android-devices)
## Request interstitial ad and show it if ready.
1. Create and load InterstitialAd
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...
// Replace TestTokn with your personal token.
String siteToken = "<PASSWORD>";
InterstitialAd interstitialAd = new InterstitialAd(this, siteToken);
interstitialAd.loadAd();
}
```
1. Show interstitial ad
```java
private void showInterstitial() {
if (interstitial.isReady()) {
interstitial.show();
}
}
```
## Request interstitial ad and show it as soon as it is loaded
1. Create InterstitialAd, set its listener, and load it.
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ..
// Replace TestTokn with your personal token.
String siteToken = "<PASSWORD>";
InterstitialAd interstitialAd = new InterstitialAd(this, SITE_TOKEN);
interstitialAd.setListener(this);
interstitialAd.loadAd();
}
```
1. Show interstitial ad in onAdLoad() event handler. Handle onAdFailedToLoad() event if needed.
```java
@Override
public void onAdLoad(Ad ad) {
interstitial.show();
}
@Override
public void onAdFailedToLoad(Ad ad) {
Toast.makeText(this, getString(R.string.interstitial_load_failed), Toast.LENGTH_SHORT).show();
}
@Override
public void onAdClick(Ad ad) {
}
@Override
public void onAdPresentScreen(Ad ad) {
}
@Override
public void onAdDismissScreen(Ad ad) {
}
@Override
public void onAdLeaveApplication(Ad ad) {
}
```
1. Stop ad loading in activity onPause() method to avoid showing interstitial after leaving the activity.
```java
@Override
protected void onPause() {
super.onPause();
interstitial.stopLoading();
}
```
1. Add below line to your activity config in AndroidManifest.xml to avoid reloading interstitial ad every time device orientation changes.
```xml
android:configChanges="keyboard|keyboardHidden|orientation|uiMode|screenLayout|screenSize|smallestScreenSize"
```
See example code [here](Example/src/com/liquidm/sdk/example/FullscreenAdActivity.java) and [here](Example/AndroidManifest.xml) for more details.
## Request video ad in xml
1. Add liquidm namespace declaration to xml root element
```xml
xmlns:liquidm="http://schemas.android.com/apk/lib/com.liquidm.sdk"
```
1. Add VideoAdView to your layout.
Remember to set your siteToken and videoPath.
```xml
<!-- Replace TestTokn with your personal token. -->
<!-- Enter videoPath to your video file. -->
<com.liquidm.sdk.VideoAdView
android:layout_width="200dp"
android:layout_height="150dp"
android:layout_gravity="center"
liquidm:videoPath=""
liquidm:siteToken="<PASSWORD>" />
```
See [example layout](Example/src/com/liquidm/sdk/example/VideoAdFromCodeActivity.java) for more details.
See [Video ad fullscreen mode](#video-ad-fullscreen-mode) for fullscreen mode integration instructions.
## Request video ad in code
```java
// Replace TestTokn with your personal token.
String siteToken = "<PASSWORD>";
// Enter path to your video file here.
String videoPath = "";
videoAdView = new VideoAdView(this, siteToken, videoPath);
int width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 200, r.getDisplayMetrics());
int height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 150, r.getDisplayMetrics());
FrameLayout mainLayout = (FrameLayout) findViewById(R.id.main_layout);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
mainLayout.addView(videoAdView, params);
```
See [example code](Example/res/layout/activity_video_ad_from_xml.xml) for more details.
See [Video ad fullscreen mode](#video-ad-fullscreen-mode) for fullscreen mode integration instructions.
# Request banner ad through DFP adapter
1. Integrate LiquidM SDK like described [above](#integrate-the-sdk-into-your-application)
1. Request AdMob banner ad like described [here](https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals) using AdMob *ad unit id* with configured LiquidM mediation.
# Request interstitial ad through DFP adapter
1. Integrate LiquidM SDK like described [above](#integrate-the-sdk-into-your-application)
1. Request AdMob interstitial ad like described [here](https://developers.google.com/mobile-ads-sdk/docs/admob/advanced) using AdMob *ad unit id* with configured LiquidM mediation.
# Other
## Video ad fullscreen mode
VideoAdView supports fullscreen mode, but part of its implementation have to be done by user.
Basic fullscreen mode implementation can be found in example in [VideoAdViewFullscreenModeProvider.java](Example/src/com/liquidm/sdk/example/VideoAdViewFullscreenModeProvider.java).
Follow below instructions to implement fullscreen mode the same way as it is implemented in example:
1. Copy [VideoAdViewFullscreenModeProvider.java](Example/src/com/liquidm/sdk/example/VideoAdViewFullscreenModeProvider.java) and its dependencies from example to your project.
1. Enable VideoAdView fullscreen button:
```java
videoAdView.setFullscreenButtonVisible(true);
```
1. Create VideoAdViewFullscreenModeProvider:
```java
videoAdViewFullscreenModeProvider = new VideoAdViewFullscreenModeProvider(activity, videoAdView, 16, 9);
```
16:9 is the aspect ratio that VideoAdViewFullscreenModeProvider will try to maintain while video player is in normal mode.
1. Invoke VideoAdViewFullscreenModeProvider.update():
```java
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
videoAdViewFullscreenModeProvider.update();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
videoAdViewFullscreenModeProvider.update();
}
```
1. Implement VideoAdViewFullscreenModeProvider.Listener and hide/show remaining activity content when video player goes into fullscreen/normal mode:
```java
public void onFullscreenChanged(boolean fullscreen) {
if (fullscreen) {
// hide content except VideoAdView
} else {
// show hidden content
}
}
```
1. Remember to hide title bar on older devices to avoid it in fullscreen mode.
Add the following code to Activity.onCreate():
```java
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
}
setContentView(R.layout.activity_video_ad_from_code);
// ...
}
```
See also [VideoAdFromCode.java](Example/src/com/liquidm/sdk/example/VideoAdFromCodeActivity.java)
or [VideoAdFromXml.java](Example/src/com/liquidm/sdk/example/VideoAdFromXmlActivity.java) for more details.
# Native ads [BETA]
Native ads allows you to customize ad rendering so it will fit the look and feel of your app.
Before you can request a native ad you have to choose a schema. The native ad schema determines what data is sent for the native ad, e.g. image , click URLs, etc. A simple example can look like the following:
```json
{
"icon": "http://example.com/icon.png",
"title": "Hello, world",
"subtitle": "LiquidM"
}
```
You can access native ad data through ```NativeAd``` object and obtain its schema by using ```nativeAd.getSchema()```.
There are two ways to integrate native ads:
- you can prepare ad template and use ```NativeAdView``` to render it or
- download ```NativeAd``` manually using ```NativeAdProvider``` and render it by yourself.
## Render native ad using ```NativeAdView```
1. Create xml ad template and mark asset views with tags. For example: asset view for "image" asset should have tag = "image", like this:
```xml
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:tag="image" />
```
For real example, take a look [here](Example/res/layout/template_feed_ad.xml)
1. Create NativeAdView in xml in the following way. Remember to replace ```siteToken```, ```schemaName``` and ```@layout/template``` with your own values.
```xml
<com.liquidm.sdk.NativeAdView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
liquidm:autoreload="true"
liquidm:schemaName="feed_ad"
liquidm:siteToken="<PASSWORD>"
liquidm:template="@layout/template" />
```
See [NativeAdFromXmlActivity.java](Example/src/com/liquidm/sdk/example/NativeAdFromXmlActivity.java) for more details.
1. ...or create NativeAdView in code in the following way. Remember to replace ```SITE_TOKEN```, ```SCHEMA_NAME```, ```TEMPLATE``` with your own values.
```java
NativeAdView nativeAdView = new NativeAdView(this, SITE_TOKEN, SCHEMA_NAME, TEMPLATE);
nativeAdView.setAutoreload(true);
content.addView(nativeAdView);
```
See [NativeAdFromCodeActivity.java](Example/src/com/liquidm/sdk/example/NativeAdFromCodeActivity.java) for more details.
## Download NativeAd manually
1. Create ```NativeAdProvider```
```java
NativeAdProvider nativeAdProvider = new NativeAdProvider(this, SITE_TOKEN, SCHEMA_NAME);
```
1. Attach ```NativeAdLoadListener``` to listen for new ads
```java
nativeAdProvider.setListener(new NativeAdLoadListener() {
@Override
public void onAdLoad(NativeAd nativeAd) {
// Render nativeAd manually
}
@Override
public void onAdFailedToLoad() {
// Handle loading failure
}
});
```
1. Load native ad
```java
nativeAdProvider.loadAd();
```
or turn on autoreloading
```java
nativeAdProvider.setAutoreload(true);
```
1. Use ```NativeAd``` methods to fetch asset data, for example:
```java
String title = nativeAd.getString("title");
int rating = nativeAd.getInt("rating");
Bitmap image = nativeAd.getPreloadedImage("image");
```
## Other
### Customize ```NativeAdView``` template rendering
```NativeAdView``` is using ```NativeAdViewFiller``` for propagating template with native ad data. You can get it in the following way:
```java
NativeAdViewFiller nativeAdViewFiller = nativeAdView.getViewFiller();
```
```NativeAdViewFiller``` can fill ```TextView```, ```ImageView``` and ```Button``` views by default, but it can also be configured to fill custom views like this:
```java
nativeAdViewFiller.setAssetViewFiller(RatingBar.class, new NativeAdViewFiller.AssetViewFiller() {
@Override
public void fillViewWithNativeAdAssetData(View assetView, NativeAd nativeAd, String assetName) {
RatingBar ratingBar = (RatingBar) assetView;
ratingBar.setProgress(nativeAd.getInt(assetName));
}
});
```
```NativeAdViewFiller``` searches for assets views by tags. It matches tag name with asset name by default. This too can be configured by writing custom ```AssetViewFnder```. Default implementation looks like this:
```java
nativeAdViewFiller.setAssetViewFinder(new NativeAdViewFiller.AssetViewFinder() {
@Override
public View findViewForAsset(String assetName, View nativeAdView) {
return nativeAdView.findViewWithTag(assetName);
}
});
```
```NativeAdViewFiller``` attaches click handler to all views by default. If you want to disable click handling on specified asset view then invoke:
```java
nativeAdViewFiller.setIgnoreAssetViewClicks(assetName, true);
```
### Native video interstitial ad
```NativeVideoInterstitialAd``` allows you to download and show native video interstitial ad. Please follow below steps to use it:
1. Create ```NativeVideoInterstitialAd```, set its listener, and load it.
```java
@Override
protected void onCreate(Bundle savedInstanceState) {
// ..
// Replace TestTokn with your personal token.
String siteToken = "<PASSWORD>";
interstitial = new NativeVideoInterstitialAd(this, "TestTokn");
interstitial.setListener(this);
interstitial.loadAd();
}
```
1. Show interstitial ad in onAdLoad() event handler. Handle onAdFailedToLoad() event if needed.
```java
@Override
public void onAdLoad(NativeVideoInterstitialAd ad) {
interstitial.show();
}
@Override
public void onAdFailedToLoad(NativeVideoInterstitialAd ad) {
Toast.makeText(this, getString(R.string.interstitial_load_failed), Toast.LENGTH_SHORT).show();
}
@Override
public void onAdClick(NativeVideoInterstitialAd ad) {
}
@Override
public void onAdPresentScreen(NativeVideoInterstitialAd ad) {
}
@Override
public void onAdDismissScreen(NativeVideoInterstitialAd ad) {
}
@Override
public void onAdLeaveApplication(NativeVideoInterstitialAd ad) {
}
```
1. Stop ad loading in activity onPause() method to avoid showing native video interstitial after leaving the activity.
```java
@Override
protected void onPause() {
super.onPause();
interstitial.stopLoading();
}
```
See [NativeVideoInterstitialAdActivity.java](Example/src/com/liquidm/sdk/example/NativeVideoInterstitialAdActivity.java) for more details.
# FAQ
## How to select the best fitting banner size for most Android devices?
LiquidM banners sizes are measured in device-independent pixels. It means that for example 300x50 ad will look similarly on different devices, but will occupy different area measured in pixels.
On Android there are four categories of screen densities: ldpi, mdpi, hdpi, xhdpi and each one has its own scaling factor like on the image below:

So a 300x50 (300dp x 50dp) ad will occupy:
- 225px x 37.5px on ldpi screen
- 300px x 50px on mdpi screen
- 450px x 75px on hdpi screen
- 600px x 100px on xhdpi screen
Having this in mind and knowing screen resolutions and densities of the devices that are the most important for you, you can determine the minimum screen size for every density category.
Having minimum screen sizes for every density category you can choose an ad size that will fit them all.
### Example
1. Let's focus on hdpi and xhdpi devices for simplicity and take the following ones into account:
- HTC Desire Z: 480px x 800px hdpi
- Samsung Galaxy S3 Mini: 480px x 800px hdpi
- Samsung Galaxy S4 Mini: 540px x 960px hdpi
- LG Nexus 4: 768px x 1280px xhdpi
- Asus Nexus 7: 1200px x 1920px xhdpi
- Samsung Galaxy Note: 800px x 1280px xhdpi
1. The smallest resolution in each group is:
- 480px x 800px for hdpi
- 768px x 1280px for xhdpi
1. The smallest resolution expressed in device-independent pixels and rounded down in each group is:
- 320dp x 533dp for hdpi
- 384dp x 640dp for xhdpi
1. And finally, the smallest resolution expressed in device-independent pixels is: 320dp x 533dp.
1. Summing up, 320x533 is the maximal ad size that will fit on all screens of above devices.
Having this in mind, you can choose to create 300x300 custom sized ad.
You will need 300px x 300px image for standard version and 600px x 600px image for hd version.
|
1827b1adef6e01a486cb66af36ab64b85ce48cee
|
[
"Markdown",
"Java"
] | 6
|
Java
|
hyongbai/android-sdk-sample
|
bc3758269d081e25780dacaf107fffc13f00eaa9
|
5d84076d0efc1b202567db339aa7c81bf79863b2
|
refs/heads/master
|
<repo_name>echo818/pay<file_sep>/pay-think/pay.sql
/*
Navicat Premium Data Transfer
Source Server : pay
Source Server Type : MySQL
Source Server Version : 80011
Source Host : localhost
Source Database : pay
Target Server Type : MySQL
Target Server Version : 80011
File Encoding : utf-8
Date: 05/14/2018 22:12:50 PM
*/
SET NAMES utf8;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for `account`
-- ----------------------------
DROP TABLE IF EXISTS `account`;
CREATE TABLE `account` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '标识',
`otr` varchar(255) NOT NULL COMMENT 'OTR',
`admin` varchar(255) DEFAULT NULL COMMENT 'admin',
`seller` varchar(255) DEFAULT NULL COMMENT 'seller',
`store` varchar(255) DEFAULT NULL COMMENT 'store',
`product` varchar(255) DEFAULT NULL COMMENT 'product',
`asin` varchar(255) DEFAULT NULL COMMENT 'asin',
`price` varchar(100) DEFAULT NULL COMMENT 'price',
`time` varchar(100) DEFAULT NULL COMMENT 'price',
`name` varchar(255) DEFAULT NULL COMMENT 'name',
`orderId` varchar(255) DEFAULT NULL COMMENT 'orderId',
`paypal` varchar(255) DEFAULT NULL COMMENT 'paypal',
`review` varchar(255) DEFAULT NULL COMMENT 'review',
`money1` tinyint(1) unsigned DEFAULT '0' COMMENT '产品钱1',
`commission1` tinyint(1) unsigned DEFAULT '0' COMMENT '佣金钱1',
`money2` tinyint(1) unsigned DEFAULT '0' COMMENT '产品钱2',
`commission2` tinyint(1) unsigned DEFAULT '0' COMMENT '佣金钱2',
`remark` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '备注',
`createTime` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='付款用户信息';
SET FOREIGN_KEY_CHECKS = 1;
<file_sep>/pay-vue/src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/Login'
import Table from '@/views/Table'
import Error from '@/views/Error'
Vue.use(Router)
export default new Router({
routes: [
{path: '/', name: 'Default', redirect: 'login'},
{path: '/login', name: 'Login', component: Login},
{path: '/table', name: 'TableDesc', component: Table},
{path: '*', name: 'Error', component: Error}
]
})
<file_sep>/README.md
# pay
thinkjs + vue
<file_sep>/pay-think/src/controller/index.js
const XLSX = require('xlsx')
const Base = require('./base.js')
module.exports = class extends Base {
indexAction() {
return this.success({
name: 'thinkjs'
})
}
async filterAction() {
const {val, type} = this.post('val,type')
const account = this.model('account')
let data = []
if (type === 'otr') {
data = await account.where({otr: ['like', `%${val}%`]}).distinct('otr').getField('otr')
} else if (type === 'admin') {
data = await account.where({admin: ['like', `%${val}%`]}).distinct('admin').getField('admin')
}
return this.success(data)
}
async listAction() {
const {page, ...params} = this.post('page,otr,admin,seller,store,asin,price')
for (let key in params) {
if (params[key] === '') delete params[key]
}
const account = this.model('account')
const data = await account.where(params).order('id DESC').page(page).countSelect()
if (think.isEmpty(data)) {
return this.fail('找不到信息')
}
return this.success(data)
}
async exportAction() {
this.header('Content-Disposition', `attachment; filename=${Date.now()}.xlsx`)
const params = this.get('otr,admin,seller,store,asin,price')
for (let key in params) {
if (params[key] === '') delete params[key]
}
const account = this.model('account')
const data = await account.where(params).order('id DESC').fieldReverse('createTime').select()
const ws = XLSX.utils.json_to_sheet(data)
const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb, ws, 'SheetJS');
const buf = XLSX.write(wb, {type:'buffer', bookType:'xlsx'})
this.body = buf
}
async storeAction() {
const {add, update, del} = this.post('add,update,del')
const account = this.model('account')
// 删除
let affectedRows = []
if (del.length) {
affectedRows = await account.where({id: ['IN', del]}).delete()
}
// 添加
let insertIds = []
if (add.length) {
insertIds = await account.addMany(add)
}
// 更新
let affectRows = []
if (update.length) {
affectRows = await account.updateMany(update)
}
return this.success({
addRows: insertIds,
updateRows: affectRows,
delRows: affectedRows
})
}
};<file_sep>/pay-think/backsql.sh
#!/bin/bash
# Name:backsql.sh
# This is a ShellScript For Auto DB Backup and Delete old Backup
#
backupdir=/mnt/backup
mysqldir=/usr/bin
time=` date +%Y%m%d%H `
$mysqldir/mysqldump -u root -pzrc123123 pay | gzip > $backupdir/pay$time.sql.gz
#
find $backupdir -name "pay*.sql.gz" -type f -mtime +5 -exec rm {} \; > /dev/null 2>&1
|
7b7d911df11809d10d9c5bd51b52edf15ab38ebc
|
[
"JavaScript",
"SQL",
"Markdown",
"Shell"
] | 5
|
SQL
|
echo818/pay
|
37413b8933c798885fae730d2491ff61307b2bee
|
66e6e655577f809879e360c8299cf266a02e94a0
|
refs/heads/master
|
<file_sep>#include "bird.h"
#include "point.h"
#include "velocity.h"
#include "flyingObject.h"
using namespace std;
Bird :: Bird(Point initialPoint)
{
point = initialPoint;
}
void Bird :: hit()
{
}<file_sep>/***********************************************************************
* Program:
* Assignment 03, Digital Forensics
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
*
* Estimated: 2.5 hrs
* Actual: 3.5 hrs
*
* By Approaching the development of this assignment with an outline of
* how I wanted the program to work, I was able to avoid a lot of what
* may have otherwise been difficulties. Deciding where to put the try,
* throw, and catch and deciding what to do during those circumstances
* provided the most uncertainty, but with the bigger picture already in
* place, the answer to those questions came relatively quickly.
************************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct AccessRecord
{
string filename;
string username;
long timestamp;
};
/**********************************************************************
* Prompt the user for a time in terms of milliseconds
***********************************************************************/
long promptForTime (string insert)
{
long time = 0;
cout << "Enter the " << insert << " time: ";
cin >> time;
return time;
}
/**********************************************************************
* prompt the user for a file-path that can be used to
* retrieve an external file
***********************************************************************/
void promptForFileName (char filename[])
{
ifstream fs;
do
{
cout << "Enter the access record file: ";
cin >> filename;
fs.open(filename);
if (fs.fail())
{
cout << "Invalid File." << endl;
}
} while (fs.fail());
fs.close();
return;
}
/**********************************************************************
* short-hand function to skip a line in console output.
***********************************************************************/
void blankLine ()
{
cout << endl;
}
/**********************************************************************
* parseFile() will read the file one line at a time, and store the
* contents of the line as a string, ignoring any errors, and populate
* an array with each line in the file given.
**********************************************************************/
int parseFile(char filename[], string fileLine[])
{
ifstream fs;
fs.open(filename);
int counter = 0;
for (; !fs.eof(); counter++)
{
getline(fs, fileLine[counter]);
}
return counter - 1;
}
/**********************************************************************
* parseLine() will receive the file in one-line segments, and break up
* each line into their 3 parts using white space as an identifier.
* An error will be thrown, and the whole line will be printed in the
* console, but not stored in the AccessRecord Struct Array.
**********************************************************************/
int parseLine(int fileLength, string fileLine[], AccessRecord recordMatches[])
{
stringstream ss;
int modifier = 0;
for (int x = 0; x < fileLength; x++)
{
ss.str(fileLine[x]);
if (ss.fail()) cout << "ERRoR: STRING-STREAM READ-IN FAILED!!." << endl;
try
{
ss >> recordMatches[x - modifier].filename;
ss >> recordMatches[x - modifier].username;
ss >> recordMatches[x - modifier].timestamp;
if (recordMatches[x - modifier].timestamp < 1000000000
|| recordMatches[x - modifier].timestamp > 10000000000)
{
throw(fileLine[x]);
}
ss.clear();
}
catch (string message)
{
cout << "Error parsing line: " << message << endl;
modifier++;
ss.clear();
}
}
return fileLength - modifier;
}
/**********************************************************************
* filterByTimeStamp() takes an AccessRecord Array, reads the timestamp
* values of each element, and removes the ones that don't fall within
* the time interval. It will record the ones that do fall within the
* interval, and overwrite the existing array with the filtered list.
**********************************************************************/
int filterByTimestamp(long start, long end, int fiLength, AccessRecord rms[])
{
int counter = 0;
for (int x = 0; x < fiLength; x++)
{
if (start <= rms[x].timestamp && rms[x].timestamp <= end)
{
rms[counter] = rms[x];
counter++;
}
}
return counter;
}
/**********************************************************************
* Displays pertinent information neatly
**********************************************************************/
void display (AccessRecord recordMatches[], int numberOfRecords)
{
cout << "The following records match your criteria:" << endl << endl;
cout << setw(15) << "Timestamp" << " ";
cout << setw(19) << "File" << " ";
cout << setw(19) << "User" << endl;
cout << "--------------- ------------------- -------------------" << endl;
for (int x = 0; x < numberOfRecords ; x++)
{
cout << setw(15) << recordMatches[x].timestamp << " ";
cout << setw(19) << recordMatches[x].filename << " ";
cout << setw(19) << recordMatches[x].username << endl;
}
cout << "End of records" << endl;
}
/**********************************************************************
* main() Handles data and calls functions.
***********************************************************************/
int main()
{
AccessRecord recordMatches[500];
string fileLine[500];
char filename[512];
long startTime = 0;
long endTime = 0;
int fileLength = 0;
promptForFileName(filename);
fileLength = parseFile(filename, fileLine);
fileLength = parseLine(fileLength, fileLine, recordMatches);
blankLine();
startTime = promptForTime("start");
endTime = promptForTime("end");
fileLength = filterByTimestamp(startTime, endTime,
fileLength, recordMatches);
blankLine();
display(recordMatches, fileLength);
return 0;
}
<file_sep>// File: address.cpp
#include <string>
#include <iostream>
#include "address.h"
using namespace std;
// Put your method bodies for the address class here
/***************************************************************
* Empty Parameter Constructor sets default variable values
***************************************************************/
Address :: Address()
{
street = "unknown";
city = "";
state = "";
zip = "00000";
}
/***************************************************************
* Full Parameter Constructor sets variables to user-specified values
***************************************************************/
Address :: Address(string setStreet, string setCity,
string setState, string setZip)
{
street = setStreet;
city = setCity;
state = setState;
zip = setZip;
}
/***************************************************************
* method to edit class variable of street
***************************************************************/
void Address :: setStreet (string setStreet)
{
street = setStreet;
}
/***************************************************************
* method to edit class variable of city
***************************************************************/
void Address :: setCity (string setCity)
{
city = setCity;
}
/***************************************************************
* method to edit class variable of state
***************************************************************/
void Address :: setState (string setState)
{
state = setState;
}
/***************************************************************
* method to edit class variable of zip
***************************************************************/
void Address :: setZip (string setZip)
{
zip = setZip;
}
/***************************************************************
* method gives a the user a copy of the variable street
***************************************************************/
string Address :: getStreet()
{
return street;
}
/***************************************************************
* method gives a the user a copy of the variable city
***************************************************************/
string Address :: getCity()
{
return city;
}
/***************************************************************
* method gives a the user a copy of the variable state
***************************************************************/
string Address :: getState()
{
return state;
}
/***************************************************************
* method gives a the user a copy of the variable zip
***************************************************************/
string Address :: getZip()
{
return zip;
}
/***************************************************************
* displays the customer's address
***************************************************************/
void Address :: display()
{
cout << street << endl
<< city << ", " << state << " " << zip << endl;
}<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Assignment
* Brother Cook, CS165
* Author:
* <NAME>
************************************************************************/
#include <iostream>
#include <string>
using namespace std;
class Canvas
{
private:
int height;
int width;
bool resolution[100][100];
public:
Canvas (int w, int h)
{
width = w;
height = h;
}
void setResolution()
{
height = 30;
width = 60;
}
void pixelOn()
{
int x;
int y;
cout << "Enter x coordinate: ";
cin >> x;
cout << "Enter y coordinate: ";
cin >> y;
if (x < width && 0 <= x && y < height && 0 <= y)
{
if(resolution[x][y])
{
cout << "That pixel is already on!";
}
else
{
resolution [y][x] = true;
cout << "Success!" << endl;
}
}
else
{
cout << "Invalid height or width." << endl;
}
};
void pixelOff()
{
int x;
int y;
cout << "Enter x coordinate: ";
cin >> x;
cout << "Enter y coordinate: ";
cin >> y;
if (x < width && y < height)
{
if(!resolution[x][y])
{
cout << "That pixel is already off!";
}
else
{
resolution[y][x] = false;
cout << "Success!" << endl;
}
}
else
{
cout << "Invalid height or width." << endl;
}
};
void pixelAllOff()
{
for (int y = 0; y <= height; y++)
{
for (int x = 0; x <= width; x++)
{
resolution[y][x] = false;
/* if(resoltion[y][x])
{
resolution[y][x] = false;
}*/
}
}
cout << "Reset All Pixels to off..." << endl;
};
void displayPixels()
{
for (int y = 0; y <= height; y++)
{
for (int x = 0; x <= width; x++)
{
if(resolution[y][x])
{
cout << 8;
}
else
{
cout << '_';
}
}
cout << endl;
}
};
};
void start()
{
cout << "This program allows you to paint pixel pictures" << endl;
cout << "type 'h' for a list of commands.";
}
void help()
{
cout << "[D] = Display all pixels." << endl
<< "[E] = Exit program." << endl
<< "[H] = Show help menu." << endl
<< "[L] = Turn on pixel. " << endl
<< "[O] = Turn off pixel. " << endl
<< "[R] = Reset all pixels to off." << endl;
cout << "WARNING: High resoultion values may cause your picture to display improperly.\n";
}
char prompt()
{
char command;
cout << "Enter a command: ";
cin >> command;
return command;
}
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
Canvas mainDisplay(60, 30);
// mainDisplay.setResolution();
mainDisplay.pixelAllOff();
char command;
bool doRunProgram = true;
start();
help();
while(doRunProgram)
{
cout << endl;
command = prompt();
if (command == 'd' || command == 'D')
{
mainDisplay.displayPixels();
}
else if (command == 'e' || command == 'E')
{
cout << "Exiting Program..." << endl;
doRunProgram = false;
}
else if (command == 'h' || command == 'H')
{
help();
}
else if (command == 'l' || command == 'L')
{
mainDisplay.pixelOn();
}
else if (command == 'o' || command == 'O')
{
mainDisplay.pixelOff();
}
else if (command == 'r' || command == 'R')
{
mainDisplay.pixelAllOff();
}
else
{
cout << "Invalid command. For a list of commands type 'h'." << endl;
}
}
return 0;
}
<file_sep>#pragma once
// #ifndef "point.h"
#include "point.h"
// #ifndef "velocity.h"
#include "velocity.h"
// #endif
using namespace std;
class Lander
{
private:
Point point;
public:
Lander();
Point getPoint() const;
Velocity getVelocity() const;
bool isAlive();
bool isLanded();
int getFuel();
bool canThrust();
void setLanded(bool);
void setAlive(bool);
void setFuel(int);
void applyGravity(float);
void applyThrustLeft();
void applyThrustRight();
void applyThrustBottom();
void advance();
void draw();
};
<file_sep>/***************************************************************
* File: product.cpp
* Author: <NAME>
* Purpose: Contains the method implementations for the Product class.
***************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include "product.h"
using namespace std;
/***************************************************************
* This will prompt for and fill all information that the user
* needs to provide in order for the program to fulfil it's functions
* defined in other functions below.
***************************************************************/
Product :: Product ()
{
cout << "Enter name: ";
getline(cin, name);
cout << "Enter description: ";
getline(cin, description);
cout << "Enter weight: ";
cin >> weight;
do {
cin.clear();
cin.ignore(1000, '\n');
cout << "Enter price: ";
cin >> basePrice;
} while (cin.fail() || basePrice < 0);
}
/***************************************************************
* This calculates sales tax for an item based on it's basePrice
* and a 6% tax.
***************************************************************/
double Product :: getSalesTax ()
{
double salesTax = basePrice * 0.06;
return salesTax;
}
/***************************************************************
* This calculates shipping cost based on item weight.
* Under 5lbs = 2$, more than that = $2 - ((weight - 5lbs) * $0.10)
***************************************************************/
double Product :: getShippingCost ()
{
double shippingCost;
if (weight > 5)
{
shippingCost = 2 + ((weight - 5) * 0.1);
}
else
{
shippingCost = 2;
}
return shippingCost;
}
/***************************************************************
* This calcuates the cost of the item after basePrice, tax, and
* shipping have been added together.
***************************************************************/
double Product :: getTotalPrice ()
{
return basePrice + getSalesTax() + getShippingCost();
}
/***************************************************************
* This displays the described product in a way optimised for
* advertising.
***************************************************************/
void Product :: displayAdvertise ()
{
cout << name << " - " << '$' << basePrice << endl
<< '(' << description << ')' << endl;
}
/***************************************************************
* This displays the described product in a way optimised for
* keeping inventory.
***************************************************************/
void Product :: displayInventory ()
{
cout << '$' << basePrice << " - " << name << " - " << weight << " lbs" << endl;
}
/***************************************************************
* This displays the described product in a way optimised for
* showing the customer the price break down for the total price.
***************************************************************/
void Product :: displayReceipt ()
{
cout << fixed << showpoint << setprecision(2);
cout << name << endl;
cout << " Price: " << "$" << setw(8) << basePrice << endl;
cout << " Sales tax: " << "$" << setw(8) << getSalesTax() << endl;
cout << " Shipping cost: " << "$" << setw(8) << getShippingCost() << endl;
cout << " Total: " << "$" << setw(8) << getTotalPrice() << endl;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* A Program that gives your terminal a blank slate.
*
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream>
//#include <iomanip>
using namespace std;
/**********************************************************************
* This enters 50 new lines to ensure that your screen is blank and beautiful.
***********************************************************************/
int main()
{
int x = 0;
while (x<50){
cout << "\n";
x=x+1;
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 12, Input & Variables - How Much Money Do You Make?
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program asks the user how much money they make, then tells them how much money they make. It always shows the decimal, the dollar amount is alligned right, and the decimal will always only be 2 spaces.
*
* Estimated: 0.25 hrs
* Actual: 0.16 hrs
* This assignement was extremely straight-forward and intuitive. I used the tools from assignment 11 to properly allign everything. Using the cin prompt I could easily obtain the desired input from the user.
************************************************************************/
#include <iostream> //cout, fixed
using namespace std;
#include <iomanip> //setw(), setprecision()
/**********************************************************************
* This function, main(), asks the user how much they make, records their response, then prints it in a neat manner.
***********************************************************************/
int main()
{
//
double income;
cout << fixed << showpoint << setprecision(2) << "\tYour monthly income: ";
cin >> income;
cout << fixed << showpoint << setprecision(2) << "Your income is: $" << setw(9) << income << "\n";
return 0;
}
<file_sep>/*****************************************************
* File: pair.h
*
* Purpose: Defines a Pair template class that can hold
* two items of arbitrary data types.
******************************************************/
#ifndef PAIR_H
#define PAIR_H
// TODO: Fill in this class
// Put all of your method bodies right in this file
#endif // PAIR_H
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream>
#include <cstdlib> // rand()
//#include <iomanip>
using namespace std;
/**********************************************************************
*
***********************************************************************/
bool isFavorite(int guess)
{
int favorite = 10;
if (guess == favorite)
{
return true;
}
else
{
if (guess < favorite)
{cout << "Too low" << endl;}
else
{cout << "Too high" << endl;}
return false;
}
}
/**********************************************************************
*
***********************************************************************/
int main()
{
int guess;
do
{
cout << "Try to guess my favorite number! : ";
cin >> guess;
}
while(isFavorite(guess) != true);
cout << rand() << endl;
cout << rand() / 100000000 << endl;
cout << rand() << endl;
cout << rand() / 100000000 << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Template
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
return 0;
}
<file_sep>/*******************
* smartphone.cpp
*******************/
#include <iostream>
#include <string>
#include "smartphone.h"
using namespace std;
// TODO: Put your SmartPhone methods heres
SmartPhone :: SmartPhone()
{
email = "<EMAIL>";
}
void SmartPhone :: prompt()
{
promptNumber();
cout << "Email: ";
cin.ignore();
getline(cin, email);
}
void SmartPhone :: display()
{
Phone::display();
cout << email << endl;
}
<file_sep>// File: order.h
#ifndef ORDER_H
#define ORDER_H
#include <string>
#include "product.h"
#include "customer.h"
using namespace std;
// Put your Order class here
class Order
{
private:
Product product;
int quantity;
Customer customer;
public:
//constructors
Order();
Order(Product, int, Customer);
//setters
void setProduct(Product);
void setQuantity(int);
void setCustomer(Customer);
//getters
Product getProduct();
int getQuantity();
Customer getCustomer();
string getShippingZip();
// other methods
double getTotalPrice();
// display methods
void displayShippingLabel();
void displayInformation();
};
#endif<file_sep>#pragma once
#include "point.h"
#include "velocity.h"
using namespace std;
class FlyingObject
{
private:
Point point;
Velocity velocity;
bool object;
public:
FlyingObject();
Point getPoint();
Velocity getVelocity();
bool isAlive();
void setPoint(Point);
void setVelocity(Velocity);
void kill();
void advance();
void draw();
};<file_sep>// File: address.h
#ifndef ADDRESS_H
#define ADDRESS_H
#include <string>
using namespace std;
// Put your Address class here
class Address
{
private:
string street;
string city;
string state;
string zip;
public:
// constructors
Address();
Address(string, string, string, string);
// setters
void setStreet(string);
void setCity(string);
void setState(string);
void setZip(string);
// getters
string getStreet();
string getCity();
string getState();
string getZip();
// display methods
void display();
};
#endif<file_sep>#include "bullet.cpp"
#include "point.h"
#include "velocity.h"
#include "flyingObject.h"
using namespace std;
Bullet :: Bullet()
{
// point = Point(0,0);
// velocity = Velocity(0,0);
}
void Bullet :: fire(Point, float)
{
}
<file_sep>/***********************************************************************
* Program:
* Project 04, Budget Project
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program gets budget information from the user, processes it,
* then displays the information on table.
*
* Estimated: 0.25 hrs
* Actual: 0.5 hrs
* I first used this format to calculate the boolean of the if statement:
* #1 <= income < #2
* After trying to figure out why it wasn't working for about 15 minutes,
* I realized that it was because I needed to make the two parameters into
* two statements with the &&.
* #1 <= income && income < #2
************************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
/**********************************************************************
* programIntroduction() displays the first two lines in the program,
* informing the user the purpose of the program.
***********************************************************************/
void programIntroduction()
{
cout << "This program keeps track of your monthly budget" << endl;
cout << "Please enter the following:" << endl;
}
/**********************************************************************
* getIncome() Prompts the user for their monthly income, stores it, then
* returns the value.
***********************************************************************/
double getIncome()
{
double income;
cout << "\tYour monthly income: ";
cin >> income;
return income;
}
/**********************************************************************
* getBudgetLiving prompts the user for their budgeted living expenses,
* stores it, then returns the value.
***********************************************************************/
double getBudgetLiving()
{
double budgetLiving;
cout << "\tYour budgeted living expenses: ";
cin >> budgetLiving;
return budgetLiving;
}
/**********************************************************************
* getActualLiving() prompts the user for their budgeted living expenses,
* stores it, then returns the value.
***********************************************************************/
double getActualLiving()
{
double actualLiving;
cout << "\tYour actual living expenses: ";
cin >> actualLiving;
return actualLiving;
}
/**********************************************************************
* getActualTax prompts the user for how much tax they actually paid,
* stores it, and returns the value.
* *********************************************************************/
double getActualTax()
{
double actualTax;
cout << "\tYour actual taxes withheld: ";
cin >> actualTax;
return actualTax;
}
/**********************************************************************
* getActualTithing() prompts the user for how much money they actually
* tithed, stores it, then returns that value.
***********************************************************************/
double getActualTithing()
{
double actualTithing;
cout << "\tYour actual tithe offerings: ";
cin >> actualTithing;
return actualTithing;
}
/**********************************************************************
* getActualOther() prompts the user for how much money they spent on other
* categories not listed above, stores it, then returns that value.
***********************************************************************/
double getActualOther()
{
double actualOther;
cout << "\tYour actual other expenses: ";
cin >> actualOther;
return actualOther;
}
/**********************************************************************
* computeTax() takes a variable, income, and uses it to compute the tax
* bracket the user falls into, and returns how much tax they need to pay.
***********************************************************************/
double computeTax(double monthlyIncome)
{
double yearlyIncome = (monthlyIncome * 12);
double yearlyTax;
double monthlyTax;
if (0 <= yearlyIncome && yearlyIncome < 15100)
{
yearlyTax = yearlyIncome * 0.10;
}
else if (15100 <= yearlyIncome && yearlyIncome < 61300)
{
yearlyTax = (1510 + (0.15 * (yearlyIncome - 15100)));
}
else if (61300 <= yearlyIncome && yearlyIncome < 123700)
{
yearlyTax = (8440 + (0.25 * (yearlyIncome - 61300)));
}
else if (123700 <= yearlyIncome && yearlyIncome < 188450)
{
yearlyTax = (24040 + (0.28 * (yearlyIncome - 123700)));
}
else if (188450 <= yearlyIncome && yearlyIncome < 336550)
{
yearlyTax = (42170 + (0.33 * (yearlyIncome - 188450)));
}
else if (336550 <= yearlyIncome)
{
yearlyTax = (91043 + (0.35 * (yearlyIncome - 336550)));
}
monthlyTax = (yearlyTax / 12);
return monthlyTax;
}
/**********************************************************************
* computeTithing() takes a variable, income, and uses it to compute
* how much tithing they would need to pay to be a full tithe payer,
* and returns that value.
***********************************************************************/
double computeTithing(double income)
{
double tenPercent = income * 0.1;
return tenPercent;
}
/**********************************************************************
* display() receives all of the user's given info from main, and uses it
* to calculate the remaining budget items that the user didn't explicitly
* give. Then now having all of the needed budget info, display's it neatly
* on a table.
***********************************************************************/
void display(double income, double budgetLiving, double actualLiving,
double actualTax, double actualTithing, double actualOther)
{
double budgetTax = computeTax(income);
double budgetTithing = computeTithing(income);
double budgetOther = income - budgetTax - budgetTithing - budgetLiving;
double actualDifference = income - actualTax - actualTithing
- actualLiving - actualOther;
double budgetDifference = 0;
cout << endl;
cout << "The following is a report on your monthly expenses" << endl;
cout << showpoint << fixed << setprecision(2);
cout << "\tItem " << " " << " Budget "
<< " " << " Actual" << endl;
cout << "\t===============" << " " << "==============="
<< " " << "===============" << endl;
cout << "\tIncome " << " " << "$" << setw(11) << income
<< " " << " " << "$" << setw(11) << income << endl;
cout << "\tTaxes " << " " << "$" << setw(11) << budgetTax
<< " " << " " << "$" << setw(11) << actualTax << endl;
cout << "\tTithing " << " " << "$" << setw(11) << budgetTithing
<< " " << " " << "$" << setw(11) << actualTithing << endl;
cout << "\tLiving " << " " << "$" << setw(11) << budgetLiving
<< " " << " " << "$" << setw(11) << actualLiving << endl;
cout << "\tOther " << " " << "$" << setw(11) << budgetOther
<< " " << " " << "$" << setw(11) << actualOther << endl;
cout << "\t===============" << " " << "==============="
<< " " << "===============" << endl;
cout << "\tDifference " << " " << "$" << setw(11) << budgetDifference
<< " " << " " << "$" << setw(11) << actualDifference << endl;
}
/**********************************************************************
* main() runs the entire program first by introducing the program, asking
* the user for 6 budget items and storing their value, then passing those
* values into display() to be processed and displayed.
***********************************************************************/
int main()
{
programIntroduction();
double income = getIncome();
double budgetLiving = getBudgetLiving();
double actualLiving = getActualLiving();
double actualTax = getActualTax();
double actualTithing = getActualTithing();
double actualOther = getActualOther();
display(income, budgetLiving, actualLiving,
actualTax, actualTithing, actualOther);
return 0;
}
<file_sep>#pragma once
#include "point.h"
#include "velocity.h"
#include "flyingObject.h"
using namespace std;
class Bird
{
private:
int pointValue; // on Kill
public:
Bird(Point);
void hit();
};<file_sep>#include "point.h"
#include "velocity.h"
#include "flyingObject"
using namespace std;
FlyingObject :: FlyingObject()
{
}
Point FlyingObject :: getPoint()
{
return Point;
}
Velocity FlyingObject :: getVelocity()
{
return Velocity;
}
bool FlyingObject :: isAlive()
{
return true;
}
void FlyingObject :: setPoint(Point setPoint)
{
}
void FlyingObject :: setVelocity(Velocity setVelocity)
{
}
void FlyingObject :: kill()
{
}
void FlyingObject :: advance()
{
}
void FlyingObject :: draw()
{
}<file_sep>/***********************************************************************
* Program:
* Assignment 30, Average Grades
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program prompts the user for 10 integers, stores them in an array,
* then processes them to find the average then displays the average.
*
* Estimated: 0.5 hrs
* Actual: 0.5 hrs
* I am very comfortable with filling arrays between functions now.
************************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* getGrades() prompts the user for 10 grades and saves that data to the
* array given to it from main.
***********************************************************************/
void getGrades(int grades[])
{
for (int x = 0; x < 10; x++)
{
cout << "Grade " << x+1 << ": ";
cin >> grades[x];
}
}
/**********************************************************************
* averageGrades takes a given array and evaluates the first ten items in
* the array and returns the averaged value of the ten items.
***********************************************************************/
int averageGrades(int grades[])
{
int average = 0;
for (int x = 0; x < 10; x++)
{
average = average + grades[x];
}
average = average / 10;
return average;
}
/**********************************************************************
* main() declares an array to be filled by getGrades() and passes it.
* Then the array is then passed to averageGrades() to be evaluated and the
* returned expression is then output to the screen.
***********************************************************************/
int main()
{
int grades[10];
getGrades(grades);
int average = averageGrades(grades);
cout << "Average Grade: " << average << "%" << endl;
return 0;
}
<file_sep>#pragma once
using namespace std;
class Velocity
{
private:
float dx;
float dy;
public:
Velocity();
Velocity(float, float);
float getDx();
float getDy();
void setDx(float);
void setDy(float);
};<file_sep>/***********************************************************************
* Program:
* Project 02, Monthly Budget
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.5 hrs
* Actual: 1.5 hrs
* Understanding StyleChecker's requirements took me a while to understand.
* and making sure everything lined up as expected took some time too.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
//bud budget, act actual _ Variables
double budIncome = 0;
double actIncome = 0;
double budTaxes = 0;
double actTaxes = 0;
double budTithing = 0;
double actTithing = 0;
double budLiving = 0;
double actLiving = 0;
double budOther = 0;
double actOther = 0;
double budDifference = 0;
double actDifference = 0;
cout << "This program keeps track of your monthly budget" << endl;
cout << "Please enter the following:" << endl;
cout << " " << "Your monthly income: ";
cin >> actIncome;
budIncome = actIncome;
cout << " " << "Your budgeted living expenses: ";
cin >> budLiving;
cout << " " << "Your actual living expenses: ";
cin >> actLiving;
cout << " " << "Your actual taxes withheld: ";
cin >> actTaxes;
cout << " " << "Your actual tithe offerings: ";
cin >> actTithing;
cout << " " << "Your actual other expenses: ";
cin >> actOther;
cout << endl;
/**********************************************************************
* setw() adds spaces before the next output item. The number of spaces
* added is equal to the argument minus the number of characters in the
* next output item.
***********************************************************************/
cout << "The following is a report on your monthly expenses" << endl;
//use a tab to indent each line
cout << showpoint << fixed << setprecision(2);
cout << "\tItem " << " " << " Budget " << " " << " Actual" << endl;
cout << "\t===============" << " " << "===============" << " " << "===============" << endl;
cout << "\tIncome " << " " << "$" << setw(11) << budIncome << " " << " " << "$" << setw(11) << actIncome << endl;
cout << "\tTaxes " << " " << "$" << setw(11) << budTaxes << " " << " " << "$" << setw(11) << actTaxes << endl;
cout << "\tTithing " << " " << "$" << setw(11) << budTithing << " " << " " << "$" << setw(11) << actTithing << endl;
cout << "\tLiving " << " " << "$" << setw(11) << budLiving << " " << " " << "$" << setw(11) << actLiving << endl;
cout << "\tOther " << " " << "$" << setw(11) << budOther << " " << " " << "$" << setw(11) << actOther << endl;
cout << "\t===============" << " " << "===============" << " " << "===============" << endl;
cout << "\tDifference " << " " << "$" << setw(11) << budDifference << " " << " " << "$" << setw(11) << actDifference << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 23, Adding Multiples
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* The program takes an input and adds the multiples of that input together
* until the multiples exceed 100.
*
* Estimated: 0.5 hrs
* Actual: 0.7 hrs
* Figuring out that I needed a second variable to store the sums apart
* from the multiples was tricky.
************************************************************************/
#include <iostream> //cout, cin, fixed
//#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* getMultiple() receives and returns user input.
***********************************************************************/
int getMultiple()
{
int uinput;
cin >> uinput;
return uinput;
}
/**********************************************************************
* addTillHundred() takes a parameter and adds multiples of that parameter
* together untill its multiples exceed 100. It returns the sum of the multiples.
***********************************************************************/
int addTillHundred(int multiple)
{
int nextMultiple = multiple;
int carryOver = 0;
while(nextMultiple < 100 && multiple > 0 )
{
carryOver = carryOver + nextMultiple;
nextMultiple += multiple;
}
return carryOver;
}
/**********************************************************************
* main() displays a promt for the user
* gathers info from the user using getMultiple()
* uses the returned value as a parameter for addTillHundred()
* display's addTillHundred() value on the screen.
***********************************************************************/
int main()
{
cout << "What multiples are we adding? ";
int multiples = getMultiple();
cout << "The sum of multiples of " << multiples << " less than 100 are: " << addTillHundred(multiples) << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, w3-test
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <iomanip>
using namespace std;
bool shouldFurnaceTurnOn (int currentTemperature, int desiredTemperature)
{
if(currentTemperature < desiredTemperature)
return true;
else
return false;
}
int main()
{
int currentTemp;
int desiredTemp;
cout << "What is the current temperature?: ";
cin >> currentTemp;
cout << "What temperature do you want it to be?: ";
cin >> desiredTemp;
int temperatureDifference;
while (shouldFurnaceTurnOn(currentTemp, desiredTemp))
{
currentTemp += 1;
temperatureDifference += 1;
}
cout << "The current temperature is now " << currentTemp << " degrees." << endl
<< "The room temperature has been raised " << temperatureDifference << " degrees." << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 01b, C++ Basics - Arrays
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* Function getSize()
* Purpose: Learn from the user how many items will be recorded and evaluated
***********************************************************************/
int getSize()
{
int size;
cout << "Enter the size of the list: ";
cin >> size;
return size;
}
/**********************************************************************
* Function: getList
* Purpose: promt the user for a number of integers equal to the size arguement
***********************************************************************/
void getList(int size, int array[])
{
for (int x = 0; x < size; x++)
{
cout << "Enter number for index " << x << ": ";
cin >> array[x];
}
}
/**********************************************************************
* Function: displayMultiples
* Purpose: Evaluate the elements in the passed array to determine which
* elements are divisible by 3 and display only those elements.
***********************************************************************/
void displayMultiples(int size, int array[])
{
cout << endl << "The following are divisible by 3:" << endl;
for(int x = 0; x < size; x++)
{
if (array[x] % 3 == 0)
{
cout << array[x] << endl;
}
}
}
/**********************************************************************
* Function: main
* Purpose: Declare an array of numbers. Call getSize(), call getList(),
* call displayMultiples()
***********************************************************************/
int main()
{
int array[20];
int size = getSize();
getList(size, array);
displayMultiples(size, array);
return 0;
}
<file_sep>#include "lander.h"
#include "velocity.h"
#include "point.h"
#include "uiDraw.h"
#include "ground.h"
using namespace std;
int Lander :: lives;
/*************************************************************************
* Set default values to lander private variabls
**************************************************************************/
Lander :: Lander() {
lives = 3;
shipAlive = true;
shipLanded = false;
point = Point(100,100);
velocity = Velocity(0,0);
}
/*************************************************************************
* returns the moon lander's current position
**************************************************************************/
Point Lander :: getPoint() const {
return point;
}
/*************************************************************************
* returns the moon lander's current velocity.
**************************************************************************/
Velocity Lander :: getVelocity() const {
return velocity;
}
/*************************************************************************
* Determine if the Lander is still alive by relying on the shipAlive variable.
* If the ship is not alive, check to see if they have any lives left. If they
* do, set the ship to alive, set to a new position, set fuel to 500, and give
* them another chance. Decrement static lives variable.
**************************************************************************/
bool Lander :: isAlive() {
if (shipAlive == false && lives > 0)
{
shipAlive = true;
lives--;
fuel = 500;
point.setX(200);
point.setY(100);
velocity.setDx(-1);
velocity.setDy(0);
}
return shipAlive;
}
/*************************************************************************
* Return true of the shipLanded is true.
**************************************************************************/
bool Lander :: isLanded() {
return shipLanded;
}
/*************************************************************************
* Return the amount of fuel that the lander has remaining.
**************************************************************************/
int Lander :: getFuel() {
return fuel;
}
/*************************************************************************
* If the Lander has fuel, is not landed, and is alive, the ship can thrust.
**************************************************************************/
bool Lander :: canThrust() {
if (fuel > 0 && isLanded() == false && isAlive())
{
return true;
}
else if (fuel < 0)
{
fuel = 0;
return false;
}
else
{
return false;
}
}
/*************************************************************************
* Set the ship to a landed state... or not. Either way is fine.
**************************************************************************/
void Lander :: setLanded(bool didLand) {
shipLanded = didLand;
}
/*************************************************************************
* Set the status of the ship, alive or not.
**************************************************************************/
void Lander :: setAlive(bool setAlive) {
shipAlive = setAlive;
}
/*************************************************************************
* set the amount of fuel the ship has.
**************************************************************************/
void Lander :: setFuel(int setFuel) {
fuel = setFuel;
}
/*************************************************************************
* Gravity has a constant downward (negative) pull of 0.1 pixels per frame.
* This pull is addative, so the longer it is left without resistance, the
* faster the ship will accelerative downward.
**************************************************************************/
void Lander :: applyGravity(float gravity) {
float gravityPower = -1 * gravity; // Negative will make gravity pull ship down.
velocity.setDy(velocity.getDy() + gravityPower);
}
/*************************************************************************
* adds momentum that pushes the ship to the right side of the screen.
**************************************************************************/
void Lander :: applyThrustLeft() {
if (canThrust())
{
float leftThrustPower = 0.1;
fuel -= 1;
velocity.setDx(velocity.getDx() + leftThrustPower);
}
}
/*************************************************************************
* adds momentum that pushes the ship to the left side of the screen.
**************************************************************************/
void Lander :: applyThrustRight() {
if (canThrust())
{
float rightThrustPower = -0.1; // Negative will move ship left
fuel -= 1;
velocity.setDx(velocity.getDx() + rightThrustPower);
}
}
/*************************************************************************
* Adds momentum that pushes the ship, upwards- ie. away from the ground.
*************************************************************************/
void Lander :: applyThrustBottom() {
if (canThrust())
{
float bottomThrustPower = 0.3;
fuel -= 3;
velocity.setDy(velocity.getDy() + bottomThrustPower);
}
}
/*************************************************************************
* This moves the ship every frame dx and dy distance.
**************************************************************************/
void Lander :: advance() {
point.addX(velocity.getDx());
point.addY(velocity.getDy());
}
/*************************************************************************
* This draws the moonlander at its current position.
**************************************************************************/
void Lander :: draw() {
drawLander(point);
}
<file_sep>#pragma once
using namespace std;
class Velocity
{
private:
public:
Velocity();
Velocity(float, float);
float getDx();
float getDy();
void setDx(float);
void setDy(float);
};<file_sep>/***********************************************************************
* Program:
* Assignment 02, Digital Forensics
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
*
* Estimated: 2.0 hrs
* Actual: 4.0 hrs
* Relearning fstream took a while on this assignment, but I feel a lot
* more comfortable now. Also, The AccessRecord struct wasn't accepting
* some forms of data, so I had to adopt strings and convert some data
* to a long before it could be stored.
************************************************************************/
#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
struct AccessRecord
{
string username;
string filename;
long timestamp;
};
/**********************************************************************
* Prompt the user for a time in terms of miliseconds
***********************************************************************/
long promptForTime (string insert)
{
long time = 0;
cout << "Enter the " << insert << " time: ";
cin >> time;
return time;
}
/**********************************************************************
* prompt the user for a filepath that can be used to retrive an external file
***********************************************************************/
void promptForFileName (char filename[])
{
cout << "Enter the access record file: ";
cin >> filename;
return;
}
/**********************************************************************
* short-hand function to skip a line in console output.
***********************************************************************/
void blankLine ()
{
cout << endl;
}
/**********************************************************************
* First this function opens a file, then begins to read it.
* Every Element is stored in the AccessRecord Array in it's correct lacation
* by cycling through the information in the correct order.
* RETURNS number of records matched and stored.
***********************************************************************/
int readAndFilterAccessFile (char filename[], AccessRecord recordMatches[], long startTime, long endTime)
{
//char fileContents[100];
string fileContents;
ifstream fs;
fs.open(filename);
while (fs.fail())
{
cout << "Invalid File." << endl;
promptForFileName(filename);
fs.open(filename);
}
int recordCounter;
for (int x = 0; !fs.eof(); x++)
{
fs >> recordMatches[x].filename;
fs >> recordMatches[x].username;
fs >> fileContents;
stringstream convert (fileContents);
convert >> recordMatches[x].timestamp;
if(startTime <= recordMatches[x].timestamp && recordMatches[x].timestamp <= endTime)
{
}
else
{
x--;
}
recordCounter = x;
}
fs.close();
return recordCounter;
}
/**********************************************************************
* Displays pertainant information neatly
***********************************************************************/
void display (AccessRecord recordMatches[], int numberOfRecords)
{
cout << "The following records match your criteria:" << endl << endl;
cout << setw(15) << "Timestamp" << " ";
cout << setw(19) << "File" << " ";
cout << setw(19) << "User" << endl;
cout << "--------------- ------------------- -------------------" << endl;
for(int x = 0; x <= numberOfRecords ; x++)
{
cout << setw(15) << recordMatches[x].timestamp << " ";
cout << setw(19) << recordMatches[x].filename << " ";
cout << setw(19) << recordMatches[x].username << endl;
}
cout << "End of records" << endl;
}
/**********************************************************************
* main() Handles data and calls functions.
***********************************************************************/
int main()
{
char filename[255];
AccessRecord recordMatches[500];
long startTime = 0;
long endTime = 0;
promptForFileName(filename);
blankLine();
startTime = promptForTime("start");
endTime = promptForTime("end");
blankLine();
int recordCount =
readAndFilterAccessFile(filename, recordMatches, startTime, endTime);
display(recordMatches, recordCount);
return 0;
}
<file_sep>#include "velocity.h"
using namespace std;
/*************************************************************************
* Initializes Velocity dx_o and dy_o to 0 by default..
**************************************************************************/
Velocity :: Velocity() {
dx = 0;
dy = 0;
}
/*************************************************************************
* But if the programmer passes in initial float values, use those values
instead.
**************************************************************************/
Velocity :: Velocity(float setDxo, float setDyo) {
dx = setDxo;
dy = setDyo;
}
/*************************************************************************
* Returns current dx velocity.
**************************************************************************/
float Velocity :: getDx() {
return dx;
}
/*************************************************************************
* returns current dy velocity.
**************************************************************************/
float Velocity :: getDy() {
return dy;
}
/*************************************************************************
* sets a new dx velocity.
**************************************************************************/
void Velocity :: setDx(float setDx) {
dx = setDx;
}
/*************************************************************************
* sets a new dx velocity.
**************************************************************************/
void Velocity :: setDy(float setDy) {
dy = setDy;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Template
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
using namespace std;
class example
{
private:
int num;
bool truthy;
char letter;
public:
void populateDefaultValues();
int numberfunction();
void another();
void thing();
void five();
void six();
};
void example::another()
{
cout << "This is my 'another' funciton." << endl;
}
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
example foo;
foo.another();
return 0;
}
<file_sep>/***************************************************************
* File: product.cpp
* Author: <NAME>
* Purpose: Contains the method implementations for the Product class.
***************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include "product.h"
using namespace std;
/***************************************************************
* Empty Parameter Constructor sets default variable values
***************************************************************/
Product :: Product ()
{
name = "none";
description = "";
weight = 0;
basePrice = 0;
}
/***************************************************************
* Full Parameter Constructor sets variables to user-specified values
***************************************************************/
Product :: Product (string setName, string setDescription, double setPrice, double setWeight)
{
name = setName;
description = setDescription;
basePrice = setPrice;
weight = setWeight;
}
/***************************************************************
* This calculates sales tax for an item based on it's basePrice
* and a 6% tax.
***************************************************************/
double Product :: getSalesTax ()
{
double salesTax = basePrice * 0.06;
return salesTax;
}
/***************************************************************
* This calculates shipping cost based on item weight.
* Under 5lbs = 2$, more than that = $2 - ((weight - 5lbs) * $0.10)
***************************************************************/
double Product :: getShippingCost ()
{
double shippingCost;
if (weight > 5)
{
shippingCost = 2 + ((weight - 5) * 0.1);
}
else if (weight == 0)
{
shippingCost = 0;
}
else
{
shippingCost = 2;
}
return shippingCost;
}
/***************************************************************
* This calcuates the cost of the item after basePrice, tax, and
* shipping have been added together.
***************************************************************/
double Product :: getTotalPrice ()
{
return basePrice + getSalesTax() + getShippingCost();
}
/***************************************************************
* This displays the described product in a way optimised for
* advertising.
***************************************************************/
void Product :: displayAdvertising ()
{
cout << fixed << showpoint << setprecision(2);
cout << name << " - " << '$' << basePrice << endl
<< '(' << description << ')' << endl;
}
/***************************************************************
* This displays the described product in a way optimised for
* keeping inventory.
***************************************************************/
void Product :: displayInventory ()
{
cout << fixed << showpoint;
cout << '$' << setprecision(2) << basePrice << " - "
<< name << " - " << setprecision(1) << weight << " lbs" << endl;
}
/***************************************************************
* This displays the described product in a way optimised for
* showing the customer the price break down for the total price.
***************************************************************/
void Product :: displayReceipt ()
{
cout << fixed << showpoint << setprecision(2);
cout << name << endl;
cout << " Price: " << "$" << setw(8) << basePrice << endl;
cout << " Sales tax: " << "$" << setw(8) << getSalesTax() << endl;
cout << " Shipping cost: " << "$" << setw(8) << getShippingCost() << endl;
cout << " Total: " << "$" << setw(8) << getTotalPrice() << endl;
}
/***************************************************************
* method to edit class variable of
***************************************************************/
void Product :: setName(string setName)
{
name = setName;
}
/***************************************************************
* method to edit class variable of description
***************************************************************/
void Product :: setDescription(string setDescription)
{
description = setDescription;
}
/***************************************************************
* method to edit class variable of basePrice
***************************************************************/
void Product :: setBasePrice(double setPrice)
{
basePrice = setPrice;
}
/***************************************************************
* method to edit class variable of weight
***************************************************************/
void Product :: setWeight(double setWeight)
{
weight = setWeight;
}
/***************************************************************
* method gives a the user a copy of the variable name
***************************************************************/
string Product :: getName()
{
return name;
}
/***************************************************************
* method gives a the user a copy of the variable description
***************************************************************/
string Product :: getDescription()
{
return description;
}
/***************************************************************
* method gives a the user a copy of the variable basePrice
***************************************************************/
double Product :: getBasePrice()
{
return basePrice;
}
/***************************************************************
* method gives a the user a copy of the variable weight
***************************************************************/
double Product :: getWeight()
{
return weight;
}<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
#include <fstream>
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
//Declare Normal Variable
int x = 33;
//Declare a Pointer
int * p;
//Stores the address of the value of variable x in p.
p = &x;
//print out variable value
cout << "x = " << x << endl;
//print out pointed to location
cout << "p = " << p << endl;
//prints out the value of the pointed to location.
cout << "*p = x = " << *p << endl;
//this below is the same value as p.
cout << "&x = p = " << &x << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 13 , Fahrenheit to Celsius
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* This program takes a user input to convert fahrenheit to celsius.
* I think that writing this header will take the longest.
* Everything takes place in main().
* Estimated: 0.1 hrs
* Actual: 0.1 hrs
* The most difficult part was learning how to correctly spell fahrenheit and celsius.
************************************************************************/
#include <iostream>
#include <iomanip> //setprecision(x);
using namespace std;
/**********************************************************************
* First prompt the user for fahrenheit. Print Fahrenheit in celsius by
* running fahrenheit variable through equation. Use a double to maintain decimal.
***********************************************************************/
int main()
{
double fahrenheit;
cout << "Please enter Fahrenheit degrees: ";
cin >> fahrenheit;
cout << fixed << setprecision(0) << "Celsius: " << (5.0/9.0)*(fahrenheit-32) << "\n";
return 0;
}
<file_sep>// File: order.cpp
#include <iostream>
#include <iomanip>
#include <string>
#include "order.h"
#include "product.h"
#include "customer.h"
using namespace std;
// Put your the method bodies for your order class here
/***************************************************************
* Empty Parameter Constructor sets default variable values
***************************************************************/
Order :: Order () {
product = Product();
quantity = 0;
customer = Customer();
}
/***************************************************************
* Full Parameter Constructor sets private variables to user-specified
* values
***************************************************************/
Order:: Order (Product setProduct, int setQuantity, Customer setCustomer)
{
product = setProduct;
quantity = setQuantity;
customer = setCustomer;
}
/***************************************************************
* method to edit class variable of product
***************************************************************/
void Order :: setProduct (Product setProduct)
{
product = setProduct;
}
/***************************************************************
* method to edit class variable of quantity
***************************************************************/
void Order :: setQuantity (int setQuantity)
{
quantity = setQuantity;
}
/***************************************************************
* method to edit class variable of customer
***************************************************************/
void Order :: setCustomer (Customer setCustomer)
{
customer = setCustomer;
}
/***************************************************************
* method gives a the user a copy of the variable product and all
* associated methods.
***************************************************************/
Product Order :: getProduct ()
{
return product;
}
/***************************************************************
* method gives a the user a copy of the variable quantity
***************************************************************/
int Order :: getQuantity ()
{
return quantity;
}
/***************************************************************
* method gives a the user a copy of the variable customer and
* access to all associated methods.
***************************************************************/
Customer Order :: getCustomer ()
{
return customer;
}
/***************************************************************
* method gives a the user a copy of the customer's zip
***************************************************************/
string Order :: getShippingZip ()
{
return customer.getAddress().getZip();
}
/***************************************************************
* method gives a the user the total price of their order, taking
* into account how many they are ordering.
***************************************************************/
double Order :: getTotalPrice ()
{
return product.getTotalPrice() * quantity;
}
/***************************************************************
* Displays the order information optimized for a shipping label.
***************************************************************/
void Order :: displayShippingLabel ()
{
customer.display();
}
/***************************************************************
* Displays the order information in a concise way that would be
* important to the customer and the store-owner both.
***************************************************************/
void Order :: displayInformation ()
{
cout << fixed << showpoint << setprecision(2);
cout << customer.getName() << endl
<< product.getName() << endl
<< "Total Price: $" << getTotalPrice() << endl;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
double costOfQuantity(double price, int quantity)
{
return price * quantity;
}
void totalCostOfItems(double costs[])
{
double total = 0;
for (int x = 0; x < 5; x++)
{
total = total + costs[x];
}
cout << "Total Cost with no discount $" << total << endl;
if (total >= 100)
{
total = total*0.8;
}
cout << "Total cost with discount $" << total << endl;
}
int main()
{
double price;
int quantity;
double cost;
do
{
cout << "Enter the price: $";
cin >> price;
cout << "Enter a quantity: ";
cin >> quantity;
cost = costOfQuantity(price, quantity);
cout << "$" << cost << endl;
}
while(cost != 0);
double costs[4];
cout << "Enter the costs of five items:" << endl;
for (int x = 0; x < 5; x++)
{
cin >> costs[x];
}
totalCostOfItems(costs);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Assignment
* Brother Cook, CS165
* Author:
* <NAME>
************************************************************************/
#include <iostream>
using namespace std;
class ForkLift{
public: void raiseLift(int &fuel, bool &isRaised)
{
int fuelRequired = 5;
if(isRaised){
cout << "The fork lift is already raised." << endl;
isRaised = isRaised;
}
else if (fuel > fuelRequired)
{
cout << "Raising the Lift." << endl;
fuel = fuel - fuelRequired;
isRaised = true;
}
else
{
cout << "Not enough fuel to raise the lift." << endl;
isRaised = false;
}
};
public: void lowerLift(int &fuel, bool &isRaised)
{
int fuelRequired = 5;
if(!isRaised){
cout << "The fork lift is already lowered." << endl;
isRaised = isRaised;
}
else if (fuel > fuelRequired)
{
cout << "Lowering the Lift." << endl;
fuel = fuel - fuelRequired;
isRaised = false;
}
else
{
cout << "Not enough fuel to lower the lift." << endl;
isRaised = true;
}
};
public: void displayStatus(int fuel, bool isRaised)
{
string forkStatus;
if (isRaised == true)
{
forkStatus = "Raised";
}
else
{
forkStatus = "Lowered";
}
cout << "Fuel Remaining: " << fuel << endl;
cout << "Fork lift Status: " << forkStatus << endl;
};
public: int fuel;
public: bool isRaised;
};
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
string userCommand;
ForkLift firstLift;
firstLift.fuel = 22;
firstLift.isRaised = false;
while (true)
{
cout << endl << "Would you like to raise [r] or lower [l] the fork lift?: " ;
cin >> userCommand;
if (userCommand == "r")
{
firstLift.raiseLift(firstLift.fuel, firstLift.isRaised);
firstLift.displayStatus(firstLift.fuel, firstLift.isRaised);
}
else if(userCommand == "l")
{
firstLift.lowerLift(firstLift.fuel, firstLift.isRaised);
firstLift.displayStatus(firstLift.fuel, firstLift.isRaised);
}
else
{
cout << endl << "You entered an invalid command: " << userCommand << "." << endl << "Enter a different command." << endl;
}
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 21, Stub Functions for Car Usage
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program provides the foundation and the map for the working program.
* While this code does nothing right now, all the programmer would need to
* do to make it work is program the individual functions because all of the
* functions and variables get passed to the correct place already.
*
* Estimated: 0.5 hrs
* Actual: 0.5 hrs
* Plugging base fuctions with no code was new to me, I wasn't sure if
* I was doing it right becasue the code did nothing, but then I realized
* that that was okay, becasue this practice is meant to just prepare the
* document to be programed, more quickly, cleanly, and efficiently.
************************************************************************/
#include <iostream> //cout, cin, fixed
//#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
///////////////////////////////////////
double promptTires()
{
return 0;
}
double promptRepairs()
{
return 0;
}
double promptGas()
{
return 0;
}
float promptMileage()
{
return 0;
}
///////////////////////////////////////
double getUsageCost()
{
promptTires();
promptRepairs();
promptGas();
promptMileage();
return 0;
}
///////////////////////////////////////
double promptDevalue()
{
return 0;
}
double promptInsurance()
{
return 0;
}
double promptParking()
{
return 0;
}
///////////////////////////////////////
double getPeriodicCost()
{
promptDevalue();
promptInsurance();
promptParking();
return 0;
}
///////////////////////////////////////
void display(double usage, double periodic)
{
cout << "Success\n";
}
///////////////////////////////////////
int main()
{
display(getUsageCost(), getPeriodicCost());
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 04, Products
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* This program takes declares a Product object, asks the user to fill in its
* information, then displays it using the specified profile, as implemented in
* product.cpp.
*
* Estimated: 3.0 hrs
* Actual: 3.0 hrs
* The most difficult part was figuring how to link the definitions to
* the method implemenatation and tying it back into main.
************************************************************************/
#include <iostream>
#include "product.h"
using namespace std;
/**********************************************************************
* main declares a Product object and displays the profile of the declared
* object based on the requested output method (by typing 1, 2, or 3).
***********************************************************************/
int main()
{
int input;
Product product;
cout << endl;
cout << "Choose from the following options:" << endl
<< "1 - Advertising profile" << endl
<< "2 - Inventory line item" << endl
<< "3 - Receipt" << endl;
cout << endl << "Enter the option that you would like displayed: ";
cin >> input;
cout << endl;
if (input == 1)
{
product.displayAdvertise();
}
else if (input == 2)
{
product.displayInventory();
}
else if (input == 3)
{
product.displayReceipt();
}
else
{
cout << "Invalid input. Program Terminating..." << endl;
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 04a, Classes and Book Class
* Bro<NAME>, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
class Book
{
private:
string title;
string author;
public:
void prompt()
{
cout << "Title: ";
getline(cin, title);
cout << "Author: ";
getline(cin, author);
}
void display()
{
cout << "\"" << title << "\" by " << author << endl;
}
};
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
Book myBook;
myBook.prompt();
myBook.display();
return 0;
}
<file_sep>#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
#include <fstream>
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
void getSentence(char sentence[])
{
cin.getline(sentence, 255);
}
int changeCase(char sentence[])
{
int uppercaseNum = 0;
for (int x = 0; sentence[x]; x++)
{
if (isupper(sentence[x]))
{
sentence[x] = tolower(sentence[x]);
uppercaseNum++;
}
else
{
sentence[x] = toupper(sentence[x]);
}
}
return uppercaseNum;
}
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
char sentence[255];
getSentence(sentence);
cout << "You printed " << changeCase(sentence) << " upper case letters" << endl;
cout << sentence;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Template
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
using namespace std;
int getTemperatures()
{
int currentTemp = 0;
cout << "What is the temperature outside?: ";
cin >> currentTemp;
return currentTemp;
}
int main()
{
int currentTemp = 0;
int numberOfValues = 0;
int accumulationOfTemps = 0;
do
{
currentTemp = getTemperatures();
if (currentTemp < 200)
{
accumulationOfTemps += currentTemp;
numberOfValues++;
}
} while(currentTemp < 200);
if (numberOfValues == 0)
{
cout << "Error. You must enter at least one valid temperature." << endl << "Exiting Program." << endl;
return 0;
}
float averageTemperature = accumulationOfTemps / numberOfValues;
cout << "The average temperature outside is " << averageTemperature << "." << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 11, Static Budget Displayer
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program prints a static table of Items and Projected costs to the console. It has a tab a the beginning of each line. The numeric values are aligned-right and always have 2 decimal points.
*
* Estimated: 0.5 hrs
* Actual: 1.0 hrs
* Playing with the functions, setpercision() and setw() to learn how they behave was the most time consuming. The most challenging to figure out was how to keep the decimal point in the numeric value and keeping it to 2 decimal points- I had to research that. I tried to organize it in such a way where I could easily swap the numeric values out for variables in the next assignment.
************************************************************************/
#include <iostream> //cout, fixed
using namespace std;
#include <iomanip> //setw(), setprecision()
/**********************************************************************
* This functions outputs a static table of items and expected expenses associated with each item.
***********************************************************************/
int main()
{
//Output table of items and projected costs
//There is a total of 25 characters per line, 13 under the first column, 2 spaces separating the two columns, and 10 in the second column. Additionally, there is a new-line char at the end of each line, and a tab-char at the beginning of each new line.
cout << fixed << showpoint << setprecision(2) << "\tItem Projected" << "\n\t" << "============= ==========" << "\n\t" << "Income $"<< setw(9) << 1000.00 << "\n\t" << "Taxes $" << setw(9) << 100.00 << "\n\t" <<"Tithing $" << setw(9) << 100.00 << "\n\t" << "Living $" << setw(9) << 650.00 << "\n\t" << "Other $" << setw(9) << 90.00 << "\n\t" << "============= ==========" << "\n\t" << "Delta $" << setw(9) << 60.00 << "\n";
return 0;
}
<file_sep>/****************
* smartphone.h
****************/
#pragma once
#ifndef SMARTPHONE_H
#define SMARTPHONE_H
#include <string>
#include "phone.h"
using namespace std;
// TODO: Put your SmartPhone definition here
class SmartPhone : Phone
{
private:
string email;
public:
SmartPhone();
void prompt();
void display();
};
#endif
<file_sep>/***********************************************************************
* Program:
* Assignment 01, Genetic Genealogy
* <NAME>, CS165
* Author:
* <NAME>
* Summary:
* This program compares similarity in genetic code by taking an initial
* char[] of values and comparing it against a user-specified number of
* other char[] and returning the percent match per array.
*
* Estimated: 1.0 hrs
* Actual: 1.5 hrs
* The most difficult part was remembering how to pass multidimensional
* arrays into functions. Turns out I need to re-specify how long the
* second element is to cause it to not throw an error. Using the embedded
* for() loop in percent match was a fun feature to add and see work.
************************************************************************/
#include <iostream>
using namespace std;
/***********************************************************************
* Prompts the user for their DNA sequence and updates the passed in array
***********************************************************************/
void getYourDNA(char yourDNA[])
{
cout << "Enter your DNA sequence: ";
cin >> yourDNA;
}
/***********************************************************************
* prompts the user for the number of relatives that the program will expect
* to get names and DNA patterns for.
***********************************************************************/
int getNumberOfRelatives()
{
int number;
cout << "Enter the number of potential relatives: ";
cin >> number;
return number;
}
/***********************************************************************
* Prompt user for names for each person who's DNA
* sample will be evaluated for
***********************************************************************/
void getRelativeNames(int numOfRel, char otherName[][10])
{
cout << endl;
for (int x = 0; x < numOfRel; x++)
{
cout << "Please enter the name of relative #" << x + 1 << ": ";
cin >> otherName[x];
}
}
/***********************************************************************
* Prompts user for DNA sequence associated with the passed
* in and displayed name.
***********************************************************************/
void getDNASequence(int numOfRel, char otherName[][10], char otherDNA[][10])
{
cout << endl;
for (int x = 0; x < numOfRel; x++)
{
cout << "Please enter the DNA sequence for " << otherName[x] << ": ";
cin >> otherDNA[x];
}
}
/***********************************************************************
* Displays who's DNA is being checked against yourDNA, and compares
* each corresponding element in both arrays for equality. If it is equal,
* add 10% to the percent match counter until all 10 values have been
* compared.
***********************************************************************/
void percentMatch(int numOfRel, char yourDNA[10],
char otherName[][10], char otherDNA[][10])
{
cout << endl;
int percentMatch = 0;
for (int x = 0; x < numOfRel; x++)
{
for (int y = 0; y < 10; y++)
{
if (yourDNA[y] == otherDNA[x][y])
{
percentMatch += 10;
}
}
cout << "Percent match for " << otherName[x] << ": "
<< percentMatch << '%' << endl;
percentMatch = 0;
}
}
/***********************************************************************
* Main declares 3 arrays of char and one int, and uses external functions
* to populate the arrays with proper data.
***********************************************************************/
int main()
{
char yourDNA[10];
getYourDNA(yourDNA);
int numberOfRelatives = getNumberOfRelatives();
char otherName[numberOfRelatives][10];
getRelativeNames(numberOfRelatives, otherName);
char otherDNA[numberOfRelatives][10];
getDNASequence(numberOfRelatives, otherName, otherDNA);
percentMatch(numberOfRelatives, yourDNA, otherName, otherDNA);
return 0;
}
<file_sep>###############################################################
# Program:
# Assignment 04, Product inventory
# Brother Cook, CS165
# Author:
# <NAME>
# Summary:
# Allow a user to declare a product and view details about
# it in different structures.
###############################################################
# We will learn fancier compilation steps later, but this is
# good enough for now...
a.out : product.h product.cpp assign04.cpp
g++ product.cpp assign04.cpp
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream>
//#include <iomanip>
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
void learning()
{
cout << "I am learning!";
}
int favnum()
{
int unum;
cout << "What is your favorite number?";
cin >> unum;
return unum;
}
void printunum(int in)
{
cout << "My favorite number is " << in << ".";
}
void newline()
{
cout << "\n";
}
int main()
{
int doublenum;
learning();
newline();
doublenum = favnum()*2;
printunum(doublenum);
newline();
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 09a, Virtual Functions
* Brother {Burton, Falin, Ercanbrack}, CS165
* Author:
* your name
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
// For this assignment, for simplicity, you may put all of your classes
// in this file.
// TODO: Define your classes here
/**********************************************************************
* Function: attachDoors
* Purpose: This function can accept any type of Car object. It will
* call the appropriate functions to display the name and the doors info.
***********************************************************************/
// TODO: Include your attachDoors function here
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
// You should not change main
Civic civic;
Odyssey odyssey;
Ferrari ferrari;
attachDoors(civic);
attachDoors(odyssey);
attachDoors(ferrari);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 04b, Classes and Book Class
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <iomanip>
#include "date.h"
using namespace std;
void Date::set(int setMonth, int setDay, int setYear)
{
month = setMonth;
day = setDay;
year = setYear;
}
void Date::displayAmerican()
{
cout << setfill('0');
cout << setw(2) << month << '/'
<< setw(2) << day << '/'
<< setw(4) << year << endl;
}
void Date::displayEuropean()
{
cout << setfill('0');
cout << setw(2) << day << '/'
<< setw(2) << month << '/'
<< setw(4) << year << endl;}
void Date::displayISO()
{
cout << setfill('0');
cout << setw(4) << year << '-'
<< setw(2) << month << '-'
<< setw(2) << day << endl;}<file_sep>#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
/**********************************************************************
* prompts user for a target month, returns that value. It will keep asking
* until the number they submit is between or equal to 1-12
***********************************************************************/
int getTargetMonth()
{
int month;
return month;
}
/**********************************************************************
* prompts user for target year, and returns that value. It will keep asking
* until the number they submit is above or equal to 1753.
***********************************************************************/
int getTargetYear()
{
int year;
return year;
}
/**********************************************************************
* determines whether a given year is a leap year.
***********************************************************************/
bool isLeapYear(int year)
{
return true;
}
/**********************************************************************
* returns a numeric value that represents a day of the week, from 0-6
* 0 being monday, 6 being sunday.
***********************************************************************/
int daysInMonthFinder(int currentMonth, int currentYear)
{
int daysInTargetMonth = 0;
return daysInTargetMonth;
}
/**********************************************************************
* Counts days till our target month and year, returns that number.
***********************************************************************/
int daysTillTargetDate(int targetMonth, int targetYear)
{
int daysCounter = 0;
int currentYear = 1753;
int currentMonth = 1;
daysCounter += daysInMonthFinder(currentMonth, currentYear);
return daysCounter;
}
/**********************************************************************
* returns a numeric value that represents a day of the week, from 0-6
* 0 being monday, 6 being sunday.
***********************************************************************/
int getWeekOffset(int daysTillDate)
{
int startingDay = daysTillDate % 7;
return startingDay;
}
/**********************************************************************
* getMonthName() takes a monthNumber as an argument, and updates the
* monthName array from main with corresponding month name.
***********************************************************************/
string getMonthName(int monthNumber, string monthName)
{
string monthName;
return monthName;
}
/**********************************************************************
* in charge of calculating how to display a calendar table based on given
* information.
***********************************************************************/
void display(int firstDayOfMonth, int targetMonth,
int targetYear, string monthName)
{
int newLineCounter = firstDayOfMonth + 1;
int daysInMonth = daysInMonthFinder (targetMonth, targetYear);
cout << '\n';
cout << monthName << ", " << targetYear << endl;
cout << " Su Mo Tu We Th Fr Sa" << endl;
//cout spaces equal to the number of days we are into the week when the
//month starts
for (int x = 0; x <= firstDayOfMonth && firstDayOfMonth != 6; x++)
{
cout << setw(4) << "";
}
if (newLineCounter == 7)
newLineCounter = 0;
//prints out days of the month, and determines when a new line is needed.
for (int x = 1; x <= daysInMonth; x++)
{
cout << setw (4) << x;
newLineCounter++;
if (newLineCounter == 7 || x == daysInMonth)
{
cout << endl;
newLineCounter = 0;
}
}
return;
}
/**********************************************************************
* Main stores the information given by targetMonth and targetYear
* and passes them to other functions for find how many days until a certain
* month, and then finds out what day of the week the firstDayOfMonth is on
* ie. Mon, Tues, Wed... and then sends that info to the display to print it.
***********************************************************************/
int main()
{
int targetMonth = getTargetMonth();
int targetYear = getTargetYear();
int daysTillDate = daysTillTargetDate(targetMonth, targetYear);
int firstDayOfMonth = firstDayOfMonthCalculator(daysTillDate);
string monthName = getMonthName(targetMonth, monthName);
display(firstDayOfMonth, targetMonth, targetYear, monthName);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Project 02, Monthly Budget
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program gathers and displays budget information given from the user.
*
* Estimated: 0.5 hrs
* Actual: 1.5 hrs
* Understanding StyleChecker's requirements took me a while to understand.
* and making sure everything lined up as expected took some time too.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* main() is in charge of the whole program. It gathers and stores user
* information, then displays the given information on a chart.
***********************************************************************/
int main()
{
//bud budget, act actual _ Variables
double budIncome = 0;
double actIncome = 0;
double budTaxes = 0;
double actTaxes = 0;
double budTithing = 0;
double actTithing = 0;
double budLiving = 0;
double actLiving = 0;
double budOther = 0;
double actOther = 0;
double budDifference = 0;
double actDifference = 0;
cout << "This program keeps track of your monthly budget" << endl;
cout << "Please enter the following:" << endl;
cout << " " << "Your monthly income: ";
cin >> actIncome;
budIncome = actIncome;
cout << " " << "Your budgeted living expenses: ";
cin >> budLiving;
cout << " " << "Your actual living expenses: ";
cin >> actLiving;
cout << " " << "Your actual taxes withheld: ";
cin >> actTaxes;
cout << " " << "Your actual tithe offerings: ";
cin >> actTithing;
cout << " " << "Your actual other expenses: ";
cin >> actOther;
cout << endl;
cout << "The following is a report on your monthly expenses" << endl;
cout << showpoint << fixed << setprecision(2);
cout << "\tItem " << " " << " Budget "
<< " " << " Actual" << endl;
cout << "\t===============" << " " << "==============="
<< " " << "===============" << endl;
cout << "\tIncome " << " " << "$" << setw(11) << budIncome
<< " " << " " << "$" << setw(11) << actIncome << endl;
cout << "\tTaxes " << " " << "$" << setw(11) << budTaxes
<< " " << " " << "$" << setw(11) << actTaxes << endl;
cout << "\tTithing " << " " << "$" << setw(11) << budTithing
<< " " << " " << "$" << setw(11) << actTithing << endl;
cout << "\tLiving " << " " << "$" << setw(11) << budLiving
<< " " << " " << "$" << setw(11) << actLiving << endl;
cout << "\tOther " << " " << "$" << setw(11) << budOther
<< " " << " " << "$" << setw(11) << actOther << endl;
cout << "\t===============" << " " << "==============="
<< " " << "===============" << endl;
cout << "\tDifference " << " " << "$" << setw(11) << budDifference
<< " " << " " << "$" << setw(11) << actDifference << endl;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Assignment
* Brother Cook, CS165
* Author:
* <NAME>
************************************************************************/
#include <iostream>
using namespace std;
class Airplane
{
private:
int currentAltitude;
int cruiseAltitude;
public:
/**********************************************************************
* Set non-default constructor, set initial values.
***********************************************************************/
Airplane(int cruizAltitude)
{
cruiseAltitude = cruizAltitude;
currentAltitude = 0;
}
/**********************************************************************
* notAtCruiseAltitude() increases the plane's current altitude by 100ft
* until the plane's altitude is greater than or equal to the specified
* crusing altitude. It returns true if it is not at cruising altitude,
* and returns false once it's at or above cruzing altitude.
***********************************************************************/
bool notAtCruiseAltitude()
{
if (currentAltitude < cruiseAltitude)
{
cout << "Plane now at " << currentAltitude << "ft." << endl;
currentAltitude += 100;
return true;
} else {
cout << "Plane now at cruising altitude: " << cruiseAltitude << "ft." << endl;
return false;
}
}
};
/**********************************************************************
* main() delcares an airplane object, then elevates its altitude
* until it reaches the specified cruising altitude, defined in the
* non-default parameter.
**********************************************************************/
int main()
{
Airplane airplane(1000);
while(airplane.notAtCruiseAltitude());
return 0;
}
<file_sep>#pragma once
#include "point.h"
#include "velocity.h"
using namespace std;
class Lander
{
private:
Point point;
Velocity velocity;
int fuel;
bool shipAlive;
bool shipLanded;
// int lives;
public:
static int lives;
Lander();
Point getPoint() const;
Velocity getVelocity() const;
bool isAlive();
bool isLanded();
int getFuel();
bool canThrust();
void setLanded(bool);
void setAlive(bool);
void setFuel(int);
void applyGravity(float);
void applyThrustLeft();
void applyThrustRight();
void applyThrustBottom();
void advance();
void draw();
};
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, w4-test
* <NAME>, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
using namespace std;
struct Telephone
{
long number;
bool isRinging;
};
void answerCall(Telephone & phone)
{
phone.isRinging = false;
}
void displayPhoneStatus(Telephone phone)
{
cout << "Phone Number: " << phone.number << endl;
if (phone.isRinging)
{
cout << "Phone Status: " << "Ringing" << endl;
}
else
{
cout << "Phone Status: " << "Not Ringing" << endl;
}
}
int main()
{
Telephone myPhone;
myPhone.number = 8014224636;
myPhone.isRinging = true;
if (myPhone.isRinging)
{
answerCall(myPhone);
}
displayPhoneStatus(myPhone);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream> //cout, cin, fixed
//#include <iomanip> //setprecision(), setw(),
using namespace std;
bool isLeap(int year)
{
if(year % 4 == 0)
{
if (year % 100 == 0)
{
if (year % 400 == 0)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
else
{
return false;
}
}
void normLeapHeader()
{
cout << "Normal\tLeap" << endl;
}
int main()
{
normLeapHeader();
for (int year = 1753; year <= 2018; year++)
{
if (isLeap(year))
{
cout << "\t" << year << endl;
}
else
{
cout << year << endl;
}
}
return 0;
}
<file_sep>/***************************************************************
* File: product.h
* Author: <NAME>
* Purpose: Contains the definition of the Product class
***************************************************************/
#ifndef PRODUCT_H
#define PRODUCT_H
#include <string>
using namespace std;
// put your class definition here
class Product
{
private:
string name;
string description;
double weight;
double basePrice;
public:
// constructors
Product();
Product(string, string, double, double);
// other methods
double getSalesTax ();
double getShippingCost ();
double getTotalPrice ();
// display methods
void displayAdvertising ();
void displayInventory ();
void displayReceipt ();
// setters
void setName(string);
void setDescription(string);
void setBasePrice(double);
void setWeight(double);
// getters
string getName();
string getDescription();
double getBasePrice();
double getWeight();
};
#endif<file_sep>/***********************************************************************
* Program:
* Checkpoint 04b, Classes and Book Class
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
#include "date.h"
using namespace std;
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
int m, d, y;
cout << "Month: ";
cin >> m;
cout << "Day: ";
cin >> d;
cout << "Year: ";
cin >> y;
cout << endl;
Date date;
date.set(m, d, y);
date.displayAmerican();
date.displayEuropean();
date.displayISO();
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 11, Static Budget Displayer
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.5 hrs
* Actual: 0.0 hrs
* Learning the Syntax
************************************************************************/
#include <iostream> //cout, fixed
using namespace std;
#include <iomanip> //setw(), setprecision()
#include <fstream> // ifstream(), fin >> ,
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
**********************************************************************/
int main()
{
ifstream fin("text.txt");
float num;
for (int x = 0; x < 10; x++)
{
fin >> num;
// cout << num << endl;
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Project 07, Calendar Project
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* This program takes two number inputs from the user, and uses them to
* determine what a calendar from year 1753 or beyond will look like.
*
* Estimated: 3.0 hrs
* Actual: 7.0 hrs
* The most difficult part was the display function. Finding all the
* number values was pretty simple, but when it came to testBed, it was
* very picky and I spent a little over an hour getting it exactly how
* it wanted it.
************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
/**********************************************************************
* prompts user for a target month, returns that value. It will keep asking
* until the number they submit is between or equal to 1-12
***********************************************************************/
int getTargetMonth()
{
int month;
cout << "Enter a month number: ";
cin >> month;
while (month < 1 || 12 < month)
{
cout << "Month must be between 1 and 12." << endl;
cout << "Enter a month number: ";
cin >> month;
}
return month;
}
/**********************************************************************
* prompts user for target year, and returns that value. It will keep asking
* until the number they submit is above or equal to 1753.
***********************************************************************/
int getTargetYear()
{
int year;
cout << "Enter year: ";
cin >> year;
while (year < 1753)
{
cout << "Year must be 1753 or later." << endl;
cout << "Enter year: ";
cin >> year;
}
return year;
}
/**********************************************************************
* determines whether a given year is a leap year.
***********************************************************************/
bool isLeapYear(int year)
{
if (year % 4 != 0 || (year % 100 == 0 && year % 400 != 0))
return false;
else
return true;
}
/**********************************************************************
* returns a numeric value that represents a day of the week, from 0-6
* 0 being monday, 6 being sunday.
***********************************************************************/
int daysInMonthFinder(int currentMonth, int currentYear)
{
int daysInTargetMonth = 0;
if (currentMonth == 1 || currentMonth == 3 || currentMonth == 5
|| currentMonth == 7 || currentMonth == 8 || currentMonth == 10
|| currentMonth == 12)
{
daysInTargetMonth = 31;
}
else if ( currentMonth == 4 || currentMonth == 6
|| currentMonth == 9 || currentMonth == 11)
{
daysInTargetMonth = 30;
}
else if (currentMonth == 2)
{
if (isLeapYear(currentYear))
daysInTargetMonth = 29;
else
daysInTargetMonth = 28;
}
return daysInTargetMonth;
}
/**********************************************************************
* Counts days till our target month and year, returns that number.
***********************************************************************/
int daysTillTargetDate(int targetMonth, int targetYear)
{
int daysCounter = 0;
int currentYear = 1753;
int currentMonth = 1;
//Counts the days till the target year,
//but not including the target year.
while (currentYear < targetYear)
{
if (isLeapYear(currentYear))
{
daysCounter = daysCounter + 366;
}
else
daysCounter = daysCounter + 365;
currentYear++;
}
//counts the days till target month within the target year,
//and adds to day counter
while (currentMonth < targetMonth)
{
daysCounter += daysInMonthFinder(currentMonth, currentYear);
currentMonth++
}
return daysCounter;
}
/**********************************************************************
* returns a numeric value that represents a day of the week, from 0-6
* 0 being monday, 6 being sunday.
***********************************************************************/
int firstDayOfMonthCalculator(int daysTillDate)
{
int startingDay = daysTillDate % 7;
return startingDay;
}
/**********************************************************************
* getMonthName() takes a monthNumber as an argument, and updates the
* monthName array from main with corresponding month name.
***********************************************************************/
string getMonthName(int monthNumber, string monthName)
{
switch (monthNumber)
{
case 1:
monthName = "January";
break;
case 2:
monthName = "February";
break;
case 3:
monthName = "March";
break;
case 4:
monthName = "April";
break;
case 5:
monthName = "May";
break;
case 6:
monthName = "June";
break;
case 7:
monthName = "July";
break;
case 8:
monthName = "August";
break;
case 9:
monthName = "September";
break;
case 10:
monthName = "October";
break;
case 11:
monthName = "November";
break;
case 12:
monthName = "December";
break;
}
return monthName;
}
/**********************************************************************
* in charge of calculating how to display a calendar table based on given
* information.
***********************************************************************/
void display(int firstDayOfMonth, int targetMonth,
int targetYear, string monthName)
{
int newLineCounter = firstDayOfMonth + 1;
int daysInMonth = daysInMonthFinder (targetMonth, targetYear);
cout << '\n';
cout << monthName << ", " << targetYear << endl;
cout << " Su Mo Tu We Th Fr Sa" << endl;
//cout spaces equal to the number of days we are into the week when the
//month starts
for (int x = 0; x <= firstDayOfMonth && firstDayOfMonth != 6; x++)
{
cout << setw(4) << "";
}
if (newLineCounter == 7)
newLineCounter = 0;
//prints out days of the month, and determines when a new line is needed.
for (int x = 1; x <= daysInMonth; x++)
{
cout << setw (4) << x;
newLineCounter++;
if (newLineCounter == 7 || x == daysInMonth)
{
cout << endl;
newLineCounter = 0;
}
}
return;
}
/**********************************************************************
* Main stores the information given by targetMonth and targetYear
* and passes them to other functions for find how many days until a certain
* month, and then finds out what day of the week the firstDayOfMonth is on
* ie. Mon, Tues, Wed... and then sends that info to the display to print it.
***********************************************************************/
int main()
{
int targetMonth = getTargetMonth();
int targetYear = getTargetYear();
int daysTillDate = daysTillTargetDate(targetMonth, targetYear);
int firstDayOfMonth = firstDayOfMonthCalculator(daysTillDate);
string monthName = getMonthName(targetMonth, monthName);
display(firstDayOfMonth, targetMonth, targetYear, monthName);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 14, Matthew 18:21-22
* Bro<NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program will address Peter's question to the Lord in
* Matthew 18:21-22
*
* Estimated: 0.1 hrs
* Actual: 0.1 hrs
* I didn't realize that testbed wanted "till 7 times" on a second
* line, so it failed the first test. After that, it was an easy fix.
* I understand functions and return values very well.
************************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* void questionPeter() prints a verse of scripture when called.
* int responseLord() returns a value which is inserted into main().
***********************************************************************/
void questionPeter()
{
cout << "Lord, how oft shall my brother sin against me, and I forgive him?\nTill seven times?\n";
}
int responseLord()
{
return 7*70;
}
/**********************************************************************
* Main calls questionPeter() then prints responseLord().
*
***********************************************************************/
int main()
{
// ask Peter's question
questionPeter();
// the first part of the Lord's response
cout << "Jesus saith unto him, I say not unto thee, Until seven\n";
cout << "times: but, Until " << responseLord() << ".\n";
return 0;
}
<file_sep>// File: customer.cpp
#include <string>
#include <iostream>
#include "customer.h"
#include "address.h"
using namespace std;
// Put the method bodies for your customer class here
/***************************************************************
* Empty Parameter Constructor sets default variable values
***************************************************************/
Customer :: Customer()
{
name = "unspecified";
address = Address();
}
/***************************************************************
* Full Parameter Constructor sets variables to user-specified values
***************************************************************/
Customer :: Customer(string setName, Address setAddress)
{
name = setName;
address = setAddress;
}
/***************************************************************
* method to edit class variable of name
***************************************************************/
void Customer :: setName (string setName)
{
name = setName;
}
/***************************************************************
* method to edit class variable of address
***************************************************************/
void Customer :: setAddress (Address setAddress)
{
address = setAddress;
}
/***************************************************************
* method gives a the user a copy of the variable name
***************************************************************/
string Customer :: getName ()
{
return name;
}
/***************************************************************
* method gives a the user a copy of the variable address
***************************************************************/
Address Customer :: getAddress ()
{
return address;
}
/***************************************************************
* displays the customer's shipping label.
***************************************************************/
void Customer :: display ()
{
cout << name << endl
<< address.getStreet() << endl
<< address.getCity() << ", " << address.getState()
<< " " << address.getZip() << endl;
}<file_sep>###############################################################
# Program:
# Checkpoint 06a, Makefiles
# <NAME>, CS165
# Author:
# <NAME>
# Summary:
# Summaries are not necessary for checkpoint assignments.
###############################################################
# Insert your rule for a.out here:
all: robot.o point.o check06a.o
g++ robot.o point.o check06a.o
# Insert your rule for robot.o here:
robot.o: robot.cpp
g++ -c robot.cpp
# Insert your rule for point.o here:
point.o: point.cpp
g++ -c point.cpp
# Insert your rule for check06a.o here:
check06a.o: check06a.cpp
g++ -c check06a.cpp
<file_sep>/***********************************************************************
* Program:
* Assignment 31, Average Grades
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program prompts the user for 10 integers, stores them in an array,
* then processes them to find the average then displays the average. This
* version includes the ability to not include not-completed assignments into
* the average.
*
* Estimated: 0.25 hrs
* Actual: 0.2 hrs
* Figuring out how to print the ---% at the end ended up being pretty
* simple but still took the most thought in this assignement.
************************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* getGrades() prompts the user for 10 grades and saves that data to the
* array given to it from main.
***********************************************************************/
void getGrades(int grades[])
{
for (int x = 0; x < 10; x++)
{
cout << "Grade " << x+1 << ": ";
cin >> grades[x];
}
}
/**********************************************************************
* averageGrades takes a given array and evaluates the first ten items in
* the array and returns the averaged value of the ten items. If the value
* input was -1, that value is considered not complete and is not included
* in the average calculation.
***********************************************************************/
int averageGrades(int grades[])
{
int average = 0;
int averageCounter = 0;
for (int x = 0; x < 10; x++)
{
if(grades[x] != -1)
{
average = average + grades[x];
averageCounter++;
}
}
if (averageCounter != 0)
{
average = average / averageCounter;
}
else
{
average = -1;
}
return average;
}
/**********************************************************************
* main() declares an array to be filled by getGrades() and passes it.
* Then the array is then passed to averageGrades() to be evaluated and the
* returned expression is then output to the screen.
***********************************************************************/
int main()
{
int grades[10];
getGrades(grades);
int average = averageGrades(grades);
if (average != -1)
{
cout << "Average Grade: " << average << "%" << endl;
}
else
{
cout << "Average Grade: ---%" << endl;
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 00, Template
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
struct Scripture
{
string name;
int chapter;
int verse;
};
Scripture promptScripture()
{
Scripture userScripture;
cout << "Enter Scripture Book: ";
cin >> userScripture.name;
cout << "Enter Chapter Number: ";
cin >> userScripture.chapter;
cout << "Enter Verse Number: ";
cin >> userScripture.verse;
return userScripture;
}
void displayScripture(Scripture userScripture)
{
cout << userScripture.name << " " << userScripture.chapter << ":" << userScripture.verse << endl;
}
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
Scripture firstScrip;
firstScrip.name = "Alma";
firstScrip.chapter = 31;
firstScrip.verse = 5;
Scripture secondScrip = promptScripture();
displayScripture(secondScrip);
return 0;
}
<file_sep>#pragma once
#include "point.h"
#include "velocity.h"
#include "flyingObject.h"
using namespace std;
class Bullet
{
private:
public:
Bullet();
void fire(Point, float);<file_sep>###############################################################
# Program:
# Assignment 05, Order Tracking
# Brother Cook, CS165
# Author:
# <NAME>
# Summary:
# This provides a collection of classes than can be populated
# with informtion and that info can be drawn upon through the
# other classes and the main program. It is a library of tools
# that can be used and reused in many use-cases.
###############################################################
# We will learn fancier compilation steps later, but this is
# good enough for now...
a.out : product.h product.cpp address.h address.cpp customer.h customer.cpp order.h order.cpp assign05.cpp
g++ product.cpp address.cpp customer.cpp order.cpp assign05.cpp
<file_sep>#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
#include <fstream>
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
void getSentence(char sentence[])
{
cin.getline(sentence, 255);
}
int (char sentence[])
{
}
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
int main()
{
char sentence[255];
getSentence(sentence);
cout << sentence;
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 10, Hello World
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* This program's function is to print the words "Hello World" and then start the next command prompt on a new line.
*
* Estimated: 0.2 hrs
* Actual: 0.2 hrs
* The most difficult part was learning how to interact with the Linux interface, but I am feeling a lot more comfortable now.
************************************************************************/
#include <iostream>
using namespace std;
/**********************************************************************
* main() runs a single command that prints hello world on the screen in the proper format.
***********************************************************************/
int main()
{
cout <<"Hello World\n";
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Read, write, and overwrite files.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
#include <fstream> // ifstream fin("") = ifstream fin \n fin.out(""), fin >>
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
main()
{
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Checkpoint 02a, Structs
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
struct Student
{
string firstName;
string lastName;
int id;
};
void displayStudent(Student user)
{
cout << endl;
cout << "Your information:" << endl;
cout << user.id << " - " << user.firstName << " " << user.lastName << endl;
}
Student retrieveUserInfo()
{
Student user;
cout << "Please enter your first name: ";
cin >> user.firstName;
cout << "Please enter your last name: ";
cin >> user.lastName;
cout << "Please enter your id number: ";
cin >> user.id;
return user;
}
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
Student user = retrieveUserInfo();
displayStudent(user);
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 26, File Reader
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* This program reads a file specified by the user, and displays the
* average of the values in the given files. The values are only displayed
* if there are 10 values to read from. It will return an error if there are
* more or less, or if the file does not exist.
* Estimated: 0.75 hrs
* Actual: 3.0 hrs
* The most difficult part of this assignment was figuring out how to
* tell the display function whether it should run based on the results
* from the readFileReturnAverage() function. I ended up using a bool
* pass-by-reference.
************************************************************************/
#include <iostream> //cout, cin, fixed
#include <iomanip> //setprecision(), setw(),
#include <fstream>
using namespace std;
/**********************************************************************
* overwrites the passed in array with user input.
***********************************************************************/
void getFileName(char fileName[])
{
cout << "Please enter the filename: ";
cin >> fileName;
}
/**********************************************************************
* reads the passed in array, calls the file, adds the values in the file
* together, and returns the average of the files.
***********************************************************************/
float readFileReturnAverage(char fileName[], bool &shouldIDisplayTheAverage)
{
float value;
float average = 0;
int arrayLength = 10;
int counter = 0;
ifstream storeFile(fileName);
while(storeFile >> value)
{
average = average + value;
counter++;
}
if (counter != arrayLength)
{
cout << "Error reading file " << '"' << fileName << '"' << endl;
storeFile.close();
shouldIDisplayTheAverage = false;
return 0;
}
else
{
average = average / arrayLength;
storeFile.close();
shouldIDisplayTheAverage = true;
return average;
}
}
/**********************************************************************
* round() determines whether a given float should or should not be rounded up
***********************************************************************/
int round (float floatValue)
{
int intValue = floatValue;
int resultValue;
cout << floatValue;
if (floatValue - intValue < 0.5)
resultValue = intValue;
else
resultValue = intValue + 1;
return resultValue;
}
/**********************************************************************
* display() prints the given value
***********************************************************************/
void display(float average)
{
cout.precision(0);
cout << fixed << "Average Grade: " << average << '%' << endl;
}
/**********************************************************************
* main() declares an array, calls a function to add value to the array,
* then passes that array value to readFileReturnAverage() and passes
* readFileReturnAverage() value to display()
***********************************************************************/
int main()
{
bool shouldIDisplayTheAverage;
char fileName[100];
getFileName(fileName);
float average = readFileReturnAverage(fileName, shouldIDisplayTheAverage);
if (shouldIDisplayTheAverage == true)
{
display(average);
}
return 0;
}
<file_sep>class Date
{
private:
int month;
int day;
int year;
public:
void set(int, int, int);
void displayAmerican();
void displayEuropean();
void displayISO();
};
<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* Enter a brief description of your program here! Please note that if
* you do not take the time to fill out this block, YOU WILL LOSE POINTS.
* Before you begin working, estimate the time you think it will
* take you to do the assignment and include it in this header block.
* Before you submit the assignment include the actual time it took.
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream> //cout, cin, fixed
//#include <iomanip> //setprecision(), setw(),
using namespace std;
/**********************************************************************
* Add text here to describe what the function "main" does. Also don't forget
* to fill this out with meaningful text or YOU WILL LOSE POINTS.
***********************************************************************/
void getEuros(double euro[])
{
cout << "Please enter 4 dollar values in euros: " << endl;
for (int x = 0; x < 4; x++)
{
cin >> euro[x];
}
}
void convertToDollar(double dollar[])
{
for (int x = 0; x < 4; x++)
{
dollar[x] = dollar[x] * 1.24;
}
}
void display(double value[])
{
cout << "This is the dollar value in USD:" << endl;
for (int x = 0; x < 4; x++)
{
cout << value[x] << endl;
}
}
int main()
{
double value[3];
getEuros(value);
convertToDollar(value);
display(value);
return 0;
}
<file_sep># linuxlab
A repository for all linux lab related assignements.
<file_sep>/***************************************************************
* File: product.h
* Author: <NAME>
* Purpose: Contains the definition of the Product class
***************************************************************/
#ifndef PRODUCT_H
#define PRODUCT_H
#include <string>
using namespace std;
// put your class definition here
class Product
{
private:
string name;
string description;
double weight;
double basePrice;
public:
Product();
double getSalesTax ();
double getShippingCost ();
double getTotalPrice ();
void displayAdvertise ();
void displayInventory ();
void displayReceipt ();
};
#endif
<file_sep>/***********************************************************************
* Program:
* Checkpoint 03b, Error Handling
* Brother Cook, CS165
* Author:
* <NAME>
* Summary:
* Summaries are not necessary for checkpoint assignments.
* ***********************************************************************/
#include <iostream>
#include <string>
using namespace std;
int prompt () {
try
{
int input = 0;
cout << "Enter a number: ";
cin >> input;
if (cin.fail())
{
cin.clear();
cin.ignore(1024, '\n');
throw string("Invalid input.");
}
else
{
return input;
}
}
catch (string message)
{
cout << message << endl;
return prompt();
}
}
/**********************************************************************
* Function: main
* Purpose: This is the entry point and driver for the program.
***********************************************************************/
int main()
{
int num = prompt();
cout << "The number is " << num << "." << endl;
return 0;
}
<file_sep>// File: customer.h
#ifndef CUSTOMER_H
#define CUSTOMER_H
#include <string>
#include "address.h"
using namespace std;
// put your Customer class here
class Customer
{
private:
string name;
Address address;
public:
// constructors
Customer();
Customer(string, Address);
// setters
void setName(string);
void setAddress(Address);
// getters
string getName();
Address getAddress();
// display methods
void display();
};
#endif<file_sep>/***********************************************************************
* Program:
* Assignment 00, Program Name
* <NAME>, CS124
* Author:
* <NAME>
* Summary:
* A program where the user gets to guess the number that the program
* creator was thinking of when they created the program.
*
*
*
*
* Estimated: 0.0 hrs
* Actual: 0.0 hrs
* Please describe briefly what was the most difficult part.
************************************************************************/
#include <iostream>
//#include <iomanip>
using namespace std;
/**********************************************************************
*
***********************************************************************/
int main()
{
int uguess = 111;
int ccreate = 7;
bool goodguess = false;
cout << "What number was I thinking of?: ";
cin >> uguess;
while (goodguess == false) {
if (0 <= uguess && uguess <=10) {
goodguess = true;
} else {
cout << "You need to guess a number between 0-10! Try again: ";
cin >> uguess;
}
}
if (goodguess){
if (uguess == ccreate)
{
cout << "You guessed correctly! The answer was " << ccreate << ".\n";
} else {
cout << "Sorry. You guessed " << uguess << ". The correct answer was " << ccreate << ".\n";
}
}
return 0;
}
<file_sep>/***********************************************************************
* Program:
* Assignment 16, Tax Bracket
* Brother Cook, CS124
* Author:
* <NAME>
* Summary:
* This program computes the user's tax bracket based on their income.
* In main() their income is retrieved, and in computeTax() their
* bracket is calculated and returned.
*
* Estimated: 0.10 hrs
* Actual: 0.16 hrs
* This project was quite straight-forward. I learned how useful the
* return function can be in modularization.
************************************************************************/
#include <iostream>
//#include <iomanip>
using namespace std;
/**********************************************************************
* computeTax() takes a parameter when called, then compares the parameter
* through a series of if and if else statements until one returns true
* then the function closes.
***********************************************************************/
int computeTax (int income)
{
if(/*0<=income &&*/ income<=15100)
{
return 10;
}
else if (15100<income && income<=61300)
{
return 15;
}
else if (61300<income && income<=123700)
{
return 25;
}
else if (123700<income && income<=188400)
{
return 28;
}
else if (188400<income && income<=336500)
{
return 33;
}
else if (336500<income)
{
return 35;
}
}
/**********************************************************************
* main() prompts the user for their income, then uses that input as the
* parameter for the computeTax() function. The result is displayed in
* the console based on the value returned by computeTax().
***********************************************************************/
int main()
{
int userincome;
cout << "Income: ";
cin >> userincome;
cout << "Your tax bracket is " << computeTax(userincome) << "%" << endl;
return 0;
}
|
5ade7005e9e1c3f0016f84dd60daa54f86b641e6
|
[
"Markdown",
"C",
"Makefile",
"C++"
] | 78
|
C++
|
ajshiff/linuxlab
|
decc8012842b88281f6f1b889a267be017586207
|
1fc6cbc027034ec8397b25134dc3bf50ea42d1dc
|
refs/heads/master
|
<file_sep>package com.android.example.appdebug
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.lang.Double.parseDouble
import kotlin.reflect.typeOf
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val util = Util()
val fbButton = findViewById(R.id.fbButton) as Button
val factButton = findViewById(R.id.factButton) as Button
val avgButton = findViewById(R.id.avgButton) as Button
val factEditText = findViewById(R.id.factEditText) as EditText
val sizeEditText = findViewById(R.id.sizeEditText) as EditText
// The facebook page URL
val url = "fb://page/218641444910278"
// Onclick of the first button
fbButton.setOnClickListener({
util.openPage(this,url)
})
// Onclick of the second button
factButton.setOnClickListener({
var numeric = true
try {
val j= parseDouble (factEditText.text.toString())
} catch (e: NumberFormatException) {
numeric = false
}
if(numeric){
if(factEditText.text.toString().toInt()<=0){
Toast.makeText(this,"Veuillez introduire un nombre supérieur à Zéro ",Toast.LENGTH_SHORT).show()
}else{
val i = util.factorial(factEditText.text.toString().toInt())
Toast.makeText(this,"Le factoriel est: $i",Toast.LENGTH_SHORT).show()
}
//Toast.makeText(this,"ceci est un nb",Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this,"Erreur , Veuillez introduire un nombre",Toast.LENGTH_SHORT).show()
}
})
// Onclick of the third button
avgButton.setOnClickListener(
{
val nb=sizeEditText.text.toString()
val bol=nb.isNullOrEmpty()
if( bol){
Toast.makeText(this,"Veuillez introduire un nombre",Toast.LENGTH_SHORT).show()
}else{
val list = util.randomList(sizeEditText.text.toString().toInt())
var sum = 0
for (item in list) {
sum+= item
}
Toast.makeText(this,"La moyenne de la liste est: ${sum/list.size}",Toast.LENGTH_SHORT).show()
}
})
}
}
<file_sep>package com.android.example.appdebug
import android.content.Context
import android.content.Intent
import android.net.Uri
class Util {
/**
* This function opens an URL
*/
fun openPage(ctx: Context, url: String) {
val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
ctx.startActivity(intent)
}
/**
* This function computes the factorial of a given number
*/
fun factorial(n: Int): Long {
return if (n == 1) n.toLong() else n*factorial(n-1)
}
/**
* This function generates a random list of Integer
*/
fun randomList(size: Int): List<Int> {
val list = mutableListOf<Int>()
for (i in 0..size - 1) {
list.add(random(10000))
}
return list
}
/**
* This function returns a random number less than n
*/
fun random(n: Int) = (Math.random() * n).toInt()
}
|
13b2657c4420b36bff17afd1a4910428d9cf1e5a
|
[
"Kotlin"
] | 2
|
Kotlin
|
mayalb/AndroidApps_TP2
|
2c5e993bf45ed81ebc06b72bb944970f5e42c467
|
49b01b24e13232599c8a399c41376750571d2bc6
|
refs/heads/master
|
<file_sep>from setuptools import find_packages, setup
setup(
name='src',
packages=find_packages(),
version='0.1.0',
description='This is a project about wine.',
author='<NAME>',
license='',
)
|
bce15ca0189cbcc03406b126bd9df1185c3360ab
|
[
"Python"
] | 1
|
Python
|
ktmbrown/wine_reviews
|
3ed0a189c6b5d619c02d4296cdf0770f9181675b
|
0178f0866df0fa6e5b255e57db133e066edfa4f1
|
refs/heads/master
|
<file_sep># sandbox-github-actions
<file_sep>import os
str = os.environ['INPUT_COUNTED_STRING']
print(len(str))
|
354b5ebf8f3e1fed0887ef1db38dd3520f6850a9
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
fchiba/sandbox-github-actions
|
32d1057c1160aabc2d39ee3b4c60e8a964341c0e
|
20348949be9d22e439332fbff80cf74f4922167d
|
refs/heads/master
|
<file_sep>import Base from "./Base";
class CodingLanguages extends Base {
private uuidCode: string;
private readonly dataKey: string = "data_coding_languages";
constructor() {
super();
this.uuidCode =
process.env.REACT_APP_WAKATIME_CHARTS_UUID_CODING_LANGUAGES || "";
}
protected getUuidCode() {
return this.uuidCode;
}
protected getDataKey() {
return this.dataKey;
}
}
export default CodingLanguages;
<file_sep># Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
#### Types of changes
- **Added** for new features.
- **Changed** for changes in existing functionality.
- **Deprecated** for soon-to-be removed features.
- **Removed** for now removed features.
- **Fixed** for any bug fixes.
- **Security** in case of vulnerabilities.
## [Unreleased](https://github.com/renatosoares/renatosoares.github.io/commits/Unreleased) - 2021-00-00
## [2.1.0](https://github.com/renatosoares/renatosoares.github.io/commits/2.1.0) - 2021-08-25
### Added
- Home page embedding of coding activity graphs.
## [2.0.0](https://github.com/renatosoares/renatosoares.github.io/commits/2.0.0) - 2021-08-08
### Changed
- Changes architecture to React.
## [1.1.0](https://github.com/renatosoares/renatosoares.github.io/commits/1.0.1) - 2020-08-16
### Added
- bootstrap toolkit
- social links
### Fixed
- mobile home
## [1.0.0](https://github.com/renatosoares/renatosoares.github.io/commits/1.0.0) - 2020-08-08
### Added
- basic information
### Changed
- new structure
<file_sep>#!/usr/bin/env sh
set -e
npm run build
cd build
echo renatosoares.dev >CNAME
git init
git add -A
git commit -m 'deploy'
git push -f <EMAIL>:renatosoares/renatosoares.github.io.git master:gh-pages
cd -
<file_sep>abstract class Base {
private base: string;
constructor() {
this.base = process.env.REACT_APP_WAKATIME_CHARTS_BASE_URI || "";
}
protected abstract getUuidCode(): string;
protected abstract getDataKey(): string;
public request(loadData: (data: any) => void) {
const elBody = document.getElementsByTagName("body")[0];
const DATA_KEY = this.getDataKey();
function callback_jsonp(response: any) {
localStorage.setItem("DATA_KEY", JSON.stringify(response.data));
}
const script = document.createElement("script");
const scriptLoad = document.createElement("script");
scriptLoad.type = "text/javascript";
scriptLoad.src = `${this.base}${this.getUuidCode()}.json?callback=${
callback_jsonp.name
}_${this.getDataKey()}`;
script.innerHTML = callback_jsonp
.toString()
.replace("DATA_KEY", `${DATA_KEY}`)
.replace(callback_jsonp.name, `${callback_jsonp.name}_${DATA_KEY}`);
elBody.appendChild(script);
elBody.appendChild(scriptLoad);
scriptLoad.addEventListener("load", () => {
loadData(JSON.parse(localStorage.getItem(DATA_KEY) || ""));
localStorage.removeItem(DATA_KEY);
});
}
}
export default Base;
<file_sep>:rocket: [run](//renatosoares.dev)
<file_sep>import Base from "./Base";
class CodingActivity extends Base {
private uuidCode: string;
private readonly dataKey: string = "data_coding_activity";
constructor() {
super();
this.uuidCode =
process.env.REACT_APP_WAKATIME_CHARTS_UUID_CODING_ACTIVITY || "";
}
protected getUuidCode() {
return this.uuidCode;
}
protected getDataKey() {
return this.dataKey;
}
}
export default CodingActivity;
<file_sep>REACT_APP_WAKATIME_CHARTS_BASE_URI="//"
REACT_APP_WAKATIME_CHARTS_UUID_CODING_LANGUAGES=""
REACT_APP_WAKATIME_CHARTS_UUID_CODING_ACTIVITY=""
|
e87f53069f9f197e687fe4f5e713f19d1028cff9
|
[
"Markdown",
"TypeScript",
"Shell"
] | 7
|
TypeScript
|
renatosoares/renatosoares.github.io
|
ec80c4031c5f4b81244d37f1ca640677473b5a93
|
a0307901b5a336433a76c5b27ea228feedc8e310
|
refs/heads/master
|
<repo_name>firstock/scraping<file_sep>/naverNewsGetLink.py
# coding: utf-8
import pandas as pd
import numpy as np
df= pd.read_csv('data/naverNewsSomePressLinks.csv', index_col=False, header=None)
len(df)
## 긁으려는 거 외 링크 지우기
# 133개 지움
exceptList= ['www.kukinews.com', 'news.kukinews.com', 'www.seouland.com', 'nownews.seoul.co', 'nownewstv.seoul.co', 'www.sporbiz.co', 'www.beautyhankook.com']
for exLink in exceptList:
df= df[df[0].map(lambda x: (exLink not in x))]
df
len(df)
df[0].map(lambda x: (exceptList[0] in x)).sum()
## dict 만들기
# key: http빼고 사이트 앞 3어절, value: XPATH
link= ['news.khan.co', 'www.khan.co', 'h2.khan.co', 'news.kmib.co', 'www.naeil.com', 'news.donga.com', 'www.donga.com', 'realestate.donga.com', 'bizn.donga.com', 'travel.donga.com', 'studio.donga.com', 'yachtpia.donga.com', 'it.donga.com', 'www.m-i.kr', 'www.munhwa.com', 'www.seoul.co', 'ntn.seoul.co', 'stv.seoul.co', 'www.segye.com', 'local.segye.com', 'www.segyefn.com', 'economysegye.segye.com', 'fn.segye.com', 'www.asiatoday.co', 'news.chosun.com', 'biz.chosun.com', 'car.chosun.com', 'life.chosun.com', 'businessnews.chosun.com', 'news.joins.com', 'realestate.joins.com', 'www.hani.co', 'babytree.hani.co', '2korea.hani.co', 'www.hankookilbo.com', 'www.newsis.com', 'sports.news.naver', 'news.naver.com', 'app.yonhapnews.co', 'www.wowtv.co', 'www.wownet.co', 'news.wowtv.co', 'sports.wowtv.co', 'wowstar.wowtv.co', 'news.jtbc.co', 'www.sisain.co', 'www.sisainlive.com']
dupCnt= [3,1,1,8,1,1,3,5,1,5,2,3,1,2,2,5,1,2]
xpaths= ['//div[@id="articleBody"]', '//div[@id="articleBody"]', '//div[@class="articleArea"]', '//div[@id="ct"]', '//div[@class="content"]', '//div[@id="NewsAdContent"]', '//div[@id="article_content"]', '//div[@id="article_txt"]', '//div[@id="font"]', '//div[@id="news_body_id"]/div[@class="par"]', '//div[@id="article_body"]', '//div[@class="article-text-font-size"]', '//article[@id="article-body"]', '//div[@id="#textBody"]', '//div[@id="articleWrap"]', '//div[@id="divNewsContent"]', '//div[@class="article_content"]', '//div[@itemprop="articleBody"]']
xpaths= np.array(xpaths)
print(len(xpaths))
print(len(dupCnt))
xpaths_s= list(xpaths.repeat(dupCnt))
xpaths_s
print(link)
print(xpaths_s)
dictLink= dict(zip(link,xpaths_s))
dictLink
## xpath 얻기
sriLink= df[0].map(lambda x: '.'.join(x.split('/')[2].split('.')[0:3]))
sriLink
sriLink.value_counts()
xpathList= list([])
for link in sriLink:
xpathList.append(dictLink[link])
xpathList
<file_sep>/saramin_passintroduction_release.py
# coding: utf-8
# 사람인 합소서 긁기. release 용
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os.path
from os import rename
from os import listdir
from os import mkdir
import time
import csv
import re
def startWeb(numPage=1):
"""
@return driver
"""
driver= webdriver.Chrome('lib/chromedriver.exe')
url= "http://www.saramin.co.kr/zf_user/public-recruit/coverletter-list/page/"+str(numPage)+"?company_nm="
driver.get(url)
return driver
def movePage(numPage):
url= "http://www.saramin.co.kr/zf_user/public-recruit/coverletter-list/page/"+str(numPage)+"?company_nm="
driver.get(url)
try:
element= WebDriverWait(driver, 10).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//h2'))
)
except Exception as e:
print('error',e)
def saveLink(dict_pass):
elements= driver.find_elements_by_xpath('//h2')
#dict_pass= dict([])
for element in elements:
dict_pass[element.text]= element.find_element_by_xpath('a').get_attribute('href')
#print(i, element.text)
#print(element.find_element_by_xpath('a').get_attribute('href'))
return dict_pass
def movePageLink(link):
driver.get(link)
try:
element= WebDriverWait(driver, 10).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//li'))
)
except Exception as e:
print('error',e)
def getContent():
"""
@return element_txt, element_duty
@except 지원분야가 써있지 않은 페이지?
"""
try:
elementCon= WebDriverWait(driver, 3).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//div[@class="box_ty3"]'))
)
element_txt= rmSpecialChr(elementCon.text)
except Exception as e:
print('error',e)
try:
elementDu= WebDriverWait(driver, 1).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//span[@class="tag_apply"]'))
)
element_duty= rmSpecialChr(elementDu.text)
except Exception as e:
element_duty= '지원분야 공통'
pass
#element_txt= driver.find_element_by_xpath('//div[@class="box_ty3"]').text
#element_duty= driver.find_element_by_xpath('//span[@class="tag_apply"]').text
return element_txt, element_duty
def rmSpecialChr(weirdStr):
"""
@param string
@return string. #특문제거, \n -> 띟띟띟
"""
regPattLine= '\n'
res= re.sub(regPattLine,'띟띟띟',weirdStr)
regPatt= '[^ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9()": ]|[[\u3131-\u318E\uAC00-\uD7A3]]'
res= re.sub(regPatt,'',res)
return res
numPages= range(1,338)
dictLinks= dict([])
for numPage in numPages:
print(numPage)
movePage(numPage)
dictLinks= saveLink(dictLinks)
# dictLinks
driver.close()
driver.quit()
mkdir('data')
with open('data/passLink.csv', 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
for key, value in dictLinks.items():
writer.writerow([key, value])
print(len(dickLinksRead) )
driver= startWeb()
## 스레드 필요!. 그냥하면 1시간 45분 가량
dictContents= dict([])
for i, (toJob, link) in enumerate(dickLinksRead.items()):
#if (62< i) and (78>=i):
print(i)#, toJob, link)
movePageLink(link)
selfintro, duty= getContent()
dictContents[toJob+' '+duty]= selfintro
with open('data/passContents.csv', 'w', newline='', encoding='cp949') as csv_file:
writer = csv.writer(csv_file)
for key, value in dictContents.items():
writer.writerow([key, value])
<file_sep>/autoApplySaramIN.py
# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os.path
from os import rename
from os import listdir
import time
# import requests # login 편하게? fail
#import copy
def startWeb():
"""
@return driver
"""
#options= setDownPath()
driver= webdriver.Chrome('lib/chromedriver.exe')#, chrome_options= options)
url= "http://www.saramin.co.kr/zf_user/member/suited-recruit-mail/list"
driver.get(url)
return driver
def login():
try:
input_id= WebDriverWait(driver, 3).until(
EC.presence_of_element_located((By.XPATH, '//input[@id="id"]'))
)
input_pw= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//input[@id="password"]'))
)
userid= "" #사람인 id
userpw= "" #사람인 pw 하드코딩
input_id.send_keys(userid)
input_pw.send_keys(<PASSWORD>pw)
loginBtn= driver.find_element_by_xpath('//button[contains(text(), "로그인")]')
loginBtn.click()
except Exception as e:
print('error',e)
def getApplyList():
try:
WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, '//span[@class="sri_btn_immediately"]'))
)
elements= driver.find_elements_by_xpath('//span[@class="sri_btn_immediately"]')
applyLen= len(elements)
print('즉시지원 개수: ',applyLen)
return elements
except Exception as e:
return 'getApplyListError'+e
def clickApplyBtn(applyList, index):
#seemore()
applyList[index].click()
aleady= aleadyApply()
print(aleady)
if not aleady: # 이미 지원한 공고가 아닐 때만
selectPart()
apply()
clickCancel() #지원완료창 종료
def aleadyApply():
"""새 창
"""
driver.switch_to.frame(driver.find_element_by_id("quick_apply_frame"))
try:
WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//span[@class="emph"]'))
)
print('이미지원한 공고 찾음. 기대값: true')
clickCancel()
driver.switch_to_default_content()
return True
except Exception as e:
driver.switch_to_default_content() # 원래 iframe로 돌아가기
return False
pass
def selectPart():
"""창의 일부
"""
driver.switch_to.frame(driver.find_element_by_id("quick_apply_frame"))
try:
elements= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//ul[@id="optSort"]/descendant::li'))
)
if 1== len(elements):
elements[0].click() #지원부문 선택지가 1개인 경우도 있다
elements[1].click()
except Exception as e:
pass
driver.switch_to_default_content() # 원래 iframe로 돌아가기
print('selectPart: 원래frame으로 돌아감')
def apply():
print('apply 진입')
driver.switch_to.frame(driver.find_element_by_id("quick_apply_frame"))
print('apply iframe찾음')
try:
#파일 추가
addFile= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//a[@class="sri_btn_type3 btn_file"]'))
)
addFile.click()
except Exception as e1:
print('파일추가없엉')
pass
try:
#포트폴리오 추가
addPortfolio1= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//input[@id="mfile_idx_4314395"]'))
)
addPortfolio2= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//input[@id="mfile_idx_4314365"]'))
)
addPortfolio1.click()
addPortfolio2.click()
except Exception as e2:
print('퐅폴input없엉')
pass
try:
#완료
submit= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//button[@class="sri_btn_complete _attachment_complete_btn"]'))
)
submit.click()
except Exception as e3:
print('완료없엉')
pass
try:
#지원하기 sri_btn_apply
applySubmit= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//button[@class="sri_btn_apply"]'))
)
applySubmit.click()
except Exception as e4:
print('지원하기버튼없엉')
pass
driver.switch_to_default_content() # 원래 iframe로 돌아가기
def clickCancel():
cancel= driver.find_element_by_xpath('//a[@class="once_ly_close"]')
cancel.click()
# applyList[1].click()
# clickCancel()
# driver.switch_to.frame(driver.find_element_by_id("quick_apply_frame"))
# driver.switch_to_default_content()
def seemore():
try:
seemore= WebDriverWait(driver, 1).until(
EC.presence_of_element_located((By.XPATH, '//button[@id="btn_more_bar"]'))
)
seemore.click()
except Exception as e3:
pass
#driver.close()
#driver.quit()
## test
driver= startWeb()
login()
applyList= getApplyList()
index= 4
clickApplyBtn(applyList, index)
#index= 3
#clickApplyBtn(applyList, index)
## RUN - ERROR !
#driver= startWeb()
#login()
#applyList= getApplyList()
#for index,apply in enumerate(applyList):
# clickApplyBtn(applyList, index) # ERROR- apply() 진입 안 함
<file_sep>/airPollution.py
# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os.path
from os import rename
from os import listdir
import time
def setDownPath():
"""
@return chrome_options
"""
saveDir= 'data' if ('data' in listdir('.')) else ""
downPath= (os.path.abspath('.')+'\\'+saveDir).replace('\\','/')
options= webdriver.ChromeOptions()
prefs= {"download.default_directory": downPath}
options.add_experimental_option("prefs",prefs)
return options
def startWeb():
"""
@return driver
"""
options= setDownPath()
driver= webdriver.Chrome('lib/chromedriver.exe', chrome_options= options)
url= "http://cleanair.seoul.go.kr/air_pollution.htm?method=period"
driver.get(url)
return driver
def set_input(xpath_id, sendKeys):
myXpath= '//input[@id="'+xpath_id+'"]'
element= driver.find_element_by_xpath(myXpath)
element.clear()
element.send_keys(sendKeys)
def set_input_year(year):
set_input("measure_cal1", year)
set_input("measure_cal2", year)
def clickSearchBtn(driver):
element= driver.find_element_by_xpath('//p[@class="schBtn1"]')
element.click()
def clickExcelDownBtn(driver):
try:
element= WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.XPATH, '//span[@class="exl_btn"]/a'))
)
except Exception as e:
print('error',e)
element.click()
time.sleep(4)
def renameDownFile(year):
for filename in listdir('data/'):
if EXCEL_FILENAME == filename:
rename('data/'+filename, 'data/'+year+'_airPollution.htm')
driver= startWeb()
EXCEL_FILENAME= "ExcelData.xls"
years= ["2016", "2017"]
for year in years:
set_input_year(year)
clickSearchBtn(driver)
clickExcelDownBtn(driver)
renameDownFile(year)
driver.close()
driver.quit()
<file_sep>/scrapeJs/testNode.js
//console.log("node, is there?");
var client= require('cheerio-httpcli');
var url= "http://book.naver.com/";
var param= {};
client.fetch(url, param, function(err, $, res){
if(err){
console.log("Error:", err); return;
}
//var body= $.html();
//console.log(body);
$("a").each(function(idx){
var text= $(this).text();
var href= $(this).attr('href');
console.log(text+":"+href);
});
});
<file_sep>/scrap_passSelfintro.py
# coding: utf-8
# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os.path
from os import rename
from os import listdir
import time
import csv
import re
# 인자: 여러개 동시에 띄울걸 감안해서?
def startWeb(numPage=1):
"""
@return driver
"""
driver= webdriver.Chrome('lib/chromedriver.exe')
url= "http://www.saramin.co.kr/zf_user/public-recruit/coverletter-list/page/"+str(numPage)+"?company_nm="
driver.get(url)
return driver
def movePage(numPage):
url= "http://www.saramin.co.kr/zf_user/public-recruit/coverletter-list/page/"+str(numPage)+"?company_nm="
driver.get(url)
try:
element= WebDriverWait(driver, 10).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//h2'))
)
except Exception as e:
print('error',e)
def saveLink(dict_pass):
elements= driver.find_elements_by_xpath('//h2')
#dict_pass= dict([])
for element in elements:
dict_pass[element.text]= element.find_element_by_xpath('a').get_attribute('href')
#print(i, element.text)
#print(element.find_element_by_xpath('a').get_attribute('href'))
return dict_pass
def movePageLink(link):
driver.get(link)
try:
element= WebDriverWait(driver, 10).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//li'))
)
except Exception as e:
print('error',e)
def getContent():
"""
@return element_txt, element_duty
@except 지원분야가 써있지 않은 페이지?
"""
try:
elementCon= WebDriverWait(driver, 3).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//div[@class="box_ty3"]'))
)
element_txt= rmSpecialChr(elementCon.text)
except Exception as e:
print('error',e)
try:
elementDu= WebDriverWait(driver, 1).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//span[@class="tag_apply"]'))
)
element_duty= rmSpecialChr(elementDu.text)
except Exception as e:
element_duty= '지원분야 공통'
pass
#element_txt= driver.find_element_by_xpath('//div[@class="box_ty3"]').text
#element_duty= driver.find_element_by_xpath('//span[@class="tag_apply"]').text
return element_txt, element_duty
def rmSpecialChr(weirdStr):
"""
@param string
@return string. #특문제거, \n -> 띟띟띟
"""
regPattLine= '\n'
res= re.sub(regPattLine,'띟띟띟',weirdStr)
regPatt= '[^ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9()": ]|[[\u3131-\u318E\uAC00-\uD7A3]]'
res= re.sub(regPatt,'',res)
return res
with open('data/passLink.csv', 'r') as csv_file:
reader = csv.reader(csv_file)
dickLinksRead = dict(reader)
len(dickLinksRead)
driver= startWeb()
dictContents= dict([])
for i, (toJob, link) in enumerate(dickLinksRead.items()):
#if (62< i) and (78>=i):
print(i)#, toJob, link)
movePageLink(link)
selfintro, duty= getContent()
dictContents[toJob+' '+duty]= selfintro
dictContents
with open('data/passContents.csv', 'w', newline='', encoding='cp949') as csv_file:
writer = csv.writer(csv_file)
for key, value in dictContents.items():
writer.writerow([key, value])
<file_sep>/naverNews.py
# coding: utf-8
# coding: utf-8
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import os.path
from os import rename, listdir, mkdir
import time
import csv
import pandas as pd
from pandas import DataFrame, Series
import numpy as np
import re
def startWeb(numPage=1):
"""
네이버 뉴스
검색어: 공공자전거
옵션유지: 켜짐. mynews=1
@return driver
"""
driver= webdriver.Chrome('lib/chromedriver.exe')
paging= str(1+10*(numPage-1))
# caution: "\ is before &"
url= "https://search.naver.com/search.naver?&where=news &query=%EA%B3%B5%EA%B3%B5%EC%9E%90%EC%A0%84%EA%B1%B0&sm=tab_pge &sort=0&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid= &nso=so:r,p:all,a:all&mynews=1&start="+paging+"&refresh_start=0"
driver.get(url)
try:
element= WebDriverWait(driver, 10).until(
# is comming content?
EC.presence_of_element_located((By.XPATH, '//li'))
)
except Exception as e:
print('error',e)
return driver
def searchOptPress():
"""
일간지, 뉴시스, 연합뉴스, 한국경제TV, JTBC, 시사IN
"""
#검색옵션
try:
element= WebDriverWait(driver, 10).until(
# is comming content?
EC.presence_of_element_located((By.XPATH, '//a[@id="_search_option_btn"]'))
)
except Exception as e:
print('error',e)
element.click()
#언론사
xpath1= '//li[@id="news_popup"]'
element= driver.find_element_by_xpath(xpath1)
element.click()
# #전체선택 해제. '18.4.24 부로 전체선택옵션이 없어졌다 ㄷㄷ
# xpath2= '//input[@id="select_all_order"]'
# element= driver.find_element_by_xpath(xpath2)
# element.click()
#일간지 선택
xpath3= '//input[@id="ca_p1"]'
element= driver.find_element_by_xpath(xpath3)
element.click()
somePress= ["뉴시스", "연합뉴스", "한국경제TV", "JTBC", "시사IN"]
for press in somePress:
xpath= '//label[@title="'+press+'"]'
element= driver.find_element_by_xpath(xpath)
element.click()
# 확인
xpathChk= '//button[@class="impact _submit_btn"]'
element= driver.find_element_by_xpath(xpathChk)
element.click()
try:
element= WebDriverWait(driver, 10).until(
# is comming content?
EC.presence_of_element_located((By.XPATH, '//li'))
)
except Exception as e:
print('error',e)
def movePage(numPage):
paging= str(1+10*(numPage-1))
url= "https://search.naver.com/search.naver?&where=news &query=%EA%B3%B5%EA%B3%B5%EC%9E%90%EC%A0%84%EA%B1%B0&sm=tab_pge &sort=0&photo=0&field=0&reporter_article=&pd=0&ds=&de=&docid= &nso=so:r,p:all,a:all&mynews=1&start="+paging+"&refresh_start=0"
driver.get(url)
try:
element= WebDriverWait(driver, 10).until(
# is comming content?
EC.presence_of_element_located((By.XPATH, '//div[@class="thumb"]'))
)
except Exception as e:
print('error',e)
def saveLink(listLink):
#caution: not '_sp_each_title' but ' _sp_each_title'
#amazing: there are no duplicated. why ??
xpathLink1= '//a[@class=" _sp_each_title"]'
elements= driver.find_elements_by_xpath(xpathLink1)
for element in elements:
listLink.append(element.get_attribute("href"))
xpathLink2= '//a[@class="_sp_each_url _sp_each_title"]'
elements= driver.find_elements_by_xpath(xpathLink2)
for element in elements:
listLink.append(element.get_attribute("href"))
return listLink
def movePageLink(link):
driver.get(link)
try:
element= WebDriverWait(driver, 10).until(
# is coming a content?
EC.presence_of_element_located((By.XPATH, '//div'))
)
except Exception as e:
print('error',e)
def mkDictNewsXpath():
"""
link scraping 결과에 unique() 하고, 의뭉스런 사이트를 직접 들어가서
해당 언론사가 필터링한 언론사 맞는지 확인한 결과
xpath가 틀렸다면 여기서 정정!
"""
link= ['news.khan.co', 'www.khan.co', 'h2.khan.co', 'news.kmib.co', 'www.naeil.com', 'news.donga.com', 'www.donga.com', 'realestate.donga.com', 'bizn.donga.com', 'travel.donga.com', 'studio.donga.com', 'yachtpia.donga.com', 'it.donga.com', 'www.m-i.kr', 'www.munhwa.com', 'www.seoul.co', 'ntn.seoul.co', 'stv.seoul.co', 'www.segye.com', 'local.segye.com', 'www.segyefn.com', 'economysegye.segye.com', 'fn.segye.com', 'www.asiatoday.co', 'news.chosun.com', 'biz.chosun.com', 'car.chosun.com', 'life.chosun.com', 'businessnews.chosun.com', 'news.joins.com', 'realestate.joins.com', 'www.hani.co', 'babytree.hani.co', '2korea.hani.co', 'www.hankookilbo.com', 'www.newsis.com', 'sports.news.naver', 'news.naver.com', 'app.yonhapnews.co', 'www.wowtv.co', 'www.wownet.co', 'news.wowtv.co', 'sports.wowtv.co', 'wowstar.wowtv.co', 'news.jtbc.co', 'www.sisain.co', 'www.sisainlive.com']
dupCnt= [3,1,1,8,1,1,3,5,1,5,2,3,1,2,2,5,1,2]
xpaths= ['//div[@id="articleBody"]', '//div[@id="articleBody"]', '//div[@class="articleArea"]', '//div[@id="ct"]', '//div[@class="content"]', '//div[@id="NewsAdContent"]', '//div[@id="article_content"]', '//div[@id="article_txt"]', '//div[@id="font"]', '//div[@id="news_body_id"]/div[@class="par"]', '//div[@id="article_body"]', '//div[@class="article-text-font-size"]', '//article[@id="article-body"]','//div[@itemprop="articleBody"]', '//div[@id="articleWrap"]', '//div[@id="divNewsContent"]', '//div[@class="article_content"]', '//div[@itemprop="articleBody"]']
xpaths= np.array(xpaths)
xpaths_s= list(xpaths.repeat(dupCnt))
dictLink= dict(zip(link,xpaths_s))
return dictLink
def mkDictNewsPress():
"""
해당 링크가 어느 신문사인지
"""
link= ['news.khan.co', 'www.khan.co', 'h2.khan.co', 'news.kmib.co', 'www.naeil.com', 'news.donga.com', 'www.donga.com', 'realestate.donga.com', 'bizn.donga.com', 'travel.donga.com', 'studio.donga.com', 'yachtpia.donga.com', 'it.donga.com', 'www.m-i.kr', 'www.munhwa.com', 'www.seoul.co', 'ntn.seoul.co', 'stv.seoul.co', 'www.segye.com', 'local.segye.com', 'www.segyefn.com', 'economysegye.segye.com', 'fn.segye.com', 'www.asiatoday.co', 'news.chosun.com', 'biz.chosun.com', 'car.chosun.com', 'life.chosun.com', 'businessnews.chosun.com', 'news.joins.com', 'realestate.joins.com', 'www.hani.co', 'babytree.hani.co', '2korea.hani.co', 'www.hankookilbo.com', 'www.newsis.com', 'sports.news.naver', 'news.naver.com', 'app.yonhapnews.co', 'www.wowtv.co', 'www.wownet.co', 'news.wowtv.co', 'sports.wowtv.co', 'wowstar.wowtv.co', 'news.jtbc.co', 'www.sisain.co', 'www.sisainlive.com']
dupCnt= [3,1,1,8,1,1,3,5,1,5,2,3,1,2,2,5,1,2]
press= ['경향신문', '국민일보', '내일신문', '동아일보', '매일일보', '문화일보', '서울신문', '세계일보', '아시아투데이', '조선일보', '중앙일보', '한겨레', '한국일보', '뉴시스', '연합뉴스', '한국경제TV ', 'JTBC', '시사IN']
press= np.array(press)
press_s= list(press.repeat(dupCnt))
dictPress= dict(zip(link,press_s))
return dictPress
dictLink= mkDictNewsXpath()
def whatLinksXpath(link):
link3piece= '.'.join(link.split('/')[2].split('.')[0:3])
xpath= dictLink[link3piece]
return xpath
dictPress= mkDictNewsPress()
def whatLinksPress(link3piece):
#link3piece= '.'.join(link.split('/')[2].split('.')[0:3])
press= dictPress[link3piece]
return press
def rmSpecialChr(weirdStr):
"""
@param string
@return string. #특문제거, \n -> ___
"""
regPattLine= '\n'
res= re.sub(regPattLine,'___',weirdStr)
regPatt= '[^ㄱ-ㅎㅏ-ㅣ가-힣a-zA-Z0-9()": ]|[[\u3131-\u318E\uAC00-\uD7A3]]'
res= re.sub(regPatt,'',res)
res= re.sub('\\s+', ' ', res) # 공백 제거 해,말아? 하자. 안 하면 헬일듯
return res
def getContent(link):
"""
@return conBodyText
"""
xpathBody= whatLinksXpath(link)
#print(xpathBody)
try:
conBody= WebDriverWait(driver, 2).until(
EC.presence_of_element_located((By.XPATH, xpathBody))
)
conBodyText= rmSpecialChr(conBody.text)
except Exception as e:
print('no match xpath',e)
conBodyText= ""
pass
return conBodyText
if not os.path.exists('data'):
mkdir("data")
# driver.close()
# driver.quit()
# TEST: link list from page-1
driver= startWeb()
searchOptPress()
numPage= 1
movePage(numPage)
listLink= list([])
listLink= saveLink(listLink)
listLink
driver.close()
driver.quit()
# TEST: news content from link-1
driver= startWeb()
searchOptPress()
# numPage= 2
# movePage(numPage)
dictLink= mkDictNewsXpath() # 최초 1번만 만들면 된다
linkEx= 'http://www.newsis.com/view/?id=NISX20180421_0000288016&cID=10803&pID=10800'
movePageLink(linkEx)
contents= getContent(linkEx)
contents
## Run
driver= startWeb()
searchOptPress()
# data/naverNewsSomePressLinks.csv 에 저장 완료!
numPages= range(1,400)
listLink= list([])
for numPage in numPages:
print(numPage)
movePage(numPage)
listLink= saveLink(listLink)
print(len(listLink))
listLink
driver.close()
driver.quit()
# scraping 직후. 옵션외 링크가 좀 섞여있다
DataFrame(listLink).to_csv("data/naverNewsSomePressLinks.csv", index= False, header=None)
linkRead= pd.read_csv("data/naverNewsSomePressLinks.csv", header=None)
linkRead= list(linkRead[0])
print(len(linkRead))
linkRead[30:35]
df= DataFrame(linkRead)
exceptList= ['www.kukinews.com', 'news.kukinews.com', 'www.seouland.com', 'nownews.seoul.co', 'nownewstv.seoul.co', 'www.sporbiz.co', 'www.beautyhankook.com']
for exLink in exceptList:
df= df[df[0].map(lambda x: (exLink not in x))]
print(len(df))
## 읽기- 광고 제거된 링크 목록
df.to_csv("data/naverNewsDailyPlusPressLinks.csv", index= False, header=None)
linkNewsDailyPlus= pd.read_csv('data/naverNewsDailyPlusPressLinks.csv',
header=None)
print(linkNewsDailyPlus.shape)
print(type(linkNewsDailyPlus[0]))
linkNewsDailyPlus.head(3)
linkNewsDailyPlus_list= list(linkNewsDailyPlus[0])
len(linkNewsDailyPlus_list)
driver.close()
driver.quit()
## 실행- 내용 얻기
linkNewsDailyPlus= pd.read_csv('data/naverNewsDailyPlusPressLinks.csv',
header=None)
linkNewsDailyPlus_list= list(linkNewsDailyPlus[0])
print(len(linkNewsDailyPlus_list))
bodyList= list([])
pressList3pie= list([])
dictLink= mkDictNewsXpath() # 최초 1번만 만들면 된다. driver와 무관
driver= startWeb()
searchOptPress()
for i, link in enumerate(linkNewsDailyPlus_list):
#if (0== i)| (1==i):
#print(link)
print(i)
movePageLink(link)
body= getContent(link)
bodyList.append(body)
link3piece= '.'.join(link.split('/')[2].split('.')[0:3])
pressList3pie.append(link3piece)
newsData= {
'link3pie': pressList3pie,
'zbody':bodyList
}
dfNews= pd.DataFrame(data= newsData)
dfNews.to_csv('data/naverNewsContent.csv', index= False, encoding= 'cp949')
dictPress= mkDictNewsPress()
dfNews['link3pie'].map(whatLinksPress).value_counts()
list(dfNews['link3pie'].map(whatLinksPress).unique())
dfNews['link3pie'].value_counts()
dfNC= pd.read_csv("data/naverNewsContent.csv", encoding= 'cp949')
dfNC.columns
## 기사중에서 특정 문자열 찾기
def findStr(inputStr):
tradein= lambda x:inputStr in x
return df[df.zbody.map(tradein)]
inputStr= '음식'
findStr(inputStr).to_csv('data/newsfind'+inputStr+'.csv', index= False, encoding= 'cp949')
|
fd194c306760648a5ecc0067315387940ff20e78
|
[
"JavaScript",
"Python"
] | 7
|
Python
|
firstock/scraping
|
e43fcd11ad8d423c9be8ee7197dd523a19924225
|
5c6d10f11b758d3343f534a590ef81091241c504
|
refs/heads/master
|
<file_sep># Selenium-TestCases
This repository contains the selenium automation test scripts tried on different web applications automation.
<file_sep>package autoSeleniumPrac;
import java.util.List;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Alert;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.remote.RemoteWebDriver;
public class TC001_Automation_Myntra {
public static RemoteWebDriver driver;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "./drivers/chromedriver.exe");
ChromeOptions opt = new ChromeOptions();
opt.addArguments("--disable-notifications");
driver = new ChromeDriver(opt);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
//1. Open https://www.myntra.com/
driver.get("https://www.myntra.com/");
//2. Mouse over on WOMEN (Actions -> moveToElement
WebElement ele = driver.findElementByXPath("(//a[text()='Women'])[1]");
Actions builder = new Actions(driver);
builder.moveToElement(ele).perform();
//3. Click Jackets & Coats
driver.findElementByXPath("//a[text()='Jackets & Coats']").click();
//4.Find the total count of item (top) -> getText -> String
String str = driver.findElementByClassName("title-count").getText();
int count = Integer.parseInt(str.replaceAll("\\D",""));
System.out.println(count);
//5. Validate the sum of categories count matches
int expCount = 0;
List <WebElement> list = driver.findElementsByXPath("//span[@class='categories-num']");
for(int i =0;i<list.size();i++) {
String text2 = list.get(i).getText();
System.out.println(text2.replaceAll("\\D",""));
int count2 = Integer.parseInt(text2.replaceAll("\\D",""));
expCount = expCount+ count2;
}
if(count == expCount) {
System.out.println("The Count matches successfully");
}else
System.out.println("The count is not matching");
//6. Check Coats
driver.findElementByXPath("(//ul[@class='categories-list']//div)[2]").click();
//7. Click + More option under BRAND
driver.findElementByClassName("brand-more").click();
//8. Type MANGO and click checkbox
driver.findElementByClassName("FilterDirectory-searchInput").sendKeys("MANGO");
driver.findElementByXPath("//ul[@class='FilterDirectory-list']//div").click();
//9. Close the pop-up x
driver.findElementByXPath("//span[@class='myntraweb-sprite FilterDirectory-close sprites-remove']").click();
//10. Confirm all the Coats are of brand MANGO
List<WebElement> listItem = driver.findElementsByXPath("//h3[@class='product-brand']");
for (int j=1;j<listItem.size();j++) {
String Str3 = listItem.get(j).getText();
if(Str3.equals("MANGO"))
System.out.println(Str3+" It is Matching.");
else
System.out.println("The fetched result is not matching");
}
//11. Sort by Better Discount
WebElement sort = driver.findElementByXPath("//div[@class='sort-sortBy']");
builder.moveToElement(sort).perform();
Thread.sleep(2000);
driver.findElementByXPath("//ul[@class='sort-list']//label[text()='Better Discount']").click();
//12. Find the price of first displayed item
List<WebElement> listPrice = driver.findElementsByXPath("(//div[@class='product-price']/span/span[1])[1]");
int price = Integer.parseInt(listPrice.get(0).getText().replaceAll("\\D",""));
System.out.println("The Price of the first item is: "+price);
//13. Mouse over on size of the first item
WebElement firstItem = listPrice.get(0);
builder.moveToElement(firstItem).perform();
//14. Click on WishList Now
driver.findElementByXPath("(//div[@class='product-price']/../../following::div[2]/span)[1]").click();
Thread.sleep(5000);
//15. Close Browser
driver.close();
}
}
|
cfffff2fc738ee2e68680a16e86c112a716a2161
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
Balaji-NH/Selenium-TestCases
|
95b587aeaa5dfba84ffc873179a7e63aa477126a
|
bf8b6ac3bb0e8f88aa1236f5145d7645b94ff65f
|
refs/heads/master
|
<repo_name>hoyin2013/exports<file_sep>/test.py
# coding: utf-8
import imapclient,re
import pyzmail
#提取邮件里面的链接
def getDowmlodUrl():
url = None
#这里是腾讯企业邮箱,其他的自行百度
imapObj = imapclient.IMAPClient('imap.exmail.qq.com',ssl=True)
#邮箱和密码
imapObj.login('<EMAIL>','<PASSWORD>!')
#默认收件箱
imapObj.select_folder('INBOX',readonly=True)
#搜索未读邮件,打印未读邮件的UID
UIDS = imapObj.search('UNSEEN')
print(UIDS)
#UIDS = imapObj.search('ALL')#搜索全部的邮件
if len(UIDS) >= 1:#存在未读邮件
#获得邮件内容
rawMessage = imapObj.fetch(UIDS[0],[b'BODY[]'])
#选择第一封未读邮件
messageObj = pyzmail.PyzMessage.factory(rawMessage[UIDS[0]][b'BODY[]'])
#打印邮件信息,可以根据这些信息进行筛选
print(messageObj.get_subject())#邮件主题
print(messageObj.get_addresses('from'))#发件人
print(messageObj.get_addresses('to'))#收件人
print(messageObj.get_addresses('cc'))
print(messageObj.get_addresses('bcc'))
#邮件内容不为空时
if messageObj.html_part != None:
messageContent = messageObj.html_part.get_payload().decode(messageObj.html_part.charset)
#打印邮件内容
print(type(messageContent),messageContent)
#提取邮件内容里面的链接
pattern = re.compile(r'//[0-9A-Za-z./\\?\\=\\:]+')
m = re.search(pattern,messageContent)
print('m',m)
if m is not None:
print('http:' + m.group(0))
url = 'http:' + m.group(0)
#如果没有则取提起邮件的附件
else:
for part in messageObj.walk():
# name = part.get_param('name')
if part.get_filename() != None:
# print(part,part.get_filename())
with open(part.get_filename(), 'wb') as f:
f.write(part.get_payload(decode=True))
#设置邮件已读
imapObj.set_flags(rawMessage, b'\\Seen', silent=False)
else:
pass
#退出邮件
imapObj.logout()
#如果邮件内容存在链接则返回链接,若不存在则直接下载邮件附件
return url
getDowmlodUrl()
<file_sep>/config.py
# coding: utf-8
# __author__ = 'Hoyin'
# __date__ = '2020/05/02'
# __Desc__ = 从数据库中导出数据到excel数据表中
import logging
# 日志格式配置
logging.basicConfig(level=logging.INFO,format='%(asctime)s :: %(levelname)s :: %(message)s', filename='exports.log')
# 数据库类型 oracle|mysql
db_type = 'oracle'
# 导出类型 excel csv
export_type = 'excel'
# mysql连接配置
mysql_config = {
'user': 'root',
'password': '<PASSWORD>',
'host': '10.80.16.64',
}
# oracle连接配置
oracle_config = ''
config_sjqx = {
'host':'10.80.16.57',
'user': 'root',
'password': '<PASSWORD>'
}
config_paas = {
'host':'10.80.16.64',
'user': 'root',
'password': '<PASSWORD>'
}
<file_sep>/exports.py
# coding: utf-8
#!/usr/bin/env python3
# __author__ = 'Hoyin'
# __date__ = '2020/06/04'
# __Desc__ = 从数据库中导出数据到excel数据表中
import csv
import os
import glob
import openpyxl
import chardet
import db
from config import *
from utils import *
from SendEmail import *
# 文件的根目录
BASE_DIR, filename = os.path.split(os.path.abspath(__file__))
# print(__file__)
BASE_DIR = BASE_DIR.replace('\\', '/')
# print(BASE_DIR)
send_to_email = False
def readfile(filename):
try:
print("read sql file")
f = open(filename, 'rb')
data = f.read()
result = chardet.detect(data)
data = data.decode(result['encoding'])
#data = re.sub('[\r\n]',' ', data)
# 替换为当前月份分区表
#this_month_format = datetime.datetime.now().strftime('%Y_%#m')
#data = data.replace('2020_5', this_month_format)
#print(data)
#exit()
print("文件:{},编码为:{}".format(filename ,result['encoding']))
logging.info("文件:{},编码为:{}".format(filename ,result['encoding']))
f.close()
return data
except Exception as e:
logging.error(e)
if data:
f.close()
return False
def export_to_excel(sql, outputpath):
logging.info("export_to_excel")
results, fields = db.get_data(sql)
#logging.info(results,fields)
if not results:
return False
wb = openpyxl.Workbook()
ws = wb.active
# 写上字段信息
# for field in range(0,len(fields)):
# ws.append(fields[field][0])
fields = [f[0] for f in fields]
# print(fields)
ws.append(fields)
for res in results:
ws.append(res)
wb.save(outputpath + '.xlsx')
return True
def export_to_csv(sql, outputpath):
if not db.get_data(sql):
return False
else:
results, fields = db.get_data(sql)
#print(results,fields)
f = open(outputpath + '.csv', 'w+', newline='', encoding='utf-8')
write = csv.writer(f)
try:
head = [ x[0] for x in fields]
#print(head)
write.writerow(head)
#print(results)
write.writerows(results)
except Exception as e:
logging.error("写入数据失败! 原因:{}".format(e))
f.close()
return True
# 找到根目录下的所有sql文件
sql_files = glob.glob(BASE_DIR + '/sql/*.*')
sql_files = [f.replace('\\', '/') for f in sql_files]
# print(sql_files)
for fp in sql_files:
logging.info("开始解析:{}".format(fp))
# 解析sql
sql = readfile(fp)
# 保存执行结果
outputpath = BASE_DIR + '/exports/' + os.path.splitext(os.path.basename(fp))[0]
if export_type == 'excel':
postfix = 'xls'
result = export_to_excel(sql, outputpath)
elif export_type == 'csv':
postfix = 'csv'
result = export_to_csv(sql, outputpath)
if result:
logging.info("生成文件:{}.{} 成功!".format(outputpath,postfix))
else:
logging.error("生成文件:{}.{} 失败!".format(outputpath,postfix))
print(gen_pass())
# 发送邮件
def sendmail(subject, attachs, receivers):
# 邮件内容存放路径
content_path = BASE_DIR + '/mail.txt'
# 传递邮件发送参数
argvs = {
'smtp_server': '10.83.1.19',
'port': 25,
'user': '<EMAIL>',
'passwd': 'xdjk2019',
'ssl': False,
'sender': '<EMAIL>',
'receivers': receivers,
'subject': subject,
'content_path': content_path,
'attach_files': attachs,
'attach_title': ''
}
# 发送邮件
sendemail = SendEmail(**argvs)
sendemail.send()
if send_to_email:
# 邮件主题日期
nowDate = datetime.datetime.now().strftime('%Y-%m-%d')
subject = '[' + nowDate + ']' + '新增非标商户数据'
# 附件路径
attachs = glob.glob(BASE_DIR + '/exports/*.xlsx')
# 接收邮件列表
#receivers = ['<EMAIL>', ]
receivers = ['<EMAIL>', '<EMAIL>','<EMAIL>']
sendmail(subject, attachs, receivers)
# 如果定期跑批,则需要清理文件
try:
for i in os.listdir(BASE_DIR + '/exports/'):
print(BASE_DIR + '/exports/' + i)
os.remove(BASE_DIR + '/exports/' + i)
logging.info("删除导出文件:%{}".format(BASE_DIR + '/exports/' + i))
except:
print("删除导出文件失败")
logging.error("删除导出文件失败")
<file_sep>/required/requirement.txt
chardet=3.0.4
et_xmlfile=1.0.1
jdcal=1.4.1
openpyxl=3.0.3
cx_Oracle
<file_sep>/README.md
# 根据给出的sql语句导出Oracle或者mysql的数据为csv或excel文件
## 用法
1. 修改config.py ,给config配置正确的信息
2. 将要提取的sql语句存放到sql文件夹下,编码为utf8,末尾不要加“;”号
3. linux直接执行 `python3 exports.py` , windows 执行 `run.bat`
4. 进入exports文件夹找到提取出来的sql语句
## 参数说明
- db_type = 'oracle' # 数据源为"oracle"或者是"mysql"
- export_type = 'excel' # 导出文件类型为"excel" 或者"csv"
- mysql_config # mysql的连接配置
- oracle_config # 暂未使用
- send_to_email = False # 是否发送邮件
<file_sep>/send.py
# coding: utf-8
from SendEmail import *
def sendmail(subject, attachs, receivers):
# 邮件内容存放路径
content_path = BASE_DIR + '/mail.txt'
# 传递邮件发送参数
argvs = {
'smtp_server': 'mail01.xdjk.com',
'port': 25,
'user': '<EMAIL>',
'passwd': '<PASSWORD>',
'ssl': False,
'sender': '<EMAIL>',
'receivers': receivers,
'subject': subject,
'content_path': content_path,
'attach_files': attachs,
'attach_title': os.path.basename(attachs[0])
}
# 发送邮件
sendemail = SendEmail(**argvs)
sendemail.send()
# 邮件主题日期
nowDate = datetime.datetime.now().strftime('%Y-%m-%d')
subject = '[' + nowDate + ']' + ''
# 附件路径
attachs = ['C:\Users\yinhb\Desktop\exports\exports\',]
# 接收邮件列表
#receivers = ['<EMAIL>', ]
receivers = receivers = ['<EMAIL>',]
sendmail(subject, attachs, receivers)
<file_sep>/db.py
# coding: utf-8
# __author__ = 'Hoyin'
# __date__ = '2020/06/02'
# __Desc__ = 从数据库中导出数据到excel数据表中
import os
import cx_Oracle
import pymysql
import chardet
from config import *
# 文件的根目录
BASE_DIR, filename = os.path.split(os.path.abspath(__file__))
# print(__file__)
BASE_DIR = BASE_DIR.replace('\\', '/')
def get_data(sql):
logging.info("get_data")
try:
if db_type == 'oracle':
logging.info('连接Oracle')
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
conn = cx_Oracle.connect('sys','Xdjk_dba','10.80.16.50/pospst',mode=cx_Oracle.SYSDBA)
elif db_type == 'mysql':
logging.info('连接MySQL')
conn = pymysql.connect(**mysql_config)
cursor = conn.cursor()
# 执行SQL
cursor.execute(sql)
# 获取全部数据
data = cursor.fetchall()
# 获取表头
fields = cursor.description
return data, fields
except Exception as e:
print("连接数据库失败! {}".format(e))
logging.error("连接数据库失败! {}".format(e))
return False, False
finally:
cursor.close()
conn.close()
<file_sep>/SendEmail.py
# coding: utf-8
import os
import smtplib
from email.header import Header
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
class SendEmail:
"""
可发送带附件的邮件或者普通邮件
"""
def __init__(self, smtp_server, port, user, passwd, ssl, sender, receivers, subject,
content_path, attach_files=None, attach_title=None, *kw, **kwargs):
"""
:param smtp_server: 发送邮件服务器
:param port: 服务端口
:param user: 登陆账号
:param passwd: 密码
:param ssl: 是否启用方式
:param sender:发送方
:param receivers:接收邮件列表
:param subject:邮件主题
:param content_path:正文文件路径
:param attach_files:附件列表
:param attach_title:附件名称
"""
self.smtp_server = smtp_server
self.port = port
self.user = user
self.passwd = <PASSWORD>
self.ssl = ssl
self.From = sender
self.To = receivers
self.subject = subject
self.attach_files = attach_files
self.content_path = content_path
self.attach_title = attach_title
def send(self):
# 邮件发送,接收及主题
multipart = MIMEMultipart()
multipart['From'] = self.From
multipart['To'] = ','.join(self.To)
multipart['Subject'] = Header(self.subject, "utf-8")
# 判断邮件正文文件是否存在
if os.path.isfile(self.content_path):
content_path = MIMEText(_text=open(self.content_path, 'rb').read(), _subtype='html', _charset='utf-8')
multipart.attach(content_path)
else:
raise IOError("content path is not exists!")
# 判断附件是否存在
if isinstance(self.attach_files, list):
for attach in self.attach_files:
if not os.path.exists(attach):
raise IOError("attach file is not exists")
# 添加附件
for attach in self.attach_files:
if self.attach_title=='':
_,attach_name = os.path.split(attach)
else:
attach_name = self.attach_title
attach = MIMEText(open(attach, 'rb').read(), 'base64', 'utf-8')
attach['Content-Type'] = 'application/octet-stream'
# attach['Content-Disposition'] = 'attachment; filename=%s' % self.attach_title
# attach['Content-Disposition'] = 'attachment;filename=attach'
attach.add_header('Content-Disposition', 'attachment', filename=attach_name)
multipart.attach(attach)
# 是否启用安全连接
if self.ssl:
smtp = smtplib.SMTP_SSL(host=self.smtp_server, port=self.port)
else:
smtp = smtplib.SMTP(host=self.smtp_server, port=self.port)
# 尝试发送
try:
smtp.login(self.user, self.passwd)
smtp.sendmail(self.From, self.To, multipart.as_string())
except smtplib.SMTPConnectError as e:
print('邮件发送失败,连接失败:', e.smtp_code, e.smtp_error)
except smtplib.SMTPAuthenticationError as e:
print('邮件发送失败,认证错误:', e.smtp_code, e.smtp_error)
except smtplib.SMTPSenderRefused as e:
print('邮件发送失败,发件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPRecipientsRefused as e:
print('邮件发送失败,收件人被拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPDataError as e:
print('邮件发送失败,数据接收拒绝:', e.smtp_code, e.smtp_error)
except smtplib.SMTPException as e:
print('邮件发送失败, ', e.message)
except Exception as e:
print('邮件发送异常, ', str(e))
finally:
smtp.quit()
def main():
send_info = {
'smtp_server': 'smtp.163.com',
'port': 25,
'user': '<EMAIL>',
'passwd': '<PASSWORD>!!!!',
'ssl': False,
'sender': '<EMAIL>',
'receivers': ['<EMAIL>', ],
'subject': 'cachecloud初始化脚本',
'content_path': 'C:/Users/hoyin/Desktop/cachecloud-init.sh',
'attach_files': ['C:/Users/hoyin/Desktop/新建XLSX工作表.xlsx'],
'attach_title': '新'
}
sendemail = SendEmail(**send_info)
sendemail.send()
if __name__ == '__main__':
main()
<file_sep>/utils.py
# coding:utf-8
import os
import datetime
def zipDir(dirpath, outFullName, password=None):
"""
压缩指定文件夹
:param dirpath: 目标文件夹路径
:param outFullName: 保存路径+xxxx.zip
:return:
"""
import os
if password:
cmd = "zip -P %s -r %s %s" % (password, outFullName, dirpath)
else:
cmd = "zip -r %s %s" % (outFullName, dirpath)
status = os.popen(cmd)
return outFullName
def gen_pass(length=8,enhance=False):
"""
生成默认长度为8的随机密码串
enhance=True: 加入特殊字符
"""
import random
# 去除0、O、o、z、Z、l
symbols = '!@#$%&*+/\~-_=^' # 还可以添加特殊字符,加强密码
if enhance:
payloads = ''.join([chr(x)+chr(x+32) for x in range(65,91) if x not in [79, 90, 108, 111, 122]]) + '123456789' + symbols
else:
payloads = ''.join([chr(x)+chr(x+32) for x in range(65,91) if x not in [79, 90, 108, 111, 122]]) + '123456789'
return ''.join([random.choice(payloads) for _ in range(length)])
def getYesterday():
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday
if __name__ == "__main__":
#print(gen_pass(4))
print(getYesterday().strftime('%Y%m%d'))
|
b1ba5d082dba55fa3e3babbc770673dae62f1740
|
[
"Markdown",
"Python",
"Text"
] | 9
|
Python
|
hoyin2013/exports
|
098c662664fca3eaf7c25bb7761308c43702a8c9
|
09150646cc1fc8c9259c4b21d48a1fbe752f60ed
|
refs/heads/master
|
<file_sep>package com.cg.dao;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.cg.dto.ScheduledSessions;
@Repository("trainingdao")
public class TrainingDAOImpl implements ITrainingDAO {
@Autowired
@PersistenceContext
EntityManager entityManager;
@Override
public void addSessions(ScheduledSessions t) {
// TODO Auto-generated method stub
entityManager.persist(t);
}
@Override
public List<ScheduledSessions> viewSessions() {
// TODO Auto-generated method stub
List<ScheduledSessions> list=new ArrayList<ScheduledSessions>();
Query q=entityManager.createQuery("from ScheduledSessions");
list=q.getResultList();
return list;
}
}
<file_sep>package com.cg.spring;
public class Holiday {
private int month;
private int day;
private String greeting;
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
public String getGreeting() {
return greeting;
}
public void setGreeting(String greeting) {
this.greeting = greeting;
}
public void display1()
{
System.out.println("Month:"+getMonth());
System.out.println("Day:"+getDay());
System.out.println("Greeting"+getGreeting());
}
}
<file_sep>package com.cg.spring.boot.jpa.SpringBootDataJPA;
import org.springframework.data.repository.CrudRepository;
public interface ProductRepository extends CrudRepository<Product,String> {
}
<file_sep>package com.cg.spring.core;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class DrawingApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
Circle c=(Circle)context.getBean("circle");
c.draw();
}
}
<file_sep>package com.cg.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Sales {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context=new ClassPathXmlApplicationContext("spring.xml");
CheckOut shop=(CheckOut)context.getBean("shop");
shop.display();
}
}
<file_sep>package com.cg.spring.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cg.spring.dto.Employee;
import com.cg.spring.service.EmployeeService;
@Controller
public class EmployeeController {
@Autowired
EmployeeService employeeService;
//ShowBalance
@RequestMapping(value="/showall", method=RequestMethod.GET)
public ModelAndView getAllEmployees()
{
List<Employee> list=employeeService.showEmployee();
return new ModelAndView("show","emps",list);
}
//For addition
@RequestMapping(value="/add", method=RequestMethod.GET)
public String myEmployee(@ModelAttribute("emp") Employee emp,Map<String,Object> model)
{
model.put("emp",emp);
return "addemployee";
}
@RequestMapping(value="/addemployee", method=RequestMethod.POST)
public String addEmployee(@Valid @ModelAttribute("emp") Employee emp, BindingResult result,Map<String,Object> model)
{
if(result.hasErrors())
return "addemployee";
employeeService.addEmployee(emp);
return "redirect:/showall";
}
//For Updation
@RequestMapping(value="/update0", method=RequestMethod.GET)
public String askId(@ModelAttribute("emp") Employee emp,Map<String,Object> model)
{
//model.put("emp",emp);
return "update1";
}
@RequestMapping(value="/update1", method=RequestMethod.POST)
public ModelAndView myEmployee2(@ModelAttribute("emp") Employee emp,Map<String,Object> model)
{
List<Employee> list = new ArrayList<>();
list.add(emp);
return new ModelAndView("update2","up",emp);
}
@RequestMapping(value="/update2", method=RequestMethod.POST)
public String updateEmployee(@Valid @ModelAttribute("emp") Employee emp, BindingResult result,Map<String,Object> model)
{
if(result.hasErrors())
return "update2";
employeeService.updateEmployee(emp);
return "redirect:/showall";
}
@RequestMapping(value="/delete0", method=RequestMethod.GET)
public String askId2(@ModelAttribute("emp") Employee emp,Map<String,Object> model)
{
//model.put("emp",emp);
return "delete1";
}
@RequestMapping(value="/delete1", method=RequestMethod.POST)
public String myEmployee3(@ModelAttribute("emp") Employee emp,Map<String,Object> model)
{
int id=emp.getId();
employeeService.deleteEmployee(id);
return "redirect:/showall";
}
}
<file_sep>package com.cg.spring;
import java.util.List;
public class HelloWorld {
private String message;
private List<Holiday> holiday;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Holiday> getHoliday() {
return holiday;
}
public void setHoliday(List<Holiday> holiday) {
this.holiday = holiday;
}
public void display()
{
System.out.println("Your Message");
for(Holiday h:holiday)
{
System.out.println("Month:"+h.getMonth());
System.out.println("Day:"+h.getDay());
System.out.println("Greeting:"+h.getGreeting());
}
}
}
<file_sep>package com.cg.controller;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.cg.dto.ScheduledSessions;
import com.cg.service.ITrainingService;
@Controller
public class TrainingController {
@Autowired
ITrainingService trainingservice;
@RequestMapping(value="/showall", method=RequestMethod.GET)
public ModelAndView getAllEmployees()
{
List<ScheduledSessions> list=trainingservice.viewSessions();
return new ModelAndView("ScheduledSessions1","emps",list);
}
@RequestMapping(value="/add", method=RequestMethod.GET)
public String myTraining(@ModelAttribute("emp") ScheduledSessions t,Map<String,Object> model)
{
model.put("emp",t);
return "addtraining";
}
@RequestMapping(value="/addtraining1", method=RequestMethod.POST)
public String addEmployee(@Valid @ModelAttribute("emp") ScheduledSessions t, BindingResult result,Map<String,Object> model)
{
if(result.hasErrors())
return "addtraining";
trainingservice.addSessions(t);
return "redirect:/showall";
}
@RequestMapping(value="/Success1", method=RequestMethod.GET)
public ModelAndView success2(@ModelAttribute("emp") ScheduledSessions t,Map<String,Object> model)
{
List<ScheduledSessions> list = new ArrayList<>();
list.add(t);
return new ModelAndView("Success","up",t);
}
}
<file_sep>package com.cg.dto;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@Entity
@Table
public class ScheduledSessions {
@Id
@Column(name="Id")
@NotNull(message="id is required")
private int t_id;
@Column(name="SessionName")
@NotNull(message="session name is required")
@Size(max=10,min=2)
private String t_name;
@Column(name="Duration")
@NotNull(message="duration is required")
private int t_duration;
@Column(name="Faculty")
@NotNull(message="faculty name is required")
private String t_faculty;
@Column(name="Mode")
@NotNull(message="mode is required")
private String t_mode;
public int getT_id() {
return t_id;
}
public void setT_id(int t_id) {
this.t_id = t_id;
}
public String getT_name() {
return t_name;
}
public void setT_name(String t_name) {
this.t_name = t_name;
}
public int getT_duration() {
return t_duration;
}
public void setT_duration(int t_duration) {
this.t_duration = t_duration;
}
public String getT_faculty() {
return t_faculty;
}
public void setT_faculty(String t_faculty) {
this.t_faculty = t_faculty;
}
public String getT_mode() {
return t_mode;
}
public void setT_mode(String t_mode) {
this.t_mode = t_mode;
}
public ScheduledSessions(int t_id, String t_name, int t_duration, String t_faculty, String t_mode) {
super();
this.t_id = t_id;
this.t_name = t_name;
this.t_duration = t_duration;
this.t_faculty = t_faculty;
this.t_mode = t_mode;
}
public ScheduledSessions()
{
}
@Override
public String toString() {
return "TrainingDTO [t_id=" + t_id + ", t_name=" + t_name + ", t_duration=" + t_duration + ", t_faculty="
+ t_faculty + ", t_mode=" + t_mode + "]";
}
}
|
49b926b93d493efc947b52cc691a4302bc5c7fe9
|
[
"Java"
] | 9
|
Java
|
ricksen100/Spring-Projects
|
6da09ccd0ec5b179a330f91937c2d99c85855011
|
a2680c193091375c2c651eef8e71273aaac05a33
|
refs/heads/master
|
<file_sep>@javax.xml.bind.annotation.XmlSchema(namespace = "http://dao.ws.soap.pupeu.edu.pe/")
package pe.edu.pupeu.soap.ws.dao;
<file_sep>package pe.edu.pupeu.soap.ws.cliente;
import java.util.List;
import pe.edu.pupeu.soap.ws.daoImp.ClienteDao;
import pe.edu.pupeu.soap.ws.daoImp.ClienteDaoImpService;
import pe.edu.pupeu.soap.ws.dao.Cliente;
public class ClienteService {
public static void main(String[] args) {
ClienteDaoImpService cds=new ClienteDaoImpService();
ClienteDao cd=cds.getClienteDaoImpPort();
System.out.println("Cliente:");
List<Cliente>clientes=cd.readCliente("2021-05-02","2021-05-15",1);
for (int i =0; i<clientes.size(); i++) {
System.out.println("Cliente: "+clientes.get(i).getNombres()+" "+clientes.get(i).getApellidos());
System.out.println("Producto: "+clientes.get(i).getNomprod());
System.out.println("Cantidad: "+clientes.get(i).getCantidad());
System.out.println("Precio: "+clientes.get(i).getPrecio());
}
}
}
|
45d014f8c8730e1f0d17c1e4ff7e313e45bb7165
|
[
"Java"
] | 2
|
Java
|
EliasMH123/Soap-reporteventas
|
9a8d0ad302f88d20e14cefb880b7a9c2757fbf1b
|
b29b2e30ba5370322bc18fbc6855604cf73b9dd4
|
refs/heads/master
|
<file_sep>import React from 'react';
import d3 from 'd3';
import $ from 'jquery';
export default class Layout extends React.Component{
constructor(){
super();
this.state = {id: "test"};
}
componentDidMount() {
this.serverRequest = $.get(this.props.source, function (res) {
var result = JSON.parse(res);
var dataset = result.data.reduce(function(all,item,index){
all.push(item[1]);
return all;
},[]);
//Width and height
var w = 1200;
var h = 900;
var barPadding = 1;
//Create SVG element
var svg = d3.select("span")
.append("svg")
.attr("width", w)
.attr("height", h);
svg.selectAll("rect")
.data(dataset)
.enter()
.append("rect")
.attr("x", function(d, i) {
return i * (w / dataset.length);
})
.attr("y", function(d) {
return h - d;
})
.attr("width", w / dataset.length - barPadding)
.attr("height", function(d) {
return d;
})
.attr("fill", function(d) {
return "rgb(0, 0, " + (d * 10) + ")";
});
svg.selectAll("text")
.data(dataset)
.enter()
.append("text")
.text(function(d) {
return d;
})
.attr("x", function(d, i) {
return i * (w / dataset.length) + 5; // +5
})
.attr("y", function(d) {
return h - (d) + 15; // +15
})
.attr("font-family", "sans-serif")
.attr("font-size", "11px")
.attr("fill", "white")
.attr("text-anchor", "middle");
this.setState({
id: result.id
});
}.bind(this));
}
componentWillUnmount() {
this.serverRequest.abort();
}
render(){
return(
<span className="chart">
</span>
);
}
}
<file_sep># d3-bar-chart
##console commands
###setup
git clone https://github.com/mstaebler/d3-bar-chart.git
cd d3-bar-chart
npm i
###dev server
npm run dev
http://localhost:8080
###build code
webpack
|
3927373487044f9e2c9461ad3a3a86583ea3dc69
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
mstaebler/d3-bar-chart
|
2210ad8e6c8b8d5af6bb47130e371c9a5c8fae2a
|
d233fdacf82222e3a8a66444f09c4076dcc8d1f0
|
refs/heads/master
|
<file_sep><?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
class CreateWorksTable extends Migration {
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('works', function(Blueprint $t)
{
$t->increments('id');
$t->string('title');
$t->text('description')->nullable();
$t->string('client')->nullable();
$t->date('date_project')->nullable();
$t->string('service')->nullable();
$t->string('image')->nullable();
$t->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::drop('works');
}
}
<file_sep><?php
// Composer: "fzaninotto/faker": "v1.3.0"
use Faker\Factory as Faker;
class WorksTableSeeder extends Seeder {
public function run()
{
$faker = Faker::create();
$images = [
'cabin', 'cake', 'circus', 'game', 'safe', 'submarine'
];
DB::table('works')->truncate();
foreach($images as $image)
{
Work::create([
'title' => $faker->sentence(3),
'date_project' => $faker->dateTime,
'client' => $faker->company,
'description' => $faker->paragraph(2),
'image' => 'freelancer/img/portfolio/'.$image.'.png',
'service' => $faker->sentence(2)
]);
}
}
}
<file_sep><?php
class Work extends \Eloquent {
// Add your validation rules here
public static $rules = [
'title' => 'required',
'date_project' => 'required|date|date_format:yy-m-d'
];
// Don't forget to fill this array
protected $fillable = ['title', 'date_project', 'service', 'client'];
protected $dates = array('date_project');
public static function boot()
{
parent::boot();
Work::saving(function($work){
if( ! Input::hasFile('image') )
return;
$image = Input::file('image');
if(is_null($work->id))
$suffix = 'uploads/'.uniqid().'.'.$image->getClientOriginalExtension();
else
$suffix = $work->image;
$work->image = $suffix;
$path = public_path().'/'.$suffix;
//dd($image->getRealPath());
Image::make($image->getRealPath())//->resize(400, 290)
->save($path);
});
}
}
|
259f7c51008d23fdefacf197f1a32a3843e4deba
|
[
"PHP"
] | 3
|
PHP
|
sheikhu/appsite
|
f0df1b6bdedbf9b8b54733f4e65327a6826e11d6
|
019eb5e941dc3266bce6162a684d24ebaf2ad4bb
|
refs/heads/master
|
<repo_name>zhaopingfu/TestDemo<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/fragments/PopularFragment.kt
package com.zhaopf.testlazyfragment.fragments
import android.os.Bundle
import android.util.Log
import android.view.View
import com.zhaopf.testlazyfragment.adapter.PopularVpAdapter
import com.zhaopf.testlazyfragment.databinding.FragmentPopularLayoutBinding
/**
* @author pingfu.zhao
* @date 2020-01-14 10:46
*/
class PopularFragment : BaseFragment<FragmentPopularLayoutBinding>() {
private val TAG = "PopularFragment"
private var mAdapter: PopularVpAdapter? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mAdapter = PopularVpAdapter(childFragmentManager)
with(binding.vpVertical) {
offscreenPageLimit = 6
adapter = mAdapter
}
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
mAdapter?.mCurrentPrimaryItem?.userVisibleHint = isVisibleToUser
}
override fun fetchData() {
Log.d(TAG, "fetchData: ")
}
override fun onUiShown() {
Log.d(TAG, "onUiShown: ")
}
override fun onUiHidden() {
Log.d(TAG, "onUiHidden: ")
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/ObjectAnimatorActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.transition.TransitionManager
import android.view.Gravity
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.meta.testmotionlayout.databinding.ActivityObjectAnimatorBinding
class ObjectAnimatorActivity : AppCompatActivity() {
private var toggle = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityObjectAnimatorBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.view.setOnClickListener { child ->
TransitionManager.beginDelayedTransition(child.parent as ViewGroup)
val viewGroup = child.parent as ViewGroup
if (viewGroup is FrameLayout) {
val layoutParams = child.layoutParams as FrameLayout.LayoutParams
if (toggle) {
layoutParams.gravity = Gravity.END or Gravity.CENTER_VERTICAL
} else {
layoutParams.gravity = Gravity.START or Gravity.CENTER_VERTICAL
}
child.layoutParams = layoutParams
} else if (viewGroup is ConstraintLayout) {
// ConstraintSet().apply {
// connect(child.id, ConstraintSet.END, ConstraintSet.PARENT_ID, ConstraintSet.END)
// applyTo(viewGroup)
// }
// ConstraintProperties(child)
// .connect(ConstraintProperties.END, ConstraintProperties.PARENT_ID, ConstraintProperties.END,0)
// .apply()
// ConstraintSet 和 ConstraintProperties 有bug,暂时只能先用这种方式
val params = child.layoutParams as ConstraintLayout.LayoutParams
params.startToStart = -1
params.endToEnd = ConstraintLayout.LayoutParams.PARENT_ID
child.layoutParams = params
}
toggle = !toggle
}
}
}
<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/FullScreenObserver.java
package com.zhaopf.testlazyfragment;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleObserver;
import androidx.lifecycle.OnLifecycleEvent;
import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.zhaopf.testlazyfragment.util.DeviceUtil;
import com.zhaopf.testlazyfragment.util.FullScreenUtil;
import com.zhaopf.testlazyfragment.util.NotchSizeUtil;
/**
* @author zhaopf
* @date 2019-08-08
*/
public class FullScreenObserver implements LifecycleObserver {
private AppCompatActivity mAppCompatActivity;
/**
* 是否全屏模式
*/
private boolean isFullScreenMode = true;
public FullScreenObserver(@NonNull AppCompatActivity appCompatActivity) {
this.mAppCompatActivity = appCompatActivity;
mAppCompatActivity.getLifecycle().addObserver(this);
}
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
mAppCompatActivity.getLifecycle().removeObserver(this);
mAppCompatActivity = null;
}
/**
* 全屏沉浸
*/
public void fullScreen(boolean isFullScreenMode) {
this.isFullScreenMode = isFullScreenMode;
}
public void setStatusBarTranslate() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
setStatusBarUpperApi21();
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setStatusBarUpperApi19();
}
}
/**
* 5.0版本以上
*/
private void setStatusBarUpperApi21() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return;
}
Window window = mAppCompatActivity.getWindow();
// 设置透明状态栏,这样才能让 ContentView 向上
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 需要设置这个 flag 才能调用 setStatusBarColor 来设置状态栏颜色
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
ViewGroup mContentView = mAppCompatActivity.findViewById(Window.ID_ANDROID_CONTENT);
View mChildView = mContentView.getChildAt(0);
if (mChildView != null) {
// 注意不是设置 ContentView 的 FitsSystemWindows, 而是设置 ContentView 的第一个子 View . 使其不为系统 View 预留空间.
mChildView.setFitsSystemWindows(false);
}
}
/**
* 设置OPPO手机状态栏字体为黑色(colorOS3.0,6.0以下部分手机)
*/
private static final int SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT = 0x00000010;
/**
* 4.4 - 5.0版本
*/
private void setStatusBarUpperApi19() {
Window window = mAppCompatActivity.getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
mAppCompatActivity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
// 创建状态栏的管理实例
SystemBarTintManager tintManager = new SystemBarTintManager(mAppCompatActivity);
// 激活状态栏设置
tintManager.setStatusBarTintEnabled(true);
tintManager.setStatusBarAlpha(1);
}
private int getStatusBarHeight() {
int result = 0;
int resId = mAppCompatActivity.getResources().getIdentifier("status_bar_height", "dimen", "android");
if (resId > 0) {
result = mAppCompatActivity.getResources().getDimensionPixelSize(resId);
}
return result;
}
/**
* @param colorRes 这个参数暂时没有用,不知道当时为什么弄这个变量
*/
public void applyKitKatTranslucencyWithColor(int colorRes) {
// 如果是华为的 8.0或 8.1的刘海屏 就拿到decorView 的第一个子view (是LinearLayout)
// 在它的顶部add 一个黑色的Linearlayout(如果已经存在的话,就不加了) 为了把我们的contentView 顶下去
if (NotchSizeUtil.hasNotchInScreen(mAppCompatActivity) && Build.VERSION.SDK_INT <= 27) {
ViewGroup decorView = (ViewGroup) mAppCompatActivity.getWindow().getDecorView();
LinearLayout childLinear = (LinearLayout) decorView.getChildAt(0);
LinearLayout linearLayout = new LinearLayout(mAppCompatActivity);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, getStatusBarHeight());
linearLayout.setLayoutParams(lp);
linearLayout.setBackgroundColor(Color.BLACK);
if (childLinear.getChildAt(0) instanceof LinearLayout) {
return;
} else {
childLinear.addView(linearLayout, 0);
}
return;
}
// 这行代码暂时没有用,不知道当时为什么弄这个变量
// int mColorRes = colorRes;
// KitKat translucent navigation/status bar.
if (isFullScreenMode) {
// 全屏-隐藏statusBar和navigationBar的
Window window = mAppCompatActivity.getWindow();
FullScreenUtil.fullScreenSet(window);
} else {
// 全屏-只隐藏statusBar的,隐藏navigationBar的
int visibility = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_FULLSCREEN;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
visibility |= View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
}
mAppCompatActivity.getWindow().getDecorView().setSystemUiVisibility(visibility);
}
}
public void applyKitKatTranslucencyColor(int color) {
//onDestroy 会把这个对象置空
if (mAppCompatActivity == null) {
return;
}
// KitKat translucent navigation/status bar.
if (isFullScreenMode) {
Window window = mAppCompatActivity.getWindow();
FullScreenUtil.fullScreenSet(window);
return;
}
if ("oppo".equalsIgnoreCase(DeviceUtil.getROMName())
|| "vivo".equalsIgnoreCase(DeviceUtil.getROMName())) {
setOppoStatusBarTextColor(color, color != R.color.lucky_toolbar_brown
&& color != R.color.black, mAppCompatActivity);
return;
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
SystemBarTintManager mTintManager = new SystemBarTintManager(mAppCompatActivity);
mTintManager.setStatusBarTintEnabled(true);
// 判断是否为小米手机
if (DeviceUtil.isMIUI() || DeviceUtil.isFlyme()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mAppCompatActivity.getWindow().getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
mTintManager.setStatusBarTintColor(color);
DeviceUtil.setMIUIStatusBarLightMode(mAppCompatActivity.getWindow(), true);
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
// 通知栏所需颜色
mTintManager.setStatusBarTintColor(
ContextCompat.getColor(mAppCompatActivity, R.color.white));
// 去除半透明状态栏
mAppCompatActivity.getWindow()
.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 一般配合fitsSystemWindows()使用,
// 或者在根部局加上属性android:fitsSystemWindows="true", 使根部局全屏显示
mAppCompatActivity.getWindow()
.getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
} else {
mTintManager.setStatusBarTintColor(color);
mAppCompatActivity.getWindow()
.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// 去除半透明状态栏
mAppCompatActivity.getWindow()
.getDecorView()
.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
// 一般配合fitsSystemWindows()使用,
// 或者在根部局加上属性android:fitsSystemWindows="true", 使根部局全屏显示
mAppCompatActivity.getWindow()
.setStatusBarColor(Color.TRANSPARENT);
}
}
}
}
private static void setOppoStatusBarTextColor(int color, boolean lightStatusBar, Activity activity) {
Window window = activity.getWindow();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
}
int vis = window.getDecorView().getSystemUiVisibility();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (lightStatusBar) {
vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
window.setBackgroundDrawable(new ColorDrawable(color));
} else {
vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
window.setBackgroundDrawable(new ColorDrawable(color));
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
if (lightStatusBar) {
vis |= SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT;
window.setBackgroundDrawable(new ColorDrawable(color));
} else {
vis &= ~SYSTEM_UI_FLAG_OP_STATUS_BAR_TINT;
window.setBackgroundDrawable(new ColorDrawable(color));
}
}
window.getDecorView().setSystemUiVisibility(vis);
}
public void applyKitKatTranslucency() {
applyKitKatTranslucencyWithColor(R.color.white);
}
private void setTranslucentStatus(boolean on) {
Window win = mAppCompatActivity.getWindow();
WindowManager.LayoutParams winParams = win.getAttributes();
final int bits = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
if (on) {
winParams.flags |= bits;
} else {
winParams.flags &= ~bits;
}
win.setAttributes(winParams);
}
}<file_sep>/TestStyleAndTheme/app/src/main/java/com/zhaopf/teststyleandtheme/Theme.kt
package com.zhaopf.teststyleandtheme
import androidx.appcompat.app.AppCompatDelegate
/**
* @author Flywith24
* @date 2020/6/24
* time 10:02
* description
*/
enum class Theme(val mode: Int) {
LIGHT(AppCompatDelegate.MODE_NIGHT_NO),
DARK(AppCompatDelegate.MODE_NIGHT_YES),
SYSTEM(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM)
}<file_sep>/GetLauncherPackageName/app/src/main/java/com/zhaopf/getlauncherpackagename/MApplication.kt
package com.zhaopf.getlauncherpackagename
import android.app.Activity
import android.app.Application
import android.os.Bundle
/**
*
* @author PingFu.Zhao
* 2019/7/29
*/
class MApplication : Application() {
companion object {
/**
* 记录当前显示的页面的个数
*/
var currVisibleActivityCount = 0
/**
* 是否是从桌面拉起的
*/
var isFromDeskop = false
}
override fun onCreate() {
super.onCreate()
// 监听生命周期,判断是否是从桌面拉起来的
registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacksAdapter() {
override fun onActivityStarted(activity: Activity?) {
super.onActivityStarted(activity)
// 如果之前没有页面显示,那么就是从桌面拉起来的
isFromDeskop = currVisibleActivityCount == 0
currVisibleActivityCount++
}
override fun onActivityStopped(activity: Activity?) {
super.onActivityStopped(activity)
currVisibleActivityCount--
}
})
}
}
/**
* 写的时候继承自这个,只需要重写需要的方法就可以了
*/
open class ActivityLifecycleCallbacksAdapter : Application.ActivityLifecycleCallbacks {
override fun onActivityPaused(activity: Activity?) {
}
override fun onActivityResumed(activity: Activity?) {
}
override fun onActivityStarted(activity: Activity?) {
}
override fun onActivityDestroyed(activity: Activity?) {
}
override fun onActivitySaveInstanceState(activity: Activity?, outState: Bundle?) {
}
override fun onActivityStopped(activity: Activity?) {
}
override fun onActivityCreated(activity: Activity?, savedInstanceState: Bundle?) {
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/4.this_异常.kt
package com.meta.kotlinstudy.基础部分
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.meta.kotlinstudy.MainActivity
class MyActivity : Activity() {
private val mRecyclerView by lazy { RecyclerView(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mRecyclerView.run {
layoutManager = GridLayoutManager(context, 3).apply {
orientation = RecyclerView.HORIZONTAL
this@apply.spanCount
this@run.hasFixedSize()
// 获取外面的,要获取java的class需要 MainActivity::class.java
this@MyActivity.startActivity(Intent(context, MainActivity::class.java))
}
}
}
}
class MyException(message: String) : Exception(message)
//// throw 表达式的类型是特殊类型 Nothing.该类型没有值,而是用于标记永远不能达到的代码位置
fun fail(message: String): Nothing {
throw MyException(message)
}
fun testException() {
// fail("fail")
// try-表达式的返回值是 try 块中的最后一个表达式或者是(所有)catch 块中的最后一个表达式。
// finally 块中的内容不会影响表达式的结果
val iStr: String? = try {
"hello"
throw MyException("error")
} catch (e: MyException) {
"catch 中的值"
null
} finally {
"finally中的值"
}
println(iStr)
// 下面两种方式效果一样
// val s = iStr?.length ?: throw MyException("iStr.length is null")
// println(s)
// val ss = iStr?.length ?: fail("iStr.length is null")
// println(ss)
// val x = null // x 具有类型 Nothing?
// val l = listOf(null) // l 具有类型 List<Nothing?>
}
//fun main(args: Array<String>) {
// testException()
//}<file_sep>/TestGradleTaskOrder/settings.gradle
include ':app'
rootProject.name='TestGradleTaskOrder'
<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/PlayVideo.kt
package com.zhaopf.testexoplayer
import android.net.Uri
import com.google.android.exoplayer2.ExoPlayer
import com.google.android.exoplayer2.ExoPlayerFactory
import com.google.android.exoplayer2.Player
import com.google.android.exoplayer2.source.ProgressiveMediaSource
import com.google.android.exoplayer2.upstream.DataSource
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory
import com.google.android.exoplayer2.util.Util
val mExoPlayer by lazy {
ExoPlayerFactory.newSimpleInstance(MyApp.instance).apply {
repeatMode = Player.REPEAT_MODE_ONE
}
}
private val dataSourceFactory: DataSource.Factory by lazy {
DefaultDataSourceFactory(
MyApp.instance,
Util.getUserAgent(MyApp.instance, "yourApplicationName")
)
}
private val progressiveMediaSourceFactory by lazy {
ProgressiveMediaSource.Factory(dataSourceFactory)
}
fun ExoPlayer.prepare(proxyUrl: String) {
val videoSource = progressiveMediaSourceFactory.createMediaSource(Uri.parse(proxyUrl))
prepare(videoSource)
}<file_sep>/RoomWordSample/app/src/main/java/com/zhaopingfu/roomwordsample/WordRepository.kt
package com.zhaopingfu.roomwordsample
import androidx.annotation.WorkerThread
import kotlinx.coroutines.flow.Flow
/**
*
* @author zhaopingfu
* @date 2021-07-22 17:02
*/
class WordRepository(private val dao: WordDao) {
val allWords: Flow<List<Word>> = dao.getAlphabetizedWords()
@Suppress("RedundantSuspendModifier")
@WorkerThread
suspend fun insert(word: Word) {
dao.insert(word)
}
}
<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/fragments/VideoItemFragment.kt
package com.zhaopf.testlazyfragment.fragments
import android.os.Bundle
import android.util.Log
import android.view.View
import com.zhaopf.testlazyfragment.databinding.FragmentChallengeLayoutBinding
/**
* @author pingfu.zhao
* @date 2020-01-14 10:46
*/
class VideoItemFragment : BaseFragment<FragmentChallengeLayoutBinding>() {
private var TAG = "VideoItemFragment"
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
TAG = arguments?.getString("TAG") ?: "VideoItemFragment"
binding.btnChallenge.text = TAG
}
override fun fetchData() {
Log.d(TAG, "fetchData: ")
}
override fun onUiShown() {
Log.d(TAG, "onUiShown: ")
}
override fun onUiHidden() {
Log.d(TAG, "onUiHidden: ")
}
}
<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/viewpager2/MainActivity.kt
package com.zhaopf.viewpager2.viewpager2
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.tabs.TabLayoutMediator
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
viewpager2.apply {
offscreenPageLimit = 5
orientation = ViewPager2.ORIENTATION_HORIZONTAL
adapter = ViewPagerFragmentStateAdapter(
supportFragmentManager,
lifecycle,
5
)
}
TabLayoutMediator(tabLayout, viewpager2) { tab, position ->
tab.text = "${position + 1}"
}.attach()
}
}
class ViewPagerFragmentStateAdapter(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val size: Int
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int = size
override fun createFragment(position: Int): Fragment =
PageFragment.newInstance(position)
}<file_sep>/TestOptimizePlugin/app/src/test/java/com/meta/testoptimizeplugin/Test.java
package com.meta.testoptimizeplugin;
import com.tinify.Source;
import com.tinify.Tinify;
import java.io.File;
import java.io.IOException;
/**
* @author zhaopf
* @date 2019-08-16
*/
public class Test {
@org.junit.Test
public void test2() {
long tempLength = 29_104;
long length = 78_301;
long cha = length - tempLength;
String format = String.format("%.2f%%", (float) cha / length * 100F);
System.out.println(format);
}
@org.junit.Test
public void test() {
// File file = new File("C:/Users/metaapp/Desktop/a/k.png");
File file = new File("C:/Users/metaapp/Desktop/a/f.jpeg");
File tempFile = new File(getTempFileName(file));
System.out.println(file.getAbsolutePath());
System.out.println(tempFile.getAbsolutePath());
try {
Tinify.setKey("<KEY>");
Source source = Tinify.fromFile(file.getAbsolutePath());
source.toFile(tempFile.getAbsolutePath());
if (tempFile.length() < file.length()) {
long cha = file.length() - tempFile.length();
double percent = (double) cha / file.length() * 100F;
String format = String.format("%.2f%%", percent);
System.out.println("压缩成功, 压了 " + format);
} else {
System.out.println("压缩之后大小: " + tempFile.length() + " 压缩之前大小: " + file.length());
}
} catch (IOException e) {
e.printStackTrace();
}
}
private static String getTempFileName(File file) {
String str = file.getAbsolutePath();
// 根据最后一个 / 分成两段
int lastIndexOf = str.lastIndexOf('\\');
String dirName = str.substring(0, lastIndexOf);
String fileName = str.substring(lastIndexOf + 1);
// 把后半段根据 . 分成两段
int pointIndex = fileName.lastIndexOf(".");
String fileNameBefore = fileName.substring(0, pointIndex);
String fileNameAfter = fileName.substring(pointIndex + 1);
// 拼接新的文件名
return dirName + "/temp_" + fileNameBefore + "." + fileNameAfter;
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/WithDrawerLayoutActivity.kt
package com.meta.testmotionlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.drawerlayout.widget.DrawerLayout
import com.meta.testmotionlayout.databinding.ActivityWithDrawerLayoutBinding
class WithDrawerLayoutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityWithDrawerLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {
override fun onDrawerStateChanged(newState: Int) {
}
override fun onDrawerSlide(drawerView: View, slideOffset: Float) {
binding.motionLayout.progress = slideOffset
}
override fun onDrawerClosed(drawerView: View) {
}
override fun onDrawerOpened(drawerView: View) {
}
})
}
}
<file_sep>/GetLauncherPackageName/README.md
* 获取手机中所有的包名
* 获取手机中所有的 `launcher` 的包名
* 获取页面的跳转来源,是从哪里跳转过来的(这个现在还没办法获取到。。)
* 判断是否是从桌面拉起来的
- 目前发现 `registerActivityLifecycleCallbacks` 方式还可以,但不知道有没有更好的方式
- `registerActivityLifecycleCallbacks` 里面的生命周期方法会优先执行, 而 `activity` 里面的生命周期方法会在后面执行
- 用变量 `count` 记录当前显示的页面个数, `onStart() + 1` , `onStop() - 1` ,这样当为 0 的时候就表示是从桌面拉起的
### 最后的解决办法
通过 `activity` 的 `getReferrer()` 方法能够获取到是从那个包跳转过来的, 但是只有 `API 22` 才支持<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/test/FunctionalProgramming.kt
package com.meta.kotlinstudy.test
/**
* 函数式编程
*/
fun Int.sample(a: Float, b: Double): Long = this * (a + b).toLong()
val function: Int.(Float, Double) -> Long = Int::sample
fun sample(a: Int.(Float, Double) -> Long): Long = 3.a(1f, 2.0)
fun main() = println(sample(function))
fun main2() = println(sample(Int::sample))
/**
* 成员引用
*/
class Test {
fun functionParam(a: Int) = println(a)
}
fun function1(a: Test.(Int) -> Unit) = Test().a(6)
fun function2(a: (Int) -> Unit) = a(6)
fun test() {
/**
* 使用成员引用,及时用类名引用成员函数(扩展函数)
* 此时 Test::functionParam 的类型为 Test.(Int) -> Unit
*/
function1(Test::functionParam)
/**
* 使用绑定引用,即直接使用对象去引用成员函数(扩展函数)
* 此时 test::functionParam 的类型为 (Int) -> Unit
*/
val test = Test()
function2(test::functionParam)
}<file_sep>/TestGradleTaskOrder/app/pre-commit
#!/bin/sh
# 确保中文日志显示正常
export LANG="zh_CN.UTF-8"
echo "开始检测"
# 获取暂存区 .java 结尾的文件
STAGE_FILES=$(git diff --cached --name-only --diff-filter=ACM -- '*.java')
annotationAdd='@Add'
annotationAddPackageImport='import com.meituan.robust.patch.annotaion.Add;'
annotationModify='@Modify'
annotationModifyPackageImport='import com.meituan.robust.patch.annotaion.Modify;'
for file in ${STAGE_FILES[@]}
do
if cat $file | grep $annotationAdd>/dev/null
then
echo "$file 发现 $annotationAdd 请删除后再提交"
exit 1
elif cat $file | grep "$annotationAddPackageImport">/dev/null
then
echo "$file 发现 $annotationAddPackageImport 请删除后再提交"
exit 1
elif cat $file | grep $annotationModify>/dev/null
then
echo "$file 发现 $annotationModify 请删除后再提交"
exit 1
elif cat $file | grep "$annotationModifyPackageImport">/dev/null
then
echo "$file 发现 $annotationModifyPackageImport 请删除后再提交"
exit 1
fi
done
exit 0<file_sep>/TestBaseQuickAdapter/app/src/main/java/com/zhaopf/testbasequickadapter/MMultipleAdapter.kt
package com.zhaopf.testbasequickadapter
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
/**
*
* @author PingFu.Zhao
* 2019/7/29
*/
class MMultipleAdapter(data: MutableList<DataItemBean>) :
BaseMultiItemQuickAdapter<DataItemBean, BaseViewHolder>(data) {
init {
addItemType(0x10, R.layout.item_rv_big_pic)
addItemType(0x20, R.layout.item_rv_small_pic)
}
override fun convert(helper: BaseViewHolder, item: DataItemBean) {
when (helper.itemViewType) {
0x10 -> {
helper.setImageResource(R.id.iv_big_pic, R.mipmap.ic_launcher)
}
0x20 -> {
helper.setImageResource(R.id.iv_small_pic, R.mipmap.ic_launcher)
}
}
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/2.函数_变量_类_枚举_类型转换_控制流.kt
package com.meta.kotlinstudy.基础部分
import android.graphics.drawable.ColorDrawable
import android.view.View
import android.widget.ImageView
import android.widget.TextView
/**
* Kotlin 中作用域默认是 public,
*
* 声明类,方法 默认都是 final 的,如果需要让别的类继承或重写,需要加 open 关键字
*
* 在一个类里面声明另一个类,默认两个类是没有关系的,和 Java 的内部类加了static 一样,如果要变成内部类需要加 inner 关键字
*/
/**
* 直接将方法写在文件里面,称为顶层函数,这里不用加public,默认就是public
* 函数接收一个 String 数组
*
* 返回值类型默认是Unit,相当于java中的 void
*
* 这里返回值写了Int,表示返回值是Int,Kotlin中只有大写的类型,没有java中的Int等小写的基础数据类型
*/
//fun main(args: Array<String>): Int {
// println(max(1, 2))
// return 1
//}
/**
* 定义方法
*
* 这里的返回值可以进行推断出来,可以省略
*
* 方法参数可以有默认值
*
* 这里 if 语句的最后一行默认当做返回值
*/
fun max(x: Int = 0, y: Int) = if (x > y) x else y
/**
* 顶层变量,声明变量可以省略类型,可以推断出来
*/
// 只有get, final
val name = "Jack"
val name2: String = "Tom"
val name3: String? = null
val name4
get() = "Bob"
// 有 set/get
var age = 20
var age2: Int = 20
var age3 = 0
get() {
return field
}
set(value) {
field = value
}
fun testField() {
// 声明变量可以
var nickName = "Jason"
// 字符串拼接使用 $,这里的获取值是静态获取,当走完这一行之后就已经确定了
// 哪怕在后面修改了nickName的值,str的值也不会改变
val str = "name: $name age: $age nickName: $nickName"
println(str)
nickName = "Danny"
println("nickName: $nickName str: $str")
}
/**
* 在Activity中声明变量一般还会用到 lateinit 和 by lazy{}
*/
// 不可空对象声明的时候需要赋值,但是需要findViewById
lateinit var tv: TextView
// 用到的时候才回去new出来这个对象
val strList by lazy { ArrayList<String>() }
/**
* Kotlin中的字符串
*/
val strHello = "Hello"
val strWorld = "World"
val strHelloWorld = "$strHello $strWorld"
val strMultiLine = """
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
""".trimMargin()
fun testStr() {
// ello World
println(strHelloWorld.substring(1))
// lo World
println(strHelloWorld.substringAfter('l'))
// d
println(strHelloWorld.substringAfterLast('l'))
// He
println(strHelloWorld.substringBefore("l"))
// Hello Wor
println(strHelloWorld.substringBeforeLast('l'))
// Kotlin为String提供了很多的扩展函数,比如各种replace等等
}
/**
* 这里的参数如果不加可见性修饰符就只是作为参数,否则是类的成员
*
* 如果类里面没有函数,可以省略类的大括号
*
* 这里变量访问的时候都是访问的get/set方法
*
* Person("test").name 实际上是调用的 getName 方法,有点类似 groovy
*/
class Person(var name: String?)
/**
* 空安全
*/
fun testNull(person: Person?) {
person ?: doSomething() // 如果person为空做一些事
person ?: return // 如果person为空直接返回
val person2: Person? = null
val length = person2?.name?.length ?: 0
val length2 = person2?.name?.length ?: getLength()
}
fun doSomething() {}
fun getLength() = 0
/**
* ==: 在 Kotlin 中 == 比较的是值,就相当于java中的equals
* ===: 比较的是内存地址
*/
fun testEquals() {
val str1 = String("Hello World.".toCharArray())
val str2 = String("Hello World.".toCharArray())
val str3 = "Hello World."
val str4 = "Hello World."
println(str1 == str2)
println(str1 === str2)
println(str3 === str4)
}
//fun main(args: Array<String>) {
// testEquals()
//}
/**
* enum 是一个软关键字,只有跟在 class 前面才是一个关键字
*/
// 这里不是关键字
val enum = 1
enum class Color(val r: Int, val g: Int, val b: Int) {
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255);
// 如果要在枚举中定义函数,需要用分号将上面的常量和方法分隔开
// 这可能是kotlin中唯一需要写分号的地方了
fun rgb() = r + g + b
}
fun test类型推断() {
// Kotlin 中有类型推断
val view: View? = null
if (view is ImageView) {
view.setImageDrawable(ColorDrawable(android.graphics.Color.RED))
}
if (view !is TextView) {
// 这里不是TextView
} else {
view.text = "这里是TextView"
}
}
/**
* 控制语句
*/
fun testControlStatement(color: Color) {
// Java 中的 switch 被换成了 when
when (color) {
Color.RED -> println("red")
// 如果有多个条件,逗号隔开
Color.GREEN, Color.BLUE -> println("green or blue")
// 如果有多行,可以加大括号
else -> {
println("other 1")
println("other 2")
}
}
when {
1 + 1 == 3 -> println("11")
test() -> println("22")
else -> println("33")
}
}
fun test() = true
fun max2(x: Int = 0, y: Int): Int = when {
x > y -> x
else -> y
}
fun testFor() {
// 这里的区间是 [0, 10],注意两边都是闭区间,总共执行11次循环
for (i in 0..10) {
}
// [0, 10)
for (i in 0 until 10) {
}
// 从 0 到 10,每次 +2 += 2
for (i in 0 until 10 step 2) {
}
// 从 10 到 0,每次 -2 -= 2
for (i in 10 downTo 0 step 2) {
}
// 这里的 0..10 是一个 IntRange
val intRange: IntRange = 1..10
// 跳出
outLoop@ for (i in intRange) {
if (i == 5) {
continue@outLoop
}
innerLoop@ for (j in intRange) {
if (i == 5) {
break@innerLoop
}
}
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/circular_reveal_helper/CircularRevealHelper.kt
package com.meta.testmotionlayout.circular_reveal_helper
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.ViewAnimationUtils
import androidx.constraintlayout.widget.ConstraintHelper
import androidx.constraintlayout.widget.ConstraintLayout
import kotlin.math.hypot
class CircularRevealHelper : ConstraintHelper {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor (context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override fun updatePostLayout(container: ConstraintLayout?) {
super.updatePostLayout(container)
container ?: return
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return
for (i in 0 until mCount) {
val view = container.getViewById(referencedIds[i])
val animator = if (i == 0) {
ViewAnimationUtils.createCircularReveal(
view, 0, 0, 0f,
hypot(view.height.toDouble(), view.width.toDouble()).toFloat()
)
} else {
ViewAnimationUtils.createCircularReveal(
view,
view.width / 2,
view.height / 2,
0f,
hypot(view.height / 2.0, view.width / 2.0).toFloat()
)
}
animator.duration = 1500L
animator.start()
}
}
}<file_sep>/CustomView/app/src/main/java/com/zhaopingfu/customview/MainActivity.kt
package com.zhaopingfu.customview
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.zhaopingfu.customview.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val binding by lazy { ActivityMainBinding.inflate(layoutInflater) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
binding.btnCustomFrameLayout.setOnClickListener {
setContentView(R.layout.layout_custom_framelayout)
}
binding.btnCustomLinearLayout.setOnClickListener {
setContentView(R.layout.layout_custom_linearlayout)
}
binding.btnCustomLinearLayoutHorizontal.setOnClickListener {
setContentView(R.layout.layout_custom_linearlayout_horizontal)
}
binding.btnSimpleNestedScrollview.setOnClickListener {
setContentView(R.layout.layout_simple_nested_scrollview)
}
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/FlipActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.motion.widget.MotionLayout
import androidx.constraintlayout.motion.widget.TransitionAdapter
import com.meta.testmotionlayout.databinding.ActivityFlipBinding
class FlipActivity : AppCompatActivity() {
private val TAG = "FlipActivity"
private lateinit var binding: ActivityFlipBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityFlipBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.root.setTransitionListener(object : TransitionAdapter() {
override fun onTransitionChange(
motionLayout: MotionLayout?,
startId: Int,
endId: Int,
progress: Float
) {
super.onTransitionChange(motionLayout, startId, endId, progress)
Log.d(TAG, "onTransitionChange: progress: $progress")
}
})
}
}
<file_sep>/TestGuava/app/src/main/java/com/zhaopf/testguava/MainActivity.kt
package com.zhaopf.testguava
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import com.google.common.base.Optional
import com.zhaopf.testguava.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityMainBinding.inflate(LayoutInflater.from(this))
setContentView(binding.root)
binding.btnGuava1.setOnClickListener {
val data1 = Optional.fromNullable(MainBean.getTestData1())
binding.btnGuava1.text = if (data1.isPresent) "不空" else "空"
// binding.btnGuava1.text = MainBean.getTestData1().homeBean.bannerList[0].url;
}
binding.btnGuava2.setOnClickListener {
val data2 = Optional.fromNullable(MainBean.getTestData2())
Log.d(TAG, "onCreate data2: ${data2.get()}")
Optional.fromNullable(MainBean.getTestData2())
.orNull()
?.mainDataBean
?.bannerList
?.getOrNull(0)
?.url
?: "a"
binding.btnGuava2.text = MainBean.getTestData2()
?.mainDataBean
?.bannerList
?.get(0)
?.url
?: "没数据"
}
binding.btnGuava3.setOnClickListener {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
binding.btnGuava3.text = Optional.fromNullable(MainBean.getTestData3())
.toJavaUtil()
.map { it.mainDataBean }
.map { it.bannerList }
.filter { it.size > 0 }
.map { it[0] }
.map { it.url }
.orElse("默认值")
}
}
binding.btnGuava4.setOnClickListener {
binding.btnGuava4.text = MainBean.getTestData3()
?.mainDataBean
?.bannerList
?.getOrNull(0)
?.url
?: "默认值"
}
}
}<file_sep>/RoomWordSample/settings.gradle
rootProject.name = "RoomWordSample"
include ':app'
<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/test.kt
package com.zhaopf.viewpager2
val a = arrayOf(1, 2, 3)
val d = intArrayOf(1, 2, 3)
val e = Array(3) { i -> i }<file_sep>/ScreenShot/settings.gradle
include ':app'
rootProject.name = "ScreenShot"<file_sep>/GetLauncherPackageName/app/src/main/java/com/zhaopf/getlauncherpackagename/activitys/ThirdActivity.kt
package com.zhaopf.getlauncherpackagename.activitys
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import com.zhaopf.getlauncherpackagename.R
import kotlinx.android.synthetic.main.activity_third.*
class ThirdActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_third)
btn_jump_to_metaapp.setOnClickListener {
val uri = Uri.parse("metaapp://233xyx/splash")
val intent = Intent(Intent.ACTION_VIEW, uri)
startActivity(intent)
}
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/test/TestKotlin.kt
@file:JvmName("TestKotlin")
package com.meta.kotlinstudy.test
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Handler
import android.util.TypedValue
import org.json.JSONException
import org.json.JSONObject
import java.io.BufferedReader
import java.io.File
import java.io.FileReader
import java.io.IOException
import java.util.concurrent.Executors
fun testKotlin() {
// test1()
// test2()
// test3(this)
// test4(this)
// test5()
// mStartActivity<MainActivity>()
// test6()
testSequence()
}
fun test1() {
val jack = User("Jack", 20)
val tom = User("Tom", 20)
val sameAge = jack sameAge tom
println(sameAge)
}
/**
* data class
*/
data class User(
val name: String,
val age: Int)
/**
* 中缀表达式
*/
infix fun User.sameAge(user: User): Boolean {
return this.age == user.age
}
fun test2() {
val json = """
{
"city_info" : {
"title" : "BeiJing",
"data" : "city is beijing."
}
}
""".trimIndent()
val jsonObject = try {
JSONObject(json)
} catch (e: JSONException) {
println("---> error: ${e.message}")
null
}
dealCityInfo(jsonObject) {
println("---> failed.")
}
}
/**
* 标准函数
*/
fun dealCityInfo(data: JSONObject?, fail: () -> Unit) {
data?.takeIf { it.has("city_info") }
?.takeIf {
with(it.getJSONObject("city_info")) {
return@takeIf has("title") && has("data")
}
}
?.let { it.getJSONObject("city_info") }
?.apply {
// do something
println("---> do something.")
} ?: fail()
}
/**
* 扩展函数
*/
fun test3(context: Context) {
println("---> ${1f.dp(context)}")
}
fun Float.dp(context: Context): Int {
return TypedValue.applyDimension(
TypedValue.COMPLEX_UNIT_DIP,
this,
context.resources.displayMetrics
).toInt()
}
/**
* 扩展POST
*/
fun test4(activity: Activity) {
activity.apply {
main {
// main thread.
println("---> main: ${Thread.currentThread().name}")
worker {
// worker thread.
println("---> worker: ${Thread.currentThread().name}")
}
println("---> main2: ${Thread.currentThread().name}")
}
}
}
fun Activity.main(todo: () -> Unit) {
Handler().post {
todo()
}
}
fun Activity.worker(todo: () -> Unit) {
Executors.newSingleThreadExecutor()
.execute {
todo()
}
}
/**
* IO
*/
fun test5() {
javaIO()
luckyIO()
}
fun javaIO() {
var br: BufferedReader? = null
try {
br = BufferedReader(FileReader(File("readme.md")))
var line: String
while (true) {
line = br.readLine() ?: break
println("---> $line")
}
} catch (ignore: Exception) {
} finally {
try {
br?.close()
} catch (ignore: IOException) {
}
}
}
// 快乐的IO
fun luckyIO() {
BufferedReader(FileReader(File("readme.md"))).use {
var line: String
while (true) {
line = it.readLine() ?: break
println("---> $line")
}
}
// 更加精简
File("readme.md").readLines().forEach(::println)
}
inline fun <reified T : Activity> Activity.mStartActivity() {
startActivity(Intent(this, T::class.java))
}
/**
* 集合类操作
*/
fun test6() {
val numList = intArrayOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 0)
val numList2 = arrayOf(1, 2, 3)
val numList3 = Array<Int>(1) { it }
// 只要有一个满足即成立
val resultAny = numList.any { it > 5 }
println("---> resultAny: $resultAny")
// 所有满足才成立
val resultAll = numList.all { it > 5 }
println("---> resultAll: $resultAll")
}
/**
* Sequence
*
* 1、当不需要中间操作时,使用List
* 2、当仅仅只有map操作时,使用sequence
* 3、当仅仅只有filter操作时,使用List
* 4、如果末端操作是first时,使用sequence
* 5、对于没有提及的其他操作符或者其他操作符的组合,请尝试使用例子去验证一下
*/
fun testSequence() {
var time = System.currentTimeMillis()
val list = (1..65535)
.toList()
.map { it * 2 }
.filter { it % 3 == 0 }
list.first()
// 76ms
println("---> list: ${System.currentTimeMillis() - time}")
time = System.currentTimeMillis()
val sequence = (1..65535)
.asSequence()
.map { it * 2 }
.filter { it % 3 == 0 }
sequence.first()
// 5ms
println("---> sequence: ${System.currentTimeMillis() - time}")
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/data/Log.kt
package com.zhaopf.testhilt.data
import androidx.room.Entity
import androidx.room.PrimaryKey
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@Entity(tableName = "logs")
data class Log(val msg: String, val timestamp: Long) {
@PrimaryKey(autoGenerate = true)
var id: Long = 0
}<file_sep>/TestLottie/README.md
* Try Lottie.<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/MainActivity.kt
package com.meta.kotlinstudy
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.asLiveData
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.liveData
import androidx.lifecycle.whenResumed
import coil.load
import com.meta.kotlinstudy.coroutine_retrofit.WanAndroidService
import com.meta.kotlinstudy.databinding.ActivityMainBinding
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.produce
import kotlinx.coroutines.flow.*
import retrofit2.Retrofit
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
private lateinit var binding: ActivityMainBinding
private val mFactory by lazy { MainViewModelFactory("11111111") }
private val mainViewModel by lazy { mFactory.create(MainViewModel::class.java) }
private val scope = MainScope()
@ExperimentalCoroutinesApi
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.ivTest.load("https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1606727167909&di=7694452bf754d33e6e38a634aeaa80a4&imgtype=0&src=http%3A%2F%2Fa3.att.hudong.com%2F13%2F41%2F01300000201800122190411861466.jpg")
// testViewModel()
lifecycleScope.launch(Dispatchers.Main) {
whenResumed {
Log.d(TAG, "onCreate: whenResumed")
val one = async(start = CoroutineStart.LAZY) { getResult(20) }
val two = async(start = CoroutineStart.LAZY) { getResult(40) }
binding.tvTest.text = (one.await() + two.await()).toString()
}
}
lifecycleScope.launch(Dispatchers.Main) {
(1..10).asFlow().flowOn(Dispatchers.IO)
.catch { }
.onCompletion { Log.d(TAG, "onCreate: onCompletion") }
.filter { it >= 5 }
.map { "${it * it} money." }
.collect { Log.d(TAG, "onCreate: it: $it") }
// whenResumed {
// createFlow()
// .collect { num ->
// Log.d(TAG, "onCreate: num: $num")
// }
// }
val flow1 = flow<Int> {
while (true) {
delay(5000)
emit(1)
}
}
val flow2 = flow<Int> {
while (true) {
delay(5000)
emit(1)
}
}
flow1.zip(flow2) { t1, t2 -> "$t1 $t2" }
.collect {
Log.d(TAG, "onCreate: test: $it")
}
}
lifecycleScope.launch {
val channel = Channel<Int>()
launch {
for (i in 1..5) {
delay(200)
channel.send(i)
}
channel.close()
}
launch {
for (i in channel) {
Log.d(TAG, "onCreate: channel value: $i")
}
}
}
lifecycleScope.launch {
val channel = produce<Int> {
for (i in 1..5) {
delay(200)
send(i * i)
}
close()
}
launch {
for (i in channel) {
Log.d(TAG, "onCreate: channel produce value: $i")
}
}
}
mainViewModel.bannerList.observe(this, { list ->
list.forEach { item ->
Log.d(TAG, "onCreate: ${item.title}")
}
})
binding.tvTestCoroutineRetrofit.setOnClickListener {
mainViewModel.getBannerList()
}
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume: ")
}
override fun onDestroy() {
super.onDestroy()
scope.cancel()
}
private fun createFlow(): Flow<Int> = flow {
for (i in 1..10) {
emit(i)
}
}
private suspend fun getResult(num: Int): Int = withContext(Dispatchers.IO) {
delay(10_000)
return@withContext num * num
}
private fun testViewModel() {
mFactory.create(MainViewModel::class.java)
mFactory.create(MainViewModel::class.java)
mFactory.create(MainViewModel::class.java)
mFactory.create(MainViewModel::class.java)
mFactory.create(MainViewModel::class.java)
MainViewModelFactory("2222222").create(MainViewModel::class.java)
MainViewModelProvider(this, MainViewModelFactory("3333333"))
.get("33333", MainViewModel::class.java)
}
}
fun fooList(): List<Int> = listOf(1, 2, 3)
fun foo(): Sequence<Int> = sequence {
for (i in 1..3) {
Thread.sleep(100L)
yield(i)
}
}
suspend fun fooList2(): List<Int> {
delay(1000L)
return listOf(1, 2, 3)
}
fun fooFlow(): Flow<Int> = flow {
for (i in 1..3) {
delay(100L)
emit(i)
}
}.flowOn(Dispatchers.IO)
fun mainFooFlow() = runBlocking {
launch {
for (i in 1..3) {
println("I'm not blocked $i")
delay(100L)
}
}
fooFlow().collect { value -> println(value) }
fooFlow()
.onStart {
}
.catch {
}
.onCompletion {
}
.asLiveData()
// .collectLatest {}
}
val a = liveData<Int> {
emit(1)
}
<file_sep>/TestImage/README.md
### 测试 `webp` 图片在 `api18` 以下的机型的显示情况
`android` 在 `api14` 开始支持 `webp` 格式的图片, 但是有限制
`api18` 以下的机型, 如果图片带有透明度通道, 那么转换为 `webp` 之后, 会显示异常, 经测试, 在 `api16` 的模拟器上直接不显示了
`api18` 开始, 支持带透明度通道的图片, 转换为 `webp` 之后, 可以正常显示, 和 `png` 没有区别
`app` 的启动图标必须是 `png` 格式的, 所以只能做压缩处理<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/coroutine_retrofit/RetrofitClient.kt
package com.meta.kotlinstudy.coroutine_retrofit
import okhttp3.OkHttpClient
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
/**
*
* @author zhaopingfu
* @date 2021-05-31 10:27
*/
object RetrofitClient {
private const val BASE_URL = "https://www.wanandroid.com/"
private val okHttpClient = OkHttpClient.Builder()
.callTimeout(30, TimeUnit.SECONDS)
.build()
private val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
val articleService = retrofit.create(WanAndroidService::class.java)
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/TestMotionEditorActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
/**
* @author zhaopingfu
* @date 2020/12/9
*/
class TestMotionEditorActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_test_motion_editor)
}
}
<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/data/LoggerDataSource.kt
package com.zhaopf.testhilt.data
/**
* @author zhaopingfu
* @date 2020/10/23
*/
interface LoggerDataSource {
fun addLog(msg: String)
fun getAllLogs(callback: (List<Log>) -> Unit)
fun removeLogs()
}
<file_sep>/CustomRecyclerViewAdapter/app/src/main/java/com/zhaopingfu/adapter/BaseTemplate.kt
package com.zhaopingfu.adapter
import android.graphics.Color
import com.zhaopingfu.adapter.databinding.LayoutATemplateBinding
import com.zhaopingfu.adapter.databinding.LayoutBTemplateBinding
/**
*
* @author zhaopingfu
* @date 2021-03-08 15:52
*/
class ATemplate : BaseTemplate<ABean, LayoutATemplateBinding>() {
override fun bindData(
holder: BindingViewHolder<LayoutATemplateBinding>,
bean: ABean,
position: Int
) {
holder.binding.root.setBackgroundColor(Color.GRAY)
}
}
class BTemplate : BaseTemplate<BBean, LayoutBTemplateBinding>() {
override fun bindData(
holder: BindingViewHolder<LayoutBTemplateBinding>,
bean: BBean,
position: Int
) {
holder.binding.root.setBackgroundColor(Color.DKGRAY)
}
}
<file_sep>/TestOptimizePlugin/meta_optimize_plugin/build.gradle
apply plugin: 'java-library'
apply plugin: 'groovy'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation gradleApi()
implementation localGroovy()
implementation 'com.android.tools.build:gradle:3.4.2'
implementation 'com.tinify:tinify:1.6.4'
}
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
apply plugin: 'maven-publish'
group "com.meta.optimizer"
version "1.0.0"
publishing {
publications {
optimizer(MavenPublication) {
from components.java
artifactId = "optimizer"
}
}
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/navigator/AppNavigator.kt
package com.zhaopf.testhilt.navigator
/**
* @author zhaopingfu
* @date 2020/10/23
*/
enum class Screens {
BUTTONS,
LOGS
}
interface AppNavigator {
fun navigateTo(screen: Screens)
}<file_sep>/TestHotFix/app/src/main/java/com/example/testhotfix/fixmethod/FixMethodInterface.java
package com.example.testhotfix.fixmethod;
import android.content.Context;
import androidx.annotation.Nullable;
public interface FixMethodInterface {
/**
* @param pathList DexPathList 对象
* @param context 获取私有目录和classLoader
* @param dexPath 新的dex路径
* @return 新的 dexElements
*/
@Nullable
Object[] getElements(Object pathList, Context context, String dexPath);
}<file_sep>/RoomWordSample/app/src/main/java/com/zhaopingfu/roomwordsample/WordRoomDatabase.kt
package com.zhaopingfu.roomwordsample
import android.content.Context
import androidx.room.Database
import androidx.room.Room
import androidx.room.RoomDatabase
import androidx.sqlite.db.SupportSQLiteDatabase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.forEach
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
/**
*
* @author zhaopingfu
* @date 2021-07-22 16:55
*/
@Database(entities = [Word::class], version = 1, exportSchema = false)
abstract class WordRoomDatabase : RoomDatabase() {
abstract fun wordDao(): WordDao
private class WordDatabaseCallback(private val scope: CoroutineScope) : RoomDatabase.Callback() {
override fun onCreate(db: SupportSQLiteDatabase) {
super.onCreate(db)
INSTANCE?.let { database ->
scope.launch {
populateDatabase(database.wordDao())
}
}
}
suspend fun populateDatabase(wordDao: WordDao) {
// Delete all content here.
wordDao.deleteAll()
// wordDao.getAlphabetizedWords()
// .take(1)
// .collect { list ->
// list.forEach { word: Word ->
// wordDao.delete(word)
// }
// }
// Add sample words.
var word = Word("Hello")
wordDao.insert(word)
word = Word("World!")
wordDao.insert(word)
// TODO: Add your own words!
}
}
companion object {
@Volatile
private var INSTANCE: WordRoomDatabase? = null
fun getDatabase(context: Context, scope: CoroutineScope): WordRoomDatabase {
return INSTANCE ?: synchronized(this) {
val instance =
Room.databaseBuilder(context.applicationContext, WordRoomDatabase::class.java, "word_database")
.addCallback(WordDatabaseCallback(scope))
.build()
INSTANCE = instance
instance
}
}
}
}
<file_sep>/RobustDemo/app/src/main/java/com/meta/robustdemo/MainActivity.java
package com.meta.robustdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Toast;
import com.meituan.robust.PatchExecutor;
import com.meituan.robust.patch.annotaion.Add;
import com.meituan.robust.patch.annotaion.Modify;
import com.meta.robustdemo.robust.PatchManipulateImp;
import com.meta.robustdemo.robust.PermissionUtils;
import com.meta.robustdemo.robust.RobustCallBackSample;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_patch).setOnClickListener(this);
findViewById(R.id.btn_to_second_activity).setOnClickListener(this);
findViewById(R.id.btn_bug).setOnClickListener(this);
}
@Modify
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_patch: {
if (isGrantSDCardReadPermission()) {
runRobust();
} else {
requestPermission();
}
}
break;
case R.id.btn_to_second_activity: {
startActivity(new Intent(v.getContext(), SecondActivity.class));
}
break;
case R.id.btn_bug: {
addMethod();
}
break;
default:
break;
}
}
@Add
private void addMethod() {
Toast.makeText(MainActivity.this, "main bug fixed.", Toast.LENGTH_SHORT)
.show();
}
private boolean isGrantSDCardReadPermission() {
return PermissionUtils.isGrantSDCardReadPermission(this);
}
private void requestPermission() {
PermissionUtils.requestSDCardReadPermission(this, REQUEST_CODE_SDCARD_READ);
}
private static final int REQUEST_CODE_SDCARD_READ = 1;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if (requestCode == REQUEST_CODE_SDCARD_READ) {
handlePermissionResult();
}
}
private void handlePermissionResult() {
if (isGrantSDCardReadPermission()) {
runRobust();
} else {
Toast.makeText(this, "failure because without sd card read permission", Toast.LENGTH_SHORT).show();
}
}
private void runRobust() {
new PatchExecutor(getApplicationContext(), new PatchManipulateImp(), new RobustCallBackSample()).start();
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/3.数组_集合_扩展函数_扩展属性_vararg_infix_析构声明.kt
package com.meta.kotlinstudy.基础部分
import android.util.Log
import android.widget.Toast
fun testArray() {
// 基础类型的数组要使用 intArrayOf 或者 floatArrayOf 等
// int[]
val array = intArrayOf(1, 2, 3)
// Integer[]
val array1 = arrayOf(1, 2, 3)
// Integer[]
val array2 = Array(3) { it }
// 取值
val num1 = array[0]
val num2 = array.last()
val num3 = array.component1()
val num4 = array.elementAt(0)
// 遍历
for (i in array) {
}
array.forEach {
// 这里默认参数名是it,可以自己改 x ->
println(it)
}
array.forEachIndexed { index, value ->
println("index: $index value: $value")
}
// 转为String
array.joinToString()
}
fun testList() {
val list = listOf<Int>(1, 2, 3)
val list2 = arrayListOf<Int>(1, 2, 3)
// 这里的 List 只能进行读取,不能进行增删
val list3: List<Int> = listOf()
// 可变的集合可以随意的增删
val list4: MutableList<Int> = mutableListOf()
list4.filter { it > 3 }
.take(3)
.map { "$it" }
.flatMap { it.toCharArray().toList() }
.sorted()
// 一个满足就返回
list4.any { it > 5 }
// 所有满足的
list4.all { it > 5 }
list4.minOrNull()
list4.maxOrNull()
list4.sum()
}
/**
* 扩展方法
* 比如一般用到字符串都会写一个StringUtil,这个时候就可以用扩展函数替代
*
* inline 表示在编译之后会把inline方法里面的内容复制到调用方法的地方
*/
inline fun String.show() {
Log.d("xxx", "show ${toString()}")
}
/**
* 扩展属性
*/
val String.lastChar: Char
get() = get(length - 1)
/**
* 可变参数: vararg 伪关键字,和 emum 一样
*/
fun test(vararg str: String) {
val vararg = str[0]
str.size
println(str.joinToString(","))
}
/**
* 方法默认值
*/
fun testFunc(name: String = "", sex: String = "") {
}
fun testFunc2() {
// 这个时候传参默认是会给到name
testFunc("男")
// 如果想给到sex怎么办呢
testFunc(sex = "男")
// 通过这样指定参数名的方式,可以节省查看方法参数的时间,而且更加规范
}
/**
* 中缀表达式
*/
infix fun Int.加(that: Int): Int = this + that
fun testExtensionFunction() {
"abc".show()
"abc".lastChar
// 中缀调用 infix: 1 to 1
val x = 1 加 1
}
fun testMap() {
val map = mapOf<Int, Int>()
val map2 = mapOf(Pair(1, 1), Pair(2, 2))
val map3 = mapOf(1 to 1, 2 to 2, "c" to 2)
map3[1]
map3["c"]
}
data class User(
val name: String,
val age: Int
)
fun test析构() {
// 从集合析构
val xxx = "androidx.recyclerview:recyclerview:1.1.0"
val (group, name, version) = xxx.split(":")
// 从map析构
val map = mapOf<Int, Int>(1 to 1, 2 to 2, 3 to 3)
for ((k, v) in map) {
}
map.mapValues {
}
map.mapValues { (k, v) ->
}
// 从这里析构
val (sex, age) = Pair("男", 1)
val (a, b, c) = Triple("a", 2, Color.RED)
// 从对象析构
val user = User("name", 20)
val (name2, age2) = user
val userArray = arrayOf<User>()
for ((name3, age3) in userArray) {
}
}<file_sep>/SophixDemo/Sophix.md
### Sophix
`AndFix` 在 `GitHub` 上的最后一次提交记录是在三年前了,而且提的很多 `issue` 也没有人回复,估计是放弃这个方案了,在推 `Sophix` .
`Sophix`:
支持方法级别的修复
支持资源的修改,添加
补丁包较小
傻瓜式接入
看了下官网的介绍,然后自己集成了一下他的SDK,模拟了几个问题,依次生成补丁包,修复,走了一遍流程
我这里试了三个版本的 `4.4`、 `6.0`、 `9.0` 的都可以成功修复
补丁是对应的指定版本走的,假如
#### 生成补丁包:(为了使新旧两个包使用同样的混淆规则,需要以下步骤)
[生成补丁失败检查步骤](https://help.aliyun.com/knowledge_detail/59422.html)
1. 打有问题的包的时候需要在 proguard-rules.pro 中 打开 -printmapping mapping.txt 关闭 -applymapping mapping.txt
2. 打完有问题的包之后需要把 mapping.txt 文件拷贝到 app/目录下, 然后把上面的两个配置切换
3. 再打修复了问题的包
4. 之后再生成补丁
#### 缺点
1. 不支持添加四大组件
2. 不支持 修改 AndroidManifest.xml
3. Application中不得使用非Android SDK 的方法
4. 获取到有补丁之后大概率会强制走冷启动,重新打开的时候修复问题
文档中的说法是:代码若变动小,一般会走即时生效热修复,而如果代码变动大,比如在已存在的类中新增方法,修改了so等情况,都会走冷启动。这是由打包工具自行检测代码变化来判断的
4. 在application的onCreate中会去请求有没有新的补丁,如果还没请求到数据就闪退了,那么就没办法了, 所以需要在启动页面拖着时间,保证能够顺利请求到补丁
#### 冷启动热启动
默认不会强制杀死APP,但是有些问题只有冷启动之后才会被修复
1. 只改不增方法,热启动 当前页面的修复不了,新的页面可以修复
2. 新增方法,冷启动才能修复<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/6.Java调用Kotlin.md
### Java 调用 Kotlin
1、kotlin编译后会生成一个 `类名 + Kt` ,如果不想使用这个名字,可以自己自定义
在文件第一行添加注解 @file:JvmName("名字")
例如 @file:JvmName("Hello")
2、访问顶层属性
var name = "1"
通过 `文件名Kt` 来调用set/get方法
String name = JavaClassKt.getName();
如果想直接通过 "文件名.属性名" 的方式
* 方法一: 通过添加@JvmField属性可以做到
@JvmField
var name1 = "1"
那么在java里 就可以
String name1 = JavaClassKt.name1;
* 方法二: 使用 `const`关键字
// const 只能用来修饰 val ,相当于java中的 public static final
const val name2 = "1"
Stringg name2 = JavaClassKt.name2;
3、合并文件
假如有
AUtils.kt,里面有个 a 方法
和
BUtils.kt,里面有个 b 方法
给AUtils.kt设置名字叫Utils(通过@file:JvmName("Utils"))
给BUtils.kt设置名字叫Utils(通过@file:JvmName("Utils"))
这个时候通过Utils调用方法的时候只能调用 a 方法,但是我还想要调用 b 方法
就需要在 @file:JvmName("Utils") 下面添加 @file:JvmMultifileClass,表示可以合并
在AUtils.kt 和 BUtils.kt 里面都添加
4、扩展方法
fun String.test() {}
fun Int.test() {}
在java 中调用的时候需要通过 文件名.test(参数就是扩展类型)
比如
Hello.test("string");
Hello.test(1);
5、相同签名的不同泛型的方法
fun List<String>.test() {}
fun List<Int>.test() {}
上面这两个方法因为java中的签名一样,都是List,所以有问题
就需要修改下方法名
@JvmName("test1")
fun List<String>.test() {}
fun List<Int>.test() {}
`java` 中调用
// 相同签名的不同泛型
Hello.test(new ArrayList<Integer>());
Hello.test1(new ArrayList<String>());
6、方法默认值
fun func(name: String = "", id: Int = 1) {}
kotlin中两个参数都有默认值,在java中调用的话两个参数都需要传
如果在 `java` 中不传参数的话需要添加注解
@JvmOverloads
fun func(name: String = "", id: Int = 1) {}
这个时候就可以调用了
// 有默认值的方法
Hello.func();
Hello.func("");
Hello.func("", 1);
7、类
class A(name: String) {
val name1 = name
@JvmField
val name2 = name
companion object AA {
val id = "2"
@JvmField
val sex = "男"
}
}
`java` 中调用
// 类
A a = new A("name");
n = a.getName1();
n = a.name2;
String id = A.AA.getId();
String sex = A.sex;
8、object
object B {
val id = "1"
}
`java` 中调用
// object
id = B.INSTANCE.getId();
9、异常
fun ex() {
throw IOException("xxx")
}
在 `kotlin` 中抛出异常,`java` 中是没有提示要处理的,如果需要提示可以添加注解
@Throws(IOException::class)
fun ex() {
throw IOException("xxx")
}
`java` 中
// 异常
try {
Hello.ex();
} catch (IOException e) {
e.printStackTrace();
} <file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/MainActivity.kt
package com.meta.testmotionlayout
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.meta.testmotionlayout.circular_reveal_helper.CircularRevealActivity
import com.meta.testmotionlayout.databinding.ActivityMainBinding
import com.meta.testmotionlayout.fly_in_helper.FlyInActivity
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btnJumpCircleActivity.setOnClickListener {
startActivity(Intent(it.context, CircleActivity::class.java))
}
binding.btnJumpGroupActivity.setOnClickListener {
startActivity(Intent(it.context, GroupActivity::class.java))
}
binding.btnJumpLayerActivity.setOnClickListener {
startActivity(Intent(it.context, LayerActivity::class.java))
}
binding.btnJumpBarrierActivity.setOnClickListener {
startActivity(Intent(it.context, BarrierActivity::class.java))
}
binding.btnJumpCircularRevealActivity.setOnClickListener {
startActivity(Intent(it.context, CircularRevealActivity::class.java))
}
binding.btnJumpFlyInActivity.setOnClickListener {
startActivity(Intent(it.context, FlyInActivity::class.java))
}
binding.btnJumpPlaceholderActivity.setOnClickListener {
startActivity(Intent(it.context, PlaceHolderActivity::class.java))
}
binding.btnJumpConstraintsetActivity.setOnClickListener {
startActivity(Intent(it.context, ConstraintSetActivity::class.java))
}
binding.btnJumpConstraintset2Activity.setOnClickListener {
startActivity(Intent(it.context, ConstraintSet2Activity::class.java))
}
binding.btnJumpFlowActivity.setOnClickListener {
startActivity(Intent(it.context, FlowActivity::class.java))
}
binding.btnJumpObjectAnimatorActivity.setOnClickListener {
startActivity(Intent(it.context, ObjectAnimatorActivity::class.java))
}
binding.btnJumpGoActivity.setOnClickListener {
startActivity(Intent(it.context, GoActivity::class.java))
}
binding.btnJumpMotionlayoutActivity.setOnClickListener {
startActivity(Intent(it.context, MotionLayoutActivity::class.java))
}
binding.btnJumpSampleActivity.setOnClickListener {
startActivity(Intent(it.context, SampleActivity::class.java))
}
binding.btnJumpKeyPositionActivity.setOnClickListener {
startActivity(Intent(it.context, TestKeyPositionActivity::class.java))
}
binding.btnYoutube.setOnClickListener {
startActivity(Intent(this@MainActivity, YoutubeActivity::class.java))
}
binding.btnMotionLayout.setOnClickListener {
startActivity(Intent(this@MainActivity, TestMotionLayoutActivity::class.java))
}
binding.btnJumpFlipActivity.setOnClickListener {
startActivity(Intent(this@MainActivity, FlipActivity::class.java))
}
binding.btnJumpWithCoordinatorlayoutActivity.setOnClickListener {
startActivity(Intent(it.context, WithCoordinatorLayoutActivity::class.java))
}
binding.btnJumpWithDrawerlayoutActivity.setOnClickListener {
startActivity(Intent(it.context, WithDrawerLayoutActivity::class.java))
}
binding.btnJumpTestMotionEditorActivity.setOnClickListener {
startActivity(Intent(it.context, TestMotionEditorActivity::class.java))
}
}
}
<file_sep>/TestMotionLayout/MotionLayout简单使用.md
### `MotionLayout简单使用`
#### `过渡动画`
- 1、 有一个简单的需求,屏幕上左边居中有一个控件,现在要慢慢向右移动 `200dp`,有什么办法呢?
我们可能会创建一个动画,然后 `translationX(px2dp(200))`,所以我们的代码可能是这样的
```
child.animate()
.translationX(px2dp(200))
.start()
```
- 2、但是,UI不可能过来跟我们说,我要把这个控件向右移动200个dp,他可能会说要把控件移动到右边,所以,代码就可能会变成这样
val parent = child.parent as ViewGroup
val distance = parent.width - child.width
child.animate()
.translationX(distance.toFloat())
.start()
- 3、现在有个问题是,UI是让我们从左边移动到右边,现在多出来一步计算的步骤,有没有办法省去呢,当然是可以的,我们可以调整布局参数,让它真正的跑到右边,所以代码可能会变成这样
```
val layoutParams = child.layoutParams as FrameLayout.LayoutParams
layoutParams.gravity = Gravity.END or Gravity.CENTER_VERTICAL
child.layoutParams = layoutParams
```
- 4、但是这种方式是直接过去的,没有动画,比较生硬,怎么办呢,加一行代码就可以了
// 注意,是在布局参数改变之前加
TransitionManager.beginDelayedTransition(child.parent as ViewGroup)
val layoutParams = child.layoutParams as FrameLayout.LayoutParams
layoutParams.gravity = Gravity.END or Gravity.CENTER_VERTICAL
child.layoutParams = layoutParams
- 5、为什么在布局参数改变之前加一行这个就可以有动画呢?
过渡动画的原理:
```
1、两个场景,一个开始场景,一个结束场景,记录场景上的控件的各种参数
2、根据参数的变化创建动画
3、播放动画
```
对应 Transition 上的关键函数:
```
1、捕获并记录对应属性
captureStartValues 和 captureEndValues
2、基于捕获的值创建对应动画,并播放动画
createAnimator 和 playTransition
```
- 6、如果动画比较复杂,那么我们需要改变的参数就非常多,那么代码就会很多,太麻烦了,所以过渡动画还有另一种使用方式: `TransitionManager.go(scene)`
```
我们可以用两个 `xml` 表示开始和结束场景,在两个场景之间进行切换
但是 `go` 函数需要我们在每次场景切换之后都要重新绑定数据,这是因为每次都把子控件全部移除了
```
- 7、有没有什么办法可以不用重新绑定数据,还能在两个场景进行切换呢?
当然是有的,只要父容器是 `ConstraintLayout`, 就可以使用 `ConstraintSet` 来做过渡动画
```
TransitionManager.beginDelayedTransition(root)
val constraintSet = ConstraintSet().apply {
clone(this@ConstraintSetActivity, R.layout.layout_constraintset_end)
}
constraintSet.applyTo(root)
```
- 8、这样就可以完成过渡动画,并且不用重新绑定数据,但是这样就完美了吗?
当然不是的,约束布局还不够好
```
1. 首先它不能停留在任意位置,动画一旦开始就必须等它结束,不能停留在任意位置
2. 其次它不支持触摸反馈,不能让动画跟着手指的滑动慢慢进行
3. 第三个是有布局重复,布局切换的套路代码不得不重复写一遍,还要同时管理两个xml文件,而且两个文件都是在layout文件夹下,第二个布局只是为了做动画用的,并不是真正的布局,没有放到专门管理动画的文件夹下
```
- 9、为了解决上面的问题,就引入了 `MotionLayout`
`MotionLayout` 是 `ConstraintLayout` 的子类,所以约束布局能做的事情它都能做
它的属性只有一个: `app:layoutDescription="@xml/motion_sample"`
创建一个文件: `res/xml/motion_sample.xml`, 根节点是 `MotionScene`
这样就有了一个布局文件和一个 `MotionScene` 文件,一个负责管理布局,一个专门用来管理动画
### MotionLayout属性介绍
##### MotionScene节点
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<Transition
app:constraintSetStart="@+id/start"
app:constraintSetEnd="@+id/end"/>
<ConstraintSet android:id="@+id/start"/>
<ConstraintSet android:id="@+id/end"/>
</MotionScene>
##### Constraint 节点
<Constraint android:id="">
<Motion/>
<Layout/>
<Transform/>
<CustomAttribute/>
<PropertySet/>
</Constraint>
运动模型
弧线路径,时间模型等
布局相关
注意, width 、 height 和 margin 的命名空间是 android: (beta1 开始)
而约束相关的命名空间是 app (或 motion )
动画变换
做旋转,位移,缩放,海拔等属性
自定义属性
attributeName 会加上 set/get 反射找到真正的函数名
比如 backgroundColor 就会调用 setBackgroundColor() 函数
custom(xxx)Value 对应属性的数据类型
特定的属性
visibility 、 alpha 等属性
##### `时间模型`
每个控件可以单独设置时间模型
在 <Motion> 节点中使用 app:transitionEasing
整个 Transition 也可以设置插值器
在 <Transition> 中使用 app:motionInterpolator
##### Transition 节点
<Transition
app:constraintSetStart="@+id/start"
app:constraintSetEnd="@+id/end"
app:duration="1000">
<OnSwipe />
<OnClick />
<KeyPositionSet >
<KeyAttribute>
<CustomAttribute/>
</KeyAttribute>
<KeyPostion/>
<KeyCycle/>
<KeyTimeCycle/>
</KeyPositionSet>
</Transition>
##### onSwipe
<OnSwipe
app:touchAnchorId="@id/view"
app:dragDirection="dragDown" />
`<OnSwipe>` 添加在 `<Transtion>` 节点中支持的参数
touchRegionId 指的是哪一个控件响应触摸事件
touchAnchorId 这个有点诡异,除了在指定的id上可以触摸,别的控件也可以触摸
autoComplete 默认的是 true , 会根据动画完成的百分比自动到最近的一个状态
dragDirection 拖拽的方向
##### OnClick
<OnClick
app:clickAction="toggle"
app:targetId="@id/view"/>
targetId 指定控件
clickAction
toggle 反转状态
transitionToEnd/Start 通过动画到结束/起始状态
jumpToEnd/Start 没有动画直接到结束/起始状态
##### KeyPositionSet
- `app:motionTarget` 目标对象ID
- `app:framePosition` 百分比 (0 - 100)
##### KeyAttribute 属性关键字
<KeyAttribute
app:framePosition="0"
app:motionTarget="@id/image_film_cover"
android:elevation="12dp">
<CustomAttribute
app:attributeName="BackgroundColor"
app:customColorValue="@color/colorAccent"/>
</KeyAttribute>
可以设置位移,旋转,缩放等属性,同时还可以通过 `CustomAttribute` 添加自定义属性
##### KeyPosition 位置关键帧
`percentX/Y` 在关键帧时,对应路径的对应百分比
`percentWidth/Height` 在关键帧时,控件大小改变的百分比
`curveFit` 运动路径的样式(直线,曲线等)
`keyPositionType` 坐标系
- `parentRelative`
(0, 0)为父容器左上⻆
(1, 1)为父容器右下⻆
- `deltaRelative`
(0, 0)为起始控件中心
(1, 1)为结束控件中心
- `pathRelative`
(0, 0)为起始控件中心
(1, 0)为结束控件中心
以 X 轴的长度顺时针旋转90度,画相同的长度就是Y轴
##### KeyCycle 和 KeyTimeCycle
通过 3 个 KeyCycle 定义一个准确的循环关键帧
<KeyFrameSet>
<KeyCycle
android:rotation="0"
app:motionTarget="@id/fab_favourite"
app:wavePeriod="0"
app:framePosition="0"
app:waveShape="sin"/>
<KeyCycle
android:rotation="180"
app:motionTarget="@id/fab_favourite"
app:wavePeriod="3"
app:framePosition="50"
app:waveShape="sin"/>
<KeyCycle
android:rotation="0"
app:motionTarget="@id/fab_favourite"
app:wavePeriod="0"
app:framePosition="100"
app:waveShape="sin"/>
</KeyFrameSet>
`wavePeriod` 循环次数 (`KeyTimeCycle` 表示的每秒循环次数)
`waveShape` 数学模型<file_sep>/GetLauncherPackageName/app/src/main/java/com/zhaopf/getlauncherpackagename/activitys/SecondActivity.kt
package com.zhaopf.getlauncherpackagename.activitys
import android.content.Intent
import android.os.Bundle
import com.zhaopf.getlauncherpackagename.R
import kotlinx.android.synthetic.main.activity_second.*
/**
* 二级页面,用来判断是否是从桌面跳转过来的
*/
class SecondActivity : BaseActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
btn_show_info.setOnClickListener {
startActivity(Intent(this@SecondActivity, ThirdActivity::class.java))
}
}
}<file_sep>/CustomRecyclerViewAdapter/app/src/test/java/com/zhaopingfu/adapter/ExampleUnitTest.kt
package com.zhaopingfu.adapter
import org.junit.Test
import org.junit.Assert.*
import java.lang.reflect.ParameterizedType
import java.lang.reflect.Type
/**
* Example local unit test, which will execute on the development machine (host).
*
* See [testing documentation](http://d.android.com/tools/testing).
*/
class ExampleUnitTest {
open class GenericsToken<T> {
var type: Type = Any::class.java
init {
val superClass = this.javaClass.genericSuperclass
type = (superClass as ParameterizedType).actualTypeArguments[0]
}
}
@Test
fun addition_isCorrect() {
// 创建一个匿名内部类
val oneKt = object : GenericsToken<BaseBean>() {}
println(oneKt.type)
val a = object :GenericsToken<String>(){}
println(a.type)
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/CircleActivity.kt
package com.meta.testmotionlayout
import android.animation.ObjectAnimator
import android.animation.ValueAnimator
import android.os.Bundle
import android.view.animation.LinearInterpolator
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout
import com.meta.testmotionlayout.databinding.ActivityCircleBinding
class CircleActivity : AppCompatActivity() {
private lateinit var binding: ActivityCircleBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityCircleBinding.inflate(layoutInflater)
setContentView(binding.root)
// earth
ObjectAnimator.ofFloat(0f, 1f).apply {
duration = 10_000L
repeatCount = ValueAnimator.INFINITE
interpolator = LinearInterpolator()
addUpdateListener {
val params = binding.earth.layoutParams as ConstraintLayout.LayoutParams
params.circleAngle = 45f + it.animatedFraction * 360f
binding.moon.requestLayout()
}
start()
}
// moon
ObjectAnimator.ofFloat(0f, 1f).apply {
duration = 2_000L
repeatCount = ValueAnimator.INFINITE
interpolator = LinearInterpolator()
addUpdateListener {
val params = binding.moon.layoutParams as ConstraintLayout.LayoutParams
params.circleAngle = 270f + it.animatedFraction * 360f
binding.moon.requestLayout()
}
start()
}
}
}
<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/LogApplication.kt
package com.zhaopf.testhilt
import android.app.Application
import dagger.hilt.android.HiltAndroidApp
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@HiltAndroidApp
class LogApplication : Application()<file_sep>/TestHotFix/hack/src/main/java/com/example/hack/AntilazyLoad.java
package com.example.hack;
public class AntilazyLoad {
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/8.委托.kt
package com.meta.kotlinstudy.基础部分
/**
* @author pingfu.zhao
* @date 2019-11-30 19:01
*/
class MyList<T> : List<T> by ArrayList<T>()
interface A {
fun sayHello()
}
class Users : A {
override fun sayHello() {
println("Hello")
}
val name = "1"
}
// 我要有 A 接口的功能,但是不想自己做,交给了另一个人帮我做,就是 by 委托
class User2 : A by Users()
fun main() {
val aaa by lazy { "" }
User2().sayHello()
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/ConstraintSetActivity.kt
package com.meta.testmotionlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.transition.TransitionManager
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
class ConstraintSetActivity : AppCompatActivity() {
private var shouldToEnd = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.layout_constraintset_start)
}
fun onClick(v: View) {
val constraintLayout = v as ConstraintLayout
TransitionManager.beginDelayedTransition(constraintLayout)
val constraintSet = ConstraintSet().apply {
if (shouldToEnd) {
clone(this@ConstraintSetActivity, R.layout.layout_constraintset_end)
} else {
clone(this@ConstraintSetActivity, R.layout.layout_constraintset_start)
}
shouldToEnd = !shouldToEnd
}
constraintSet.applyTo(constraintLayout)
}
}<file_sep>/RoomWordSample/app/src/main/java/com/zhaopingfu/roomwordsample/MainActivity.kt
package com.zhaopingfu.roomwordsample
import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.floatingactionbutton.FloatingActionButton
class MainActivity : AppCompatActivity() {
private val wordViewModel: WordViewModel by viewModels {
WordViewModelFactory((application as WordsApplication).repository)
}
private val registerForActivityResult =
registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result: ActivityResult ->
if (result.resultCode == Activity.RESULT_OK) {
result.data?.getStringExtra(NewWordActivity.EXTRA_REPLY)?.let {
val word = Word(it)
wordViewModel.insert(word)
}
} else {
Toast.makeText(
applicationContext,
R.string.empty_not_saved,
Toast.LENGTH_LONG
).show()
}
}
private val mAdapter by lazy { WordListAdapter() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<RecyclerView>(R.id.recyclerview).apply {
layoutManager = LinearLayoutManager(context)
adapter = mAdapter
}
findViewById<FloatingActionButton>(R.id.fab).setOnClickListener {
val intent = Intent(this@MainActivity, NewWordActivity::class.java)
registerForActivityResult.launch(intent)
}
wordViewModel.allWords.observe(this, Observer { words ->
words.let { mAdapter.submitList(it) }
})
}
override fun onDestroy() {
super.onDestroy()
registerForActivityResult.unregister()
}
}
<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/YoujiVideoFragment.kt
package com.zhaopf.testexoplayer
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import kotlinx.android.synthetic.main.fragment_youji_video.*
/**
* A simple [Fragment] subclass.
*/
class YoujiVideoFragment : Fragment() {
private val mDataList: MutableList<VideoBean> by lazy { ArrayList<VideoBean>() }
private lateinit var mVpAdapter: ViewPagerFragmentStateAdapter3
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_youji_video, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mVpAdapter = ViewPagerFragmentStateAdapter3(childFragmentManager, lifecycle, mDataList)
vpVideo.apply {
orientation = ViewPager2.ORIENTATION_VERTICAL
offscreenPageLimit = 4
adapter = mVpAdapter
registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageSelected(position: Int) {
super.onPageSelected(position)
swipeRefreshLayout.isEnabled = position == 0
if (position == mDataList.size - 1) {
getData(1)
}
}
})
}
swipeRefreshLayout.setOnRefreshListener { getData(0) }
getData(0)
}
private fun getData(page: Int) {
mDataList.apply {
if (page == 0) {
clear()
}
addAll(getVideoList())
mVpAdapter.notifyDataSetChanged()
if (page == 0) {
swipeRefreshLayout.isRefreshing = false
}
}
}
}
class ViewPagerFragmentStateAdapter3(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val videoList: List<VideoBean>
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int = videoList.size
override fun createFragment(position: Int): Fragment =
VideoItemFragment.newInstance(videoList[position])
}<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/MainActivity.kt
package com.zhaopf.testexoplayer
import android.graphics.Color
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val colorList = arrayListOf(Color.RED, Color.YELLOW, Color.BLUE, Color.GRAY)
with(viewPager) {
offscreenPageLimit = 5
adapter = MyVpAdapter(
supportFragmentManager,
FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT,
colorList
)
}
tabLayout.setupWithViewPager(viewPager)
}
}
class MyVpAdapter(fm: FragmentManager, behavior: Int, private val colorList: List<Int>) :
FragmentStatePagerAdapter(fm, behavior) {
override fun getItem(position: Int): Fragment =
if (position == 0) YoujiVideoFragment()
else HomeOtherFragment.newInstance(colorList[position - 1])
override fun getCount() = colorList.size + 1
override fun getPageTitle(position: Int): CharSequence? = "${position + 1}"
}<file_sep>/GetLauncherPackageName/app/src/test/java/com/zhaopf/getlauncherpackagename/JavaTest.java
package com.zhaopf.getlauncherpackagename;
import org.junit.Test;
import java.util.Calendar;
/**
* @author PingFu.Zhao
* 2019/7/31
*/
public class JavaTest {
@Test
public void test() {
// 上次记录的时间
Calendar oldCalendar = Calendar.getInstance();
// oldCalendar.setTimeInMillis(1564588799000L);
oldCalendar.setTimeInMillis(1564588700000L);
// 现在的时间
Calendar currCalendar = Calendar.getInstance();
// 判断是否是同一天
boolean result = oldCalendar.get(Calendar.YEAR) == currCalendar.get(Calendar.YEAR)
&& oldCalendar.get(Calendar.MONTH) == currCalendar.get(Calendar.MONTH)
&& oldCalendar.get(Calendar.DATE) == currCalendar.get(Calendar.DATE);
System.out.println(result);
}
@Test
public void test2() {
checkTestBean(new TestBean());
checkTestBean(null);
}
private void checkTestBean(Object testBean) {
if (testBean instanceof TestBean) {
System.out.println(testBean + " instance TestBean");
} else {
System.out.println(testBean + " not instance TestBean");
}
}
static class TestBean {
}
}<file_sep>/TestSerializable/settings.gradle
include ':app'
rootProject.name='TestSerializable'
<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/viewpager2/PageFragment2.kt
package com.zhaopf.viewpager2.viewpager2
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.fragment_page2.*
class PageFragment2 : Fragment() {
companion object {
fun newInstance(position1: Int, position2: Int): PageFragment2 = PageFragment2().apply {
arguments = Bundle().apply {
putInt("position1", position1)
putInt("position2", position2)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_page2, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewpager2.apply {
orientation = ViewPager2.ORIENTATION_VERTICAL
offscreenPageLimit = 4
adapter =
ViewPagerFragmentStateAdapter3(
childFragmentManager,
lifecycle,
(arguments?.getInt("position1") ?: 0),
(arguments?.getInt("position2") ?: 0),
arrayListOf(
"第1页",
"第2页",
"第3页",
"第4页",
"第5页",
"第6页",
"第7页",
"第8页",
"第9页",
"第10页"
)
)
}
}
}
class ViewPagerFragmentStateAdapter3(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val position1: Int,
private val position2: Int,
private val strList: List<String>
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int = strList.size
override fun createFragment(position: Int): Fragment =
PageFragment3.newInstance(
strList[position],
position1,
position2
)
}<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/util/DeviceUtil.java
package com.zhaopf.testlazyfragment.util;
import android.annotation.SuppressLint;
import android.os.Build;
import android.view.Window;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class DeviceUtil {
/**
* 设置MIUI状态栏的模式
*/
public static void setMIUIStatusBarLightMode(Window window, boolean dark) {
if (window != null) {
Class clazz = window.getClass();
try {
int darkModeFlag;
@SuppressLint("PrivateApi") Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
darkModeFlag = field.getInt(layoutParams);
Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
if (dark) {
// 状态栏透明且黑色字体
extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
} else {
// 清除黑色字体
extraFlagField.invoke(window, 0, darkModeFlag);
}
} catch (Exception ignore) {
}
}
}
/**
* 是否是小米
*/
public static boolean isMIUI() {
return DeviceUtil.getRomType() == ROM_TYPE.MIUI;
}
/**
* 是否是魅族
*/
public static boolean isFlyme() {
return DeviceUtil.getRomType() == DeviceUtil.ROM_TYPE.FLYME;
}
/**
* 获取ROM类型: MIUI_ROM, FLYME_ROM, EMUI_ROM, OTHER_ROM
*/
private static ROM_TYPE getRomType() {
try {
String brand = getROMName();
String s = brand.toLowerCase();
if (s.contains("xiaomi")) {
// 小米 红米
return ROM_TYPE.MIUI;
} else if (s.contains("huawei") || s.contains("honor")) {
// 华为 honor
return ROM_TYPE.EMUI;
} else if (s.contains("meizu")) {
// 魅族
return ROM_TYPE.FLYME;
} else {
return ROM_TYPE.OTHER;
}
} catch (Exception e) {
e.printStackTrace();
return ROM_TYPE.OTHER;
}
}
public enum ROM_TYPE {
/**
* 小米
*/
MIUI,
/**
* 魅族
*/
FLYME,
/**
* 华为
*/
EMUI,
/**
* 其他
*/
OTHER
}
/**
* Rom厂商
*/
public static String getROMName() {
return Build.MANUFACTURER;
}
}<file_sep>/CustomRecyclerViewAdapter/app/src/main/java/com/zhaopingfu/adapter/adapter/BaseAdapter.kt
package com.zhaopingfu.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
import java.io.Serializable
import java.lang.reflect.ParameterizedType
/**
*
* @author zhaopingfu
* @date 2021-03-08 15:52
*/
class BaseAdapter<T : BaseBean, VB : ViewBinding> :
RecyclerView.Adapter<BindingViewHolder<VB>>() {
private val dataList: MutableList<T> by lazy { mutableListOf() }
private val holderMap: MutableMap<Int, BaseTemplate<T, VB>> by lazy { mutableMapOf() }
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): BindingViewHolder<VB> {
val data = dataList[viewType]
val template = holderMap[data.getViewType()]
val method = template?.bindingClass?.getMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.java
)
val binding =
method?.invoke(null, LayoutInflater.from(parent.context), parent, false) as ViewBinding
return BindingViewHolder(binding)
}
override fun onBindViewHolder(holder: BindingViewHolder<VB>, position: Int) {
val bean = dataList[position]
holderMap[bean.getViewType()]?.bindData(holder, bean, position)
}
override fun getItemCount(): Int = dataList.size
override fun getItemViewType(position: Int): Int {
return dataList[position].getViewType()
}
fun addHolder(type: Int, holder: BaseTemplate<T, VB>) {
holderMap[type] = holder
}
fun addData(dataList: List<T>) {
this.dataList.addAll(dataList)
}
}
abstract class BaseTemplate<out T : BaseBean, out VB : ViewBinding> {
lateinit var bindingClass: Class<*>
init {
val superClass = javaClass.genericSuperclass
if (superClass is ParameterizedType) {
val typeArray = superClass.actualTypeArguments
bindingClass = typeArray[1] as Class<*>
}
}
abstract fun bindData(
holder: BindingViewHolder<VB>,
bean: @UnsafeVariance T,
position: Int
)
}
abstract class BaseBean : Serializable {
abstract fun getViewType(): Int
}
/**
* ViewHolder binding
*/
class BindingViewHolder<in VB : ViewBinding>(val binding: @UnsafeVariance VB) :
RecyclerView.ViewHolder(binding.root)
<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/data/AppDatabase.kt
package com.zhaopf.testhilt.data
import androidx.room.Database
import androidx.room.RoomDatabase
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@Database(entities = arrayOf(Log::class), version = 1, exportSchema = true)
abstract class AppDatabase : RoomDatabase() {
abstract fun logDao(): LogDao
}<file_sep>/ViewPager2/README.md
- 使用 `ViewPager2`
- 添加 `view` 到 `window` 最好用 `activity.getWindow().getDecorView().addView()` 来做, 如果直接用 `windowManager` 来添加的话, 不好做动画<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/di/NavigationModel.kt
package com.zhaopf.testhilt.di
import com.zhaopf.testhilt.navigator.AppNavigator
import com.zhaopf.testhilt.navigator.AppNavigatorImpl
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@InstallIn(ActivityComponent::class)
@Module
abstract class NavigationModel {
@Binds
abstract fun bind(impl: AppNavigatorImpl): AppNavigator
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/LayerActivity.kt
package com.meta.testmotionlayout
import android.animation.ValueAnimator
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.meta.testmotionlayout.databinding.ActivityLayerBinding
class LayerActivity : AppCompatActivity() {
private lateinit var binding: ActivityLayerBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityLayerBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btn8.setOnClickListener {
val anim = ValueAnimator.ofFloat(0f, 360f)
anim.duration = 300
anim.addUpdateListener { animation ->
val angle = animation.animatedValue as Float
binding.layer.rotation = angle
binding.layer.scaleX = 1 + (180 - Math.abs(angle - 180)) / 20f
binding.layer.scaleY = 1 + (180 - Math.abs(angle - 180)) / 20f
val shiftX = 500 * Math.sin(Math.toRadians((angle * 5).toDouble())).toFloat()
val shiftY = 500 * Math.sin(Math.toRadians((angle * 7).toDouble())).toFloat()
binding.layer.translationX = shiftX
binding.layer.translationY = shiftY
}
anim.duration = 4000
anim.start()
}
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/BarrierActivity.kt
package com.meta.testmotionlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
class BarrierActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_barrier)
}
}<file_sep>/SophixDemo/build.gradle
buildscript {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://jitpack.io' }
// sophix
maven { url 'http://maven.aliyun.com/nexus/content/repositories/releases/' }
}
dependencies {
// 这里升级上去的话,gradle 版本也要升级。
classpath 'com.android.tools.build:gradle:3.1.3'
// 添加 emas-services 插件
classpath 'com.aliyun.ams:emas-services:1.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
mavenCentral()
maven { url 'https://jitpack.io' }
maven { url 'http://maven.aliyun.com/nexus/content/repositories/releases/' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
tasks.withType(JavaCompile) {
options.encoding = "UTF-8"
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/ui/ButtonFragment.kt
package com.zhaopf.testhilt.ui
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import com.zhaopf.testhilt.R
import com.zhaopf.testhilt.data.LoggerDataSource
import com.zhaopf.testhilt.data.User
import com.zhaopf.testhilt.di.DatabaseLogger
import com.zhaopf.testhilt.di.InMemoryLogger
import com.zhaopf.testhilt.navigator.AppNavigator
import com.zhaopf.testhilt.navigator.Screens
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@AndroidEntryPoint
class ButtonFragment : Fragment() {
private val TAG = "ButtonFragment"
@DatabaseLogger
@Inject
lateinit var logger: LoggerDataSource
@Inject
lateinit var navigator: AppNavigator
@Inject
lateinit var user: User
private var num: Int = 100
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_buttons, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
view.findViewById<Button>(R.id.button1).setOnClickListener {
logger.addLog("Interaction with 'Button 1'")
}
view.findViewById<Button>(R.id.button2).setOnClickListener {
logger.addLog("Interaction with 'Button 2'")
}
view.findViewById<Button>(R.id.button3).setOnClickListener {
logger.addLog("Interaction with 'Button 3'")
}
view.findViewById<Button>(R.id.all_logs).setOnClickListener {
navigator.navigateTo(Screens.LOGS)
}
view.findViewById<Button>(R.id.delete_logs).setOnClickListener {
logger.removeLogs()
// user.age = num++
android.util.Log.d(TAG, "$user")
}
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/fly_in_helper/FlyInHelper.kt
package com.meta.testmotionlayout.fly_in_helper
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.PointF
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintHelper
import androidx.constraintlayout.widget.ConstraintLayout
class FlyInHelper : ConstraintHelper {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet) : super(context, attrs)
constructor (context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
override fun updatePostLayout(container: ConstraintLayout?) {
super.updatePostLayout(container)
container ?: return
// 中心点的位置
val centerPointF = PointF((left + right) / 2f, (top + bottom) / 2f)
ValueAnimator.ofFloat(0F, 1F).apply {
duration = 1000L
addUpdateListener {
getViews(container).forEach { view ->
val viewCenterX = (view.left + view.right) / 2f
val viewCenterY = (view.top + view.bottom) / 2f
val startTranslationX = if (viewCenterX > centerPointF.x) 600F else -600F
val startTranslationY = if (viewCenterY > centerPointF.y) 600F else -600F
view.translationX = (1f - animatedFraction) * startTranslationX
view.translationY = (1f - animatedFraction) * startTranslationY
}
}
start()
}
}
}<file_sep>/RobustDemo/app/src/main/java/com/meta/robustdemo/robust/RobustCallBackSample.java
package com.meta.robustdemo.robust;
import android.util.Log;
import com.meituan.robust.Patch;
import com.meituan.robust.RobustCallBack;
import java.util.List;
/**
* @author PingFu.Zhao
* 2019/8/5
*/
public class RobustCallBackSample implements RobustCallBack {
private static final String TAG = "RobustCallBackSample";
@Override
public void onPatchListFetched(boolean result, boolean isNet, List<Patch> patches) {
Log.d(TAG, "onPatchListFetched result: " + result);
Log.d(TAG, "onPatchListFetched isNet: " + isNet);
for (Patch patch : patches) {
Log.d(TAG, "onPatchListFetched patch: " + patch.getName());
}
}
@Override
public void onPatchFetched(boolean result, boolean isNet, Patch patch) {
Log.d(TAG, "onPatchFetched result: " + result);
Log.d(TAG, "onPatchFetched isNet: " + isNet);
Log.d(TAG, "onPatchFetched patch: " + patch.getName());
}
@Override
public void onPatchApplied(boolean result, Patch patch) {
Log.d(TAG, "onPatchApplied result: " + result);
Log.d(TAG, "onPatchApplied patch: " + patch.getName());
}
@Override
public void logNotify(String log, String where) {
Log.d(TAG, "logNotify log: " + log);
Log.d(TAG, "logNotify where: " + where);
}
@Override
public void exceptionNotify(Throwable throwable, String where) {
Log.e(TAG, "exceptionNotify where: " + where, throwable);
}
}<file_sep>/SophixDemo/app/src/main/java/com/meta/sophixdemo/SecondActivity.java
package com.meta.sophixdemo;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Button;
import android.widget.Toast;
/**
* @author zhaopf
*/
public class SecondActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
// 跳转到第三个页面
Button btnJumpToThirdActivity = findViewById(R.id.btn_jump_to_third_activity);
// 吐司
Button btnToast = findViewById(R.id.btn_toast);
btnJumpToThirdActivity.setOnClickListener(v ->
startActivity(new Intent(v.getContext(), ThirdActivity.class)));
btnToast.setOnClickListener(v -> addNewMethod());
}
private void addNewMethod() {
Toast.makeText(this, "新增的方法", Toast.LENGTH_SHORT).show();
}
}<file_sep>/TestBaseQuickAdapter/app/src/main/java/com/zhaopf/testbasequickadapter/MAdapter.kt
package com.zhaopf.testbasequickadapter
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
/**
*
* @author PingFu.Zhao
* 2019/7/29
*
* 最简单的显示数据
*/
class MAdapter(layoutResId: Int, data: MutableList<DataItemBean>) :
BaseQuickAdapter<DataItemBean, BaseViewHolder>(layoutResId, data) {
override fun convert(helper: BaseViewHolder, item: DataItemBean) {
helper.setImageResource(R.id.iv_item, R.mipmap.ic_launcher)
.setText(R.id.btn_item, "${helper.adapterPosition}")
.addOnClickListener(R.id.btn_item)
}
}<file_sep>/TestOptimizePlugin/settings.gradle
include ':app'
include ':test_lib'
include ':meta_optimize_plugin'
<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/adapter/MainVpAdapter.kt
package com.zhaopf.testlazyfragment.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.zhaopf.testlazyfragment.fragments.*
/**
* @author pingfu.zhao
* @date 2020-01-14 10:56
*/
class MainVpAdapter(fm: FragmentManager) : BaseVpAdapter(fm) {
override fun getItem(position: Int): Fragment = when (position) {
0 -> HomeFragment()
1 -> ChallengeFragment()
2 -> MakeMoneyFragment()
3 -> TaskFragment()
else -> GameLibraryFragment()
}
override fun getCount(): Int = 5
override fun getPageTitle(position: Int): CharSequence? = when (position) {
0 -> "首页"
1 -> "挑战"
2 -> "赚钱"
3 -> "任务"
else -> "游戏库"
}
}<file_sep>/TestHotFix/app/src/main/java/com/example/testhotfix/fixmethod/ReflectUtil.java
package com.example.testhotfix.fixmethod;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectUtil {
public static Field getField(Object obj, String name) throws NoSuchFieldException {
Class<?> clazz = obj.getClass();
while (null != clazz) {
try {
Field field = clazz.getDeclaredField(name);
field.setAccessible(true);
return field;
} catch (NoSuchFieldException e) {
clazz = clazz.getSuperclass();
}
}
throw new NoSuchFieldException("Field:" + name + " not found in " + obj.getClass());
}
public static Method getMethod(Object obj, String name, Class<?>... params) {
Class<?> clazz = obj.getClass();
while (null != clazz) {
try {
Method method = clazz.getDeclaredMethod(name, params);
method.setAccessible(true);
return method;
} catch (NoSuchMethodException e) {
clazz = clazz.getSuperclass();
}
}
return null;
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/1.kotlin配置.md
### 1、`Android` 中使用 `Kotlin`
1. 需要在项目的根节点下的 `build.gradle` 添加依赖
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50"
2. 在 `Module` 的 `build.gradle` 下添加相关插件和依赖
- 添加插件
apply plugin: 'kotlin-android'
// 扩展插件,用来在代码中直接使用控件ID来进行操作
apply plugin: 'kotlin-android-extensions'
- 添加依赖
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.50"
### 2、将现有的 `Java` 代码转为 `Kotlin` 代码
选中要转换的 `Java` 类, 选择顶部工具栏中的 `Code -> Convert Java File to Kotlin File`
### 3、查看 `Kotlin` 代码转为 `Java` 之后大概是什么代码
1. 打开 `Kotlin` 文件
2. 选择顶部工具栏 `Tools -> Kotlin -> Show Kotlin Bytecode`
3. 在右侧的区域中点击左上角的 `Decompile`<file_sep>/TestStyleAndTheme/app/src/main/java/com/zhaopf/teststyleandtheme/WindowPreFerencesManager.kt
package com.zhaopf.teststyleandtheme
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Color.TRANSPARENT
import android.os.Build.VERSION.SDK_INT
import android.os.Build.VERSION_CODES.*
import android.view.View
import androidx.annotation.ColorInt
import androidx.appcompat.app.AppCompatActivity
import androidx.core.graphics.ColorUtils
import com.google.android.material.color.MaterialColors
/**
* @author Flywith24
* @date 2020/6/24
* time 9:17
* description
*/
private const val EDGE_TO_EDGE_BAR_ALPHA = 128
private const val EDGE_TO_EDGE_FLAGS =
View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
/**
* 设置是否全屏(状态栏和导航栏不占空间)
*/
@SuppressLint("ObsoleteSdkInt")
fun AppCompatActivity.applyEdgeToEdgePreference(edgeToEdgeEnabled: Boolean) {
if (SDK_INT < LOLLIPOP) return
val statusBarColor = getStatusBarColor(edgeToEdgeEnabled, this)
val navBarColor = getNavBarColor(edgeToEdgeEnabled, this)
val lightBackground =
isColorLight(MaterialColors.getColor(this, android.R.attr.colorBackground, Color.BLACK))
val lightNavBar = isColorLight(navBarColor)
val showDarkNavBarIcons =
lightNavBar || navBarColor == TRANSPARENT && lightBackground
with(window) {
val currentStatusBar =
if (SDK_INT >= M) decorView.systemUiVisibility and View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR else 0
val currentNavBar =
if (showDarkNavBarIcons && SDK_INT >= O) View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR else 0
this.navigationBarColor = navBarColor
this.statusBarColor = statusBarColor
val systemUiVisibility =
((if (edgeToEdgeEnabled) EDGE_TO_EDGE_FLAGS else View.SYSTEM_UI_FLAG_VISIBLE)
or currentStatusBar
or currentNavBar)
decorView.systemUiVisibility = systemUiVisibility
}
}
/**
* 获取状态栏颜色
*/
@SuppressLint("ObsoleteSdkInt")
fun getStatusBarColor(edgeToEdgeEnabled: Boolean, context: Context): Int = when {
//低版本
edgeToEdgeEnabled && SDK_INT < M -> {
val opaqueStatusBarColor =
MaterialColors.getColor(context, android.R.attr.statusBarColor, Color.BLACK)
ColorUtils.setAlphaComponent(opaqueStatusBarColor, EDGE_TO_EDGE_BAR_ALPHA)
}
edgeToEdgeEnabled -> TRANSPARENT
else -> MaterialColors.getColor(context, android.R.attr.statusBarColor, Color.BLACK)
}
/**
* 获取导航栏颜色
*/
fun getNavBarColor(edgeToEdgeEnabled: Boolean, context: Context): Int = when {
//低版本
edgeToEdgeEnabled && SDK_INT < O_MR1 -> {
val opaqueStatusBarColor =
MaterialColors.getColor(context, android.R.attr.navigationBarColor, Color.BLACK)
ColorUtils.setAlphaComponent(opaqueStatusBarColor, EDGE_TO_EDGE_BAR_ALPHA)
}
edgeToEdgeEnabled -> TRANSPARENT
else -> MaterialColors.getColor(context, android.R.attr.navigationBarColor, Color.BLACK)
}
fun isColorLight(@ColorInt color: Int): Boolean {
return color != TRANSPARENT && ColorUtils.calculateLuminance(color) > 0.5
}<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/adapter/BaseVpStateAdapter.kt
package com.zhaopf.testlazyfragment.adapter
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentStatePagerAdapter
/**
* @author pingfu.zhao
* @date 2020-01-14 11:28
*/
abstract class BaseVpStateAdapter(fm: FragmentManager) :
FragmentStatePagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
var mCurrentPrimaryItem: Fragment? = null
override fun setPrimaryItem(container: ViewGroup, position: Int, obj: Any) {
super.setPrimaryItem(container, position, obj)
if (obj is Fragment) {
mCurrentPrimaryItem = obj
}
}
}<file_sep>/RoomWordSample/README.md
链接: https://developer.android.com/codelabs/android-room-with-a-view-kotlin<file_sep>/TestGuava/settings.gradle
rootProject.name='TestGuava'
include ':app'
<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/5.Singleton.kt
package com.meta.kotlinstudy.基础部分
import android.app.Application
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.TextView
// 最简单的单例
object Singleton {
var name: String = ""
fun test() {}
}
fun testSingleton() {
Singleton.name = "testName"
Singleton.test()
}
/**
* 在Kotlin中一般实现接口或者抽象类都是用object
*/
fun testObject() {
val tv: TextView? = null
tv?.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
}
})
// 如果接口只有一个方法,可以直接用大括号
tv?.setOnClickListener { }
tv?.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
/**
* 有时候Android中需要全局单例Application
*/
class MyApp : Application() {
companion object {
lateinit var INSTANCE: MyApp
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
}
}
/**
* 可以直接声明顶层变量加 lazy
*/
val testList by lazy { ArrayList<String>() }
/**
* 加锁的,类似java的DCL
*/
class DoubleCheckSingleton private constructor() {
companion object {
// kotlin 写法
val INSTANCE_1 by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
DoubleCheckSingleton()
}
// 翻译Java写法
private var INSTANCE_2: DoubleCheckSingleton? = null
// 如果要给方法加锁要用
// @Synchronized
fun getInstance(): DoubleCheckSingleton {
if (null == INSTANCE_2) {
synchronized(DoubleCheckSingleton::class) {
if (null == INSTANCE_2) {
INSTANCE_2 = DoubleCheckSingleton()
}
}
}
// 这里用!! 表示强制转换为非空的
return INSTANCE_2!!
}
}
}
/**
* 内部类的方式
*/
class InnerStaticSingleton private constructor() {
companion object {
fun getInstance() = Holder.INSTANCE
}
private object Holder {
val INSTANCE = InnerStaticSingleton()
}
}<file_sep>/TestGradleTaskOrder/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
defaultConfig {
applicationId "com.meta.testgradletaskorder"
minSdkVersion 19
targetSdkVersion 29
versionCode 1
versionName "1.0"
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
signingConfigs {
release {
storeFile file('app.jks')
storePassword '<PASSWORD>'
keyAlias 'testAlias'
keyPassword '123456'
v1SigningEnabled true
v2SigningEnabled true
}
}
buildTypes {
debug {
signingConfig signingConfigs.release
}
release {
signingConfig signingConfigs.release
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
flavorDimensions "app"
productFlavors {
dev {
dimension "app"
}
stub {
dimension "app"
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
/**
* 热修复相关的文件拷贝
*/
project.afterEvaluate {
// preBuild 任务执行之前执行 copyPreCommitFile
preBuild.dependsOn 'copyPreCommitFile'
// 打包成功之后执行复制任务
if (project.plugins.hasPlugin('kotlin-android')) {
project.android.applicationVariants.all { com.android.build.gradle.api.BaseVariant variant ->
def taskVariantName = "${variant.flavorName.capitalize()}${variant.buildType.name.capitalize()}"
def taskName = "assemble$taskVariantName"
def task = project.tasks.findByName(taskName)
if (null != task) {
task.doLast {
def basePath = "${variant.flavorName}/${variant.buildType.name}"
def apkDir = new File("${rootDir.absolutePath}/app/build/outputs/apk/$basePath/")
if (apkDir.exists() && apkDir.isDirectory()) {
def apkDirList = apkDir.listFiles(new FilenameFilter() {
@Override
boolean accept(File file, String s) {
return s.endsWith(".apk")
}
})
if (null != apkDirList && apkDirList.size() > 0) {
def apkPath = apkDirList.getAt(0).absolutePath
def mappingPath = "${rootDir.absolutePath}/app/build/outputs/mapping/$basePath/mapping.txt"
def robustMethodsMapPath = "${rootDir.absolutePath}/app/build/outputs/robust/methodsMap.robust"
// 目标文件夹
def targetPath = "${rootDir.absolutePath}/app/robust/"
// 复制文件
copyFile(apkPath, "$targetPath/${new File(apkPath).name}")
copyFile(mappingPath, "$targetPath/${new File(mappingPath).name}")
copyFile(robustMethodsMapPath, "$targetPath/${new File(robustMethodsMapPath).name}")
}
}
}
}
}
}
}
/**
* 复制文件
*/
void copyFile(String src, String dsc) {
def srcFile = new File(src)
if (srcFile.exists()) {
def desFile = new File(dsc)
if (desFile.exists()) {
desFile.delete()
} else {
desFile.parentFile.mkdirs()
desFile.createNewFile()
}
desFile.setBytes(srcFile.getBytes())
}
}
/**
* 将 pre-commit 复制到 .git/hooks/ 目录下
*/
task copyPreCommitFile(type: Copy) {
from('./pre-commit')
into('../.git/hooks')
}<file_sep>/GetLauncherPackageName/app/src/main/java/com/zhaopf/getlauncherpackagename/activitys/BaseActivity.kt
package com.zhaopf.getlauncherpackagename.activitys
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import com.zhaopf.getlauncherpackagename.utils.checkIsFromHomeLauncherApp
/**
* @author PingFu.Zhao
* 2019/7/30
*/
open class BaseActivity : AppCompatActivity() {
private val TAG = "BaseActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (checkIsFromHomeLauncherApp(this)) {
Log.d(TAG, "from desktop")
} else {
Log.d(TAG, "not from desktop")
}
}
}<file_sep>/TestOptimizePlugin/README.md
### 图片压缩
这里没有考虑兼容 `api18` 以下的机型(api18以下带透明度通道的不支持转换为webp)
1、先收集所有 `assets`, `res` 目录下的 `png`, `jpg` 图片
排除 `.9.png` 和 `启动图标`
2、将图片转换为 `webp`
3、`webp` 转换失败的进行压缩处理
`png` 优先使用 `tiny` 压缩, 如果压缩失败采用 `pngCrush` 压缩
`jpg` 采用 `guetzli` 压缩
### 使用
1、添加插件依赖 apply plugin: 'com.meta.optimizer'
如果找不到插件, 先把插件注释掉, 然后执行 `meta_optimize_plugin` 模块下 `/publishing/publishOptimizerPublicationToMavenLocal` 任务
2、配置参数
optimizePicture {
// 是否使用tiny压缩
useTinyCompress true
// 如果使用tiny压缩的话, 需要去官网申请key, 每个月前500张图片免费
tinyKey rootConfig.tinyKey
// 是否压缩 assets 下的图片
isCompressAssets true
}
3、执行模块下的 `optimizer/optimizePicture` 任务<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/VideoItemFragment.kt
package com.zhaopf.testexoplayer
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.google.android.exoplayer2.Player
import kotlinx.android.synthetic.main.fragment_video_item.*
class VideoItemFragment : Fragment() {
private val TAG = "VideoItemFragment"
private var mData: VideoBean? = null
private lateinit var mProxyUrl: String
companion object {
fun newInstance(videoBean: VideoBean): VideoItemFragment =
VideoItemFragment().apply {
arguments = Bundle().apply {
putSerializable("videoBean", videoBean)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_video_item, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mData = arguments?.getSerializable("videoBean") as VideoBean?
Log.d(TAG, "onViewCreated ${mData?.nickname}")
tvText.text = mData?.title ?: "未知"
Glide.with(this)
.load(mData?.videoCover ?: "")
.into(ivCover)
mProxyUrl = MyApp.proxy.getProxyUrl(mData?.videoUrl ?: "")
}
override fun onResume() {
super.onResume()
Log.d(TAG, "onResume ${mData?.nickname}")
mExoPlayer.prepare(mProxyUrl)
// 避免不显示的问题
if (playerView.player == mExoPlayer) {
playerView.player = null
}
playerView.player = mExoPlayer
mExoPlayer.addListener(object : Player.EventListener {
override fun onPlayerStateChanged(playWhenReady: Boolean, playbackState: Int) {
super.onPlayerStateChanged(playWhenReady, playbackState)
if (playWhenReady && playbackState == Player.STATE_READY) {
ivCover?.visibility = View.GONE
} else if (playWhenReady) {
// Not playing because playback ended, the player is buffering, stopped or
// failed. Check playbackState and player.getPlaybackError for details.
} else {
// Paused by app.
}
}
})
mExoPlayer.playWhenReady = true
}
override fun onPause() {
super.onPause()
mExoPlayer.playWhenReady = false
Log.d(TAG, "onPause ${mData?.nickname}")
}
}<file_sep>/TestHotFix/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.example.testhotfix"
minSdkVersion 16
targetSdkVersion 29
versionCode 1
versionName "1.0"
multiDexEnabled true
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
// https://mvnrepository.com/artifact/org.ow2.asm/asm
implementation 'org.ow2.asm:asm:7.2'
}
afterEvaluate {
android.applicationVariants.all { variant ->
// 获得: debug/release
String variantName = variant.getName()
// 首字母大写
String capitalizeName = variantName.capitalize()
println capitalizeName
// 获取打包时jar和class打包成dex 的任务
Task dexTask = project.tasks.findByName("transformClassesWithDexBuilderFor$capitalizeName")
// 在打包之前插桩
dexTask.doFirst {
// 任务的输入,也就是 class 和 jar
Set<File> files = dexTask.inputs.files.files
for (File file : files) {
String filePath = file.absolutePath
if (filePath.endsWith(".jar")) {
processJar(file)
} else if (filePath.endsWith(".class")) {
// processClass(variant.getDirName(), file)
processClass("classes", file)
}
}
}
}
}
static boolean isAndroidClass(String filePath) {
return filePath.startsWith("android") ||
filePath.startsWith("androidx")
}
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
static byte[] referHackWhenInit(InputStream inputStream) throws IOException {
ClassReader cr = new ClassReader(inputStream)
ClassWriter cw = new ClassWriter(cr, 0)
ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
@Override
MethodVisitor visitMethod(int access, final String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions)
mv = new MethodVisitor(Opcodes.ASM5, mv) {
@Override
void visitInsn(int opcode) {
// 在构造方法中插入 AntilazyLoad 引用
if ("<init>".equals(name) && opcode == Opcodes.RETURN) {
super.visitLdcInsn(Type.getType("Lcom/example/hack/AntilazyLoad;"))
}
super.visitInsn(opcode)
}
}
return mv
}
}
cr.accept(cv, 0)
return cw.toByteArray()
}
static void processClass(String dirName, File file) {
String filePath = file.absolutePath
// 这里的filePath包含了目录+包名+类名,所以去掉目录
String className = filePath.split(dirName)[1].substring(1)
// application 或者android support不管
if (isAndroidClass(className) ||
className.startsWith("com\\example\\testhotfix\\MyApplication") ||
className.startsWith("com\\example\\testhotfix\\fixmethod")) {
return
}
try {
FileInputStream fis = new FileInputStream(filePath)
// 执行插桩
byte[] byteCode = referHackWhenInit(fis)
fis.close()
FileOutputStream fos = new FileOutputStream(filePath)
fos.write(byteCode)
fos.close()
} catch (Exception e) {
e.printStackTrace()
}
}
static void processJar(File file) {
try {
File bakJar = new File(file.parent, "${file.name}.bak")
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(bakJar))
JarFile jarFile = new JarFile(file)
Enumeration<JarEntry> entries = jarFile.entries()
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement()
jarOutputStream.putNextEntry(new JarEntry(jarEntry.name))
InputStream is = jarFile.getInputStream(jarEntry)
String className = jarEntry.getName()
if (className.endsWith(".class")
&& !className.startsWith("com/example/testhotfix/MyApplication")
&& !isAndroidClass(className)
&& !className.startsWith("com/example/testhotfix/fixmethod")) {
}
}
} catch (Exception e) {
e.printStackTrace()
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/WithCoordinatorLayoutActivity.kt
package com.meta.testmotionlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.google.android.material.appbar.AppBarLayout
import com.meta.testmotionlayout.databinding.ActivityWithCoordinatorLayoutBinding
class WithCoordinatorLayoutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityWithCoordinatorLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.appBar.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
binding.motionLayout.progress =
-verticalOffset / appBarLayout.totalScrollRange.toFloat()
})
}
}
<file_sep>/TestHotFix/settings.gradle
include ':app', ':hack'
rootProject.name='TestHotFix'
<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/test/Singleton.kt
package com.meta.kotlinstudy.test
/**
* @author pingfu.zhao
* @date 2019-09-21 15:20
*/
object BaseSingleton {
}
class LazyLoadSingleton private constructor() {
companion object {
/**
* 这里是线程安全的
*/
val INSTANCE by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
LazyLoadSingleton()
}
}
}
class LazySynchronizedSingleton private constructor() {
companion object {
private var INSTANCE: LazySynchronizedSingleton? = null
@Synchronized
fun getInstance(): LazySynchronizedSingleton {
if (null == INSTANCE) {
INSTANCE = LazySynchronizedSingleton()
}
return INSTANCE!!
}
}
}<file_sep>/TestBaseQuickAdapter/app/src/main/java/com/zhaopf/testbasequickadapter/MDraggableAdapter.kt
package com.zhaopf.testbasequickadapter
import com.chad.library.adapter.base.BaseItemDraggableAdapter
import com.chad.library.adapter.base.BaseViewHolder
/**
*
* @author PingFu.Zhao
* 2019/7/29
*
* 侧滑
*/
class MDraggableAdapter(layoutResId: Int, data: MutableList<DataItemBean>?) :
BaseItemDraggableAdapter<DataItemBean, BaseViewHolder>(layoutResId, data) {
override fun convert(helper: BaseViewHolder, item: DataItemBean?) {
}
}<file_sep>/CustomView/app/src/main/java/com/zhaopingfu/customview/SimpleNestedScrollView.kt
package com.zhaopingfu.customview
import android.content.Context
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.ScrollView
import kotlin.math.abs
/**
* https://juejin.cn/post/6844903761060577294
*
* @author zhaopingfu
* @date 2021-03-10 16:37
*/
class SimpleNestedScrollView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
private var isFirstIntercept = true
/**
* 第一次「拦截滑动的判定条件」成立时,先不进行拦截,如果内部没有申请外部不拦截,第二次条件成立时,再进行拦截
*/
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
if (ev.actionMasked == MotionEvent.ACTION_DOWN) {
isFirstIntercept = true
}
val result = super.onInterceptTouchEvent(ev)
if (result && isFirstIntercept) {
isFirstIntercept = false
return false
}
return result
}
}
class InnerNestedScrollView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
override fun scrollBy(x: Int, y: Int) {
if ((y > 0 && isScrollToTop()) || (y < 0 && isScrollToBottom())) {
(parent as View).scrollBy(x, y)
} else {
super.scrollBy(x, y)
}
}
private var isNeedRequestDisallowIntercept: Boolean? = null
private val mTouchSlop by lazy { ViewConfiguration.get(context).scaledTouchSlop }
/**
* 在自己无法滑动时,返回false
*/
override fun onTouchEvent(ev: MotionEvent): Boolean {
if (ev.actionMasked == MotionEvent.ACTION_DOWN) isNeedRequestDisallowIntercept = null
if (ev.actionMasked == MotionEvent.ACTION_MOVE) {
if (isNeedRequestDisallowIntercept == false) return false
if (isNeedRequestDisallowIntercept == null) {
val offsetY = ev.y.toInt() - getInt("mLastMotionY")
if (abs(offsetY) > mTouchSlop) {
if ((offsetY > 0 && isScrollToTop()) || (offsetY < 0 && isScrollToBottom())) {
isNeedRequestDisallowIntercept = false
return false
}
}
}
}
return super.onTouchEvent(ev)
}
private fun getInt(fieldName: String): Int {
val field = javaClass.superclass.getDeclaredField(fieldName).apply { isAccessible = true }
return field.getInt(this)
}
private fun isScrollToTop(): Boolean = scrollY == 0
private fun isScrollToBottom(): Boolean {
return scrollY + height - paddingTop - paddingBottom == getChildAt(0).height
}
}
class InnerNestedScrollView2 @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ScrollView(context, attrs, defStyleAttr) {
private val TAG = "InnerNestedScrollView2"
override fun scrollBy(x: Int, y: Int) {
if ((y > 0 && isScrollToTop()) || (y < 0 && isScrollToBottom())) {
Log.d(TAG, "scrollBy: 1111")
(parent as View).scrollBy(x, y)
} else {
Log.d(TAG, "scrollBy: 222: $y")
super.scrollBy(x, y)
}
}
private val mTouchSlop by lazy { ViewConfiguration.get(context).scaledTouchSlop }
override fun dispatchTouchEvent(ev: MotionEvent): Boolean {
if (ev.actionMasked == MotionEvent.ACTION_DOWN) {
parent?.requestDisallowInterceptTouchEvent(true)
}
if (ev.actionMasked == MotionEvent.ACTION_MOVE) {
val offsetY = ev.y.toInt() - getInt("mLastMotionY")
if (abs(offsetY) > mTouchSlop) {
if ((offsetY > 0 && isScrollToTop()) || (offsetY < 0 && isScrollToBottom())) {
parent?.requestDisallowInterceptTouchEvent(false)
return false
}
}
}
return super.dispatchTouchEvent(ev)
}
private fun getInt(fieldName: String): Int {
val field = javaClass.superclass.getDeclaredField(fieldName).apply { isAccessible = true }
return field.getInt(this)
}
private fun isScrollToTop(): Boolean = scrollY == 0
private fun isScrollToBottom(): Boolean {
return scrollY + height - paddingTop - paddingBottom == getChildAt(0).height
}
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/MainViewModel.kt
package com.meta.kotlinstudy
import android.util.Log
import androidx.lifecycle.*
import com.meta.kotlinstudy.coroutine_retrofit.BannerItemBean
import com.meta.kotlinstudy.coroutine_retrofit.RetrofitClient
import kotlinx.coroutines.launch
/**
* @author zhaopingfu
* @date 2019-09-21 17:11
*/
class MainViewModel(private val str: String) : ViewModel() {
private val TAG = "MainViewModel"
val bannerList: MutableLiveData<List<BannerItemBean>> by lazy { MutableLiveData() }
fun getBannerList() {
viewModelScope.launch {
val listRepos = RetrofitClient.articleService.listRepos()
Log.d(TAG, "getBannerList: $listRepos")
bannerList.value = listRepos.data
}
}
}
class MainViewModelProvider(owner: ViewModelStoreOwner, factory: Factory) :
ViewModelProvider(owner, factory)
class MainViewModelFactory(private val str: String) : ViewModelProvider.NewInstanceFactory() {
override fun <T : ViewModel?> create(modelClass: Class<T>): T {
return modelClass.getConstructor(String::class.java)
.newInstance(str)
}
}<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/adapter/PopularVpAdapter.kt
package com.zhaopf.testlazyfragment.adapter
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.zhaopf.testlazyfragment.fragments.*
/**
* @author pingfu.zhao
* @date 2020-01-14 10:56
*/
class PopularVpAdapter(fm: FragmentManager) : BaseVpStateAdapter(fm) {
override fun getItem(position: Int): Fragment = VideoItemFragment().apply {
arguments = Bundle().apply {
putString("TAG", "视频: ${position + 1}")
}
}
override fun getCount(): Int = 10
override fun getPageTitle(position: Int): CharSequence? = "视频: ${position + 1}"
}<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/coroutine_retrofit/WanAndroidService.kt
package com.meta.kotlinstudy.coroutine_retrofit
import retrofit2.http.GET
/**
*
* @author zhaopingfu
* @date 2021-05-31 10:18
*/
interface WanAndroidService {
@GET("banner/json")
suspend fun listRepos(): ResultData<List<BannerItemBean>>
}
<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/testReified.kt
package com.meta.kotlinstudy
import android.app.Activity
import android.app.Application
import android.content.Intent
import android.os.Bundle
import java.lang.reflect.InvocationHandler
import java.lang.reflect.Proxy
/**
*
*
* @author zhaopingfu
* @date 2020/12/2
*/
inline fun <reified T : Any> noOpDelegate(): T {
val javaClass = T::class.java
val noOpHandler = InvocationHandler { _, _, _ ->
}
return Proxy.newProxyInstance(javaClass.classLoader, arrayOf(javaClass), noOpHandler) as T
}
val lifecycleCallbacks = object : Application.ActivityLifecycleCallbacks by noOpDelegate() {
override fun onActivityDestroyed(activity: Activity) {
}
override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) {
}
}
inline fun <reified T : Activity> Activity.startActivity() {
startActivity(Intent(this, T::class.java))
}
class AaActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
startActivity<MainActivity>()
}
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/navigator/AppNavigatorImpl.kt
package com.zhaopf.testhilt.navigator
import androidx.fragment.app.FragmentActivity
import com.zhaopf.testhilt.R
import com.zhaopf.testhilt.ui.ButtonFragment
import com.zhaopf.testhilt.ui.LogFragment
import javax.inject.Inject
/**
* @author zhaopingfu
* @date 2020/10/23
*/
class AppNavigatorImpl @Inject constructor(private val activity: FragmentActivity) : AppNavigator {
override fun navigateTo(screen: Screens) {
val fragment = when (screen) {
Screens.BUTTONS -> ButtonFragment()
Screens.LOGS -> LogFragment()
}
activity.supportFragmentManager
.beginTransaction()
.replace(R.id.main_container, fragment)
.addToBackStack(fragment::class.java.canonicalName)
.commit()
}
}<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/viewpager2/PageFragment3.kt
package com.zhaopf.viewpager2.viewpager2
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.fragment_page3.*
class PageFragment3 : Fragment() {
companion object {
fun newInstance(strText: String, position1: Int, position2: Int): PageFragment3 =
PageFragment3().apply {
arguments = Bundle().apply {
putString("text", strText)
putInt("position1", position1)
putInt("position2", position2)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_page3, container, false)
}
private val TAG = "PageFragment3"
private lateinit var mStr: String
private var position1: Int = 0
private var position2: Int = 0
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mStr = arguments?.getString("text") ?: "未知"
position1 = arguments?.getInt("position1") ?: 0
position2 = arguments?.getInt("position2") ?: 0
tvText.text = "${javaClass.name} $mStr"
}
override fun onResume() {
super.onResume()
if (position1 == 0 && position2 == 0) {
Log.d(TAG, "onResume $mStr")
}
}
override fun onPause() {
super.onPause()
if (position1 == 0 && position2 == 0) {
Log.d(TAG, "onPause $mStr")
}
}
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/di/LoggingModule.kt
package com.zhaopf.testhilt.di
import com.zhaopf.testhilt.data.LoggerDataSource
import com.zhaopf.testhilt.data.LoggerInLocalDataSource
import com.zhaopf.testhilt.data.LoggerInMemoryDataSource
import dagger.Binds
import dagger.Module
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
import dagger.hilt.android.components.ApplicationComponent
import dagger.hilt.android.scopes.ActivityScoped
import javax.inject.Qualifier
import javax.inject.Singleton
/**
* @author zhaopingfu
* @date 2020/10/29
*/
@Qualifier
annotation class InMemoryLogger
@Qualifier
annotation class DatabaseLogger
@InstallIn(ActivityComponent::class)
@Module
abstract class LoggingMemoryModule {
@InMemoryLogger
@ActivityScoped
@Binds
abstract fun bindInMemoryLogger(impl: LoggerInMemoryDataSource): LoggerDataSource
}
@InstallIn(ApplicationComponent::class)
@Module
abstract class LoggingDatabaseModule {
@DatabaseLogger
@Singleton
@Binds
abstract fun bindDatabaseLogger(impl: LoggerInLocalDataSource): LoggerDataSource
}
<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/views/MyTextView.kt
package com.zhaopf.testhilt.views
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatTextView
import com.zhaopf.testhilt.data.User
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* @author zhaopingfu
* @date 2020/10/30
*/
@AndroidEntryPoint
class MyTextView : AppCompatTextView {
@Inject
lateinit var user: User
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
context,
attrs,
defStyleAttr
)
@SuppressLint("SetTextI18n")
override fun onAttachedToWindow() {
super.onAttachedToWindow()
text = "name: ${user.name} age: ${user.age}"
}
}
<file_sep>/TestBaseQuickAdapter/app/src/main/java/com/zhaopf/testbasequickadapter/DataBean.kt
package com.zhaopf.testbasequickadapter
import com.chad.library.adapter.base.entity.MultiItemEntity
import java.io.Serializable
/**
*
* @author PingFu.Zhao
* 2019/7/29
*/
data class DataItemBean(
val avatarUrl: String?,
val mItemType: Int
) : Serializable, MultiItemEntity {
override fun getItemType(): Int = mItemType
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/fly_in_helper/FlyInActivity.kt
package com.meta.testmotionlayout.fly_in_helper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.meta.testmotionlayout.R
class FlyInActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_fly_in)
}
}<file_sep>/TestStyleAndTheme/app/src/main/java/com/zhaopf/teststyleandtheme/ThemeViewModel.kt
package com.zhaopf.teststyleandtheme
import androidx.annotation.StyleRes
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
/**
* @author Flywith24
* @date 2020/6/23
* time 19:13
* description
*/
class ThemeViewModel : ViewModel() {
val primaryColor = MutableLiveData<@StyleRes Int>()
val currentTheme = MutableLiveData<Theme>(Theme.SYSTEM)
val edgeToEdgeEnabled = MutableLiveData<Boolean>(false)
fun setCurrentTheme(theme: Theme) {
// 防抖
if (theme == currentTheme.value) return
currentTheme.value = theme
}
}<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/fragments/BaseFragment.kt
package com.zhaopf.testlazyfragment.fragments
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.InvocationTargetException
import java.lang.reflect.ParameterizedType
/**
* @author pingfu.zhao
* @date 2020-01-14 10:39
*/
abstract class BaseFragment<T : ViewBinding> : Fragment() {
private var isViewInitiated = false
private var isVisibleToUser = false
private var isDataInitiated = false
protected lateinit var binding: T
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
isViewInitiated = true
if (!isLazyLoad) {
if (!isDataInitiated) {
fetchData()
isDataInitiated = true
}
} else {
prepareFetchData()
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// 利用反射,调用指定ViewBinding中的inflate方法填充视图
val superclass = javaClass.genericSuperclass
val aClass = (superclass as ParameterizedType).actualTypeArguments[0] as Class<*>
try {
val method = aClass.getDeclaredMethod(
"inflate",
LayoutInflater::class.java,
ViewGroup::class.java,
Boolean::class.javaPrimitiveType
)
binding = method.invoke(null, inflater, container, false) as T
} catch (e: NoSuchMethodException) {
e.printStackTrace()
} catch (e: IllegalAccessException) {
e.printStackTrace()
} catch (e: InvocationTargetException) {
e.printStackTrace()
}
return binding.root
}
override fun onResume() {
super.onResume()
if (isUiVisible) {
onUiShown()
}
}
override fun onPause() {
super.onPause()
onUiHidden()
}
override fun onDestroyView() {
super.onDestroyView()
isViewInitiated = false
isDataInitiated = false
}
/**
* 多层ViewPager嵌套需要自行调用此方法传递给当前visible child fragment
*
* @param isVisibleToUser 是否对用户展示
*/
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
this.isVisibleToUser = isVisibleToUser
if (isLazyLoad) {
prepareFetchData()
}
if (isAdded) {
if (isUiVisible) {
onUiShown()
} else {
onUiHidden()
}
}
}
/**
* 只会调用一次
*/
protected abstract fun fetchData()
/**
* ui可见
*/
protected abstract fun onUiShown()
/**
* ui隐藏
*/
protected abstract fun onUiHidden()
private fun prepareFetchData() {
if (isVisibleToUser && isViewInitiated && !isDataInitiated) {
fetchData()
isDataInitiated = true
}
}
private val isLazyLoad: Boolean
get() = true
private val isUiVisible: Boolean
get() = isResumed && userVisibleHint && isParentFragVisible
private val isParentFragVisible: Boolean
get() {
val tFrag = parentFragment
val parentFrag = if (tFrag is BaseFragment<*>) tFrag else null
return parentFrag == null || parentFrag.isUiVisible
}
}
<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/ui/MainActivity.kt
package com.zhaopf.testhilt.ui
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.zhaopf.testhilt.R
import com.zhaopf.testhilt.navigator.AppNavigator
import com.zhaopf.testhilt.navigator.Screens
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
@Inject
lateinit var navigator: AppNavigator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
if (savedInstanceState == null) {
navigator.navigateTo(Screens.BUTTONS)
}
}
override fun onBackPressed() {
super.onBackPressed()
if (supportFragmentManager.backStackEntryCount == 0) {
finish()
}
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/PlaceHolderActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.transition.TransitionManager
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.meta.testmotionlayout.databinding.ActivityPlaceHolderBinding
class PlaceHolderActivity : AppCompatActivity() {
private lateinit var binding: ActivityPlaceHolderBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityPlaceHolderBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.placeholder.postDelayed({
TransitionManager.beginDelayedTransition(binding.placeholderContainer)
binding.placeholder.setContentId(binding.favorite.id)
}, 60L)
}
fun onClick(v: View) {
TransitionManager.beginDelayedTransition(binding.placeholderContainer)
binding.placeholder.setContentId(v.id)
}
}
<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/7.Kotlin调用Java.md
### Kotlin 调用 Java
1、属性名或者方法名是关键字
在 kotlin 中 is、object等都是关键字,但是 java 中不是
public static void is() {}
public static void object() {}
在 `kotlin` 中调用的时候需要添加 \`名字\`
// is object 是关键字
JavaTest.`is`()
JavaTest.`object`()
2、 `Java` 中数组与可变长度参数
`Java` 中的可变参数其实是一个数组
public static void array(String[] args) {
array2(args);
}
public static void array2(String... args) {}
在 `Kotlin` 中调用
// java数组与可变长度参数
JavaTest.array(arrayOf<String>("a", "b"))
// 这里要前面加一个 * 号,展开操作符,相当于参数就是 "a","b"
JavaTest.array2(*arrayOf("a", "b"))
3、 `Java Object`
Java 中类的父类是 Object,Object 里面有 wait() 等
如果要在 Kotlin 中调用 wait()
// 调用java object里的方法
val o = JavaTest() as java.lang.Object
o.wait()
4、操作符重载
/**
* invoke 在kotlin中是操作符
*/
public void invoke() {}
`invoke` 在 `kotlin` 中是操作符重载方法的方法名,则可以使用操作符调用相应的 `java` 方法
val jt = JavaTest()
jt.invoke()
JavaTest()()
jt() <file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/di/UserModule.kt
package com.zhaopf.testhilt.di
import com.zhaopf.testhilt.data.User
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.android.components.ActivityComponent
import dagger.hilt.android.scopes.ActivityScoped
/**
* @author zhaopingfu
* @date 2020/10/30
*/
@InstallIn(ActivityComponent::class)
@Module
object UserModule {
@ActivityScoped
@Provides
fun user(): User {
return User("admin", System.currentTimeMillis())
}
}
<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/addwindow/AddWindowActivity.kt
package com.zhaopf.viewpager2.addwindow
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.constraintlayout.widget.ConstraintSet
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.activity_add_window.*
class AddWindowActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_add_window)
val view = LayoutInflater.from(this)
.inflate(R.layout.layout_add_view, null, false) as ConstraintLayout
val btn = view.findViewById<Button>(R.id.btn)
val decorView = window.decorView as FrameLayout
decorView.addView(
view,
ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
)
)
btn.setOnTouchListener(View.OnTouchListener { v, event ->
ConstraintSet().apply {
clone(view)
setHorizontalBias(v.id, (event.rawX + v.width / 2) / view.width)
setVerticalBias(v.id, event.rawY / view.height)
applyTo(view)
}
return@OnTouchListener true
})
}
}<file_sep>/TestSerializable/README.md
### 序列化和反序列化
##### 1、什么是序列化和反序列化?
```
比如说,我看到埃菲尔铁塔很漂亮,想把它搬到我家门口,要求搬过去之后还是原来的样子,怎么办呢?
我需要把每一根钢筋都拆下来,做上标记,然后把钢筋都装到飞机上
运到目的地之后,把钢筋都卸下来,然后按照之前的标记,把钢筋组装起来,就变回埃菲尔铁塔了
```
**这就是现实生活中的序列化和反序列化,那么反映到程序里面是怎样的呢?**
```
要把一个对象,写入到文件里,在需要的时候再恢复
需要把这个对象的全类名,所有的属性的类型、属性名、属性值,按照一定的规则都保存起来
在恢复的时候在按照规则读取出来就组成了原来的对象
```
**序列化是一个对象存到文件里的过程**
**反序列化是从文件读取信息恢复到一个对象的过程**
##### 2、在代码中如何实现?
- 2.1 可以实现 `Serializable` 接口,实现持久保存
JDK里面提供了 `Serializable` 接口,里面没有任何方法,只是起到一个标记作用
在写入到文件里的时候如果检测到这个标记会按照一定的规则写入文件
```
// 将两个对象序列化道 test.txt
val user1 = User("Bob", 20)
val user2 = User("Tom", 21)
val oos = ObjectOutputStream(FileOutputStream(File("test.txt")))
oos.writeObject(user1)
oos.writeObject(user2)
oos.close()
// 从 test.txt 反序列化两个对象
val ois = ObjectInputStream(FileInputStream(File("test.txt")))
val user1 = ois.readObject() as User
val user2 = ois.readObject() as User
ois.close()
println(user1)
println(user2)
// 打印结果
User(name=Bob, age=20)
User(name=Tom, age=21)
```
- 2.1.1 为什么实现 Serializable 接口,就能实现序列化呢?
```
在写入文件的时候会检测是否是 Serializable 接口,如果是,就会根据响应的规则写入文件
ObjectOutputStream.java
if (obj instanceof Class) {
writeClass((Class) obj, unshared);
} else if (obj instanceof ObjectStreamClass) {
writeClassDesc((ObjectStreamClass) obj, unshared);
// END Android-changed: Make Class and ObjectStreamClass replaceable.
} else if (obj instanceof String) {
writeString((String) obj, unshared);
} else if (cl.isArray()) {
writeArray(obj, desc, unshared);
} else if (obj instanceof Enum) {
writeEnum((Enum<?>) obj, desc, unshared);
} else if (obj instanceof Serializable) {
writeOrdinaryObject(obj, desc, unshared);
} else {
if (extendedDebugInfo) {
throw new NotSerializableException(
cl.getName() + "\n" + debugInfoStack.toString());
} else {
throw new NotSerializableException(cl.getName());
}
}
```
- 2.2 可以实现 `Parcelable` 接口,序列化到内存
```
data class User(
val name: String,
val age: Int
) : Serializable, Parcelable {
constructor(parcel: Parcel) : this(parcel.readString() ?: "null", parcel.readInt())
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeInt(age)
}
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel): User {
return User(parcel)
}
override fun newArray(size: Int): Array<User?> {
return arrayOfNulls(size)
}
}
}
```
**测试**
```
val user1 = User("Bob", 20)
// 序列化
val parcel = Parcel.obtain()
user1.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
// 反序列化
val user = User.createFromParcel(parcel)
println("user: $user")
// 打印结果
user: User(name=Bob, age=20)
```
##### 3、总结
```
1、Serializable 是 Java 提供的持久序列化的一种规则,会保存整个类的全部信息,其中用到了反射,还有流的操作,所以大量使用可能会有性能问题。
2、Parcelable 是 Android 提供的内存序列化规则,不能用来持久序列化,序列化的时候按照字节长度将信息写入内存中,读取的时候也要按照写入的顺序读取,否则会数据错乱。
3、 Serializable 和 Parcelable 都是一种规则,Json 也是一种序列化规则,只不过 Json 相对于人来说,能让我们看懂,而前两个只有机器才能看懂。
```<file_sep>/CustomRecyclerViewAdapter/app/src/main/java/com/zhaopingfu/adapter/BaseBean.kt
package com.zhaopingfu.adapter
/**
*
* @author zhaopingfu
* @date 2021-03-08 15:51
*/
class ABean : BaseBean() {
override fun getViewType(): Int = 0
}
class BBean : BaseBean() {
override fun getViewType(): Int = 1
}
<file_sep>/TestOptimizePlugin/app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.meta.optimizer'
android {
compileSdkVersion 28
defaultConfig {
applicationId "com.meta.testoptimizeplugin"
minSdkVersion 16
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = '1.8'
targetCompatibility = '1.8'
}
flavorDimensions "app"
productFlavors {
master {
buildConfigField "String", "TAG", '"master"'
}
dev {
buildConfigField "String", "TAG", '"dev"'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation project(':test_lib')
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.tinify:tinify:1.6.4'
}
optimizePicture {
useTinyCompress false
tinyKey rootConfig.tinyKey
isCompressAssets false
}<file_sep>/GetLauncherPackageName/app/src/main/java/com/zhaopf/getlauncherpackagename/utils/Util.kt
package com.zhaopf.getlauncherpackagename.utils
import android.annotation.SuppressLint
import android.app.Activity
import android.app.ActivityManager
import android.appwidget.AppWidgetManager
import android.appwidget.AppWidgetProviderInfo
import android.content.Context
import android.content.Intent
import android.content.pm.ResolveInfo
import android.util.Log
/**
*
* @author PingFu.Zhao
* 2019/7/29
*/
/**
* 获取手机上所有 app 的桌面的包名和类名
*/
fun getAllHomeIntentName(context: Context): List<ResolveInfo>? {
// 启动页面的 intent 配置
// AndroidManifest.xml 里面配置了 <category android:name="android.intent.category.HOME"/>
val intent = Intent(Intent.ACTION_MAIN, null).apply {
addCategory(Intent.CATEGORY_HOME)
}
// 获取手机上所有的桌面应用的包名和类名
return context.packageManager.queryIntentActivities(intent, 0)
}
/**
* 判断是否是从桌面应用跳转过来的
*/
fun checkIsFromHomeLauncherApp(activity: Activity): Boolean {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP_MR1) {
val referrer = activity.referrer ?: return false
return getAllHomeIntentName(activity)
?.map { it.activityInfo?.packageName ?: "" }
?.contains(referrer.host ?: "")
?: false
}
return false
}
/**
* 获取手机上所有 app 的启动页面的包名和类名
*/
fun getAllLauncherIntentName(context: Context): List<ResolveInfo> {
// 启动页面的 intent 配置
val intent = Intent(Intent.ACTION_MAIN, null).apply {
addCategory(Intent.CATEGORY_LAUNCHER)
}
// 获取手机上所有的启动页面的包名和类名
val result = context.packageManager.queryIntentActivities(intent, 0)
result.forEach { resolveInfo ->
Log.d(
"getAllLauncherIntentNam",
"---> installed package name: ${resolveInfo.activityInfo.packageName} class name: ${resolveInfo.activityInfo.name}"
)
}
return result
}
/**
* 获取手机 widget 的包名和类名
*/
fun getWidgetName(context: Context): List<AppWidgetProviderInfo> {
val installedProviders = AppWidgetManager.getInstance(context).installedProviders
installedProviders.forEach { appWidgetProviderInfo ->
Log.d(
"getWidgetName",
"---> installed package name: ${appWidgetProviderInfo.provider.packageName} class name: ${appWidgetProviderInfo.provider.className}"
)
}
return installedProviders
}
@SuppressLint("SetTextI18n")
fun check(context: Context, intent: Intent?) {
val TAG = "check"
val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
val fromTask = activityManager.getRunningTasks(2)
fromTask.forEach {
Log.d(TAG, "---===> task top activity: ${it?.topActivity?.packageName ?: ""} ${it?.topActivity?.className}")
Log.d(
TAG,
"---===> task base activity: ${it?.baseActivity?.packageName ?: ""} ${it?.baseActivity?.className}"
)
}
// 通过反射拿到当前栈所有的activity
val activityList =
JavaUtil.getActivitiesByApplication((context as Activity).application)
activityList.forEach {
Log.d(TAG, "---<<<> ${it.packageName} ${it.componentName.className}")
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/circular_reveal_helper/CircularRevealActivity.kt
package com.meta.testmotionlayout.circular_reveal_helper
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.meta.testmotionlayout.R
class CircularRevealActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_circular_reveal)
}
}<file_sep>/ScreenShot/app/src/main/java/com/zhaopf/screenshot/ScreenShotHelper.kt
package com.zhaopf.screenshot
import android.provider.MediaStore
import android.util.Log
/**
* @author zhaopingfu
* @date 2020/12/23
*/
class ScreenShotHelper {
companion object {
const val TAG = "ScreenShotLog"
/**
* 读取媒体数据库时需要读取的列
*/
val MEDIA_PROJECTIONS = arrayOf(
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DATE_TAKEN
)
/**
* 读取媒体数据库时需要读取的列,其中 width、height 字段在 API 16 之后才有
*/
val MEDIA_PROJECTIONS_API_16 = arrayOf(
MediaStore.Images.ImageColumns.DATA,
MediaStore.Images.ImageColumns.DATE_TAKEN,
MediaStore.Images.ImageColumns.WIDTH,
MediaStore.Images.ImageColumns.HEIGHT
)
/**
* 截屏路径判断的关键字
*/
val KEYWORDS = arrayOf(
"screenshot", "screen_shot", "screen-shot", "screen shot",
"screencapture", "screen_capture", "screen-capture", "screen capture",
"screencap", "screen_cap", "screen-cap", "screen cap"
)
fun showLog(msg: String) {
Log.d(TAG, msg)
}
}
}<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/viewpager2/PageFragment.kt
package com.zhaopf.viewpager2.viewpager2
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.lifecycle.Lifecycle
import androidx.viewpager2.adapter.FragmentStateAdapter
import com.google.android.material.tabs.TabLayoutMediator
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.fragment_page.*
class PageFragment : Fragment() {
companion object {
fun newInstance(position1: Int): PageFragment = PageFragment().apply {
arguments = Bundle().apply {
putInt("position1", position1)
}
}
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_page, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewpager2.apply {
offscreenPageLimit = 3
adapter =
ViewPagerFragmentStateAdapter2(
childFragmentManager,
lifecycle,
(arguments?.getInt("position1") ?: 0),
arrayListOf("第1页", "第2页", "第3页")
)
}
TabLayoutMediator(tabLayout, viewpager2) { tab, position ->
tab.text = "${position + 1}"
}.attach()
}
}
class ViewPagerFragmentStateAdapter2(
fragmentManager: FragmentManager,
lifecycle: Lifecycle,
private val position1: Int,
private val strList: List<String>
) :
FragmentStateAdapter(fragmentManager, lifecycle) {
override fun getItemCount(): Int = strList.size
override fun createFragment(position: Int): Fragment =
PageFragment2.newInstance(position1, position)
}<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/VideoBean.kt
package com.zhaopf.testexoplayer
import com.google.gson.Gson
import java.io.Serializable
val mGson: Gson = Gson()
fun getVideoList(): List<VideoBean> {
return mGson.fromJson(VIDEO_DATA, BaseBean::class.java).data
}
data class BaseBean(val data: List<VideoBean>)
data class VideoBean(
val nickname: String?,
val title: String?,
val description: String?,
val portrait: String?,
val videoCover: String?,
val videoUrl: String?,
val duration: Int?,
val likeCount: Int?,
val commentCount: Int?,
val shareCount: Int?,
val videoHeight: Int?,
val videoWidth: Int?,
val isLike: Boolean?,
val isFollow: Boolean?
) : Serializable
val VIDEO_DATA = """
{
"return_code": 200,
"return_msg": null,
"data": [
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "食客达人",
"title": "食客达人:吃不胖的番茄鸡肉丸子!",
"description": "吃不胖的番茄鸡肉丸子!",
"portrait": "http://images2.jumei.com/user_avatar/593/356/593356617-200-1568210339.jpg?1568210339",
"videoCover": "http://showlive-10012585.image.myqcloud.com/86e83891-695e-4bf3-9f77-a1048ca11844?imageView2/format/jpg",
"videoUrl": "https://homevideo.233xyx.com/homevideo/video/short/shb_SMALL_VIDEO_11758294.mp4",
"duration": 23,
"likeCount": 200,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "大白很爱做饭",
"title": "大白很爱做饭:南瓜糯米糍,大家学会了吗",
"description": "南瓜糯米糍,大家学会了吗",
"portrait": "http://images2.jumei.com/user_avatar/622/114/622114731-200-1568197787.jpg?1568197788",
"videoCover": "http://showlive-10012585.image.myqcloud.com/68a140c8-089a-4b64-81e0-2f9068657e67?imageView2/format/jpg",
"videoUrl": "http://ccvideo1.shuabaoba.cn/dGVzdA_E_E/MTU2Mzc3OTkzODYyMQ_E_E/Mzk3ODg5OQ_E_E/NTc0MTc3Lm1wNA_E_E.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "暴走职场君",
"title": "暴走职场君:缘分这东西,半分不由人!",
"description": "缘分这东西,半分不由人!",
"portrait": "http://images2.jumei.com/user_avatar/396/501/396501526-200-1552028737.jpg?1552028737",
"videoCover": "http://showlive-10012585.image.myqcloud.com/2245c801-d3ad-4316-a409-bc564138f09d?imageView2/format/jpg",
"videoUrl": "http://ccvideo1.shuabaoba.cn/ZGVmYXVsdFVzZXI_E/MTU2ODYxOTQ5NTMyOQ_E_E/NzcyMDcyNQ_E_E/NzYwMTAxLm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "非凡娱乐",
"title": "非凡娱乐:angelababy黄晓明同框同台,两人结婚已四年而小海绵也已2岁。被屡传分手,你们看好这对娱乐圈夫妻吗?【关注我】",
"description": "angelababy黄晓明同框同台,两人结婚已四年而小海绵也已2岁。被屡传分手,你们看好这对娱乐圈夫妻吗?【关注我】",
"portrait": "http://images2.jumei.com/user_avatar/677/138/677138721-200-1567666359.jpg?1567666360?1568115437",
"videoCover": "http://showlive-10012585.image.myqcloud.com/24bbee34-9bf9-47e2-98c3-30aabd9cdd5d?imageView2/format/jpg",
"videoUrl": "http://ccvideo1.shuabaoba.cn/dGVzdA_E_E/MTU2NzY4OTM0NTU3Mg_E_E/NDA2ODcyOA_E_E/MTgwNDIubXA0_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "历史冷知识",
"title": "历史冷知识:为什么高铁夜间不运行?",
"description": "为什么高铁夜间不运行?",
"portrait": "http://images2.jumei.com/user_avatar/411/583/411583038-200-1550040549.jpg?1550040550?1565076581",
"videoCover": "http://showlive-10012585.image.myqcloud.com/4b4fa7df-35b7-465c-ba34-c514284dc8e7?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/dGVzdA_E_E/MTU2Njc4NjA1ODE5Mg_E_E/NjM1NDk4NTc_E/MjE1MzI0Lm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "娜娜❥1",
"title": "娜娜❥1:全网最火🔥隐形针法",
"description": "全网最火🔥隐形针法",
"portrait": "http://images2.jumei.com/user_avatar/629/149/629149567-200-1563335058.jpg?1563335059?1565591791",
"videoCover": "http://showlive-10012585.image.myqcloud.com/c0566cbe-cc1e-403e-b867-03641a14096e?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/dGVzdA_E_E/MTU2ODg4NTA2NzgxNw_E_E/NzkzMzUzOA_E_E/MjQ5NzE5Lm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "叁木大大",
"title": "叁木大大:是你先吃的吗?不让你先吃还生气了.",
"description": "是你先吃的吗?不让你先吃还生气了.",
"portrait": "http://images2.jumei.com/user_avatar/396/468/396468191-200-1568535593.jpg?1568535922",
"videoCover": "http://showlive-10012585.image.myqcloud.com/867454f0-03a5-4e6f-b2de-37fc4e969132?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/ZGVmYXVsdFVzZXI_E/MTU2ODc5NjQ1NjE0MQ_E_E/Mzc2MzI3NQ_E_E/NzIzMTQubXA0_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "糖诗 ",
"title": "糖诗 :能截到算我输",
"description": "能截到算我输",
"portrait": "http://images2.jumei.com/user_avatar/613/124/613124997-200-1563259875.jpg?1563259875?1564985182",
"videoCover": "http://showlive-10012585.image.myqcloud.com/6158c0ed-d0ce-4136-ab08-427d9b6e281b?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/dGVzdA_E_E/MTU2NTU4ODg0MTM4NQ_E_E/MTk1MjczOQ_E_E/MzcxODIxLm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "坐赤道吃冰棍",
"title": "坐赤道吃冰棍:这红包抢错地方了吧!",
"description": "这红包抢错地方了吧!",
"portrait": "http://images2.jumei.com/user_avatar/641/489/641489267-200-1565084349.jpg?1565084349",
"videoCover": "http://showlive-10012585.image.myqcloud.com/51693d0f-e820-443c-91a4-33fd8b45600d?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/NjQxNDg5MjY3/MTU2NjQ0ODI0MDY5Mw_E_E/MzMxMjAyODU_E/NDk4NzkwLm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
},
{
"vid": "shb_SMALL_VIDEO_8701774",
"uid": "shb_593356617",
"nickname": "中意0510",
"title": "中意0510:看了止不住眼泪,武警部队蒙眼踢正步,必须赞!",
"description": "看了止不住眼泪,武警部队蒙眼踢正步,必须赞!",
"portrait": "http://thirdwx.qlogo.cn/mmopen/vi_32/q58U5JfVfhcGyBkXodibKmwRPIbs7x5huMY6wjYnMt8RsgRSEMYvdez8qj8ib5sAVkUpsHxr3ciadSDkHFIqjEeIw/132?1569079517",
"videoCover": "http://showlive-10012585.image.myqcloud.com/da021b37-e797-4407-a9db-7b1e6e23c19d?imageView2/format/jpg",
"videoUrl": "http://jmvideo1.shuabaoba.cn/NzAwMTkyOTU2/MTU2OTUwMTc3NDMyMA_E_E/MTk5MDE2NA_E_E/NjM1MDQ0Lm1wNA_E_E_0_default.mp4",
"duration": 23,
"likeCount": 390000,
"commentCount": 1276,
"shareCount": 3028,
"videoHeight": 1024,
"videoWidth": 576,
"isLike": true,
"isFollow": false,
"createTime": 1572015922
}
]
}
""".trimIndent()<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/MyApp.kt
package com.zhaopf.testexoplayer
import android.app.Application
import com.danikula.videocache.HttpProxyCacheServer
class MyApp : Application() {
companion object {
lateinit var instance: MyApp
val proxy: HttpProxyCacheServer by lazy {
HttpProxyCacheServer.Builder(instance)
.cacheDirectory(instance.getExternalFilesDir("videoCache"))
.build()
}
}
override fun onCreate() {
super.onCreate()
instance = this
}
}<file_sep>/CustomRecyclerViewAdapter/app/src/main/java/com/zhaopingfu/adapter/MainActivity.kt
package com.zhaopingfu.adapter
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewbinding.ViewBinding
class MainActivity : AppCompatActivity() {
private val listAdapter by lazy {
BaseAdapter<BaseBean, ViewBinding>().apply {
addHolder(ABean().getViewType(), ATemplate())
addHolder(BBean().getViewType(), BTemplate())
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
findViewById<RecyclerView>(R.id.rv).apply {
layoutManager = LinearLayoutManager(context)
adapter = listAdapter
}
val list = mutableListOf<BaseBean>()
for (i in 0 until 20) {
if (i % 2 == 0) {
list.add(ABean())
} else {
list.add(BBean())
}
}
listAdapter.addData(list)
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/GroupActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.transition.TransitionManager
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.meta.testmotionlayout.databinding.ActivityGroupBinding
class GroupActivity : AppCompatActivity() {
private lateinit var binding: ActivityGroupBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGroupBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.btn4.setOnClickListener {
TransitionManager.beginDelayedTransition(binding.clGroupContainer)
binding.group.visibility = if (binding.group.visibility == View.VISIBLE) {
View.GONE
} else {
View.VISIBLE
}
}
}
}
<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/TestMotionLayoutActivity.kt
package com.meta.testmotionlayout
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.meta.testmotionlayout.databinding.ActivityTestMotionLayoutBinding
class TestMotionLayoutActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val binding = ActivityTestMotionLayoutBinding.inflate(layoutInflater)
setContentView(binding.root)
binding.ratingFilmRating.rating = 4.5f
binding.textFilmTitle.text = getString(R.string.film_title)
binding.textFilmDescription.text = getString(R.string.film_description)
}
}
<file_sep>/README.md
# TestDemo
practice demo.
<file_sep>/TestHotFix/README.md
### 1、热修复原理
一般我们自己写的类都是由 `PathClassLoader` 加载的,
类加载器在加载某个类的时候是先去父加载器那里找,
父加载器再去爷爷加载器那里找,一直往上,如果都找不到,才自己去找,
这就是java的**双亲委托机制**

通过 `ClassLoader.loadClass` 的时候会先走 `parent` 的 `loadClass`, 如果没找到会自己去找。
调用 `findClass` 方法,具体实现是在 `PathClassLoader` 的父类, 也就是 `BaseDexClassLoader` 里面。
而 `BaseDexClassLoader` 中的 `findClass` 会调用 `pathList.findClass`,代码又来到了 `DexPathList.java`

在这里可以发现,是通过遍历 `dexElements` 数组来加载类的,而 `dexElements` 是通过 `makePathElements`得到的。
如果我们把有bug的类打成一个 `dex` 包,然后通过反射放到 `dexElements` 的最前面,那不就达到修复的效果了吗。
### 2、获取补丁包
1. 生成 `class` 文件
```
选中app模块, 点击 Build -> Make Modules 'app'
```
2. 获取 `jar` 或者 `dex`
```
这里 --output=patch.jar 也可以是 --output=patch.dex
E:\software\AndroidStudio\SDK\build-tools\29.0.0\dx.bat --dex --output=patch.jar com/example/testhotfix/TestBug.class
```
3. 将获取到的 patch.jar 放入到自己写的路径下
```
最好放到私有目录吧,这样不用申请权限
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
FixUtil.fix(this, cacheDir.absolutePath + "/patch.jar")
}
```
### 3、问题
1. 为什么java要使用双亲委托这种机制?
```
1. 避免重复查找。一个类只需要加载一次就可以了,没必要加载多次,浪费资源。
2. 避免修改系统代码。如果不用双亲委托,那么每次都要自己查找,如果自己写一个String.java,然后交给ClassLoader去加载,那么别的使用String的地方就很可能会出现问题。
```
2. `Class.forName 和 ClassLoader.loadClass 有什么区别`
```
Class.forName 不仅会加载类,还会走初始化流程。比如在类里面有静态代码块,也是会执行到的。
ClassLoader.loadClass 只是把类加载到类加载器,而不会走类的初始化流程。
```
3. 版本兼容问题
需要兼容的就是反射调用的方法,各版本可能不同
[Tinker兼容代码](https://github.com/Tencent/tinker/blob/dev/tinker-android/tinker-android-loader/src/main/java/com/tencent/tinker/loader/SystemClassLoaderAdder.java)
```
9.0: private static Element[] makeDexElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions, ClassLoader loader)
8.0: private static Element[] makeDexElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions, ClassLoader loader)
7.0: private static Element[] makeDexElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions,ClassLoader loader)
6.0: private static Element[] makePathElements(List<File> files, File optimizedDirectory,List<IOException> suppressedExceptions)
5.0: private static Element[] makeDexElements(ArrayList<File> files, File optimizedDirectory,ArrayList<IOException> suppressedExceptions)
4.4: private static Element[] makeDexElements(ArrayList<File> files, File optimizedDirectory,ArrayList<IOException> suppressedExceptions)
4.3: private static Element[] makeDexElements(ArrayList<File> files,File optimizedDirectory) {
4.2: private static Element[] makeDexElements(ArrayList<File> files,File optimizedDirectory)
4.1: private static Element[] makeDexElements(ArrayList<File> files,File optimizedDirectory)
```
4. `java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation`
[Demo](https://github.com/zhaopingfu/TestDemo/tree/master/TestHotFix)
在5.0以下机型会报这个错误,具体原因下面这个链接里面写的很详细了,我就不再重复了
[错误产生原因](https://mp.weixin.qq.com/s?__biz=MzI1MTA1MzM2Nw==&mid=400118620&idx=1&sn=b4fdd5055731290eef12ad0d17f39d4a)
解决方法,避免让类打上 `CLASS_ISPREVERIFIED`
```
1. 生成一个新的单独的dex
1.1、 创建一个 JavaLibrary hack,新建一个空的类 com/example/hack/AntilazyLoad.java
1.2、 make module 会在 /build/libs/ 生成 hack.jar
1.3、 将 jar 转为 dex: E:\software\AndroidStudio\SDK\build-tools\29.0.0\dx.bat --dex --output=hack.dex hack.jar
1.4、 将 hack.dex 放入 app/src/main/assets/
2. 在 app/build.gradle 中添加以下代码
dependencies {
// https://mvnrepository.com/artifact/org.ow2.asm/asm
implementation 'org.ow2.asm:asm:7.2'
}
afterEvaluate {
android.applicationVariants.all { variant ->
// 获得: debug/release
String variantName = variant.getName()
// 首字母大写
String capitalizeName = variantName.capitalize()
println capitalizeName
// 获取打包时jar和class打包成dex 的任务
Task dexTask = project.tasks.findByName("transformClassesWithDexBuilderFor$capitalizeName")
// 在打包之前插桩
dexTask.doFirst {
// 任务的输入,也就是 class 和 jar
Set<File> files = dexTask.inputs.files.files
for (File file : files) {
String filePath = file.absolutePath
if (filePath.endsWith(".jar")) {
processJar(file)
} else if (filePath.endsWith(".class")) {
// processClass(variant.getDirName(), file)
processClass("classes", file)
}
}
}
}
}
static boolean isAndroidClass(String filePath) {
return filePath.startsWith("android") ||
filePath.startsWith("androidx")
}
import java.util.jar.JarEntry
import java.util.jar.JarFile
import java.util.jar.JarOutputStream
import org.objectweb.asm.ClassReader
import org.objectweb.asm.ClassWriter
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.MethodVisitor
import org.objectweb.asm.Opcodes
import org.objectweb.asm.Type
static byte[] referHackWhenInit(InputStream inputStream) throws IOException {
ClassReader cr = new ClassReader(inputStream)
ClassWriter cw = new ClassWriter(cr, 0)
ClassVisitor cv = new ClassVisitor(Opcodes.ASM5, cw) {
@Override
MethodVisitor visitMethod(int access, final String name, String desc,
String signature, String[] exceptions) {
MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions)
mv = new MethodVisitor(Opcodes.ASM5, mv) {
@Override
void visitInsn(int opcode) {
// 在构造方法中插入 AntilazyLoad 引用
if ("<init>".equals(name) && opcode == Opcodes.RETURN) {
super.visitLdcInsn(Type.getType("Lcom/example/hack/AntilazyLoad;"))
}
super.visitInsn(opcode)
}
}
return mv
}
}
cr.accept(cv, 0)
return cw.toByteArray()
}
static void processClass(String dirName, File file) {
String filePath = file.absolutePath
// 这里的filePath包含了目录+包名+类名,所以去掉目录
String className = filePath.split(dirName)[1].substring(1)
// application 或者android support不管
if (isAndroidClass(className) ||
className.startsWith("com\\example\\testhotfix\\MyApplication") ||
className.startsWith("com\\example\\testhotfix\\fixmethod")) {
return
}
try {
FileInputStream fis = new FileInputStream(filePath)
// 执行插桩
byte[] byteCode = referHackWhenInit(fis)
fis.close()
FileOutputStream fos = new FileOutputStream(filePath)
fos.write(byteCode)
fos.close()
} catch (Exception e) {
e.printStackTrace()
}
}
static void processJar(File file) {
try {
File bakJar = new File(file.parent, "${file.name}.bak")
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(bakJar))
JarFile jarFile = new JarFile(file)
Enumeration<JarEntry> entries = jarFile.entries()
while (entries.hasMoreElements()) {
JarEntry jarEntry = entries.nextElement()
jarOutputStream.putNextEntry(new JarEntry(jarEntry.name))
InputStream is = jarFile.getInputStream(jarEntry)
String className = jarEntry.getName()
if (className.endsWith(".class")
&& !className.startsWith("com/example/testhotfix/MyApplication")
&& !isAndroidClass(className)
&& !className.startsWith("com/example/testhotfix/fixmethod")) {
}
}
} catch (Exception e) {
e.printStackTrace()
}
}
3、在 application 中加载 hack.dex, 避免 ClassNotFoundException
static File getHackDex(Context context) {
File hackDir = context.getDir("hack", Context.MODE_PRIVATE);
File hackFile = new File(hackDir, "hack.dex");
if (hackFile.exists()) {
return hackFile;
}
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(context.getAssets().open("hack.dex"));
bos = new BufferedOutputStream(new FileOutputStream(hackFile));
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1) {
bos.write(bytes, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bos) {
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (null != bis) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return hackFile;
}
```
经过测试: 4.4, 5.0, 6.0, 9.0 都可以正常修复<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/data/User.kt
package com.zhaopf.testhilt.data
/**
* @author zhaopingfu
* @date 2020/10/30
*/
data class User constructor(val name: String, var age: Long)
//data class User constructor(val name: String, var age: Long) {
// @Inject
// constructor() : this("zhaopf", System.currentTimeMillis()){
// Log.d("User", ": new user")
// }
//}
<file_sep>/CustomView/app/src/main/java/com/zhaopingfu/customview/TestLinearLayout.kt
package com.zhaopingfu.customview
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import androidx.annotation.IntDef
import kotlin.math.max
/**
*
* @author zhaopingfu
* @date 2021-03-01 09:54
*/
class TestLinearLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {
private var mTotalLength = 0
@OrientationMode
private var mOrientation = OrientationMode.VERTICAL
private var mGravity = Gravity.START or Gravity.TOP
init {
attrs?.apply {
val a = context.obtainStyledAttributes(this, R.styleable.TestLinearLayout)
mOrientation =
a.getInt(R.styleable.TestLinearLayout_android_orientation, OrientationMode.VERTICAL)
mGravity =
a.getInt(R.styleable.TestLinearLayout_android_gravity, Gravity.START or Gravity.TOP)
a.recycle()
}
setWillNotDraw(true)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
mTotalLength = 0
if (mOrientation == OrientationMode.VERTICAL) {
var maxWidth = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child == null || child.visibility == View.GONE) {
continue
}
val lp = child.layoutParams as LinearLayoutParams
measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, mTotalLength)
mTotalLength += child.measuredHeight + lp.topMargin + lp.bottomMargin
maxWidth = max(maxWidth, child.measuredWidth + lp.leftMargin + lp.rightMargin)
}
mTotalLength += paddingTop + paddingBottom
maxWidth += paddingLeft + paddingRight
mTotalLength = max(mTotalLength, suggestedMinimumHeight)
maxWidth = max(maxWidth, suggestedMinimumWidth)
setMeasuredDimension(
resolveSize(maxWidth, widthMeasureSpec),
resolveSize(mTotalLength, heightMeasureSpec)
)
} else if (mOrientation == OrientationMode.HORIZONTAL) {
var maxHeight = 0
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child == null || child.visibility == View.GONE) {
continue
}
val lp = child.layoutParams as LinearLayoutParams
measureChildWithMargins(child, widthMeasureSpec, mTotalLength, heightMeasureSpec, 0)
mTotalLength += child.measuredWidth + lp.leftMargin + lp.rightMargin
maxHeight = max(maxHeight, child.measuredHeight + lp.topMargin + lp.bottomMargin)
}
mTotalLength += paddingLeft + paddingRight
maxHeight += paddingTop + paddingBottom
mTotalLength = max(mTotalLength, suggestedMinimumWidth)
maxHeight = max(maxHeight, suggestedMinimumHeight)
setMeasuredDimension(
resolveSize(mTotalLength, widthMeasureSpec),
resolveSize(maxHeight, heightMeasureSpec)
)
}
}
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
if (mOrientation == OrientationMode.VERTICAL) {
layoutVertical(l, t, r, b)
} else {
layoutHorizontal(l, t, r, b)
}
}
@SuppressLint("RtlHardcoded")
private fun layoutVertical(left: Int, top: Int, right: Int, bottom: Int) {
val majorGravity = mGravity and Gravity.VERTICAL_GRAVITY_MASK
val minorGravity = mGravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK
var childTop = when (majorGravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.CENTER_VERTICAL -> (bottom - top) / 2 - mTotalLength / 2 + paddingTop
Gravity.BOTTOM -> (bottom - top) - mTotalLength + paddingTop
else -> paddingTop
}
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child == null || child.visibility == View.GONE) {
continue
}
val childWidth = child.measuredWidth
val childHeight = child.measuredHeight
val lp = child.layoutParams as LinearLayoutParams
val gravity = if (lp.gravity < 0) minorGravity else lp.gravity
val absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection)
val childLeft = when (absoluteGravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.CENTER_HORIZONTAL -> (right - left - paddingLeft - paddingRight) / 2 -
childWidth / 2 + lp.leftMargin + paddingLeft - lp.rightMargin
Gravity.RIGHT, Gravity.END -> right - left - paddingRight - childWidth - lp.rightMargin
else -> paddingLeft + lp.leftMargin
}
childTop += lp.topMargin
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight)
childTop += childHeight + lp.bottomMargin
}
}
@SuppressLint("RtlHardcoded")
private fun layoutHorizontal(left: Int, top: Int, right: Int, bottom: Int) {
val majorGravity = mGravity and Gravity.RELATIVE_HORIZONTAL_GRAVITY_MASK
val minorGravity = mGravity and Gravity.VERTICAL_GRAVITY_MASK
var childLeft = when (Gravity.getAbsoluteGravity(majorGravity, layoutDirection)) {
Gravity.CENTER_HORIZONTAL -> (right - left) / 2 - mTotalLength / 2 + paddingLeft
Gravity.RIGHT, Gravity.END -> right - left - mTotalLength + paddingLeft
else -> paddingLeft
}
for (i in 0 until childCount) {
val child = getChildAt(i)
if (child == null || child.visibility == View.GONE) {
continue
}
val childWidth = child.measuredWidth
val childHeight = child.measuredHeight
val lp = child.layoutParams as LinearLayoutParams
val gravity = if (lp.gravity < 0) minorGravity else lp.gravity
val childTop = when (gravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.TOP -> paddingTop + lp.topMargin
Gravity.CENTER_VERTICAL -> (bottom - top - paddingTop - paddingBottom) / 2 -
childHeight / 2 + lp.topMargin - lp.bottomMargin
Gravity.BOTTOM -> bottom - top - paddingBottom - childHeight - lp.bottomMargin
else -> paddingTop
}
childLeft += lp.leftMargin
child.layout(childLeft, childTop, childLeft + childWidth, childTop + childHeight)
childLeft += childWidth + lp.rightMargin
}
}
override fun generateDefaultLayoutParams(): LayoutParams? {
if (mOrientation == OrientationMode.HORIZONTAL) {
return LinearLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)
} else if (mOrientation == OrientationMode.VERTICAL) {
return LinearLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)
}
return null
}
override fun generateLayoutParams(attrs: AttributeSet): LayoutParams {
return LinearLayoutParams(context, attrs)
}
override fun generateLayoutParams(p: LayoutParams): LayoutParams {
if (p is LinearLayoutParams) {
return LinearLayoutParams(p)
} else if (p is MarginLayoutParams) {
return LinearLayoutParams(p)
}
return LinearLayoutParams(p)
}
override fun checkLayoutParams(p: LayoutParams): Boolean {
return p is LinearLayoutParams
}
}
class LinearLayoutParams : ViewGroup.MarginLayoutParams {
private var weight = 0.0f
var gravity = -1
constructor(width: Int, height: Int) : super(width, height)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
attrs?.apply {
val a =
context.obtainStyledAttributes(attrs, R.styleable.TestLinearLayout_Layout)
this@LinearLayoutParams.weight =
a.getFloat(R.styleable.TestLinearLayout_Layout_weight, 0.0f)
this@LinearLayoutParams.gravity =
a.getInt(R.styleable.TestLinearLayout_Layout_android_layout_gravity, -1)
a.recycle()
}
}
constructor(params: ViewGroup.LayoutParams) : super(params) {
weight = 0.0f
gravity = -1
}
constructor(params: ViewGroup.MarginLayoutParams) : super(params) {
weight = 0.0f
gravity = -1
}
constructor(params: LinearLayoutParams) : super(params) {
weight = params.weight
gravity = params.gravity
}
}
@IntDef(value = [OrientationMode.HORIZONTAL, OrientationMode.VERTICAL])
@Retention(AnnotationRetention.SOURCE)
annotation class OrientationMode {
companion object {
const val HORIZONTAL = 0
const val VERTICAL = 1
}
}
<file_sep>/CustomView/app/src/main/java/com/zhaopingfu/customview/TestFrameLayout.kt
package com.zhaopingfu.customview
import android.annotation.SuppressLint
import android.content.Context
import android.util.AttributeSet
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import kotlin.math.max
/**
*
* @author zhaopingfu
* @date 2021-02-25 17:36
*/
class TestFrameLayout @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ViewGroup(context, attrs, defStyleAttr) {
companion object {
private const val DEFAULT_CHILD_GRAVITY = Gravity.START or Gravity.TOP
}
private val matchParentChildren by lazy { ArrayList<View>(1) }
init {
setWillNotDraw(true)
}
override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec)
// FrameLayout 本身不是 MatchParent 或者 具体值
// 也就是说 FrameLayout本身是 wrap Content
val measureMatchParentChildren =
MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY
|| MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY
matchParentChildren.clear()
var maxWidth = 0
var maxHeight = 0
var childState = 0
var count = childCount
for (i in 0 until count) {
val child = getChildAt(i)
if (child.visibility != View.GONE) {
measureChildWithMargins(
child, widthMeasureSpec, 0,
heightMeasureSpec, 0
)
val lp = child.layoutParams as FrameLayoutParams
maxWidth =
max(maxWidth, child.measuredWidth + lp.leftMargin + lp.rightMargin)
maxHeight =
max(maxHeight, child.measuredHeight + lp.topMargin + lp.bottomMargin)
childState = combineMeasuredStates(childState, child.measuredState)
if (measureMatchParentChildren) {
if (lp.width == LayoutParams.MATCH_PARENT
|| lp.height == LayoutParams.MATCH_PARENT
) {
matchParentChildren.add(child)
}
}
}
}
maxWidth += paddingLeft + paddingRight
maxHeight += paddingTop + paddingBottom
maxWidth = max(maxWidth, suggestedMinimumWidth)
maxHeight = max(maxHeight, suggestedMinimumHeight)
setMeasuredDimension(
resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
resolveSizeAndState(
maxHeight,
heightMeasureSpec,
childState.shl(MEASURED_HEIGHT_STATE_SHIFT)
)
)
count = matchParentChildren.size
for (i in 0 until count) {
val child = getChildAt(i)
val lp = child.layoutParams as FrameLayoutParams
val childWidthMeasureSpec = if (lp.width == LayoutParams.MATCH_PARENT) {
MeasureSpec.makeMeasureSpec(
max(
0,
measuredWidth - paddingLeft - paddingRight - lp.leftMargin - lp.rightMargin
), MeasureSpec.EXACTLY
)
} else {
getChildMeasureSpec(
widthMeasureSpec,
paddingLeft + paddingRight + lp.leftMargin + lp.rightMargin,
lp.width
)
}
val childHeightMeasureSpec = if (lp.height == LayoutParams.MATCH_PARENT) {
MeasureSpec.makeMeasureSpec(
max(
0,
measuredHeight - paddingTop - paddingBottom - lp.topMargin - lp.bottomMargin
), MeasureSpec.EXACTLY
)
} else {
getChildMeasureSpec(
heightMeasureSpec,
paddingTop + paddingBottom + lp.topMargin + lp.bottomMargin,
lp.height
)
}
child.measure(childWidthMeasureSpec, childHeightMeasureSpec)
}
}
@SuppressLint("RtlHardcoded")
override fun onLayout(changed: Boolean, l: Int, t: Int, r: Int, b: Int) {
val paddingLeft = paddingLeft
val paddingRight = r - l - paddingRight
val parentTop = paddingTop
val parentBottom = b - t - paddingBottom
val count = childCount
for (i in 0 until count) {
val child = getChildAt(i)
if (child.visibility != View.GONE) {
val lp = child.layoutParams as FrameLayoutParams
val width = child.measuredWidth
val height = child.measuredHeight
val gravity = if (lp.gravity == -1) DEFAULT_CHILD_GRAVITY else lp.gravity
val layoutDirection = layoutDirection
val absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection)
val verticalGravity = gravity and Gravity.VERTICAL_GRAVITY_MASK
val childLeft = when (absoluteGravity and Gravity.HORIZONTAL_GRAVITY_MASK) {
Gravity.CENTER_HORIZONTAL -> paddingLeft + (paddingRight - paddingLeft) / 2 -
width / 2 + lp.leftMargin - lp.rightMargin
Gravity.END, Gravity.RIGHT -> paddingRight - width - lp.rightMargin
else -> paddingLeft + lp.leftMargin
}
val childTop = when (verticalGravity and Gravity.VERTICAL_GRAVITY_MASK) {
Gravity.CENTER_VERTICAL -> parentTop + (parentBottom - parentTop) / 2 -
height / 2 + lp.topMargin - lp.bottomMargin
Gravity.BOTTOM -> parentBottom - height - lp.bottomMargin
else -> parentTop + lp.topMargin
}
child.layout(
childLeft,
childTop,
childLeft + width,
childTop + height
)
}
}
}
override fun generateDefaultLayoutParams(): LayoutParams {
return FrameLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)
}
override fun checkLayoutParams(p: LayoutParams): Boolean {
return p is FrameLayoutParams
}
override fun generateLayoutParams(attrs: AttributeSet?): LayoutParams {
return FrameLayoutParams(context, attrs)
}
override fun generateLayoutParams(p: LayoutParams): LayoutParams {
if (p is FrameLayoutParams) {
return FrameLayoutParams(p)
} else if (p is MarginLayoutParams) {
return FrameLayout.LayoutParams(p)
}
return FrameLayoutParams(p)
}
}
class FrameLayoutParams : ViewGroup.MarginLayoutParams {
companion object {
const val UNSPECIFIED_GRAVITY = -1
}
var gravity: Int = UNSPECIFIED_GRAVITY
constructor(width: Int, height: Int) : super(width, height)
constructor(p: ViewGroup.LayoutParams) : super(p)
constructor(p: FrameLayoutParams) : super(p) {
this.gravity = p.gravity
}
constructor(c: Context, attrs: AttributeSet?) : super(c, attrs) {
val a = c.obtainStyledAttributes(attrs, R.styleable.TestFrameLayout_Layout)
gravity = a.getInt(
R.styleable.TestFrameLayout_Layout_android_layout_gravity,
UNSPECIFIED_GRAVITY
)
a.recycle()
}
}
<file_sep>/KotlinStudy/settings.gradle
include ':app'
rootProject.name='KotlinStudy'
<file_sep>/KotlinStudy/resources2/KotlinEverywhere2019_README.md
### 用 `Kotlin` 提升你的开发效率
#### 1、data class

#### 2、中缀表达式

#### 3、标准函数

#### 4、扩展方法

#### 5、IO

#### 6、集合类操作

#### 7、Sequence

<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/test/HencoderKotlin.kt
package com.meta.kotlinstudy.test
import java.util.*
/**
* @author pingfu.zhao
* @date 2019-09-21 15:26
*/
open class Fruit
class Apple : Fruit()
fun <T> fill(array: Array<T>, t: T) {
array[0] = t
}
fun testHencoder1() {
val array = arrayOf<Fruit>(Fruit())
fill(array, Fruit())
println("--> ${Arrays.toString(array)}")
fill(array, Apple())
println("--> ${Arrays.toString(array)}")
}
fun <T> copy(src: Array<out T>, des: Array<in T>) {
src.forEachIndexed { index, t -> des[index] = t }
}
fun testHencoder2() {
val src = arrayOf(Fruit())
val des = arrayOf(Fruit())
copy(src, des)
println("--> 111 ${Arrays.toString(des)}")
val src2 = arrayOf(Apple())
val des2 = arrayOf(Fruit())
copy(src2, des2)
println("--> 222 ${Arrays.toString(des2)}")
}<file_sep>/TestSerializable/app/src/main/java/com/example/testserializable/Test.kt
package com.example.testserializable
import android.os.Parcel
import android.os.Parcelable
import java.io.*
data class User(
val name: String,
val age: Int
) : Serializable, Parcelable {
constructor(parcel: Parcel) : this(parcel.readString() ?: "null", parcel.readInt()) {
}
override fun describeContents(): Int = 0
override fun writeToParcel(dest: Parcel, flags: Int) {
dest.writeString(name)
dest.writeInt(age)
}
companion object CREATOR : Parcelable.Creator<User> {
override fun createFromParcel(parcel: Parcel): User {
return User(parcel)
}
override fun newArray(size: Int): Array<User?> {
return arrayOfNulls(size)
}
}
}
fun testSerializable() {
val user1 = User("Bob", 20)
val user2 = User("Tom", 21)
val oos = ObjectOutputStream(FileOutputStream(File("test.txt")))
oos.writeObject(user1)
oos.writeObject(user2)
oos.close()
}
fun testDeSerializable() {
val ois = ObjectInputStream(FileInputStream(File("test.txt")))
val user1 = ois.readObject() as User
val user2 = ois.readObject() as User
ois.close()
println(user1)
println(user2)
}
fun testParcelable() {
val user1 = User("Bob", 20)
// 序列化
val parcel = Parcel.obtain()
user1.writeToParcel(parcel, 0)
parcel.setDataPosition(0)
// 反序列化
val user = User.createFromParcel(parcel)
println("user: $user")
}<file_sep>/TestExoPlayer/README.md
ExoPlayer 单例播放
通过 AndroidVideoCache 进行缓存
刷新数据的时候没有刷新<file_sep>/TestBaseQuickAdapter/README.md
* 多类型布局
* 侧滑<file_sep>/RobustDemo/Robust.md
### `Robust` 美团热修复方案
`Robust` 刚上手感觉比 `Sophix` 麻烦一些,实际用下来确实麻烦一些
优点:
支持实时修复,不需要重新启动应用,当前类的也可以修复
新增字段不支持,不过可以通过将字段放在新的类来达到目的
Lamda 表达式(比如 (v -> LogUtil.d("xxx") )) 修改不了,文档上说是在里面添加 RobustModify.modify(); 实测不好使,没效果,可以添加一个新的类来解决
补丁中添加点击事件的时候不要直接
setOnClickListener(new View.OnClickListener{
// ignore
})
这样补丁修复不成功,应该添加一个新的类 XXX,实现 View.OnClickListener 接口,然后setOnClickListener(new XXX())
@Add
public static class XXX implements View.OnClickListener{
// ignore
}
缺点:
代码侵入,每个修改的方法上面都要加 `@Modify` 注解,新增的方法要加 `@Add` 注解
不支持资源的修复
生成补丁的时候失败:
patch method com.meituan.sample.robusttest.SampleClass.multiple(int) haven't insert code by Robust.Cannot patch this method, method.signature (I)I
这表明我们想要打补丁的方法并没有被robust插入代码,Robust对一个方法里面只有字段调用的方法的没有插入代码,简单的来说就是这个方法里面都是字段(局部变量和成员变量)的方法,没有方法调用,new操作等,这类方法被我们归类为简单方法,可以在调用这个方法的地方修复这个问题。
如果加载补丁提示找不到类,那么需要配置混淆规则,不要把配置代码混淆掉
踩了个坑:
setPatchesInfoImplClassFullName 的参数需要是 robust.xml 中 <patchPackname/>的包名,类名必须是 PatchesInfoImpl
setPatchesInfoImplClassFullName("com.meta.robustdemo.robust.PatchesInfoImpl")
又踩了个坑:
把 patch.jar 往手机里推的时候
用的 adb push ./patch.jar /storage/emulated/0/robust/
在 OPPO A57t 上面可以,但是 OPPO R7, 1+7Pro上面都不可以
一直说找不到文件,最后用
adb push ./patch.jar /storage/emulated/0/robust/patch.jar
# 总结
### Sophix
默认不会强制杀死APP,但是有些问题只有冷启动之后才会被修复
1. 只改不增方法,热启动 当前页面的修复不了,新的页面可以修复
2. 新增方法,冷启动才能修复
修复时长:计算code9到code12的时间
第一次加载补丁在1.5-2s左右,加载完之后就检测不到新的补丁
### Robust
支持实时修复,不需要重新启动应用,当前类的也可以修复
修复时长:第一次加载补丁在200-300ms左右,之后再加载再25-45ms左右<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/MainActivity.kt
package com.zhaopf.testlazyfragment
import android.app.Activity
import android.app.Dialog
import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import com.zhaopf.testlazyfragment.adapter.MainVpAdapter
import com.zhaopf.testlazyfragment.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private val mFullScreenObserver by lazy { FullScreenObserver(this) }
private val binding by lazy { inflate<ActivityMainBinding>() }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
with(binding.vpAppMainTopVp) {
offscreenPageLimit = 5
adapter = MainVpAdapter(supportFragmentManager)
}
with(binding.tlAppMainBottomTab) {
setTabTextColors(Color.GREEN, Color.RED)
setupWithViewPager(binding.vpAppMainTopVp)
}
}
override fun onWindowFocusChanged(hasFocus: Boolean) {
super.onWindowFocusChanged(hasFocus)
// 沉浸式
mFullScreenObserver.applyKitKatTranslucencyWithColor(Color.BLACK)
}
}
inline fun <reified T : ViewBinding> Activity.inflate(): T = inflateBinding<T>(layoutInflater)
inline fun <reified T : ViewBinding> Fragment.inflate(): T = inflateBinding(layoutInflater)
inline fun <reified T : ViewBinding> Dialog.inflate(): T = inflateBinding<T>(layoutInflater)
inline fun <reified T : ViewBinding> inflateBinding(layoutInflater: LayoutInflater): T {
val method = T::class.java.getMethod("inflate", LayoutInflater::class.java)
return method.invoke(null, layoutInflater) as T
}
<file_sep>/ViewPager2/app/src/main/java/com/zhaopf/viewpager2/recyclerview/RecyclerViewActivity.kt
package com.zhaopf.viewpager2.recyclerview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.LayoutInflaterCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.PagerSnapHelper
import androidx.recyclerview.widget.RecyclerView
import com.zhaopf.viewpager2.R
import kotlinx.android.synthetic.main.activity_recycler_view.*
class RecyclerViewActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_recycler_view)
val listOf = listOf("1", "2", "3", "4", "5", "6", "7", "8", "9", "10")
rvTest.apply {
setRecycledViewPool(RecyclerView.RecycledViewPool().apply {
setMaxRecycledViews(0, 20)
})
layoutManager = LinearLayoutManager(context).apply {
isItemPrefetchEnabled = true
initialPrefetchItemCount = 5
}
adapter = TestRvAdapter(listOf)
}
PagerSnapHelper().attachToRecyclerView(rvTest)
}
}
class TestRvAdapter(val list: List<String>) : RecyclerView.Adapter<TestRvHolder>() {
private val TAG = "TestRvAdapter"
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TestRvHolder {
Log.d(TAG, "onCreateViewHolder ")
return TestRvHolder(
LayoutInflater.from(parent.context).inflate(
R.layout.layout_recyclerview_item,
parent,
false
)
)
}
override fun getItemCount(): Int = list.size
override fun onBindViewHolder(holder: TestRvHolder, position: Int) {
Log.d(TAG, "onBindViewHolder 111 $position")
holder.tv.text = list[position]
}
override fun onBindViewHolder(holder: TestRvHolder, position: Int, payloads: MutableList<Any>) {
super.onBindViewHolder(holder, position, payloads)
Log.d(TAG, "onBindViewHolder 222 $position")
}
override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
super.onAttachedToRecyclerView(recyclerView)
Log.d(TAG, "onAttachedToRecyclerView ")
}
override fun onDetachedFromRecyclerView(recyclerView: RecyclerView) {
super.onDetachedFromRecyclerView(recyclerView)
Log.d(TAG, "onDetachedFromRecyclerView ")
}
override fun onViewAttachedToWindow(holder: TestRvHolder) {
super.onViewAttachedToWindow(holder)
Log.d(TAG, "onViewAttachedToWindow ")
}
override fun onViewDetachedFromWindow(holder: TestRvHolder) {
super.onViewDetachedFromWindow(holder)
Log.d(TAG, "onViewDetachedFromWindow ")
}
}
class TestRvHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var tv: TextView = itemView.findViewById(R.id.tv)
}<file_sep>/TestOptimizePlugin/meta_optimize_plugin/src/main/resources/META-INF/gradle-plugins/com.meta.optimizer.properties
implementation-class=com.meta.optimize_plugin.OptimizePlugin<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/adapter/HomeVpAdapter.kt
package com.zhaopf.testlazyfragment.adapter
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import com.zhaopf.testlazyfragment.fragments.MoreFragment
import com.zhaopf.testlazyfragment.fragments.PopularFragment
import com.zhaopf.testlazyfragment.fragments.SmallGameFragment
/**
* @author pingfu.zhao
* @date 2020-01-14 10:56
*/
class HomeVpAdapter(fm: FragmentManager) : BaseVpAdapter(fm) {
override fun getItem(position: Int): Fragment = when (position) {
0 -> PopularFragment()
1 -> SmallGameFragment()
else -> MoreFragment()
}
override fun getCount(): Int = 3
override fun getPageTitle(position: Int): CharSequence? = when (position) {
0 -> "热门"
1 -> "小游戏"
else -> "更多"
}
}<file_sep>/TestLazyFragment/app/src/main/java/com/zhaopf/testlazyfragment/fragments/HomeFragment.kt
package com.zhaopf.testlazyfragment.fragments
import android.graphics.Color
import android.os.Bundle
import android.util.Log
import android.view.View
import com.zhaopf.testlazyfragment.adapter.HomeVpAdapter
import com.zhaopf.testlazyfragment.databinding.FragmentHomeLayoutBinding
/**
* @author pingfu.zhao
* @date 2020-01-14 10:46
*/
class HomeFragment : BaseFragment<FragmentHomeLayoutBinding>() {
private val TAG = "HomeFragment"
private var mAdapter: HomeVpAdapter? = null
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mAdapter = HomeVpAdapter(childFragmentManager)
with(binding.appHomeBottomVp) {
offscreenPageLimit = 5
adapter = mAdapter
}
with(binding.tlAppHomeTopTab) {
setTabTextColors(Color.GREEN, Color.RED)
setupWithViewPager(binding.appHomeBottomVp)
}
}
override fun fetchData() {
Log.d(TAG, "fetchData: ")
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
mAdapter?.mCurrentPrimaryItem?.userVisibleHint = isVisibleToUser
}
override fun onUiShown() {
Log.d(TAG, "onUiShown: ")
}
override fun onUiHidden() {
Log.d(TAG, "onUiHidden: ")
}
}
<file_sep>/ScreenShot/app/src/main/java/com/zhaopf/screenshot/MainActivity.kt
package com.zhaopf.screenshot
import android.Manifest
import android.content.pm.PackageManager
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.content.PermissionChecker
class MainActivity : AppCompatActivity() {
private lateinit var screenShotListener: ScreenShotListener
var isHasScreenShotListener = false
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
screenShotListener = ScreenShotListener.getInstance(this)
// 申请权限
val permission = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE)
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.READ_EXTERNAL_STORAGE
) != PackageManager.PERMISSION_GRANTED
) {
ActivityCompat.requestPermissions(this, permission, 1001)
}
}
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<out String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == 1001) {
if (grantResults[0] == PermissionChecker.PERMISSION_GRANTED) {
customToast("权限申请成功")
} else {
customToast("权限申请失败")
}
}
}
override fun onResume() {
super.onResume()
startScreenShotListen()
}
override fun onPause() {
super.onPause()
stopScreenShotListen()
}
private fun startScreenShotListen() {
if (!isHasScreenShotListener) {
screenShotListener.setListener(object : ScreenShotListener.OnScreenShotListener {
override fun onScreenShot(picPath: String) {
customToast("监听截屏成功")
Log.d(ScreenShotHelper.TAG, "==== picPath: $picPath")
}
})
screenShotListener.startListener()
isHasScreenShotListener = true
}
}
private fun stopScreenShotListen() {
if (isHasScreenShotListener) {
screenShotListener.stopListener()
isHasScreenShotListener = false
}
}
private fun customToast(s: String) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show()
}
}
<file_sep>/TestStyleAndTheme/README.md
学习Style与Theme
[参考地址](https://juejin.im/post/5ef7e6305188252e8a080c10?utm_source=gold_browser_extension)<file_sep>/TestGuava/app/src/main/java/com/zhaopf/testguava/MainBean.java
package com.zhaopf.testguava;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import org.checkerframework.checker.nullness.qual.Nullable;
import java.util.ArrayList;
import java.util.List;
public class MainBean {
MainDataBean mainDataBean;
public static class MainDataBean {
List<BannerItemBean> bannerList;
}
public static class BannerItemBean {
String url;
}
public static MainBean getTestData1() {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
String strUrl = Optional.fromNullable(MainBean.getTestData1())
.toJavaUtil()
.map(new Function<MainBean, String>() {
@Nullable
@Override
public String apply(@Nullable MainBean input) {
return input.mainDataBean.bannerList.get(0).url;
}
})
.orElse("默认值");
}
return null;
}
public static MainBean getTestData2() {
return new MainBean();
}
public static MainBean getTestData3() {
MainBean mainBean = new MainBean();
mainBean.mainDataBean = new MainDataBean();
return mainBean;
}
public static MainBean getTestData4() {
MainBean mainBean = new MainBean();
mainBean.mainDataBean = new MainDataBean();
mainBean.mainDataBean.bannerList = new ArrayList<>();
return mainBean;
}
public static List<MainBean.BannerItemBean> getTestData5() {
return null;
}
}<file_sep>/TestBaseQuickAdapter/app/src/main/java/com/zhaopf/testbasequickadapter/MainActivity.kt
package com.zhaopf.testbasequickadapter
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 简单的展示数据
// testSample()
// 测试多布局
testMultipleAdapter()
}
private fun testMultipleAdapter() {
val dataList = mutableListOf<DataItemBean>()
for (i in 0..50) {
dataList.add(DataItemBean("", if (i % 5 == 0) 0x10 else 0x20))
}
// 经过测试发现,重写adapter里面的 spanSizeLookup 方法不管用,layoutManager里面的好使
val mAdapter = MMultipleAdapter(dataList)
val mLayoutManager = GridLayoutManager(this, 2).apply {
spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
override fun getSpanSize(position: Int): Int {
val viewType = mAdapter.getItemViewType(position)
return if (viewType == 0x10) spanCount else 1
}
}
}
rv.apply {
adapter = mAdapter
layoutManager = mLayoutManager
}
}
/**
* 简单的展示数据
*/
private fun testSample() {
val dataList = mutableListOf<DataItemBean>()
for (i in 0..50) {
dataList.add(DataItemBean("", if (i % 5 == 0) 0x10 else 0x20))
}
val mAdapter = MAdapter(R.layout.item_rv, dataList).apply {
// rv 的点击事件
setOnItemClickListener { adapter, view, position ->
Log.d(TAG, "点击了 rv: $position")
}
// rv item child 的点击事件
setOnItemChildClickListener { adapter, view, position ->
when (view.id) {
R.id.btn_item -> {
Log.d(TAG, "点击了 rv child: $position")
}
}
}
}
rv.apply {
adapter = mAdapter
layoutManager = LinearLayoutManager(context)
}
}
}<file_sep>/TestLazyFragment/settings.gradle
include ':app'
rootProject.name='TestLazyFragment'
<file_sep>/KotlinStudy/app/src/main/java/com/meta/kotlinstudy/基础部分/Kotlin01.md
# 1. Kotlin配置
### 1、`Android` 中使用 `Kotlin`
1. 需要在项目的根节点下的 `build.gradle` 添加依赖
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50"
2. 在 `Module` 的 `build.gradle` 下添加相关插件和依赖
- 添加插件
apply plugin: 'kotlin-android'
// 扩展插件,用来在代码中直接使用控件ID来进行操作
apply plugin: 'kotlin-android-extensions'
- 添加依赖
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk8:1.3.50"
### 2、将现有的 `Java` 代码转为 `Kotlin` 代码
选中要转换的 `Java` 类, 选择顶部工具栏中的 `Code -> Convert Java File to Kotlin File`
### 3、查看 `Kotlin` 代码转为 `Java` 之后大概是什么代码
1. 打开 `Kotlin` 文件
2. 选择顶部工具栏 `Tools -> Kotlin -> Show Kotlin Bytecode`
3. 在右侧的区域中点击左上角的 `Decompile`
# 2.函数_变量_类_美剧_类型转换_控制流
/**
* Kotlin 中作用域默认是 public,
*
* 声明类,方法 默认都是 final 的,如果需要让别的类继承或重写,需要加 open 关键字
*
* 在一个类里面声明另一个类,默认两个类是没有关系的,和 Java 的内部类加了static 一样,如果要变成内部类需要加 inner 关键字
*/
/**
* 直接将方法写在文件里面,称为顶层函数,这里不用加public,默认就是public
* 函数接收一个 String 数组
*
* 返回值类型默认是Unit,相当于java中的 void
*
* 这里返回值写了Int,表示返回值是Int,Kotlin中只有大写的类型,没有java中的Int等小写的基础数据类型
*/
//fun main(args: Array<String>): Int {
// println(max(1, 2))
// return 1
//}
/**
* 定义方法
*
* 这里的返回值可以进行推断出来,可以省略
*
* 方法参数可以有默认值
*
* 这里 if 语句的最后一行默认当做返回值
*/
fun max(x: Int = 0, y: Int) = if (x > y) x else y
/**
* 顶层变量,声明变量可以省略类型,可以推断出来
*/
// 只有get, final
val name = "Jack"
val name2: String = "Tom"
val name3: String? = null
val name4
get() = "Bob"
// 有 set/get
var age = 20
var age2: Int = 20
var age3 = 0
get() {
return field
}
set(value) {
field = value
}
fun testField() {
// 声明变量可以
var nickName = "Jason"
// 字符串拼接使用 $,这里的获取值是静态获取,当走完这一行之后就已经确定了
// 哪怕在后面修改了nickName的值,str的值也不会改变
val str = "name: $name age: $age nickName: $nickName"
println(str)
nickName = "Danny"
println("nickName: $nickName str: $str")
}
/**
* 在Activity中声明变量一般还会用到 lateinit 和 by lazy{}
*/
// 不可空对象声明的时候需要赋值,但是需要findViewById
lateinit var tv: TextView
// 用到的时候才回去new出来这个对象
val strList by lazy { ArrayList<String>() }
/**
* Kotlin中的字符串
*/
val strHello = "Hello"
val strWorld = "World"
val strHelloWorld = "$strHello $strWorld"
val strMultiLine = """
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
""".trimMargin()
fun testStr() {
// ello World
println(strHelloWorld.substring(1))
// lo World
println(strHelloWorld.substringAfter('l'))
// d
println(strHelloWorld.substringAfterLast('l'))
// He
println(strHelloWorld.substringBefore("l"))
// Hello Wor
println(strHelloWorld.substringBeforeLast('l'))
// Kotlin为String提供了很多的扩展函数,比如各种replace等等
}
/**
* 这里的参数如果不加可见性修饰符就只是作为参数,否则是类的成员
*
* 如果类里面没有函数,可以省略类的大括号
*
* 这里变量访问的时候都是访问的get/set方法
*
* Person("test").name 实际上是调用的 getName 方法,有点类似 groovy
*/
class Person(var name: String?)
/**
* 空安全
*/
fun testNull(person: Person?) {
person ?: doSomething() // 如果person为空做一些事
person ?: return // 如果person为空直接返回
val person2: Person? = null
val length = person2?.name?.length ?: 0
val length2 = person2?.name?.length ?: getLength()
}
fun doSomething() {}
fun getLength() = 0
/**
* ==: 在 Kotlin 中 == 比较的是值,就相当于java中的equals
* ===: 比较的是内存地址
*/
fun testEquals() {
val str1 = String("Hello World.".toCharArray())
val str2 = String("Hello World.".toCharArray())
val str3 = "Hello World."
val str4 = "Hello World."
println(str1 == str2)
println(str1 === str2)
println(str3 === str4)
}
//fun main(args: Array<String>) {
// testEquals()
//}
/**
* enum 是一个软关键字,只有跟在 class 前面才是一个关键字
*/
// 这里不是关键字
val enum = 1
enum class Color(val r: Int, val g: Int, val b: Int) {
RED(255, 0, 0),
GREEN(0, 255, 0),
BLUE(0, 0, 255);
// 如果要在枚举中定义函数,需要用分号将上面的常量和方法分隔开
// 这可能是kotlin中唯一需要写分号的地方了
fun rgb() = r + g + b
}
fun test类型推断() {
// Kotlin 中有类型推断
val view: View? = null
if (view is ImageView) {
view.setImageDrawable(ColorDrawable(android.graphics.Color.RED))
}
if (view !is TextView) {
// 这里不是TextView
} else {
view.text = "这里是TextView"
}
}
/**
* 控制语句
*/
fun testControlStatement(color: Color) {
// Java 中的 switch 被换成了 when
when (color) {
Color.RED -> println("red")
// 如果有多个条件,逗号隔开
Color.GREEN, Color.BLUE -> println("green or blue")
// 如果有多行,可以加大括号
else -> {
println("other 1")
println("other 2")
}
}
when {
1 + 1 == 3 -> println("11")
test() -> println("22")
else -> println("33")
}
}
fun test() = true
fun max2(x: Int = 0, y: Int): Int = when {
x > y -> x
else -> y
}
fun testFor() {
// 这里的区间是 [0, 10],注意两边都是闭区间,总共执行11次循环
for (i in 0..10) {
}
// [0, 10)
for (i in 0 until 10) {
}
// 从 0 到 10,每次 +2 += 2
for (i in 0 until 10 step 2) {
}
// 从 10 到 0,每次 -2 -= 2
for (i in 10 downTo 0 step 2) {
}
// 这里的 0..10 是一个 IntRange
val intRange: IntRange = 1..10
// 跳出
outLoop@ for (i in intRange) {
if (i == 5) {
continue@outLoop
}
innerLoop@ for (j in intRange) {
if (i == 5) {
break@innerLoop
}
}
}
}
# 3.数组_集合_扩展函数_扩展属性_vararg_infix_析构
fun testArray() {
// 基础类型的数组要使用 intArrayOf 或者 floatArrayOf 等
// int[]
val array = intArrayOf(1, 2, 3)
// Integer[]
val array1 = arrayOf(1, 2, 3)
// Integer[]
val array2 = Array(3) { it }
// 取值
val num1 = array[0]
val num2 = array.last()
val num3 = array.component1()
val num4 = array.elementAt(0)
// 遍历
for (i in array) {
}
array.forEach {
// 这里默认参数名是it,可以自己改 x ->
println(it)
}
array.forEachIndexed { index, value ->
println("index: $index value: $value")
}
// 转为String
array.joinToString()
}
fun testList() {
val list = listOf<Int>(1, 2, 3)
val list2 = arrayListOf<Int>(1, 2, 3)
// 这里的 List 只能进行读取,不能进行增删
val list3: List<Int> = listOf()
// 可变的集合可以随意的增删
val list4: MutableList<Int> = mutableListOf()
list4.filter { it > 3 }
.take(3)
.map { "$it" }
.flatMap { it.toCharArray().toList() }
.sorted()
// 一个满足就返回
list4.any { it > 5 }
// 所有满足的
list4.all { it > 5 }
list4.min()
list4.max()
list4.sum()
}
/**
* 扩展方法
* 比如一般用到字符串都会写一个StringUtil,这个时候就可以用扩展函数替代
*
* inline 表示在编译之后会把inline方法里面的内容复制到调用方法的地方
*/
inline fun String.show() {
Log.d("xxx", "show ${toString()}")
}
/**
* 扩展属性
*/
val String.lastChar: Char
get() = get(length - 1)
/**
* 可变参数: vararg 伪关键字,和 emum 一样
*/
fun test(vararg str: String) {
val vararg = str[0]
str.size
println(str.joinToString(","))
}
/**
* 方法默认值
*/
fun testFunc(name: String = "", sex: String = "") {
}
fun testFunc2() {
// 这个时候传参默认是会给到name
testFunc("男")
// 如果想给到sex怎么办呢
testFunc(sex = "男")
// 通过这样指定参数名的方式,可以节省查看方法参数的时间,而且更加规范
}
/**
* 中缀表达式
*/
infix fun Int.加(that: Int): Int = this + that
fun testExtensionFunction() {
"abc".show()
"abc".lastChar
// 中缀调用 infix: 1 to 1
val x = 1 加 1
}
fun testMap() {
val map = mapOf<Int, Int>()
val map2 = mapOf(Pair(1, 1), Pair(2, 2))
val map3 = mapOf(1 to 1, 2 to 2, "c" to 2)
map3[1]
map3["c"]
}
data class User(
val name: String,
val age: Int
)
fun test析构() {
// 从集合析构
val xxx = "androidx.recyclerview:recyclerview:1.1.0"
val (group, name, version) = xxx.split(":")
// 从map析构
val map = mapOf<Int, Int>(1 to 1, 2 to 2, 3 to 3)
for ((k, v) in map) {
}
map.mapValues {
}
map.mapValues { (k, v) ->
}
// 从这里析构
val (sex, age) = Pair("男", 1)
val (a, b, c) = Triple("a", 2, Color.RED)
// 从对象析构
val user = User("name", 20)
val (name2, age2) = user
val userArray = arrayOf<User>()
for ((name3, age3) in userArray) {
}
}
# 4. this_异常
class MyActivity : Activity() {
private val mRecyclerView by lazy { RecyclerView(this) }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
mRecyclerView.run {
layoutManager = GridLayoutManager(context, 3).apply {
orientation = RecyclerView.HORIZONTAL
this@apply.spanCount
this@run.hasFixedSize()
// 获取外面的,要获取java的class需要 MainActivity::class.java
this@MyActivity.startActivity(Intent(context, MainActivity::class.java))
}
}
}
}
class MyException(message: String) : Exception(message)
//// throw 表达式的类型是特殊类型 Nothing.该类型没有值,而是用于标记永远不能达到的代码位置
fun fail(message: String): Nothing {
throw MyException(message)
}
fun testException() {
// fail("fail")
// try-表达式的返回值是 try 块中的最后一个表达式或者是(所有)catch 块中的最后一个表达式。
// finally 块中的内容不会影响表达式的结果
val iStr: String? = try {
"hello"
throw MyException("error")
} catch (e: MyException) {
"catch 中的值"
null
} finally {
"finally中的值"
}
println(iStr)
// 下面两种方式效果一样
// val s = iStr?.length ?: throw MyException("iStr.length is null")
// println(s)
// val ss = iStr?.length ?: fail("iStr.length is null")
// println(ss)
// val x = null // x 具有类型 Nothing?
// val l = listOf(null) // l 具有类型 List<Nothing?>
}
//fun main(args: Array<String>) {
// testException()
//}
# 5.单例
// 最简单的单例
object Singleton {
var name: String = ""
fun test() {}
}
fun testSingleton() {
Singleton.name = "testName"
Singleton.test()
}
/**
* 在Kotlin中一般实现接口或者抽象类都是用object
*/
fun testObject() {
val tv: TextView? = null
tv?.setOnClickListener(object : View.OnClickListener {
override fun onClick(v: View?) {
}
})
// 如果接口只有一个方法,可以直接用大括号
tv?.setOnClickListener { }
tv?.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
})
}
/**
* 有时候Android中需要全局单例Application
*/
class MyApp : Application() {
companion object {
lateinit var INSTANCE: MyApp
}
override fun onCreate() {
super.onCreate()
INSTANCE = this
}
}
/**
* 可以直接声明顶层变量加 lazy
*/
val testList by lazy { ArrayList<String>() }
/**
* 加锁的,类似java的DCL
*/
class DoubleCheckSingleton private constructor() {
companion object {
// kotlin 写法
val INSTANCE_1 by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
DoubleCheckSingleton()
}
// 翻译Java写法
private var INSTANCE_2: DoubleCheckSingleton? = null
// 如果要给方法加锁要用
// @Synchronized
fun getInstance(): DoubleCheckSingleton {
if (null == INSTANCE_2) {
synchronized(DoubleCheckSingleton::class) {
if (null == INSTANCE_2) {
INSTANCE_2 = DoubleCheckSingleton()
}
}
}
// 这里用!! 表示强制转换为非空的
return INSTANCE_2!!
}
}
}
/**
* 内部类的方式
*/
class InnerStaticSingleton private constructor() {
companion object {
fun getInstance() = Holder.INSTANCE
}
private object Holder {
val INSTANCE = InnerStaticSingleton()
}
}
# 6.Java调用Kotlin
1、kotlin编译后会生成一个 `类名 + Kt` ,如果不想使用这个名字,可以自己自定义
在文件第一行添加注解 @file:JvmName("名字")
例如 @file:JvmName("Hello")
2、访问顶层属性
var name = "1"
通过 `文件名Kt` 来调用set/get方法
String name = JavaClassKt.getName();
如果想直接通过 "文件名.属性名" 的方式
* 方法一: 通过添加@JvmField属性可以做到
@JvmField
var name1 = "1"
那么在java里 就可以
String name1 = JavaClassKt.name1;
* 方法二: 使用 `const`关键字
// const 只能用来修饰 val ,相当于java中的 public static final
const val name2 = "1"
Stringg name2 = JavaClassKt.name2;
3、合并文件
假如有
AUtils.kt,里面有个 a 方法
和
BUtils.kt,里面有个 b 方法
给AUtils.kt设置名字叫Utils(通过@file:JvmName("Utils"))
给BUtils.kt设置名字叫Utils(通过@file:JvmName("Utils"))
这个时候通过Utils调用方法的时候只能调用 a 方法,但是我还想要调用 b 方法
就需要在 @file:JvmName("Utils") 下面添加 @file:JvmMultifileClass,表示可以合并
在AUtils.kt 和 BUtils.kt 里面都添加
4、扩展方法
fun String.test() {}
fun Int.test() {}
在java 中调用的时候需要通过 文件名.test(参数就是扩展类型)
比如
Hello.test("string");
Hello.test(1);
5、相同签名的不同泛型的方法
fun List<String>.test() {}
fun List<Int>.test() {}
上面这两个方法因为java中的签名一样,都是List,所以有问题
就需要修改下方法名
@JvmName("test1")
fun List<String>.test() {}
fun List<Int>.test() {}
`java` 中调用
// 相同签名的不同泛型
Hello.test(new ArrayList<Integer>());
Hello.test1(new ArrayList<String>());
6、方法默认值
fun func(name: String = "", id: Int = 1) {}
kotlin中两个参数都有默认值,在java中调用的话两个参数都需要传
如果在 `java` 中不传参数的话需要添加注解
@JvmOverloads
fun func(name: String = "", id: Int = 1) {}
这个时候就可以调用了
// 有默认值的方法
Hello.func();
Hello.func("");
Hello.func("", 1);
7、类
class A(name: String) {
val name1 = name
@JvmField
val name2 = name
companion object AA {
val id = "2"
@JvmField
val sex = "男"
}
}
`java` 中调用
// 类
A a = new A("name");
n = a.getName1();
n = a.name2;
String id = A.AA.getId();
String sex = A.sex;
8、object
object B {
val id = "1"
}
`java` 中调用
// object
id = B.INSTANCE.getId();
9、异常
fun ex() {
throw IOException("xxx")
}
在 `kotlin` 中抛出异常,`java` 中是没有提示要处理的,如果需要提示可以添加注解
@Throws(IOException::class)
fun ex() {
throw IOException("xxx")
}
`java` 中
// 异常
try {
Hello.ex();
} catch (IOException e) {
e.printStackTrace();
}
# 7. Kotlin调用Java
1、属性名或者方法名是关键字
在 kotlin 中 is、object等都是关键字,但是 java 中不是
public static void is() {}
public static void object() {}
在 `kotlin` 中调用的时候需要添加 \`名字\`
// is object 是关键字
JavaTest.`is`()
JavaTest.`object`()
2、 `Java` 中数组与可变长度参数
`Java` 中的可变参数其实是一个数组
public static void array(String[] args) {
array2(args);
}
public static void array2(String... args) {}
在 `Kotlin` 中调用
// java数组与可变长度参数
JavaTest.array(arrayOf<String>("a", "b"))
// 这里要前面加一个 * 号,展开操作符,相当于参数就是 "a","b"
JavaTest.array2(*arrayOf("a", "b"))
3、 `Java Object`
Java 中类的父类是 Object,Object 里面有 wait() 等
如果要在 Kotlin 中调用 wait()
// 调用java object里的方法
val o = JavaTest() as java.lang.Object
o.wait()
4、操作符重载
/**
* invoke 在kotlin中是操作符
*/
public void invoke() {}
`invoke` 在 `kotlin` 中是操作符重载方法的方法名,则可以使用操作符调用相应的 `java` 方法
val jt = JavaTest()
jt.invoke()
JavaTest()()
jt()
# 8.委托
class MyList<T> : List<T> by ArrayList<T>()
interface A {
fun sayHello()
}
class Users : A {
override fun sayHello() {
println("Hello")
}
val name = "1"
}
// 我要有 A 接口的功能,但是不想自己做,交给了另一个人帮我做,就是 by 委托
class User2 : A by Users()
fun main() {
val aaa by lazy { "" }
User2().sayHello()
}<file_sep>/ScreenShot/app/src/main/java/com/zhaopf/screenshot/ScreenShotListener.kt
package com.zhaopf.screenshot
import android.annotation.SuppressLint
import android.content.Context
import android.database.ContentObserver
import android.database.Cursor
import android.graphics.BitmapFactory
import android.graphics.Point
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.view.WindowManager
import java.util.*
import kotlin.collections.ArrayList
/**
* @author zhaopingfu
* @date 2020/12/23
*/
class ScreenShotListener constructor(context: Context?) {
private var mContext: Context
private var mScreenRealSize: Point? = null
private val mHasCallbackPaths: ArrayList<String> = ArrayList()
private var mListener: OnScreenShotListener? = null
private var mStartListenTime: Long = 0
/**
* 内部存储器内容观察者
*/
private var mInternalObserver: MediaContentObserver? = null
/**
* 外部存储器内容观察者
*/
private var mExternalObserver: MediaContentObserver? = null
/**
* 运行在 UI 线程的 Handler, 用于运行监听器回调
*/
private var mUiHandler = Handler(Looper.getMainLooper())
init {
ScreenShotHelper.showLog("init")
assertInMainThread()
requireNotNull(context) { "The context must not be null." }
mContext = context
if (mScreenRealSize == null) {
mScreenRealSize = getRealScreenSize()
if (mScreenRealSize != null) {
ScreenShotHelper.showLog("Screen Real Size: " + mScreenRealSize!!.x + " * " + mScreenRealSize!!.y)
} else {
ScreenShotHelper.showLog("Get screen real size failed.")
}
}
}
/**
* 单例
*/
companion object {
fun getInstance(context: Context): ScreenShotListener {
return ScreenShotListener(context)
}
}
/**
* 开启监听
*/
fun startListener() {
assertInMainThread()
// 记录开始监听的时间戳
mStartListenTime = System.currentTimeMillis()
// 创建内容观察者
mInternalObserver =
MediaContentObserver(MediaStore.Images.Media.INTERNAL_CONTENT_URI, mUiHandler)
mExternalObserver =
MediaContentObserver(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, mUiHandler)
// 注册内容观察者
mContext.contentResolver.registerContentObserver(
MediaStore.Images.Media.INTERNAL_CONTENT_URI,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
mInternalObserver!!
)
mContext.contentResolver.registerContentObserver(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q,
mExternalObserver!!
)
}
fun stopListener() {
assertInMainThread()
// 注销内容观察者
if (mInternalObserver != null) {
try {
mContext.contentResolver.unregisterContentObserver(mInternalObserver!!)
} catch (e: Exception) {
e.printStackTrace()
}
mInternalObserver = null
}
if (mExternalObserver != null) {
try {
mContext.contentResolver.unregisterContentObserver(mExternalObserver!!)
} catch (e: Exception) {
e.printStackTrace()
}
mExternalObserver = null
}
// 清空数据
mStartListenTime = 0
mListener = null
}
/**
* 处理媒体数据库的内容改变
*/
fun handleMediaContentChange(contentUri: Uri) {
var cursor: Cursor? = null
try {
cursor = mContext.contentResolver.query(
contentUri,
ScreenShotHelper.MEDIA_PROJECTIONS_API_16,
null,
null,
"${MediaStore.Images.ImageColumns.DATE_ADDED} desc limit 1"
)
if (cursor == null) {
ScreenShotHelper.showLog("Deviant logic.")
return
}
if (!cursor.moveToFirst()) {
ScreenShotHelper.showLog("Cursor no data.")
return
}
// 获取各列的索引
val dataIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA)
val dateTakenIndex = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATE_TAKEN)
val widthIndex: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.WIDTH)
val heightIndex: Int = cursor.getColumnIndex(MediaStore.Images.ImageColumns.HEIGHT)
// 获取行数据
val data = cursor.getString(dataIndex)
val dateTaken = cursor.getLong(dateTakenIndex)
val width: Int
val height: Int
if (widthIndex >= 0 && heightIndex >= 0) {
width = cursor.getInt(widthIndex)
height = cursor.getInt(heightIndex)
} else {
val size = getImageSize(data)
width = size.x
height = size.y
}
// 处理获取到的第一行数据
handleMediaRowData(data, dateTaken, width, height)
} catch (e: Exception) {
ScreenShotHelper.showLog("Exception: ${e.message}")
e.printStackTrace()
} finally {
if (cursor != null && !cursor.isClosed) {
cursor.close()
}
}
}
private fun getImageSize(imagePath: String): Point {
val options = BitmapFactory.Options()
options.inJustDecodeBounds = true
BitmapFactory.decodeFile(imagePath, options)
return Point(options.outWidth, options.outHeight)
}
/**
* 处理获取到的一行数据
*/
private fun handleMediaRowData(data: String, dateTaken: Long, width: Int, height: Int) {
if (checkScreenShot(data, dateTaken, width, height)) {
ScreenShotHelper.showLog("ScreenShot: path = $data; size = $width * $height; date = $dateTaken")
if (mListener != null && !checkCallback(data)) {
mListener!!.onScreenShot(data)
}
} else {
// 如果在观察区间媒体数据库有数据改变,又不符合截屏规则,则输出到 log 待分析
ScreenShotHelper.showLog("Media content changed, but not screenshot: path = $data; size = $width * $height; date = $dateTaken")
}
}
/**
* 判断指定的数据行是否符合截屏条件
*/
private fun checkScreenShot(data: String?, dateTaken: Long, width: Int, height: Int): Boolean {
// 判断依据一: 时间判断
// 如果加入数据库的时间在开始监听之前, 或者与当前时间相差大于10秒, 则认为当前没有截屏
if (dateTaken < mStartListenTime || System.currentTimeMillis() - dateTaken > 10 * 1000) {
return false
}
// 判断依据二: 尺寸判断
if (mScreenRealSize != null) {
// 如果图片尺寸超出屏幕, 则认为当前没有截屏
if (!(width <= mScreenRealSize!!.x && height <= mScreenRealSize!!.y)
|| (height <= mScreenRealSize!!.x && width <= mScreenRealSize!!.y)
) {
return false
}
}
// 判断依据三: 路径判断
if (data.isNullOrEmpty()) {
return false
}
val lowerData = data.toLowerCase(Locale.getDefault())
// 判断图片路径是否含有指定的关键字之一, 如果有, 则认为当前截屏了
for (keyWork in ScreenShotHelper.KEYWORDS) {
if (lowerData.contains(keyWork)) {
return true
}
}
return false
}
/**
* 判断是否已回调过, 某些手机ROM截屏一次会发出多次内容改变的通知; <br></br>
* 删除一个图片也会发通知, 同时防止删除图片时误将上一张符合截屏规则的图片当做是当前截屏.
*/
private fun checkCallback(imagePath: String): Boolean {
if (mHasCallbackPaths.contains(imagePath)) {
ScreenShotHelper.showLog("ScreenShot: imgPath has done; imagePath = $imagePath")
return true
}
// 大概缓存15~20条记录便可
if (mHasCallbackPaths.size >= 20) {
for (i in 0..4) {
mHasCallbackPaths.removeAt(0)
}
}
mHasCallbackPaths.add(imagePath)
return false
}
/**
* 获取屏幕分辨率
*/
@SuppressLint("ServiceCast")
private fun getRealScreenSize(): Point? {
var screenSize: Point? = null
try {
screenSize = Point()
val windowManager = mContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
val defaultDisplay = windowManager.defaultDisplay
defaultDisplay.getRealSize(screenSize)
} catch (e: Exception) {
e.printStackTrace()
}
return screenSize
}
private fun assertInMainThread() {
if (Looper.myLooper() != Looper.getMainLooper()) {
val stackTrace = Thread.currentThread().stackTrace
var methodMsg: String? = null
if (stackTrace.size >= 4) {
methodMsg = stackTrace[3].toString()
}
ScreenShotHelper.showLog("Call the method must be in main thread: $methodMsg")
}
}
/**
* 媒体内容观察者
*/
private inner class MediaContentObserver(var contentUri: Uri, handler: Handler) :
ContentObserver(handler) {
override fun onChange(selfChange: Boolean) {
super.onChange(selfChange)
handleMediaContentChange(contentUri)
}
}
/**
* 设置截屏监听器回调
*/
fun setListener(listener: OnScreenShotListener) {
this.mListener = listener
}
/**
* 截屏监听接口
*/
interface OnScreenShotListener {
fun onScreenShot(picPath: String)
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/ConstraintSet2Activity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.transition.TransitionManager
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintSet
import com.meta.testmotionlayout.databinding.LayoutConstraintsetStart2Binding
class ConstraintSet2Activity : AppCompatActivity(), View.OnClickListener {
private lateinit var binding: LayoutConstraintsetStart2Binding
private var toggle = true
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = LayoutConstraintsetStart2Binding.inflate(layoutInflater)
setContentView(binding.root)
bindData()
}
private fun bindData() {
binding.imageFilmCover.setOnClickListener(this)
binding.ratingFilmRating.rating = 4.5f
binding.textFilmTitle.text = getString(R.string.film_title)
binding.textFilmDescription.text = getString(R.string.film_description)
}
override fun onClick(v: View?) {
v ?: return
TransitionManager.beginDelayedTransition(binding.root2)
val constraintSet = ConstraintSet().apply {
if (toggle) {
clone(this@ConstraintSet2Activity, R.layout.layout_constraintset_end2)
} else {
clone(this@ConstraintSet2Activity, R.layout.layout_constraintset_start2)
}
}
constraintSet.applyTo(binding.root2)
toggle = !toggle
}
}
<file_sep>/TestStyleAndTheme/app/src/main/java/com/zhaopf/teststyleandtheme/MainActivity.kt
package com.zhaopf.teststyleandtheme
import android.content.res.ColorStateList
import android.graphics.Color
import android.os.Bundle
import androidx.activity.viewModels
import androidx.annotation.StyleableRes
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatRadioButton
import androidx.core.widget.CompoundButtonCompat
import androidx.lifecycle.observe
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity(R.layout.activity_main) {
private val mThemeViewModel by viewModels<ThemeViewModel>()
override fun onCreate(savedInstanceState: Bundle?) {
//配置 primaryColor 是否全屏,在配置布局之前
with(mThemeViewModel) {
primaryColor.value?.let { setTheme(it) }
edgeToEdgeEnabled.value?.let { applyEdgeToEdgePreference(it) }
}
super.onCreate(savedInstanceState)
initPrimaryRadioButton()
initToolbar()
mThemeViewModel.currentTheme.observe(this) { delegate.localNightMode = it.mode }
initThemeRadioButton()
}
private fun initThemeRadioButton() {
rgTheme.check(getThemeCheckId())
rgTheme.setOnCheckedChangeListener { _, checkedId ->
when (checkedId) {
R.id.themeLight -> mThemeViewModel.setCurrentTheme(Theme.LIGHT)
R.id.themeDark -> mThemeViewModel.setCurrentTheme(Theme.DARK)
R.id.themeDefault -> mThemeViewModel.setCurrentTheme(Theme.SYSTEM)
}
}
}
/**
* 根据 mThemeViewModel.currentTheme 选中默认的 theme radio button
*/
private fun getThemeCheckId(): Int {
return when (mThemeViewModel.currentTheme.value) {
Theme.LIGHT -> R.id.themeLight
Theme.DARK -> R.id.themeDark
Theme.SYSTEM -> R.id.themeDefault
else -> -1
}
}
private fun initToolbar() {
val edgeToEdgeEnabled = mThemeViewModel.edgeToEdgeEnabled.value ?: false
toolbar1.setNavigationIcon(if (edgeToEdgeEnabled) R.drawable.ic_edge_to_edge_disable_24dp else R.drawable.ic_edge_to_edge_enable_24dp)
toolbar1.setNavigationOnClickListener {
mThemeViewModel.edgeToEdgeEnabled.value = !edgeToEdgeEnabled
recreate()
}
}
private fun initPrimaryRadioButton() {
createPrimaryButton()
rgPrimary.setOnCheckedChangeListener { group, checkedId ->
mThemeViewModel.primaryColor.value =
group.findViewById<AppCompatRadioButton>(checkedId).tag as Int
recreate()
}
}
private fun createPrimaryButton() {
val primaryArray = resources.obtainTypedArray(R.array.primary_palettes)
val descriptionArray = resources.obtainTypedArray(R.array.palettes_content_description)
var style: Int
if (primaryArray.length() != descriptionArray.length()) {
throw IllegalArgumentException("primary_palettes 与 palettes_content_description 长度不等!")
}
for (index in 0 until primaryArray.length()) {
style = primaryArray.getResourceId(index, 0)
rgPrimary.addView(AppCompatRadioButton(this).apply {
text = descriptionArray.getString(index)
val a = obtainStyledAttributes(style, PRIMARY_THEME_OVERLAY_ATTRS)
CompoundButtonCompat.setButtonTintList(
this, ColorStateList.valueOf(a.getColor(0, Color.TRANSPARENT))
)
// 与 mThemeViewModel.primaryColor 一致则选中
isChecked = mThemeViewModel.primaryColor.value == style
tag = style
a.recycle()
})
}
primaryArray.recycle()
descriptionArray.recycle()
}
companion object {
@StyleableRes
private val PRIMARY_THEME_OVERLAY_ATTRS = intArrayOf(
R.attr.colorPrimary, R.attr.colorPrimaryDark
)
}
}<file_sep>/TestMotionLayout/app/src/main/java/com/meta/testmotionlayout/GoActivity.kt
package com.meta.testmotionlayout
import android.os.Bundle
import android.transition.Scene
import android.transition.TransitionManager
import android.view.View
import android.widget.ImageView
import android.widget.RatingBar
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.meta.testmotionlayout.databinding.ActivityGoBinding
class GoActivity : AppCompatActivity(), View.OnClickListener {
private var toggle = true
private lateinit var binding: ActivityGoBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityGoBinding.inflate(layoutInflater)
setContentView(binding.root)
bindData()
}
private fun bindData() {
findViewById<ImageView>(R.id.image_film_cover).setOnClickListener(this)
findViewById<RatingBar>(R.id.rating_film_rating).rating = 4.5f
findViewById<TextView>(R.id.text_film_title).text = getString(R.string.film_title)
findViewById<TextView>(R.id.text_film_description).text =
getString(R.string.film_description)
}
override fun onClick(view: View) {
val startScene = Scene.getSceneForLayout(binding.root, R.layout.layout_go_start, this)
val endScene = Scene.getSceneForLayout(binding.root, R.layout.layout_go_end, this)
if (toggle) {
TransitionManager.go(endScene)
} else {
TransitionManager.go(startScene)
}
bindData()
toggle = !toggle
}
}
<file_sep>/TestExoPlayer/app/src/main/java/com/zhaopf/testexoplayer/HomeOtherFragment.kt
package com.zhaopf.testexoplayer
import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_home_other.*
/**
* 首页第一个fragment之外的内容
*/
class HomeOtherFragment : Fragment() {
companion object {
fun newInstance(backgroundColor: Int): HomeOtherFragment {
return HomeOtherFragment().apply {
arguments = Bundle().apply {
putInt("backgroundColor", backgroundColor)
}
}
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
return inflater.inflate(R.layout.fragment_home_other, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
flRootContainer.setBackgroundColor(arguments?.getInt("backgroundColor") ?: Color.RED)
}
}<file_sep>/TestHilt/app/src/main/java/com/zhaopf/testhilt/data/LogDao.kt
package com.zhaopf.testhilt.data
import android.database.Cursor
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
/**
* @author zhaopingfu
* @date 2020/10/23
*/
@Dao
interface LogDao {
@Query("SELECT * FROM logs ORDER BY id DESC")
fun getAll(): List<Log>
@Insert
fun insertAll(vararg logs: Log)
@Query("DELETE FROM logs")
fun nukeTable()
@Query("SELECT * FROM logs ORDER BY id ASC")
fun selectAllLogsCursor(): Cursor
@Query("SELECT * FROM logs WHERE id = :id")
fun selectLogById(id: Long): Cursor?
}
|
a0289c6b1678348e71c4b45a12a2c84eac78c8b1
|
[
"Markdown",
"INI",
"Gradle",
"Java",
"Kotlin",
"Shell"
] | 148
|
Kotlin
|
zhaopingfu/TestDemo
|
90a8c74278d5a7d588403298651393aa6d6d1a10
|
21036af76d2314c43b96b8226c2894b49bb505ff
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
"""
Created on Tue Dec 27 09:01:21 2016
@author: joaquin
"""
'''
Distintas funciones de visualización de datos
'''
import matplotlib.pyplot as plt
import scipy.signal as sig
import numpy
import matplotlib.pyplot as plt
def ajusteCuadratico(datos_crudos, graficar = False):
maximo = max(datos_crudos)
cant_datos = len(datos_crudos)
datos_normalizados = [0]*cant_datos
for n in xrange(cant_datos):
datos_normalizados[n] = datos_crudos[n]/maximo
datos_savgol = sig.savgol_filter(datos_normalizados, 5, 1)
fit_datos = numpy.polyfit(range(cant_datos), datos_savgol, 2)
polinomio = numpy.poly1d(fit_datos)
datos_poly = polinomio(range(cant_datos))
if graficar:
plt.plot(datos_savgol)
plt.plot(datos_poly)
plt.show()
return datos_poly, fit_datos<file_sep>analisis_acciones_RAVA
El proyecto busca poder bajar los históricos de las acciones desde RAVAonline. Una vez leídos los valores, el programa busca hacer un primer análisis para determinar si una acción puede llegar a subir o bajar
<file_sep># -*- coding: utf-8 -*-
"""
Created on Sun Dec 25 18:01:37 2016
@author: joaquin
"""
import urllib2
import csv
import time
class especie:
'''
Esta clase guarda toda la informacion de los valores historicos leidos
desde RAVAonline.
En RAVA se guardan todos los valores historicos en un csv. Esta clase los
lee y los guarda en distintas propiedades
'''
def __init__ (self, nombre_especie, nombre = ''):
self.nombre = nombre[:];
self.url = 'http://www.ravaonline.com/v2/empresas/precioshistoricos.php?e=' + nombre_especie + '&csv=1';
downloaded_data = urllib2.urlopen(self.url);
historicos = csv.DictReader(downloaded_data);
self.fecha = [];
self.apertura = [];
self.maximo = [];
self.minimo = [];
self.cierre = [];
self.volumen = [];
self.media = [];
for dia in historicos:
self.fecha.append(time.strptime( dia['fecha'] , '%Y-%m-%d' ) )
self.apertura.append( float(dia['apertura']));
self.maximo.append( float(dia['maximo']));
self.minimo.append( float(dia['minimo']));
self.cierre.append( float(dia['cierre']));
self.volumen.append( float(dia['volumen']));
self.media.append( (float(dia['apertura']) + float(dia['cierre']))/2.0 );
downloaded_data.close()
def getName(self):
return self.nombre;
def getFecha(self, ultimos_dias = 0):
'''
Devuelve las fechas de los ultimos_dias. El default es toda la lista completa
'''
return self.fecha[-ultimos_dias : ];
def getApertura(self, ultimos_dias = 0):
'''
Devuelve las aperturas de los ultimos_dias. El default es toda la lista completa
'''
return self.apertura[-ultimos_dias : ];
def getMaximo(self, ultimos_dias = 0):
'''
Devuelve los maximos de los ultimos_dias. El default es toda la lista completa
'''
return self.maximo[-ultimos_dias : ];
def getMinimo(self, ultimos_dias = 0):
'''
Devuelve los minimos de los ultimos_dias. El default es toda la lista completa
'''
return self.minimo[-ultimos_dias : ];
def getCierre(self, ultimos_dias = 0):
'''
Devuelve los cierres de los ultimos_dias. El default es toda la lista completa
'''
return self.cierre[-ultimos_dias : ];
def getVolumen(self, ultimos_dias = 0):
'''
Devuelve los volumenes de los ultimos_dias. El default es toda la lista completa
'''
return self.volumen[-ultimos_dias : ];
def getMedia(self, ultimos_dias = 0):
'''
Devuelve la media de los ultimos_dias. El default es toda la lista completa
'''
return self.media[-ultimos_dias : ];
|
eb5ac06c34df180af2e633179a3e691d792cfcce
|
[
"Markdown",
"Python"
] | 3
|
Python
|
joacoFisico/Analisis-Acciones-RAVA
|
6e250f1d5d64d3eeffeb2205c8a65de8e471d595
|
4d7a8b19ce1597175648dbec107fcb4cfd0060ac
|
refs/heads/master
|
<repo_name>lkasdolka/BubbleDatingServer<file_sep>/src/edu/bupt/util/HXTool.java
package edu.bupt.util;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.LayeredConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;
public class HXTool {
private static final String CLIENT_ID = "YXA6LUM2wPFDEeSFuOcmeziT4Q";
private static final String CLIENT_SECRET = "<KEY>";
private static final String GET_ACCESS_URL = "https://a1.easemob.com/halfdog/bubbledating/token";
private static final String REGISTER_URL = "https://a1.easemob.com/halfdog/bubbledating/users";
private static final String CER_PATH = "F:\\Program Files\\Java\\jre1.8.0_31\\lib\\security\\cacerts";
private static final String CER_PATH2 = "F:\\Program Files\\Java\\jre1.8.0_31\\lib\\security\\cacerts";
public static void main(String[] args) {
// System.setProperty("javax.net.ssl.trustStore", CER_PATH);
// System.out.println(getAccessToken());
// int resCode = registerHXUser("aaa", "aaa");
// if(resCode == 200)System.out.println("register successfully");
// else System.out.println("certain problem occurred");
getAccessToken();
System.out.println(getUser("aaa"));
}
public static String getAccessToken() {
// System.setProperty("javax.net.ssl.trustStore", CER_PATH);
String res = null;
CloseableHttpClient httpclient = getHttpClient();
HttpPost httpPost = new HttpPost(GET_ACCESS_URL);
JSONObject body = new JSONObject();
body.put("grant_type", "client_credentials");
body.put("client_id", CLIENT_ID);
body.put("client_secret", CLIENT_SECRET);
System.out.println(body.toString());
CloseableHttpResponse response2 = null;
try {
StringEntity entity = new StringEntity(body.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
String content = EntityUtils.toString(entity2);
// System.out.println("response:"+content);
JSONObject jsonObject = new JSONObject(content);
ConstantArgs.HX_ACCESS_TOKEN = jsonObject.getString("access_token");
System.out.println("HX_ACCESS_TOKEN:"+ConstantArgs.HX_ACCESS_TOKEN);
res = content;
EntityUtils.consume(entity2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (response2 != null) {
response2.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
public static boolean getUser(String username){
String ans = null;
int statusCode = -1;
// CloseableHttpClient httpclient = HttpClients.createDefault();
CloseableHttpClient httpclient = getHttpClient();
HttpGet httpGet = new HttpGet(REGISTER_URL+"/"+username);
System.out.println("get user:"+REGISTER_URL+"/"+username);
httpGet.setHeader("Authorization","Bearer "+ConstantArgs.HX_ACCESS_TOKEN);
CloseableHttpResponse response1 = null;
try {
response1 = httpclient.execute(httpGet);
System.out.println(response1.getStatusLine());
statusCode = response1.getStatusLine().getStatusCode();
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
ans = EntityUtils.toString(entity1);
System.out.println(ans);
EntityUtils.consume(entity1);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally {
try {
response1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(statusCode == 200) return true;
else return false;
// return statusCode;
}
public static int registerHXUser(String user, String pw){
String ans = null;
int statusCode = -1;
int registerStatus = -1;
CloseableHttpClient httpclient = getHttpClient();
HttpPost httpPost = new HttpPost(REGISTER_URL);
JSONObject body = new JSONObject();
body.put("username", user);
body.put("password", pw);
httpPost.setHeader("Content-Type", "application/json");
httpPost.setHeader("Authorization","Bearer "+ ConstantArgs.HX_ACCESS_TOKEN);
CloseableHttpResponse response2 = null;
try {
StringEntity entity = new StringEntity(body.toString(), ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
statusCode = response2.getStatusLine().getStatusCode();
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
String content = EntityUtils.toString(entity2);
// System.out.println("response:"+content);
ans = content;
EntityUtils.consume(entity2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
if (response2 != null) {
response2.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return statusCode;
}
public static String get(String url) {
String res = null;
CloseableHttpClient httpclient = getHttpClient();
HttpGet httpGet = new HttpGet(url);
CloseableHttpResponse response1 = null;
try {
response1 = httpclient.execute(httpGet);
System.out.println(response1.getStatusLine());
HttpEntity entity1 = response1.getEntity();
if (entity1 != null) {
res = EntityUtils.toString(entity1);
System.out.println(res);
EntityUtils.consume(entity1);
}
} catch (ClientProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
finally {
try {
response1.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
public static String post(String url, String username, String pw) {
String res = null;
CloseableHttpClient httpclient = getHttpClient();
HttpPost httpPost = new HttpPost(url);
List<NameValuePair> nvps = new ArrayList<NameValuePair>();
nvps.add(new BasicNameValuePair("username", username));
nvps.add(new BasicNameValuePair("password", pw));
CloseableHttpResponse response2 = null;
try {
httpPost.setEntity(new UrlEncodedFormEntity(nvps));
response2 = httpclient.execute(httpPost);
System.out.println(response2.getStatusLine());
HttpEntity entity2 = response2.getEntity();
if (entity2 != null) {
res = EntityUtils.toString(entity2);
System.out.println(res);
EntityUtils.consume(entity2);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
response2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
private static CloseableHttpClient getHttpClient() {
RegistryBuilder<ConnectionSocketFactory> registryBuilder = RegistryBuilder.<ConnectionSocketFactory>create();
ConnectionSocketFactory plainSF = new PlainConnectionSocketFactory();
registryBuilder.register("http", plainSF);
//指定信任密钥存储对象和连接套接字工厂
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
//信任任何链接
TrustStrategy anyTrustStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
return true;
}
};
SSLContext sslContext = SSLContexts.custom().useTLS().loadTrustMaterial(trustStore, anyTrustStrategy).build();
LayeredConnectionSocketFactory sslSF = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
registryBuilder.register("https", sslSF);
} catch (KeyStoreException e) {
throw new RuntimeException(e);
} catch (KeyManagementException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
Registry<ConnectionSocketFactory> registry = registryBuilder.build();
//设置连接管理器
PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
// connManager.setDefaultConnectionConfig(connConfig);
// connManager.setDefaultSocketConfig(socketConfig);
//构建客户端
return HttpClientBuilder.create().setConnectionManager(connManager).build();
}
}
<file_sep>/README.md
# BubbleDatingServer
This is a simple server for handling requests from android app <strong><em>Bubble Dating</em></strong>.
<strong>Servlets</strong> wrapped in <em>Tom Cat</em> dealing with requests and send reponses
other functionalities to be added
<file_sep>/src/edu/bupt/servlets/HandlePeopleAround.java
package edu.bupt.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONObject;
import edu.bupt.util.SqlTool;
public class HandlePeopleAround extends HttpServlet {
/**
* Constructor of the object.
*/
public HandlePeopleAround() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("get a request to query people around");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
ArrayList<JSONObject> data = SqlTool.queryPeopleAround();
JSONArray dataArray = new JSONArray(data);
for(int i=0;i<dataArray.length();i++){
JSONObject item = dataArray.getJSONObject(i);
System.out.println("u_name:"+item.getString("u_name")+",u_gender:"+item.getString("u_gender")
+",u_navi:"+item.getString("u_invi")+"u_posttime:"+item.getLong("u_posttime"));
}
System.out.println("get the json array ready to respond");
out.print(dataArray);
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
<file_sep>/src/edu/bupt/servlets/HandleLogin.java
package edu.bupt.servlets;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
import edu.bupt.bean.User;
import edu.bupt.util.HXTool;
import edu.bupt.util.SqlTool;
public class HandleLogin extends HttpServlet {
/**
* Constructor of the object.
*/
public HandleLogin() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("application/json");
PrintWriter out = response.getWriter();
JSONObject resData = new JSONObject();
String userName = request.getParameter("username");
String password = request.getParameter("password");
String latString = request.getParameter("lat");
String lonString = request.getParameter("lon");
double lat = Double.parseDouble(latString);
double lon = Double.parseDouble(lonString);
System.out.println("username:"+userName);
System.out.println("password:"+password);
ArrayList<String> queryKeys = new ArrayList<String>();
ArrayList<String> queryValues = new ArrayList<String>();
queryKeys.add("u_name");
queryKeys.add("u_pw");
queryValues.add(userName);
queryValues.add(password);
if(!SqlTool.isExist("u_name", userName)){
/*user not exist in database */
resData.put(SqlTool.STATUS_KEY, SqlTool.ResponseStatus.UNKOWN_USERNAME.getValue());
}else{
//update user location
SqlTool.updateUserLoc(userName, lat, lon);
// register HX user
User user = SqlTool.isExistMultiParam(queryKeys,queryValues,userName);
if(user != null){
//check if HX server has this name
boolean HX_OK = false;
boolean isExistOnHx = HXTool.getUser(userName);
if(!isExistOnHx){
int statusCode = HXTool.registerHXUser(userName, password);
if(statusCode != 200){
System.out.println("Oops, register "+userName+" failed");
resData.put(SqlTool.STATUS_KEY, SqlTool.ResponseStatus.HX_REGISTER_FAILED.getValue());
}else{
HX_OK = true;
}
}else{
HX_OK = true;
}
// System.out.println("user bean:"+user.toString());
if(HX_OK){
resData.put(SqlTool.STATUS_KEY, SqlTool.ResponseStatus.OK.getValue());
Map<String, Object> map = new HashMap<String, Object>();
map.put("u_id", user.getmId());
map.put("u_name", user.getmName());
map.put("u_password", <PASSWORD>.getmPw());
map.put("u_email", user.getmEmail());
map.put("u_gender", user.getmGender());
map.put("u_image", user.getmImage());
map.put("u_online", user.getmOnline());
JSONObject u_info = new JSONObject(map);
System.out.println(u_info.toString());
resData.put("user_info", u_info);
}
}else{
resData.put(SqlTool.STATUS_KEY, SqlTool.ResponseStatus.USERNAME_PASSWORD_UNCOMPATIBLE.getValue());
}
}
out.print(resData);
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
|
ba436b39c3eafebb964daedb8b78e5c01bf4589b
|
[
"Markdown",
"Java"
] | 4
|
Java
|
lkasdolka/BubbleDatingServer
|
2978a5d9aca630d55aa40266a5a071bac6257462
|
e14e83dafeb9e948d99c817123d123883e6213a6
|
refs/heads/master
|
<file_sep>//Array of images and data for html doc
var photoArray = [
{
image: '../images/roadtrip2017_1c5.jpg',
description: 'Happy to have made it to the top. What a great Hike!',
likes: 0,
visible: true
},
{
image: '../images/roadtrip2017_1ab.jpg',
description: 'Even Otto was tired after making it to the top of Little Devils Tower.',
likes: 0,
visible: true
},
{
image: '../images/roadtrip2017_1d8.jpg',
description: 'Taking a much desired rest at the top of Little Devils Tower',
likes: 0,
visible: true
},
{
image: '../images/roadtrip2017_1c3.jpg',
description: 'Steven and Otto were bouldering like pros.',
likes: 0,
visible: true
},
{
image: '../images/roadtrip2017_178.jpg',
description: 'The views were amazing when we were hiking in the Black Hills.',
likes: 0,
visible: true
},
{
image: '../images/roadtrip2017_203.jpg',
description: 'My two favorite guys posing when we started our 3 hr hike.',
likes: 0,
visible: true
},
];
<file_sep># photo_gallery_wk4
Photo Gallery
- [x] Setup file structure
- [x] Add images folder - need 6 or more images
- [x] Add Bootstrap for easy styling
- [x] Get server up and running
- [x] When picture is clicked show brief description
- [x] Thumbs up/heart/favorite image option for users
- [x] Counter for how many people have thumbs up/heart/favorite
- [ ]
|
ef63091119e37ce967d95e05a8ad81a2e251e584
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
emilykuplic/photo_gallery_wk4
|
95f48791e46611caf5053640d601467f793f760d
|
274ce179024db5137e0455430138fcc9759481e0
|
refs/heads/master
|
<repo_name>elliotjr/CSSE2002<file_sep>/Assignment3/src/festival/gui/PlannerController.java
package festival.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileNotFoundException;
import java.io.IOException;
import com.itextpdf.text.DocumentException;
import festival.Event;
import festival.FormatException;
/**
* The controller for the Festival Planner.
*/
public class PlannerController {
// the model that is being controlled
private PlannerModel model;
// the view that is being controlled
private PlannerView view;
private Pdf pdf = new Pdf();
/**
* Initialises the Controller for the Festival Planner.
*/
public PlannerController(PlannerModel model, PlannerView view) {
// Initiates the view.
this.view = view;
// Initiates the model.
this.model = model;
try {
model.initiateDayPlan();
setDayPlanList();
} catch (IOException e) {
// Catch exception where file doesn't load.
view.showErrorMessage(e.getMessage());
// Close the system.
System.exit(-1);
} catch (FormatException e) {
// Catch a format error from the timetable file.
view.showErrorMessage("timetable.txt", e.getMessage());
System.exit(-1);
}
try {
model.initiateLineUp();
setLineUpLists();
} catch (IOException e) {
// Catch an IOException error from the line up file.
view.showErrorMessage(e.getMessage());
System.exit(-1);
} catch (FormatException e) {
// Catch a format error from the line up file.
view.showErrorMessage("lineUp.txt", e.getMessage());
System.exit(-1);
}
// If there are no events in the line up, disable the add button.
if (model.getLineUpModel().size() == 0) {
view.getAddButton().setEnabled(false);
}
// Adds event listeners to the view components.
addListeners();
}
/**
* Adds event listeners to the components in the view.
*
* @require The view contains a component that takes a listener.
* @ensure That an event listener will be added to that component.
*/
private void addListeners() {
// Add a listener to the add button.
this.view.addAddListener(new AddActionListener());
// Add a listener to the remove button.
this.view.addRemoveListener(new RemoveActionListener());
// Add a listener to the session combo box.
this.view.addSessionListListener(new AddSessionListListener());
this.view.addSaveListener(new AddSaveListener());
}
/**
* Sets the model lists to their respective view components.
*
* @require dayPlan && lineUp are not null.
* @ensure A model will be set for the respective lists and any errors will
* be handled appropriately.
*/
private void setDayPlanList() {
// Gets the current day plan list from model and add it to the view.
view.updateDayPlan(model.getDayPlanModel());
}
private void setLineUpLists() {
// Gets the current line up from the model and add it to the view.
view.updateLineUp(model.getLineUpModel());
// Gets the current session model from the model and adds it to the
// view.
view.updateSessionList(model.getSessionList());
checkSessionSize();
}
/**
* Checks the model for errors and displays error in view
*
* @require model and view are not null.
* @ensure If there is an error, it will be displayed appropriatly in the
* view.
*/
private void checkSessionSize() {
// If there is are no events, disable the add button and tell there user
// that there are no events.
if (model.getSessionList().size() == 1) {
view.getAddButton().setEnabled(false);
view.errorBoxMessage("There are no events.", 2);
// Tell the user that their plan is empty.
} else {
view.errorBoxMessage("Your plan is empty", 2);
}
}
/**
* A private class which implements an action listener on an add button in
* the view.
*/
private class AddActionListener implements ActionListener {
/**
* A method which adds the selected event from a lineup to the proposed
* day plan.
*
* @require !(model.equals(null) && !(view.equals(null) &&
* !selection.equals(null)
* @ensure That either the event will be added to the proposed day plan
* or the user is informed of an invalid entry.
*/
public void actionPerformed(ActionEvent event) {
// The selected event from the list.
Event selection = view.getSelectedLineUpEvent();
model.getIntermediatePlan().add(selection);
checkAddExceptions(selection);
// The size of the model is greater than 0.
if (model.getDayPlanModel().size() > 0) {
view.getRemoveButton().setEnabled(true);
// If there are no events in the day plan, disable the remove
// button.
} else {
view.getRemoveButton().setEnabled(false);
}
}
}
private class AddSaveListener implements ActionListener {
public void actionPerformed(ActionEvent event) {
try {
String name = view.getUserName();
pdf.addOwner(name);
pdf.addLineUp(model.getDayPlanModel());
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//view.getSave().setEnabled(false);
}
}
/**
* A method which checks the validity of adding a new event to the proposed
* day plan
*
* @require model && view && selection are not null.
* @ensure Either the successful adding of an event to the day plan or
* message sent to the user.
* @param selection
* - the event the user wants added to the day plan.
*/
private void checkAddExceptions(Event selection) {
// The day plan already contains selection, inform the user.
if (model.containsEvent(selection)) {
view.errorBoxMessage("The day plan already contains '" + selection
+ "'", 0);
model.getIntermediatePlan().remove(selection);
// The day plan already contains an event with the same session as
// selection.
} else if (model.isNotUniqueSession(selection)) {
view.errorBoxMessage(
"The plan already includes an event in session "
+ selection.getSession(), 0);
model.getIntermediatePlan().remove(selection);
// The previous event in the day plan cannot reach selection.
} else if (!model.canReachPrevious(selection)) {
view.errorBoxMessage(selection
+ " cannot be reached by the previous event.", 0);
// Selection cannot reach the next event in the day plan.
} else if (!model.canReachNext(selection)) {
view.errorBoxMessage(selection + " cannot reach the next event.", 0);
// Add selection to the day plan.
} else {
view.errorBoxMessage("Successfully added '" + selection + "'", 1);
model.addToDayPlan(selection);
setDayPlanList();
}
}
/**
* A private class which implements the action listener for a list full of
* sessions. The user is able to select a session which will then sort the
* line up by that session.
*/
private class AddSessionListListener implements ActionListener {
/**
* Populates the line up list with a respective session number which has
* been selected form the session number list.
*
* @require model and view are not null.
* @ensure If session x is selected, all events with session x in the
* line up will be added to the line up model.
* @param event
* - The event that has taken place in the view.
*/
public void actionPerformed(ActionEvent event) {
String selection = view.getSelectedSession();
// Populates the line up model that have the session number of
// selected session.
model.createSessionModel(selection);
// Update the line up with these events.
view.updateLineUp(model.getLineUpModel());
}
}
/**
* A private class which implements an action listener on an remove button
* in the view.
*/
private class RemoveActionListener implements ActionListener {
/**
* A method which removes the selected event from a lineup to the
* proposed day plan.
*
* @require model && view && selection are not null.
* @ensure That either the event will be removed from the proposed day
* plan or the user is informed of an invalid removal.
* @param event
* - the event that has taken place on the view - (The user
* has clicked the remove button).
*/
public void actionPerformed(ActionEvent event) {
Event selection = view.getSelectedDayPlanEvent();
checkRemoveErrors(selection);
}
}
/**
* A method which checks the validity of removing an event from the proposed
* day plan
*
* @require model && view && selection are not null.
* @ensure Either the successful removal of an event from the day plan or
* message sent to the user.
* @param selection
* - The event that the user wants removed from the day plan.
*/
private void checkRemoveErrors(Event selection) {
// The model cannot remove the event without cause the day plan to be
// compatible.
if (view.getDayPlan().isSelectionEmpty()) {
view.errorBoxMessage("Please select an event to remove.", 0);
// Remove the event from the day plan.
} else {
view.errorBoxMessage("'" + selection + "' has been removed.", 1);
model.removeFromDayPlan(selection);
view.getDayPlan().clearSelection();
setDayPlanList();
}
// If the day plan model is empty, the remove button is disabled.
if (model.getDayPlanModel().size() == 0) {
view.getRemoveButton().setEnabled(false);
}
}
}
<file_sep>/Assignment3/src/festival/gui/PlannerView.java
package festival.gui;
import javax.swing.*;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import festival.Event;
import java.awt.*;
import java.awt.event.ActionListener;
import java.util.ArrayList;
/**
* The view for the Festival Planner.
*/
@SuppressWarnings("serial")
public class PlannerView extends JFrame {
// The model of the view.
private PlannerModel model;
// A combo box which contains the line up events.
private JComboBox<Event> lineUp;
// A combo box which contains the session times of the festival.
private JComboBox<String> sessions;
// A button used to add events to the day plan.
private JButton addButton;
// A button used to remove events from the day plan.
private JButton removeButton;
// A JList used to store the users proposed plan.
private JList<Event> dayPlan;
// The error dialog scroll pane.
private JScrollPane errorDialog;
// The error dialog text box.
private JTextArea errorDialogText;
// The model of the users proposed day plan.
private DefaultListModel<Event> dayPlanListModel;
// The model for the sessions of the festival.
private DefaultComboBoxModel<String> sessionModel;
// The model for the line up of the festival.
private DefaultComboBoxModel<Event> lineUpModel;
// The button to save the list to a pdf
private JButton save;
// The button to add the author of the festival
private JTextField name;
/**
* Creates a new Festival Planner window.
*/
public PlannerView(PlannerModel model) {
this.model = model;
setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setSize(600, 500);
// Set the title of the window.
this.setTitle("Festival Day Planner");
this.setResizable(false);
// View appears in the middle of the screen.
this.setLocationRelativeTo(null);
// Total area of the view.
Container content = getContentPane();
content.setLayout(new BoxLayout(content, BoxLayout.PAGE_AXIS));
JPanel topTitle = new JPanel();
topTitle.setLayout(new FlowLayout(FlowLayout.CENTER));
JLabel title = new JLabel(
"Please Select a session to find some events.");
// Add a title to the top of the screen. (Not the window title).
topTitle.add(title);
content.add(topTitle);
addTop(content);
// Adds a horizontal line across the view.
content.add(new JSeparator());
addBottom(content);
}
/**
* A method which adds the bottom panel to the JFrame (day plan list and the
* buttons)
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addBottom(Container content) {
// A panel at the bottom of the window.
JPanel bottomPanel = new JPanel();
bottomPanel.setLayout(new BoxLayout(bottomPanel, BoxLayout.PAGE_AXIS));
// Add the day plan into this panel.
addDayPlan(bottomPanel);
JPanel bottom = new JPanel();
bottom.setLayout(new FlowLayout(FlowLayout.CENTER));
// A label describing the users day plan.
bottom.add(new JLabel("Your Day Plan:"));
bottom.add(bottomPanel);
// Creates a space between elements.
bottom.add(Box.createRigidArea(new Dimension(25, 0)));
// Add the remove buttons.
addBottomButtons(bottom);
content.add(bottom);
}
/**
* A method which adds the top panel to the JFrame
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addTop(Container content) {
// A panel at the top of the window.
JPanel topPanel = new JPanel();
name = new JTextField("Default");
// Set the size of the top panel.
topPanel.setPreferredSize(new Dimension(500, 100));
topPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
// Add a new JLabel describing the line up combo box.
topPanel.add(name);
topPanel.add(new JLabel("Festival Line Up:", JLabel.LEFT));
// Add the combo boxes to this panel.
addComboBoxes(topPanel);
topPanel.add(Box.createRigidArea(new Dimension(25, 0)));
// Add the top buttons to this panel.
addTopButtons(topPanel);
content.add(topPanel);
}
/**
*
* @return The name of the person who is making lineup
*/
public String getUserName() {
return name.getText();
}
public JButton getSave() {
return save;
}
/**
* A method which adds combo boxes to a container.
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addComboBoxes(Container content) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
sessions = new JComboBox<String>();
// Hover tips for the session combo box.
sessions.setToolTipText("Sessions for the line-up");
panel.add(sessions);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
lineUp = new JComboBox<Event>();
// Text appears when mouse hovers over line up combo box.
lineUp.setToolTipText("The line-up for the festival");
lineUp.setPreferredSize(new Dimension(260, 20));
// Add the line up into this panel.
panel.add(lineUp);
content.add(panel);
panel.add(Box.createRigidArea(new Dimension(0, 10)));
// Add the error box into this panel.
addErrorBox(panel);
}
/**
* A method which adds the day plan component to a container.
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addDayPlan(Container content) {
JPanel panel = new JPanel();
dayPlan = new JList<Event>();
// Single selection only.
dayPlan.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
// Add the day plan into the scroll pane.
JScrollPane scrollPane = new JScrollPane(dayPlan);
// Set the size of scroll pane
scrollPane.setPreferredSize(new Dimension(258, 200));
scrollPane.setMaximumSize(new Dimension(258, 200));
panel.add(scrollPane);
content.add(panel, BorderLayout.AFTER_LAST_LINE);
}
/**
* A method which adds the top buttons panel to a container
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addTopButtons(Container content) {
JPanel panel = new JPanel();
// The size of the largest button - make all buttons this size.
JButton buttonSize = new JButton("remove event");
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
addButton = new JButton("add event");
// Hover hints for add event button.
addButton.setToolTipText("Click here to add the event to the day plan");
// Make the add button the size of the largest button.
addButton.setPreferredSize(buttonSize.getPreferredSize());
// Adds the add button to this panel.
panel.add(addButton);
content.add(panel);
}
/**
* A method which adds the bottom buttons panel to a container
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addBottomButtons(Container content) {
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS));
removeButton = new JButton("remove event");
save = new JButton("Save");
// Disable the "remove event" button.
removeButton.setEnabled(false);
// Add the remove button to this panel.
panel.add(removeButton);
panel.add(save);
content.add(panel);
}
/**
* A method which adds the error panel to a container
*
* @require content is not null.
* @ensure that the elements will be added to the content component
* @param content
* - the component where elements in this method are put into
*/
private void addErrorBox(Container content) {
JPanel panel = new JPanel();
panel.setLayout(new GridLayout());
panel.setPreferredSize(new Dimension(256, 50));
// Create an etched border for the error text area.
Border errorTitle = new EtchedBorder(EtchedBorder.LOWERED);
panel.setBorder(errorTitle);
errorDialogText = new JTextArea();
errorDialogText = new JTextArea("Your day plan is currently empty.");
// Add a margin to the inside of the text area.
errorDialogText.setMargin(new Insets(2, 2, 2, 2));
errorDialogText.setLineWrap(true);
// The user is not able to edit this text area.
errorDialogText.setEditable(false);
errorDialogText.setWrapStyleWord(true);
// Make errorDialogText scrollable.
errorDialog = new JScrollPane(errorDialogText);
// Add the error dialog to this panel.
panel.add(errorDialog);
content.add(panel);
}
/**
* Updates the users proposed day plan.
*
* @require dayPlanListModel && dayPlan && dayPlanModel are not null.
* @ensure the view will be updated with current model.
* @param dayPlanModel
* - A list of events from the model of the GUI.
*/
public void updateDayPlan(ArrayList<Event> dayPlanModel) {
dayPlanListModel = new DefaultListModel<Event>();
// Add events to the day plan model.
for (Event event : dayPlanModel) {
dayPlanListModel.addElement(event);
}
// Sets the updated model to the JList
dayPlan.setModel(dayPlanListModel);
}
/**
* Updates the session combo box.
*
* @require sessionListModel && sessionModel && sessions are not null.
* @ensure the view will be updated with the current model.
* @param sessionListModel
* - A list of sessions from the model of the GUI.
*/
public void updateSessionList(ArrayList<String> sessionListModel) {
sessionModel = new DefaultComboBoxModel<String>();
// Add all session numbers to the sessionModel so they are displayed in
// the JComboBox.
for (String session : sessionListModel) {
sessionModel.addElement(session);
}
// Sets the model to the combo box.
sessions.setModel(sessionModel);
}
/**
* Updates the line up list.
*
* @require likeUpListModel && lineUpModel && lineUp are not null.
* @ensure the view will be updated with the current model.
* @param lineUpListModel
* - A list of events in the festival.
*/
public void updateLineUp(ArrayList<Event> lineUpListModel) {
lineUpModel = new DefaultComboBoxModel<Event>();
// For each event in the line up, add to the line up JList.
for (Event event : lineUpListModel) {
lineUpModel.addElement(event);
}
// Sets the model to the combo box.
lineUp.setModel(lineUpModel);
}
/**
* A method which returns the day plan JList.
*
* @require dayPlan is not null.
* @ensure dayPlan will be returned.
* @return The day plan JList
*/
public JList<Event> getDayPlan() {
return dayPlan;
}
/**
* A mathod which returns the line up JComboBox.
*
* @require lineUp is not null.
* @ensure lineUp will be returned.
* @return The line up JComboBox.
*/
public JComboBox<Event> getLineUp() {
return lineUp;
}
/**
* A mathod which returns the session JComboBox.
*
* @require sessions is not null.
* @ensure sessions will be returned.
* @return The session JComboBox.
*/
public JComboBox<String> getSessions() {
return sessions;
}
/**
* A mathod which returns the add button.
*
* @require addButton is not null.
* @ensure addButton will be returned.
* @return The add JButton.
*/
public JButton getAddButton() {
return addButton;
}
/**
* A mathod which returns the remove button.
*
* @require removeButton is not null.
* @ensure removeButton will be returned.
* @return The remove JButton.
*/
public JButton getRemoveButton() {
return removeButton;
}
/**
* A method to update the view when an error is caused by user input or an
* invalid file.
*
* @require exceptionMessage is not null.
* @ensure The exception message will be displayed to the user without
* crashing the program.
*
* @param exceptionMessage
* - the exception message that is to be displayed in the view
*/
public void showErrorMessage(String exceptionMessage) {
// Creates a dialog box that contains an exception message.
JOptionPane.showMessageDialog(this, exceptionMessage, "Invalid File",
JOptionPane.WARNING_MESSAGE);
}
/**
* A method to update the view when an error is caused by user input or an
* invalid file.
*
* @require
* @ensure The exception message will be displayed to the user without
* crashing the program.
*
* @param exceptionMessage
* - the exception message that is to be displayed in the view
* @param filename
* - the file that emmitted the error
*/
public void showErrorMessage(String filename, String exceptionMessage) {
// Creates a dialog box that contains an exception message.
JOptionPane.showMessageDialog(this, exceptionMessage, filename,
JOptionPane.WARNING_MESSAGE);
}
/**
* A method to update the view when an error is caused by user input or an
* invalid file.
*
* @require message is not null and success >= 0 && success <=2.
* @ensure The exception message will be displayed to the user without
* crashing the program.
*
* @param exceptionMessage
* - the exception message that is to be displayed in the view
* @param success
* - 0 for failed user input, 1 for valid, 2 for neutral (when
* application first starts up)
*/
public void errorBoxMessage(String message, int success) {
// There was a failure in trying to add the event.
if (success == 0) {
errorDialog.getParent().setBackground(new Color(240, 128, 128));
// Adding the event was successful.
} else if (success == 1) {
errorDialog.getParent().setBackground(new Color(50, 205, 50));
// Neither a success or failure - i.e. when the application starts
// up.
} else if (success == 2) {
errorDialog.getParent().setBackground(errorDialog.getBackground());
}
errorDialogText.setText(message);
}
/**
* A method which returns the selected event in the day plan list.
*
* @require Day plan model is not null.
* @ensure That the selected event is returned.
* @return The Event selected in the dayPlan JList.
*/
public Event getSelectedDayPlanEvent() {
Event event = (Event) dayPlan.getSelectedValue();
return event;
}
/**
* A method which returns the selected event in the day plan list.
*
* @require Line up model is not null.
* @ensure That the selected event is returned.
* @return The Event selected in the lineUp JList.
*/
public Event getSelectedLineUpEvent() {
Event event = (Event) lineUp.getSelectedItem();
return event;
}
/**
* A method which returns the selected event in the day plan list.
*
* @require sessions is not null.
* @ensure That the selected event is returned.
* @return The Event selected in the lineUp JList.
*/
public String getSelectedSession() {
// The selected session.
String session = (String) sessions.getSelectedItem();
return session;
}
/**
* A method which adds an action listener to the session JList.
*
* @require (!sessions.equals(null) && !a.equals(null))
* @ensure An action listener will be added to the respective component.
* @param actionListener
* - An action listener class.
*/
public void addSessionListListener(ActionListener actionListener) {
sessions.addActionListener(actionListener);
}
/**
* A method which adds an action listener to the add JButton.
*
* @require (!add.equals(null) && !a.equals(null))
* @ensure An action listener will be added to the respective component.
* @param actionListener
* - An action listener class.
*/
public void addAddListener(ActionListener actionListener) {
addButton.addActionListener(actionListener);
}
/**
* A method which adds an action listener to the remove JButton.
*
* @require (!remove.equals(null) && !a.equals(null))
* @ensure An action listener will be added to the respective component.
* @param actionListener
* - An action listener class.
*/
public void addRemoveListener(ActionListener actionListener) {
removeButton.addActionListener(actionListener);
}
public void addSaveListener(ActionListener actionListener) {
save.addActionListener(actionListener);
}
}
|
fdfdb8651062d829a3d340ff584c1be73f2ab92a
|
[
"Java"
] | 2
|
Java
|
elliotjr/CSSE2002
|
de469762bdb02754ce33fc7640a98a9cd01bd4af
|
82bfa3c6938a8d06c28a65c3b961c42f86284d10
|
refs/heads/master
|
<file_sep><?php
$flag = "CTF{th1s_1s_gi3_13ak}";
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Version v5</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<script src="script.js"></script>
</body>
</html>
|
bd912ef3fe4e52834ab09c1f5ec8af8f191092c6
|
[
"PHP"
] | 1
|
PHP
|
toyraynei/gitleak
|
1470696ef56a03e3462f3f41e1722b7985fa4a71
|
75929ed6e7fb013bfa60efbc054bd9c8f1ace1a6
|
refs/heads/master
|
<repo_name>jeronimofagundes/rss-to-kindle<file_sep>/test.php
<?php
require('vendor/autoload.php');
$url = 'https://jeronimofagundes.github.io/feed.xml';
$feed = new ezcFeed;
$feed = ezcFeed::parse($url);
var_dump($feed->item);
<file_sep>/README.md
# rss-to-kindle
Sends RSS articles to Kindle
|
35938510c5cc741d7d3bd15e31ce6233f4c0ae99
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
jeronimofagundes/rss-to-kindle
|
99e32759f429236a227e0ff7e0b104675e63b847
|
cbaff121ef23b6aee5697c6d891b1ddc04993aa4
|
refs/heads/master
|
<file_sep># 1 for Checking Account
# 2 for Savings Account
def extract_money(account_type, amount):
print("Amount to extract "+str(amount) +
" account_type is "+str(account_type))
if(amount % 500 == 0 and amount > 0 and 0 < account_type < 3): # conditions to be checked
flag = 1
if(account_type == 1):
f = open(
"checking_account_balance.txt", "r")
chk_bal = int(f.read())
if(chk_bal > amount):
chk_bal -= amount
else:
flag = 0
f.close()
if(flag == 1):
f = open(
"checking_account_balance.txt", "w")
f.write(str(chk_bal))
f.close()
f = open(
"checking_account_transaction.txt", "a")
f.write(str("Debit "+str(amount))+"\n")
f.close()
elif(account_type == 2):
f = open(
"savings_account_balance.txt", "r")
sav_bal = int(f.read())
if(sav_bal > amount):
sav_bal -= amount
else:
flag = 0
f.close()
if(flag == 1):
f = open(
"savings_account_balance.txt", "w")
f.write(str(sav_bal))
f.close()
f = open(
"saving_account_transaction.txt", "a")
f.write("Debit "+str(amount)+"\n")
f.close()
if(flag == 1):
print("Transaction successfull")
else:
print("Not Sufficient Amount to extract")
else:
print("Not valid amount or account type to extract")
def add_money(account_type, amount):
print("Amount to add "+str(amount) +
" account_type is "+str(account_type))
if(amount % 500 == 0 and amount > 0 and 0 < account_type < 3): # conditions to be checked
if(account_type == 1):
f = open(
"checking_account_balance.txt", "r")
chk_bal = int(f.read())
chk_bal += amount
f.close()
f = open(
"checking_account_balance.txt", "w")
f.write(str(chk_bal))
f.close()
f = open(
"checking_account_transaction.txt", "a")
f.write("Credit "+str(amount)+"\n")
f.close()
if(account_type == 2):
f = open(
"savings_account_balance.txt", "r")
chk_bal = int(f.read())
chk_bal += amount
f.close()
f = open(
"savings_account_balance.txt", "w")
f.write(str(chk_bal))
f.close()
f = open(
"saving_account_transaction.txt", "a")
f.write("Credit "+str(amount)+"\n")
f.close()
print("Transaction successfull")
else:
print("Not valid amount or account type to extract")
if __name__ == '__main__':
extract_money(2, -10)
print()
extract_money(2, 20)
print()
extract_money(2, 3000)
print()
add_money(2, 40)
print()
add_money(2, 4000)
print()
extract_money(2, 12000)
print()
extract_money(1, 0)
print()
extract_money(1, 20)
print()
extract_money(1, 2000)
print()
add_money(1, 40)
print()
add_money(1, 1000)
print()
print("Saving account Transactions")
f = open(
"saving_account_transaction.txt", "r")
saving_transactions = f.read()
print(saving_transactions)
f.close()
print()
print("Saving account Final Balance")
f = open(
"savings_account_balance.txt", "r")
print(f.read())
f.close()
print()
print("Checking account Transactions")
f = open(
"checking_account_transaction.txt", "r")
checking_transactions = f.read()
print(checking_transactions)
f.close()
print()
print("Checking account Final Balance")
f = open(
"checking_account_balance.txt", "r")
print(f.read())
f.close()
|
c6826414207691d86c0a0367973b9765d4a95539
|
[
"Python"
] | 1
|
Python
|
hiren2599/ajmera_practical_round
|
9d700aa76caf5d966b5f19867f1e9fc93b35f4b9
|
f14c45eda90db3111bdf2b7524ebe46f49fd1d68
|
refs/heads/master
|
<repo_name>jtertil/pytest<file_sep>/case1/test_phonebook.py
import pytest
from phonebook import Phonebook
@pytest.fixture
def phonebook(tmpdir):
"""test"""
return Phonebook(tmpdir)
def test_lookup_by_name(phonebook):
phonebook.add("Bob", "1234")
assert "1234" == phonebook.lookup("Bob")
def test_contain_all_names(phonebook):
phonebook.add("Bob", "1234")
assert "Bob" in phonebook.get_names()
def test_missing_name_raises_error(phonebook):
with pytest.raises(KeyError):
phonebook.lookup("Missing")
<file_sep>/case1/phonebook.py
import os
class Phonebook:
def __init__(self, cache_directory):
self.entries = {}
self.filename = os.path.join(cache_directory, "phonebook.txt")
self.cache = open(self.filename, "w")
def clear(self):
self.cache.close()
os.remove(self.filename)
def add(self, name, number):
self.entries[name] = number
def lookup(self, name):
return self.entries[name]
def get_names(self):
return self.entries.keys()
def get_numbers(self):
return self.entries.values()
def is_consistent(self):
# check for duplicate entries
if len(self.entries) != len(set(self.entries.values())):
return False
# check for numbers that prefix one another
for number in self.entries.values():
for value in self.entries.values():
if value == number:
pass
elif value.startswith(number):
return False
else:
return True
|
a42a28485e0619604446df496cf8affb65337787
|
[
"Python"
] | 2
|
Python
|
jtertil/pytest
|
7f270b8d8d1dfb75998345295a9353e5d4762a64
|
4e104d868d83cd5cb4ba3f765213feedf877e098
|
refs/heads/main
|
<file_sep>package com.estudantes.repository;
import com.estudantes.entities.Estudantes;
import org.springframework.data.jpa.repository.JpaRepository;
public interface EstudantesRepository extends JpaRepository <Estudantes,Long> {
}
|
c08abdfe114eea440de3fab223f9b2eba3caa77c
|
[
"Java"
] | 1
|
Java
|
gabrielguariglia/fatec_backend_estudantes
|
0a2a2a4ddeed6e977a1f89e3e9121adb1d090e7f
|
ea14a512735cc9d6c16bc24519bebfb0e255c1a5
|
refs/heads/main
|
<repo_name>SpiriitLabs/poliris-bundle<file_sep>/Models/Annonce/Photo.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Photo
{
private Column $photo1;
private Column $photo2;
private Column $photo3;
private Column $photo4;
private Column $photo5;
private Column $photo6;
private Column $photo7;
private Column $photo8;
private Column $photo9;
private Column $photo10;
private Column $photo11;
private Column $photo12;
private Column $photo13;
private Column $photo14;
private Column $photo15;
private Column $photo16;
private Column $photo17;
private Column $photo18;
private Column $photo19;
private Column $photo20;
private Column $photo21;
private Column $photo22;
private Column $photo23;
private Column $photo24;
private Column $photo25;
private Column $photo26;
private Column $photo27;
private Column $photo28;
private Column $photo29;
private Column $photo30;
private Column $titre1;
private Column $titre2;
private Column $titre3;
private Column $titre4;
private Column $titre5;
private Column $titre6;
private Column $titre7;
private Column $titre8;
private Column $titre9;
private Column $titre10;
private Column $titre11;
private Column $titre12;
private Column $titre13;
private Column $titre14;
private Column $titre15;
private Column $titre16;
private Column $titre17;
private Column $titre18;
private Column $titre19;
private Column $titre20;
private Column $titre21;
private Column $titre22;
private Column $titre23;
private Column $titre24;
private Column $titre25;
private Column $titre26;
private Column $titre27;
private Column $titre28;
private Column $titre29;
private Column $titre30;
private Column $photoPanoramique;
private Column $urlVisiteVirtuelle;
public function __construct(
$photo1,
$photo2,
$photo3,
$photo4,
$photo5,
$photo6,
$photo7,
$photo8,
$photo9,
$photo10,
$photo11,
$photo12,
$photo13,
$photo14,
$photo15,
$photo16,
$photo17,
$photo18,
$photo19,
$photo20,
$photo21,
$photo22,
$photo23,
$photo24,
$photo25,
$photo26,
$photo27,
$photo28,
$photo29,
$photo30,
$titre1,
$titre2,
$titre3,
$titre4,
$titre5,
$titre6,
$titre7,
$titre8,
$titre9,
$titre10,
$titre11,
$titre12,
$titre13,
$titre14,
$titre15,
$titre16,
$titre17,
$titre18,
$titre19,
$titre20,
$titre21,
$titre22,
$titre23,
$titre24,
$titre25,
$titre26,
$titre27,
$titre28,
$titre29,
$titre30,
$photoPanoramique,
$urlVisiteVirtuelle
) {
$this->photo1 = new Column(85, $photo1);
$this->photo2 = new Column(86, $photo2);
$this->photo3 = new Column(87, $photo3);
$this->photo4 = new Column(88, $photo4);
$this->photo5 = new Column(89, $photo5);
$this->photo6 = new Column(90, $photo6);
$this->photo7 = new Column(91, $photo7);
$this->photo8 = new Column(92, $photo8);
$this->photo9 = new Column(93, $photo9);
$this->photo10 = new Column(164, $photo10);
$this->photo11 = new Column(165, $photo11);
$this->photo12 = new Column(166, $photo12);
$this->photo13 = new Column(167, $photo13);
$this->photo14 = new Column(168, $photo14);
$this->photo15 = new Column(169, $photo15);
$this->photo16 = new Column(170, $photo16);
$this->photo17 = new Column(171, $photo17);
$this->photo18 = new Column(172, $photo18);
$this->photo19 = new Column(173, $photo19);
$this->photo20 = new Column(174, $photo20);
$this->photo21 = new Column(264, $photo21);
$this->photo22 = new Column(265, $photo22);
$this->photo23 = new Column(266, $photo23);
$this->photo24 = new Column(267, $photo24);
$this->photo25 = new Column(268, $photo25);
$this->photo26 = new Column(269, $photo26);
$this->photo27 = new Column(270, $photo27);
$this->photo28 = new Column(271, $photo28);
$this->photo29 = new Column(272, $photo29);
$this->photo30 = new Column(273, $photo30);
$this->titre1 = new Column(94, $titre1);
$this->titre2 = new Column(95, $titre2);
$this->titre3 = new Column(96, $titre3);
$this->titre4 = new Column(97, $titre4);
$this->titre5 = new Column(98, $titre5);
$this->titre6 = new Column(99, $titre6);
$this->titre7 = new Column(100, $titre7);
$this->titre8 = new Column(101, $titre8);
$this->titre9 = new Column(102, $titre9);
$this->titre10 = new Column(274, $titre10);
$this->titre11 = new Column(275, $titre11);
$this->titre12 = new Column(276, $titre12);
$this->titre13 = new Column(277, $titre13);
$this->titre14 = new Column(278, $titre14);
$this->titre15 = new Column(279, $titre15);
$this->titre16 = new Column(280, $titre16);
$this->titre17 = new Column(281, $titre17);
$this->titre18 = new Column(282, $titre18);
$this->titre19 = new Column(283, $titre19);
$this->titre20 = new Column(284, $titre20);
$this->titre21 = new Column(285, $titre21);
$this->titre22 = new Column(286, $titre22);
$this->titre23 = new Column(287, $titre23);
$this->titre24 = new Column(288, $titre24);
$this->titre25 = new Column(289, $titre25);
$this->titre26 = new Column(290, $titre26);
$this->titre27 = new Column(291, $titre27);
$this->titre28 = new Column(292, $titre28);
$this->titre29 = new Column(293, $titre29);
$this->titre30 = new Column(294, $titre30);
$this->photoPanoramique = new Column(103, $photoPanoramique);
$this->urlVisiteVirtuelle = new Column(104, $urlVisiteVirtuelle);
}
public function getPhoto1(): Column
{
return $this->photo1;
}
public function getPhoto2(): Column
{
return $this->photo2;
}
public function getPhoto3(): Column
{
return $this->photo3;
}
public function getPhoto4(): Column
{
return $this->photo4;
}
public function getPhoto5(): Column
{
return $this->photo5;
}
public function getPhoto6(): Column
{
return $this->photo6;
}
public function getPhoto7(): Column
{
return $this->photo7;
}
public function getPhoto8(): Column
{
return $this->photo8;
}
public function getPhoto9(): Column
{
return $this->photo9;
}
public function getPhoto10(): Column
{
return $this->photo10;
}
public function getPhoto11(): Column
{
return $this->photo11;
}
public function getPhoto12(): Column
{
return $this->photo12;
}
public function getPhoto13(): Column
{
return $this->photo13;
}
public function getPhoto14(): Column
{
return $this->photo14;
}
public function getPhoto15(): Column
{
return $this->photo15;
}
public function getPhoto16(): Column
{
return $this->photo16;
}
public function getPhoto17(): Column
{
return $this->photo17;
}
public function getPhoto18(): Column
{
return $this->photo18;
}
public function getPhoto19(): Column
{
return $this->photo19;
}
public function getPhoto20(): Column
{
return $this->photo20;
}
public function getPhoto21(): Column
{
return $this->photo21;
}
public function getPhoto22(): Column
{
return $this->photo22;
}
public function getPhoto23(): Column
{
return $this->photo23;
}
public function getPhoto24(): Column
{
return $this->photo24;
}
public function getPhoto25(): Column
{
return $this->photo25;
}
public function getPhoto26(): Column
{
return $this->photo26;
}
public function getPhoto27(): Column
{
return $this->photo27;
}
public function getPhoto28(): Column
{
return $this->photo28;
}
public function getPhoto29(): Column
{
return $this->photo29;
}
public function getPhoto30(): Column
{
return $this->photo30;
}
public function getTitre1(): Column
{
return $this->titre1;
}
public function getTitre2(): Column
{
return $this->titre2;
}
public function getTitre3(): Column
{
return $this->titre3;
}
public function getTitre4(): Column
{
return $this->titre4;
}
public function getTitre5(): Column
{
return $this->titre5;
}
public function getTitre6(): Column
{
return $this->titre6;
}
public function getTitre7(): Column
{
return $this->titre7;
}
public function getTitre8(): Column
{
return $this->titre8;
}
public function getTitre9(): Column
{
return $this->titre9;
}
public function getTitre10(): Column
{
return $this->titre10;
}
public function getTitre11(): Column
{
return $this->titre11;
}
public function getTitre12(): Column
{
return $this->titre12;
}
public function getTitre13(): Column
{
return $this->titre13;
}
public function getTitre14(): Column
{
return $this->titre14;
}
public function getTitre15(): Column
{
return $this->titre15;
}
public function getTitre16(): Column
{
return $this->titre16;
}
public function getTitre17(): Column
{
return $this->titre17;
}
public function getTitre18(): Column
{
return $this->titre18;
}
public function getTitre19(): Column
{
return $this->titre19;
}
public function getTitre20(): Column
{
return $this->titre20;
}
public function getTitre21(): Column
{
return $this->titre21;
}
public function getTitre22(): Column
{
return $this->titre22;
}
public function getTitre23(): Column
{
return $this->titre23;
}
public function getTitre24(): Column
{
return $this->titre24;
}
public function getTitre25(): Column
{
return $this->titre25;
}
public function getTitre26(): Column
{
return $this->titre26;
}
public function getTitre27(): Column
{
return $this->titre27;
}
public function getTitre28(): Column
{
return $this->titre28;
}
public function getTitre29(): Column
{
return $this->titre29;
}
public function getTitre30(): Column
{
return $this->titre30;
}
public function getPhotoPanoramique(): Column
{
return $this->photoPanoramique;
}
public function getUrlVisiteVirtuelle(): Column
{
return $this->urlVisiteVirtuelle;
}
public function toArray(): array
{
return [
$this->getPhoto1(),
$this->getPhoto2(),
$this->getPhoto3(),
$this->getPhoto4(),
$this->getPhoto5(),
$this->getPhoto6(),
$this->getPhoto7(),
$this->getPhoto8(),
$this->getPhoto9(),
$this->getPhoto10(),
$this->getPhoto11(),
$this->getPhoto12(),
$this->getPhoto13(),
$this->getPhoto14(),
$this->getPhoto15(),
$this->getPhoto16(),
$this->getPhoto17(),
$this->getPhoto18(),
$this->getPhoto19(),
$this->getPhoto20(),
$this->getPhoto21(),
$this->getPhoto22(),
$this->getPhoto23(),
$this->getPhoto24(),
$this->getPhoto25(),
$this->getPhoto26(),
$this->getPhoto27(),
$this->getPhoto28(),
$this->getPhoto29(),
$this->getPhoto30(),
$this->getTitre1(),
$this->getTitre2(),
$this->getTitre3(),
$this->getTitre4(),
$this->getTitre5(),
$this->getTitre6(),
$this->getTitre7(),
$this->getTitre8(),
$this->getTitre9(),
$this->getTitre10(),
$this->getTitre11(),
$this->getTitre12(),
$this->getTitre13(),
$this->getTitre14(),
$this->getTitre15(),
$this->getTitre16(),
$this->getTitre17(),
$this->getTitre18(),
$this->getTitre19(),
$this->getTitre20(),
$this->getTitre21(),
$this->getTitre22(),
$this->getTitre23(),
$this->getTitre24(),
$this->getTitre25(),
$this->getTitre26(),
$this->getTitre27(),
$this->getTitre28(),
$this->getTitre29(),
$this->getTitre30(),
$this->getPhotoPanoramique(),
$this->getUrlVisiteVirtuelle(),
];
}
}
<file_sep>/Models/Column.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models;
class Column
{
private int $pos;
private $val;
public function __construct(int $pos, $val)
{
$this->pos = $pos;
$this->val = $val;
}
public function getPos(): int
{
return $this->pos;
}
public function getVal()
{
return $this->val;
}
public function getTransformedVal()
{
switch (\gettype($this->getVal())) {
case 'boolean':
return $this->getVal() ? 'OUI' : 'NON';
case 'string':
$replacedQuotes = str_replace('"', "'", $this->getVal());
$replacedQuotes = str_replace(\PHP_EOL, ' ', $replacedQuotes);
return trim(preg_replace('/\s+/', ' ', $replacedQuotes));
case 'object':
if (($date = $this->getVal()) instanceof \DateTimeInterface) {
/* @var \DateTimeInterface $date */
return $date->format('d/m/Y');
}
return $this->getVal();
default:
return $this->getVal();
}
}
public function toArray(): array
{
return [
'pos' => $this->getPos(),
'val' => $this->getTransformedVal(),
];
}
}
<file_sep>/tests/Models/Annonce/TerrainTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Terrain;
class TerrainTest extends TestCase
{
/**
* @test
*/
public function it_must_create_terrain()
{
$terrain = new Terrain(
true,
true,
true,
true,
100,
true,
true
);
self::assertTrue($terrain->getAgricole()->getVal());
self::assertTrue($terrain->getConstructible()->getVal());
self::assertTrue($terrain->getPente()->getVal());
self::assertTrue($terrain->getPlanEau()->getVal());
self::assertTrue($terrain->getDonneSurLaRue()->getVal());
self::assertTrue($terrain->getViabilise()->getVal());
self::assertEquals(100, $terrain->getLongueurFacade()->getVal());
$expectedArray = [
$terrain->getAgricole(),
$terrain->getConstructible(),
$terrain->getPente(),
$terrain->getPlanEau(),
$terrain->getLongueurFacade(),
$terrain->getDonneSurLaRue(),
$terrain->getViabilise(),
];
self::assertEquals($expectedArray, $terrain->toArray());
}
}
<file_sep>/tests/Models/Annonce/ViagerTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Viager;
class ViagerTest extends TestCase
{
/**
* @test
*/
public function it_must_create_viager()
{
$viager = new Viager(
$prixBouquet = 2000,
$renteMensuelle = 500,
$ageHomme = 50,
$ageFemme = 52,
$venduLibre = true,
);
self::assertEquals($prixBouquet, $viager->getPrixBouquet()->getVal());
self::assertEquals($renteMensuelle, $viager->getRenteMensuelle()->getVal());
self::assertEquals($ageHomme, $viager->getAgeHomme()->getVal());
self::assertEquals($ageFemme, $viager->getAgeFemme()->getVal());
self::assertEquals($venduLibre, $viager->getVenduLibre()->getVal());
$expectedArray = [
$viager->getPrixBouquet(),
$viager->getRenteMensuelle(),
$viager->getAgeHomme(),
$viager->getAgeFemme(),
$viager->getVenduLibre(),
];
self::assertEquals($expectedArray, $viager->toArray());
}
}
<file_sep>/tests/Models/Annonce/PhotoTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Photo;
class PhotoTest extends TestCase
{
/**
* @test
*/
public function it_must_create_photo()
{
$photo = new Photo(
'photo1.jpeg',
'photo2.jpeg',
'photo3.jpeg',
'photo4.jpeg',
'photo5.jpeg',
'photo6.jpeg',
'photo7.jpeg',
'photo8.jpeg',
'photo9.jpeg',
'photo10.jpeg',
'photo11.jpeg',
'photo12.jpeg',
'photo13.jpeg',
'photo14.jpeg',
'photo15.jpeg',
'photo16.jpeg',
'photo17.jpeg',
'photo18.jpeg',
'photo19.jpeg',
'photo20.jpeg',
'photo21.jpeg',
'photo22.jpeg',
'photo23.jpeg',
'photo24.jpeg',
'photo25.jpeg',
'photo26.jpeg',
'photo27.jpeg',
'photo28.jpeg',
'photo29.jpeg',
'photo30.jpeg',
'Titre 1',
'Titre 2',
'Titre 3',
'Titre 4',
'Titre 5',
'Titre 6',
'Titre 7',
'Titre 8',
'Titre 9',
'Titre 10',
'Titre 11',
'Titre 12',
'Titre 13',
'Titre 14',
'Titre 15',
'Titre 16',
'Titre 17',
'Titre 18',
'Titre 19',
'Titre 20',
'Titre 21',
'Titre 22',
'Titre 23',
'Titre 24',
'Titre 25',
'Titre 26',
'Titre 27',
'Titre 28',
'Titre 29',
'Titre 30',
'panorama',
'visite'
);
self::assertEquals('photo1.jpeg', $photo->getPhoto1()->getVal());
self::assertEquals('photo2.jpeg', $photo->getPhoto2()->getVal());
self::assertEquals('photo3.jpeg', $photo->getPhoto3()->getVal());
self::assertEquals('photo4.jpeg', $photo->getPhoto4()->getVal());
self::assertEquals('photo5.jpeg', $photo->getPhoto5()->getVal());
self::assertEquals('photo6.jpeg', $photo->getPhoto6()->getVal());
self::assertEquals('photo7.jpeg', $photo->getPhoto7()->getVal());
self::assertEquals('photo8.jpeg', $photo->getPhoto8()->getVal());
self::assertEquals('photo9.jpeg', $photo->getPhoto9()->getVal());
self::assertEquals('photo10.jpeg', $photo->getPhoto10()->getVal());
self::assertEquals('photo11.jpeg', $photo->getPhoto11()->getVal());
self::assertEquals('photo12.jpeg', $photo->getPhoto12()->getVal());
self::assertEquals('photo13.jpeg', $photo->getPhoto13()->getVal());
self::assertEquals('photo14.jpeg', $photo->getPhoto14()->getVal());
self::assertEquals('photo15.jpeg', $photo->getPhoto15()->getVal());
self::assertEquals('photo16.jpeg', $photo->getPhoto16()->getVal());
self::assertEquals('photo17.jpeg', $photo->getPhoto17()->getVal());
self::assertEquals('photo18.jpeg', $photo->getPhoto18()->getVal());
self::assertEquals('photo19.jpeg', $photo->getPhoto19()->getVal());
self::assertEquals('photo20.jpeg', $photo->getPhoto20()->getVal());
self::assertEquals('photo21.jpeg', $photo->getPhoto21()->getVal());
self::assertEquals('photo22.jpeg', $photo->getPhoto22()->getVal());
self::assertEquals('photo23.jpeg', $photo->getPhoto23()->getVal());
self::assertEquals('photo24.jpeg', $photo->getPhoto24()->getVal());
self::assertEquals('photo25.jpeg', $photo->getPhoto25()->getVal());
self::assertEquals('photo26.jpeg', $photo->getPhoto26()->getVal());
self::assertEquals('photo27.jpeg', $photo->getPhoto27()->getVal());
self::assertEquals('photo28.jpeg', $photo->getPhoto28()->getVal());
self::assertEquals('photo29.jpeg', $photo->getPhoto29()->getVal());
self::assertEquals('photo30.jpeg', $photo->getPhoto30()->getVal());
self::assertEquals('Titre 1', $photo->getTitre1()->getVal());
self::assertEquals('Titre 2', $photo->getTitre2()->getVal());
self::assertEquals('Titre 3', $photo->getTitre3()->getVal());
self::assertEquals('Titre 4', $photo->getTitre4()->getVal());
self::assertEquals('Titre 5', $photo->getTitre5()->getVal());
self::assertEquals('Titre 6', $photo->getTitre6()->getVal());
self::assertEquals('Titre 7', $photo->getTitre7()->getVal());
self::assertEquals('Titre 8', $photo->getTitre8()->getVal());
self::assertEquals('Titre 9', $photo->getTitre9()->getVal());
self::assertEquals('Titre 10', $photo->getTitre10()->getVal());
self::assertEquals('Titre 11', $photo->getTitre11()->getVal());
self::assertEquals('Titre 12', $photo->getTitre12()->getVal());
self::assertEquals('Titre 13', $photo->getTitre13()->getVal());
self::assertEquals('Titre 14', $photo->getTitre14()->getVal());
self::assertEquals('Titre 15', $photo->getTitre15()->getVal());
self::assertEquals('Titre 16', $photo->getTitre16()->getVal());
self::assertEquals('Titre 17', $photo->getTitre17()->getVal());
self::assertEquals('Titre 18', $photo->getTitre18()->getVal());
self::assertEquals('Titre 19', $photo->getTitre19()->getVal());
self::assertEquals('Titre 20', $photo->getTitre20()->getVal());
self::assertEquals('Titre 21', $photo->getTitre21()->getVal());
self::assertEquals('Titre 22', $photo->getTitre22()->getVal());
self::assertEquals('Titre 23', $photo->getTitre23()->getVal());
self::assertEquals('Titre 24', $photo->getTitre24()->getVal());
self::assertEquals('Titre 25', $photo->getTitre25()->getVal());
self::assertEquals('Titre 26', $photo->getTitre26()->getVal());
self::assertEquals('Titre 27', $photo->getTitre27()->getVal());
self::assertEquals('Titre 28', $photo->getTitre28()->getVal());
self::assertEquals('Titre 29', $photo->getTitre29()->getVal());
self::assertEquals('Titre 30', $photo->getTitre30()->getVal());
self::assertEquals('panorama', $photo->getPhotoPanoramique()->getVal());
self::assertEquals('visite', $photo->getUrlVisiteVirtuelle()->getVal());
$expectedArray = [
$photo->getPhoto1(),
$photo->getPhoto2(),
$photo->getPhoto3(),
$photo->getPhoto4(),
$photo->getPhoto5(),
$photo->getPhoto6(),
$photo->getPhoto7(),
$photo->getPhoto8(),
$photo->getPhoto9(),
$photo->getPhoto10(),
$photo->getPhoto11(),
$photo->getPhoto12(),
$photo->getPhoto13(),
$photo->getPhoto14(),
$photo->getPhoto15(),
$photo->getPhoto16(),
$photo->getPhoto17(),
$photo->getPhoto18(),
$photo->getPhoto19(),
$photo->getPhoto20(),
$photo->getPhoto21(),
$photo->getPhoto22(),
$photo->getPhoto23(),
$photo->getPhoto24(),
$photo->getPhoto25(),
$photo->getPhoto26(),
$photo->getPhoto27(),
$photo->getPhoto28(),
$photo->getPhoto29(),
$photo->getPhoto30(),
$photo->getTitre1(),
$photo->getTitre2(),
$photo->getTitre3(),
$photo->getTitre4(),
$photo->getTitre5(),
$photo->getTitre6(),
$photo->getTitre7(),
$photo->getTitre8(),
$photo->getTitre9(),
$photo->getTitre10(),
$photo->getTitre11(),
$photo->getTitre12(),
$photo->getTitre13(),
$photo->getTitre14(),
$photo->getTitre15(),
$photo->getTitre16(),
$photo->getTitre17(),
$photo->getTitre18(),
$photo->getTitre19(),
$photo->getTitre20(),
$photo->getTitre21(),
$photo->getTitre22(),
$photo->getTitre23(),
$photo->getTitre24(),
$photo->getTitre25(),
$photo->getTitre26(),
$photo->getTitre27(),
$photo->getTitre28(),
$photo->getTitre29(),
$photo->getTitre30(),
$photo->getPhotoPanoramique(),
$photo->getUrlVisiteVirtuelle(),
];
self::assertEquals($expectedArray, $photo->toArray());
}
}
<file_sep>/Builders/AnnonceExportBuilder.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Builders;
use Spiriit\PolirisBundle\Models\AnnonceExport;
class AnnonceExportBuilder
{
private array $lines = [];
public function startLine(): AnnonceBuilder
{
$builder = new AnnonceBuilder();
$this->lines[] = $builder;
return $builder;
}
public function build(): AnnonceExport
{
$annonce = new AnnonceExport();
/** @var AnnonceBuilder $line */
foreach ($this->lines as $line) {
$annonce->addLine($line->build());
}
return $annonce;
}
public function getLines(): array
{
return $this->lines;
}
}
<file_sep>/Models/Annonce/Exterieur.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Exterieur
{
private Column $ascenseur;
private Column $calme;
private Column $piscine;
private Column $vueDegagee;
private Column $entree;
private Column $visAVis;
private Column $monteCharge;
public function __construct(
$ascenseur,
$calme,
$piscine,
$vueDegagee,
$entree,
$visAVis,
$monteCharge
) {
$this->ascenseur = new Column(41, $ascenseur);
$this->calme = new Column(63, $calme);
$this->piscine = new Column(65, $piscine);
$this->vueDegagee = new Column(78, $vueDegagee);
$this->entree = new Column(189, $entree);
$this->visAVis = new Column(192, $visAVis);
$this->monteCharge = new Column(197, $monteCharge);
}
public function getAscenseur(): Column
{
return $this->ascenseur;
}
public function getCalme(): Column
{
return $this->calme;
}
public function getPiscine(): Column
{
return $this->piscine;
}
public function getVueDegagee(): Column
{
return $this->vueDegagee;
}
public function getEntree(): Column
{
return $this->entree;
}
public function getVisAVis(): Column
{
return $this->visAVis;
}
public function getMonteCharge(): Column
{
return $this->monteCharge;
}
public function toArray(): array
{
return [
$this->getAscenseur(),
$this->getCalme(),
$this->getPiscine(),
$this->getVueDegagee(),
$this->getEntree(),
$this->getVisAVis(),
$this->getMonteCharge(),
];
}
}
<file_sep>/Models/Annonce/Localisation.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Localisation
{
private Column $cp;
private Column $ville;
private Column $pays;
private Column $adresse;
private Column $quartierProximite;
private Column $situation;
private Column $procheLac;
private Column $procheTennis;
private Column $procheSki;
private Column $cpReel;
private Column $villeReelle;
private Column $idQuartier;
private Column $transportLigne;
private Column $transportStation;
private Column $latitude;
private Column $longitude;
private Column $precisionGps;
private Column $localisation;
public function __construct(
$cp,
$ville,
$pays,
$adresse,
$quartierProximite,
$situation,
$procheLac,
$procheTennis,
$procheSki,
$cpReel,
$villeReelle,
$idQuartier,
$transportLigne,
$transportStation,
$latitude,
$longitude,
$precisionGps,
$localisation
) {
$this->cp = new Column(5, $cp);
$this->ville = new Column(6, $ville);
$this->pays = new Column(7, $pays);
$this->adresse = new Column(8, $adresse);
$this->quartierProximite = new Column(9, $quartierProximite);
$this->situation = new Column(57, $situation);
$this->procheLac = new Column(75, $procheLac);
$this->procheTennis = new Column(76, $procheTennis);
$this->procheSki = new Column(77, $procheSki);
$this->cpReel = new Column(108, $cpReel);
$this->villeReelle = new Column(109, $villeReelle);
$this->idQuartier = new Column(180, $idQuartier);
$this->transportLigne = new Column(193, $transportLigne);
$this->transportStation = new Column(194, $transportStation);
$this->latitude = new Column(298, $latitude);
$this->longitude = new Column(299, $longitude);
$this->precisionGps = new Column(300, $precisionGps);
$this->localisation = new Column(322, $localisation);
}
public function getCp(): Column
{
return $this->cp;
}
public function getVille(): Column
{
return $this->ville;
}
public function getPays(): Column
{
return $this->pays;
}
public function getAdresse(): Column
{
return $this->adresse;
}
public function getQuartierProximite(): Column
{
return $this->quartierProximite;
}
public function getSituation(): Column
{
return $this->situation;
}
public function getProcheLac(): Column
{
return $this->procheLac;
}
public function getProcheTennis(): Column
{
return $this->procheTennis;
}
public function getProcheSki(): Column
{
return $this->procheSki;
}
public function getCpReel(): Column
{
return $this->cpReel;
}
public function getVilleReelle(): Column
{
return $this->villeReelle;
}
public function getIdQuartier(): Column
{
return $this->idQuartier;
}
public function getTransportLigne(): Column
{
return $this->transportLigne;
}
public function getTransportStation(): Column
{
return $this->transportStation;
}
public function getLatitude(): Column
{
return $this->latitude;
}
public function getLongitude(): Column
{
return $this->longitude;
}
public function getPrecisionGps(): Column
{
return $this->precisionGps;
}
public function getLocalisation(): Column
{
return $this->localisation;
}
public function toArray()
{
return [
$this->getCp(),
$this->getVille(),
$this->getPays(),
$this->getAdresse(),
$this->getQuartierProximite(),
$this->getSituation(),
$this->getProcheLac(),
$this->getProcheTennis(),
$this->getProcheSki(),
$this->getCpReel(),
$this->getVilleReelle(),
$this->getIdQuartier(),
$this->getTransportLigne(),
$this->getTransportStation(),
$this->getLatitude(),
$this->getLongitude(),
$this->getPrecisionGps(),
$this->getLocalisation(),
];
}
}
<file_sep>/tests/Models/Annonce/ProduitInvestissementTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\ProduitInvestissement;
class ProduitInvestissementTest extends TestCase
{
/**
* @test
*/
public function it_must_create_produit_investissement()
{
$produitInvestissement = new ProduitInvestissement(
$valeurAchat = 1,
$montantRapport = 2,
);
self::assertEquals($valeurAchat, $produitInvestissement->getValeurAchat()->getVal());
self::assertEquals($montantRapport, $produitInvestissement->getMontantRapport()->getVal());
$expectedArray = [
$produitInvestissement->getValeurAchat(),
$produitInvestissement->getMontantRapport(),
];
self::assertEquals($expectedArray, $produitInvestissement->toArray());
}
}
<file_sep>/tests/Builders/AnnonceBuilderTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Builders;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Builders\AnnonceBuilder;
use Spiriit\PolirisBundle\Models\Annonce\Annonce;
class AnnonceBuilderTest extends TestCase
{
/**
* @test
*/
public function it_must_build_annonce_line()
{
$annonceLineBuilder = new AnnonceBuilder();
$annonceLine = $annonceLineBuilder
->withIdentifiant('test', 'test', 'test', 'test')
->withType('test', 'test')
->build();
$this->assertInstanceOf(Annonce::class, $annonceLine);
}
}
<file_sep>/tests/Functional/Bundle/DependencyInjection/BundleExtension.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Functional\Bundle\DependencyInjection;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
use Symfony\Component\HttpKernel\Kernel;
class BundleExtension extends Extension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function load(array $configs, ContainerBuilder $container): void
{
}
/**
* {@inheritdoc}
*/
public function prepend(ContainerBuilder $container): void
{
// Annotation must be disabled since this bundle doesn't use Doctrine
// The framework allows enabling/disabling them only since symfony 3.2 where
// doctrine/annotations has been removed from required dependencies
$annotationsEnabled = (int) Kernel::MAJOR_VERSION >= 3 && (int) Kernel::MINOR_VERSION >= 2;
if (!$annotationsEnabled) {
return;
}
$container->prependExtensionConfig('framework', ['annotations' => ['enabled' => false]]);
}
}
<file_sep>/Models/Annonce/Prix.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Prix
{
private Column $prix;
private Column $loyerMoisMur;
private Column $loyerCC;
private Column $loyerHT;
private Column $depotGarantie;
private Column $prixMasque;
private Column $prixHT;
private Column $copropriete;
private Column $nbLots;
private Column $syndicatCopro;
private Column $syndicatCoproDetails;
private Column $prixTerrain;
private Column $prixModeleMaison;
private Column $prixMin;
private Column $prixMax;
public function __construct(
$prix,
$loyerMoisMur,
$loyerCC,
$loyerHT,
$depotGarantie,
$prixMasque,
$prixHT,
$copropriete,
$nbLots,
$syndicatCopro,
$syndicatCoproDetails,
$prixTerrain,
$prixModeleMaison,
$prixMin,
$prixMax
) {
$this->prix = new Column(11, $prix);
$this->loyerMoisMur = new Column(12, $loyerMoisMur);
$this->loyerCC = new Column(13, $loyerCC);
$this->loyerHT = new Column(14, $loyerHT);
$this->depotGarantie = new Column(161, $depotGarantie);
$this->prixMasque = new Column(201, $prixMasque);
$this->prixHT = new Column(245, $prixHT);
$this->copropriete = new Column(258, $copropriete);
$this->nbLots = new Column(259, $nbLots);
$this->syndicatCopro = new Column(261, $syndicatCopro);
$this->syndicatCoproDetails = new Column(262, $syndicatCoproDetails);
$this->prixTerrain = new Column(295, $prixTerrain);
$this->prixModeleMaison = new Column(296, $prixModeleMaison);
$this->prixMin = new Column(308, $prixMin);
$this->prixMax = new Column(309, $prixMax);
}
public function getPrix(): Column
{
return $this->prix;
}
public function getLoyerMoisMur(): Column
{
return $this->loyerMoisMur;
}
public function getLoyerCC(): Column
{
return $this->loyerCC;
}
public function getLoyerHT(): Column
{
return $this->loyerHT;
}
public function getDepotGarantie(): Column
{
return $this->depotGarantie;
}
public function getPrixMasque(): Column
{
return $this->prixMasque;
}
public function getPrixHT(): Column
{
return $this->prixHT;
}
public function getCopropriete(): Column
{
return $this->copropriete;
}
public function getNbLots(): Column
{
return $this->nbLots;
}
public function getSyndicatCopro(): Column
{
return $this->syndicatCopro;
}
public function getSyndicatCoproDetails(): Column
{
return $this->syndicatCoproDetails;
}
public function getPrixTerrain(): Column
{
return $this->prixTerrain;
}
public function getPrixModeleMaison(): Column
{
return $this->prixModeleMaison;
}
public function getPrixMin(): Column
{
return $this->prixMin;
}
public function getPrixMax(): Column
{
return $this->prixMax;
}
public function toArray(): array
{
return [
$this->getPrix(),
$this->getLoyerMoisMur(),
$this->getLoyerCC(),
$this->getLoyerHT(),
$this->getDepotGarantie(),
$this->getPrixMasque(),
$this->getPrixHT(),
$this->getCopropriete(),
$this->getNbLots(),
$this->getSyndicatCopro(),
$this->getSyndicatCoproDetails(),
$this->getPrixTerrain(),
$this->getPrixModeleMaison(),
$this->getPrixMin(),
$this->getPrixMax(),
];
}
}
<file_sep>/ecs.php
<?php
declare(strict_types=1);
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
use PhpCsFixer\Fixer\ArrayNotation\ArraySyntaxFixer;
use PhpCsFixer\Fixer\Comment\HeaderCommentFixer;
use PhpCsFixer\Fixer\Import\OrderedImportsFixer;
use PhpCsFixer\Fixer\Phpdoc\PhpdocScalarFixer;
use Symplify\EasyCodingStandard\Config\ECSConfig;
use Symplify\EasyCodingStandard\ValueObject\Set\SetList;
return static function (ECSConfig $config): void {
$header = <<<EOF
This file is part of the composer-write-changelogs project.
(c) <NAME> <<EMAIL>>
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
EOF;
$config->sets([SetList::PSR_12, ]);
$config->rule(OrderedImportsFixer::class);
$config->ruleWithConfiguration(ArraySyntaxFixer::class, [
'syntax' => 'short',
]);
$config->ruleWithConfiguration(HeaderCommentFixer::class, [
'header' => $header
]);
$config->services()->remove(PhpdocScalarFixer::class);
$config->parallel();
$config->paths([__DIR__]);
$config->skip([
__DIR__ . '/.github',
__DIR__ . '/vendor',
]);
};
<file_sep>/Models/Annonce/Publication.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Publication
{
private Column $publications;
private Column $coupDeCoeur;
private Column $versionFormat;
public function __construct(
$publications,
$coupDeCoeur,
$versionFormat
) {
$this->publications = new Column(82, $publications);
$this->coupDeCoeur = new Column(84, $coupDeCoeur);
$this->versionFormat = new Column(301, $versionFormat);
}
public function getPublications(): Column
{
return $this->publications;
}
public function getCoupDeCoeur(): Column
{
return $this->coupDeCoeur;
}
public function getVersionFormat(): Column
{
return $this->versionFormat;
}
public function toArray(): array
{
return [
$this->getPublications(),
$this->getCoupDeCoeur(),
$this->getVersionFormat(),
];
}
}
<file_sep>/tests/Models/Annonce/ExterieurTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Exterieur;
class ExterieurTest extends TestCase
{
/**
* @test
*/
public function it_must_create_exterieur()
{
$exterieur = new Exterieur(
$ascenseur = true,
$calme = false,
$piscine = true,
$vueDegagee = false,
$entree = true,
$visAVis = false,
$monteCharge = true
);
self::assertEquals($ascenseur, $exterieur->getAscenseur()->getVal());
self::assertEquals($calme, $exterieur->getCalme()->getVal());
self::assertEquals($piscine, $exterieur->getPiscine()->getVal());
self::assertEquals($vueDegagee, $exterieur->getVueDegagee()->getVal());
self::assertEquals($entree, $exterieur->getEntree()->getVal());
self::assertEquals($visAVis, $exterieur->getVisAVis()->getVal());
self::assertEquals($monteCharge, $exterieur->getMonteCharge()->getVal());
$expectedArray = [
$exterieur->getAscenseur(),
$exterieur->getCalme(),
$exterieur->getPiscine(),
$exterieur->getVueDegagee(),
$exterieur->getEntree(),
$exterieur->getVisAVis(),
$exterieur->getMonteCharge(),
];
self::assertEquals($expectedArray, $exterieur->toArray());
}
}
<file_sep>/Models/AnnonceExport.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models;
use Spiriit\PolirisBundle\Models\Annonce\Annonce;
class AnnonceExport implements ExportInterface
{
private array $annonces = [];
public function getAnnonces(): array
{
return $this->annonces;
}
public function addLine(Annonce $annonce): void
{
$this->annonces[] = $annonce;
}
public function removeLine(int $line): void
{
$key = $line - 1;
if (\array_key_exists($key, $this->annonces)) {
unset($this->annonces[$key]);
}
}
public function removeLines(array $lines): void
{
/** @var int $line */
foreach ($lines as $line) {
$this->removeLine($line);
}
}
public function toArray(): array
{
return array_map(fn (Annonce $annonce) => $annonce->toArray(), $this->annonces);
}
}
<file_sep>/tests/Models/Annonce/AnnonceTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Annonce;
use Spiriit\PolirisBundle\Models\Annonce\Boutique;
use Spiriit\PolirisBundle\Models\Annonce\Bureau;
use Spiriit\PolirisBundle\Models\Annonce\ChampCustom;
use Spiriit\PolirisBundle\Models\Annonce\ChauffageClim;
use Spiriit\PolirisBundle\Models\Annonce\Contact;
use Spiriit\PolirisBundle\Models\Annonce\Detail;
use Spiriit\PolirisBundle\Models\Annonce\Diagnostic;
use Spiriit\PolirisBundle\Models\Annonce\Etage;
use Spiriit\PolirisBundle\Models\Annonce\Exterieur;
use Spiriit\PolirisBundle\Models\Annonce\FondsCommerce;
use Spiriit\PolirisBundle\Models\Annonce\Garage;
use Spiriit\PolirisBundle\Models\Annonce\HonoraireCharge;
use Spiriit\PolirisBundle\Models\Annonce\Identifiant;
use Spiriit\PolirisBundle\Models\Annonce\Interieur;
use Spiriit\PolirisBundle\Models\Annonce\Langue;
use Spiriit\PolirisBundle\Models\Annonce\Localisation;
use Spiriit\PolirisBundle\Models\Annonce\Location;
use Spiriit\PolirisBundle\Models\Annonce\LocationVacances;
use Spiriit\PolirisBundle\Models\Annonce\Mandat;
use Spiriit\PolirisBundle\Models\Annonce\Parking;
use Spiriit\PolirisBundle\Models\Annonce\PartieJour;
use Spiriit\PolirisBundle\Models\Annonce\Photo;
use Spiriit\PolirisBundle\Models\Annonce\Prix;
use Spiriit\PolirisBundle\Models\Annonce\ProduitInvestissement;
use Spiriit\PolirisBundle\Models\Annonce\Publication;
use Spiriit\PolirisBundle\Models\Annonce\Securite;
use Spiriit\PolirisBundle\Models\Annonce\Surface;
use Spiriit\PolirisBundle\Models\Annonce\Terrain;
use Spiriit\PolirisBundle\Models\Annonce\Type;
use Spiriit\PolirisBundle\Models\Annonce\Viager;
class AnnonceTest extends TestCase
{
/**
* @test
*/
public function it_must_create_annonce()
{
$annonce = new Annonce();
$identifiant = new Identifiant('id', 'ref', 'type annonce', 'annonce id technique');
$annonce->setIdentifiant($identifiant);
$type = new Type('type', 'sous type');
$annonce->setType($type);
$photo = new Photo(
'photo 1',
'photo 2',
'photo 3',
'photo 4',
'photo 5',
'photo 6',
'photo 7',
'photo 8',
'photo 9',
'photo 10',
'photo 11',
'photo 12',
'photo 13',
'photo 14',
'photo 15',
'photo 16',
'photo 17',
'photo 18',
'photo 19',
'photo 20',
'photo 21',
'photo 22',
'photo 23',
'photo 24',
'photo 25',
'photo 26',
'photo 27',
'photo 28',
'photo 29',
'photo 30',
'titre 1',
'titre 2',
'titre 3',
'titre 4',
'titre 5',
'titre 6',
'titre 7',
'titre 8',
'titre 9',
'titre 10',
'titre 11',
'titre 12',
'titre 13',
'titre 14',
'titre 15',
'titre 16',
'titre 17',
'titre 18',
'titre 19',
'titre 20',
'titre 21',
'titre 22',
'titre 23',
'titre 24',
'titre 25',
'titre 26',
'titre 27',
'titre 28',
'titre 29',
'titre 30',
'panorama',
'visite'
);
$annonce->setPhoto($photo);
$champCustom = new ChampCustom(
'champ 1',
'champ 2',
'champ 3',
'champ 4',
'champ 5',
'champ 6',
'champ 7',
'champ 8',
'champ 9',
'champ 10',
'champ 11',
'champ 12',
'champ 13',
'champ 14',
'champ 15',
'champ 16',
'champ 17',
'champ 18',
'champ 19',
'champ 20',
'champ 21',
'champ 22',
'champ 23',
'champ 24',
'champ 25',
'champ 26',
);
$annonce->setChampCustom($champCustom);
$langue = new Langue(
'code',
'code',
'code',
'prox',
'prox',
'prox',
'label',
'label',
'label',
'desc',
'desc',
'desc',
);
$annonce->setLangue($langue);
$mandat = new Mandat(
true,
'01',
new \DateTimeImmutable(),
'nom',
'prenom',
'raison',
'adresse',
'34000',
'Montpellier',
'0123456789',
'commentaire'
);
$annonce->setMandat($mandat);
$locationVacances = new LocationVacances(
'periodes dispo',
'periodes bs',
'prix semaine bs',
'prix quinzaine bs',
'prix mois bs',
'periodes hs',
'prix semaine hs',
'prix quinzaine hs',
'prix mois hs',
1,
true,
'type'
);
$annonce->setLocationVacances($locationVacances);
$viager = new Viager(
2000,
500,
50,
52,
true,
);
$annonce->setViager($viager);
$terrain = new Terrain(
true,
true,
true,
true,
100,
true,
true
);
$annonce->setTerrain($terrain);
$bureau = new Bureau(
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
true,
11,
12,
'conditions',
'prestations',
true,
13
);
$annonce->setBureau($bureau);
$diagnostic = new Diagnostic(
true,
false,
1,
'D',
3,
'E',
new \DateTimeImmutable(),
'1',
0,
10,
'2021',
null
);
$annonce->setDiagnostic($diagnostic);
$parking = new Parking(1, true, false);
$annonce->setParking($parking);
$boutique = new Boutique(true, 'situation');
$annonce->setBoutique($boutique);
$prix = new Prix(
1,
2,
3,
4,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
);
$annonce->setPrix($prix);
$location = new Location(
1,
2,
3,
'location meublée',
4,
null,
null,
null
);
$annonce->setLocation($location);
$produitInvestissement = new ProduitInvestissement(
1,
2,
);
$annonce->setProduitInvestissement($produitInvestissement);
$fondsCommerce = new FondsCommerce(
1,
'70 % bar / 30 % restaurant',
'Tous commerces sauf restauration',
2,
3,
4,
5,
6,
);
$annonce->setFondsCommerce($fondsCommerce);
$honoraireCharge = new HonoraireCharge(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
);
$annonce->setHonoraireCharge($honoraireCharge);
$localisation = new Localisation(
'34000',
'MTP',
'France',
'425 Rue <NAME>',
'Commerces',
'ville',
false,
false,
false,
'34000',
'MONTPELLIER',
null,
'8',
'Opera',
22.1,
23.4,
1,
'75,92,93,94,95'
);
$annonce->setLocalisation($localisation);
$surface = new Surface(
1,
2,
3,
4,
5,
6,
7,
8,
9,
26,
10,
true,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
false,
24,
25
);
$annonce->setSurface($surface);
$contact = new Contact(
'0123456789',
'<NAME>',
'<EMAIL>',
true,
false,
'MARTIN',
'<NAME>'
);
$annonce->setContact($contact);
$etage = new Etage(
0,
1,
3
);
$annonce->setEtage($etage);
$interieur = new Interieur(
true,
'1985',
true,
false,
true,
false,
false,
false,
true,
1,
2,
3,
false,
true,
false,
true,
false,
false,
false,
true,
true
);
$annonce->setInterieur($interieur);
$partieJour = new PartieJour(
'type',
false,
true,
false,
true,
false,
true,
false,
true
);
$annonce->setPartieJour($partieJour);
$exterieur = new Exterieur(
true,
false,
true,
false,
true,
false,
true
);
$annonce->setExterieur($exterieur);
$garage = new Garage(
true,
1
);
$annonce->setGarage($garage);
$securite = new Securite(
true,
false,
true,
false
);
$annonce->setSecurite($securite);
$detail = new Detail(
'BAR, TABAC, PMU',
'Maison 3 pièces',
'Très belle maison',
new \DateTimeImmutable(),
true,
false,
true,
'Clefs à prendre chez le gardien',
false,
'Tradition'
);
$annonce->setDetail($detail);
$publication = new Publication(
'SL,BD,WA',
true,
'4.09'
);
$annonce->setPublication($publication);
$chauffageClim = new ChauffageClim(1, true);
$annonce->setChauffageClim($chauffageClim);
self::assertFalse($annonce->isTypeVente());
self::assertFalse($annonce->isTypeLocation());
self::assertFalse($annonce->isModeleMaison());
self::assertEquals($identifiant, $annonce->getIdentifiant());
self::assertEquals($type, $annonce->getType());
self::assertEquals($photo, $annonce->getPhoto());
self::assertEquals($champCustom, $annonce->getChampCustom());
self::assertEquals($langue, $annonce->getLangue());
self::assertEquals($mandat, $annonce->getMandat());
self::assertEquals($locationVacances, $annonce->getLocationVacances());
self::assertEquals($viager, $annonce->getViager());
self::assertEquals($terrain, $annonce->getTerrain());
self::assertEquals($bureau, $annonce->getBureau());
self::assertEquals($diagnostic, $annonce->getDiagnostic());
self::assertEquals($parking, $annonce->getParking());
self::assertEquals($boutique, $annonce->getBoutique());
self::assertEquals($prix, $annonce->getPrix());
self::assertEquals($location, $annonce->getLocation());
self::assertEquals($produitInvestissement, $annonce->getProduitInvestissement());
self::assertEquals($fondsCommerce, $annonce->getFondsCommerce());
self::assertEquals($honoraireCharge, $annonce->getHonoraireCharge());
self::assertEquals($localisation, $annonce->getLocalisation());
self::assertEquals($surface, $annonce->getSurface());
self::assertEquals($contact, $annonce->getContact());
self::assertEquals($etage, $annonce->getEtage());
self::assertEquals($interieur, $annonce->getInterieur());
self::assertEquals($partieJour, $annonce->getPartieJour());
self::assertEquals($exterieur, $annonce->getExterieur());
self::assertEquals($garage, $annonce->getGarage());
self::assertEquals($securite, $annonce->getSecurite());
self::assertEquals($chauffageClim, $annonce->getChauffageClim());
self::assertEquals($detail, $annonce->getDetail());
self::assertEquals($publication, $annonce->getPublication());
}
}
<file_sep>/Models/Annonce/Parking.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Parking
{
private Column $nbVehicules;
private Column $immeuble;
private Column $isole;
public function __construct(
$nbVehicules,
$immeuble,
$isole
) {
$this->nbVehicules = new Column(217, $nbVehicules);
$this->immeuble = new Column(227, $immeuble);
$this->isole = new Column(228, $isole);
}
public function getNbVehicules(): Column
{
return $this->nbVehicules;
}
public function getImmeuble(): Column
{
return $this->immeuble;
}
public function getIsole(): Column
{
return $this->isole;
}
public function toArray(): array
{
return [
$this->getNbVehicules(),
$this->getImmeuble(),
$this->getIsole(),
];
}
}
<file_sep>/Models/Annonce/Type.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Type
{
private Column $type;
private Column $sousType;
public function __construct($type, $sousType)
{
$this->type = new Column(4, $type);
$this->sousType = new Column(181, $sousType);
}
public function getType(): Column
{
return $this->type;
}
public function getSousType(): Column
{
return $this->sousType;
}
public function toArray(): array
{
return [
$this->getType(),
$this->getSousType(),
];
}
}
<file_sep>/Models/Annonce/ChampCustom.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class ChampCustom
{
private Column $champ1;
private Column $champ2;
private Column $champ3;
private Column $champ4;
private Column $champ5;
private Column $champ6;
private Column $champ7;
private Column $champ8;
private Column $champ9;
private Column $champ10;
private Column $champ11;
private Column $champ12;
private Column $champ13;
private Column $champ14;
private Column $champ15;
private Column $champ16;
private Column $champ17;
private Column $champ18;
private Column $champ19;
private Column $champ20;
private Column $champ21;
private Column $champ22;
private Column $champ23;
private Column $champ24;
private Column $champ25;
private Column $champ26;
public function __construct(
$champ1,
$champ2,
$champ3,
$champ4,
$champ5,
$champ6,
$champ7,
$champ8,
$champ9,
$champ10,
$champ11,
$champ12,
$champ13,
$champ14,
$champ15,
$champ16,
$champ17,
$champ18,
$champ19,
$champ20,
$champ21,
$champ22,
$champ23,
$champ24,
$champ25,
$champ26
) {
$this->champ1 = new Column(136, $champ1);
$this->champ2 = new Column(137, $champ2);
$this->champ3 = new Column(138, $champ3);
$this->champ4 = new Column(139, $champ4);
$this->champ5 = new Column(140, $champ5);
$this->champ6 = new Column(141, $champ6);
$this->champ7 = new Column(142, $champ7);
$this->champ8 = new Column(143, $champ8);
$this->champ9 = new Column(144, $champ9);
$this->champ10 = new Column(145, $champ10);
$this->champ11 = new Column(146, $champ11);
$this->champ12 = new Column(147, $champ12);
$this->champ13 = new Column(148, $champ13);
$this->champ14 = new Column(149, $champ14);
$this->champ15 = new Column(150, $champ15);
$this->champ16 = new Column(151, $champ16);
$this->champ17 = new Column(152, $champ17);
$this->champ18 = new Column(153, $champ18);
$this->champ19 = new Column(154, $champ19);
$this->champ20 = new Column(155, $champ20);
$this->champ21 = new Column(156, $champ21);
$this->champ22 = new Column(157, $champ22);
$this->champ23 = new Column(158, $champ23);
$this->champ24 = new Column(159, $champ24);
$this->champ25 = new Column(160, $champ25);
$this->champ26 = new Column(263, $champ26);
}
public function getChamp1(): Column
{
return $this->champ1;
}
public function getChamp2(): Column
{
return $this->champ2;
}
public function getChamp3(): Column
{
return $this->champ3;
}
public function getChamp4(): Column
{
return $this->champ4;
}
public function getChamp5(): Column
{
return $this->champ5;
}
public function getChamp6(): Column
{
return $this->champ6;
}
public function getChamp7(): Column
{
return $this->champ7;
}
public function getChamp8(): Column
{
return $this->champ8;
}
public function getChamp9(): Column
{
return $this->champ9;
}
public function getChamp10(): Column
{
return $this->champ10;
}
public function getChamp11(): Column
{
return $this->champ11;
}
public function getChamp12(): Column
{
return $this->champ12;
}
public function getChamp13(): Column
{
return $this->champ13;
}
public function getChamp14(): Column
{
return $this->champ14;
}
public function getChamp15(): Column
{
return $this->champ15;
}
public function getChamp16(): Column
{
return $this->champ16;
}
public function getChamp17(): Column
{
return $this->champ17;
}
public function getChamp18(): Column
{
return $this->champ18;
}
public function getChamp19(): Column
{
return $this->champ19;
}
public function getChamp20(): Column
{
return $this->champ20;
}
public function getChamp21(): Column
{
return $this->champ21;
}
public function getChamp22(): Column
{
return $this->champ22;
}
public function getChamp23(): Column
{
return $this->champ23;
}
public function getChamp24(): Column
{
return $this->champ24;
}
public function getChamp25(): Column
{
return $this->champ25;
}
public function getChamp26(): Column
{
return $this->champ26;
}
public function toArray(): array
{
return [
$this->getChamp1(),
$this->getChamp2(),
$this->getChamp3(),
$this->getChamp4(),
$this->getChamp5(),
$this->getChamp6(),
$this->getChamp7(),
$this->getChamp8(),
$this->getChamp9(),
$this->getChamp10(),
$this->getChamp11(),
$this->getChamp12(),
$this->getChamp13(),
$this->getChamp14(),
$this->getChamp15(),
$this->getChamp16(),
$this->getChamp17(),
$this->getChamp18(),
$this->getChamp19(),
$this->getChamp20(),
$this->getChamp21(),
$this->getChamp22(),
$this->getChamp23(),
$this->getChamp24(),
$this->getChamp25(),
$this->getChamp26(),
];
}
}
<file_sep>/Centers/CsvCenter/AnnonceCsvCenter.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Centers\CsvCenter;
use Spiriit\PolirisBundle\Models\AnnonceExport;
use Spiriit\PolirisBundle\Models\ExportInterface;
use Symfony\Component\Serializer\Encoder\CsvEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
use function Symfony\Component\String\u;
class AnnonceCsvCenter extends CsvCenter
{
public function generateCsvFile(ExportInterface $export, string $formatEncodage): string
{
/** @var AnnonceExport $annonceExport */
$annonceExport = $export;
$csvEncoderOptions = [
CsvEncoder::DELIMITER_KEY => '#',
CsvEncoder::ENCLOSURE_KEY => '$',
CsvEncoder::NO_HEADERS_KEY => true,
];
$serializer = new Serializer([new ObjectNormalizer()], [new CsvEncoder($csvEncoderOptions)]);
$content = $serializer->encode($this->getTransformedContent($annonceExport->toArray()), 'csv');
$path = u(sys_get_temp_dir())->append('/Annonces.csv')->toString();
file_put_contents($path, mb_convert_encoding($this->getCleanedContent($content), $formatEncodage, 'UTF-8'));
return $path;
}
}
<file_sep>/tests/Functional/Bundle/Bundle.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Functional\Bundle;
use Spiriit\PolirisBundle\Tests\Functional\Bundle\DependencyInjection\BundleExtension;
use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\HttpKernel\Bundle\Bundle as BaseBundle;
class Bundle extends BaseBundle
{
public function getContainerExtension(): ?ExtensionInterface
{
return new BundleExtension();
}
}
<file_sep>/tests/Models/Annonce/HonoraireChargeTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\HonoraireCharge;
class HonoraireChargeTest extends TestCase
{
/**
* @test
*/
public function it_must_create_honoraire_charge()
{
$honoraireCharge = new HonoraireCharge(
$honoraires = 1,
$charges = 2,
$honorairesChargeAcquereur = 3,
$pourcentageHonorairesTTC = 4,
$chargesAnnuelles = 5,
$honorairesCharge = 6,
$prixHorsHonorairesAcquereur = 7,
$modalitesChargesLocataire = 8,
$partHonorairesEtatLieux = 9,
$urlBaremeHonorairesAgence = 10
);
self::assertEquals($honoraires, $honoraireCharge->getHonoraires()->getVal());
self::assertEquals($charges, $honoraireCharge->getCharges()->getVal());
self::assertEquals($honorairesChargeAcquereur, $honoraireCharge->getHonorairesChargeAcquereur()->getVal());
self::assertEquals($pourcentageHonorairesTTC, $honoraireCharge->getPourcentageHonorairesTTC()->getVal());
self::assertEquals($chargesAnnuelles, $honoraireCharge->getChargesAnnuelles()->getVal());
self::assertEquals($honorairesCharge, $honoraireCharge->getHonorairesCharge()->getVal());
self::assertEquals($prixHorsHonorairesAcquereur, $honoraireCharge->getPrixHorsHonorairesAcquereur()->getVal());
self::assertEquals($modalitesChargesLocataire, $honoraireCharge->getModalitesChargesLocataire()->getVal());
self::assertEquals($partHonorairesEtatLieux, $honoraireCharge->getPartHonorairesEtatLieux()->getVal());
self::assertEquals($urlBaremeHonorairesAgence, $honoraireCharge->getUrlBaremeHonorairesAgence()->getVal());
$expectedArray = [
$honoraireCharge->getHonoraires(),
$honoraireCharge->getCharges(),
$honoraireCharge->getHonorairesChargeAcquereur(),
$honoraireCharge->getPourcentageHonorairesTTC(),
$honoraireCharge->getChargesAnnuelles(),
$honoraireCharge->getHonorairesCharge(),
$honoraireCharge->getPrixHorsHonorairesAcquereur(),
$honoraireCharge->getModalitesChargesLocataire(),
$honoraireCharge->getPartHonorairesEtatLieux(),
$honoraireCharge->getUrlBaremeHonorairesAgence(),
];
self::assertEquals($expectedArray, $honoraireCharge->toArray());
}
}
<file_sep>/Models/Annonce/Bureau.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Bureau
{
private Column $loyerAnnuelGlobal;
private Column $loyerAnnuelM2;
private Column $loyerAnnuelCC;
private Column $loyerAnnuelM2CC;
private Column $loyerAnnuelHT;
private Column $loyerAnnuelM2HT;
private Column $chargesAnnuellesGlobales;
private Column $chargesAnnuellesM2;
private Column $chargesMensuellesHT;
private Column $chargesAnnuellesM2HT;
private Column $chargesAnnuellesHT;
private Column $divisible;
private Column $surfaceDivisibleMin;
private Column $surfaceDivisibleMax;
private Column $conditionsFinancieres;
private Column $prestationsDiverses;
private Column $immeubleBureaux;
private Column $surfaceMaxBureau;
public function __construct(
$loyerAnnuelGlobal,
$loyerAnnuelM2,
$loyerAnnuelCC,
$loyerAnnuelM2CC,
$loyerAnnuelHT,
$loyerAnnuelM2HT,
$chargesAnnuellesGlobales,
$chargesAnnuellesM2,
$chargesMensuellesHT,
$chargesAnnuellesM2HT,
$chargesAnnuellesHT,
$divisible,
$surfaceDivisibleMin,
$surfaceDivisibleMax,
$conditionsFinancieres,
$prestationsDiverses,
$immeubleBureaux,
$surfaceMaxBureau
) {
$this->loyerAnnuelGlobal = new Column(202, $loyerAnnuelGlobal);
$this->chargesAnnuellesGlobales = new Column(203, $chargesAnnuellesGlobales);
$this->loyerAnnuelM2 = new Column(204, $loyerAnnuelM2);
$this->chargesAnnuellesM2 = new Column(205, $chargesAnnuellesM2);
$this->chargesMensuellesHT = new Column(206, $chargesMensuellesHT);
$this->loyerAnnuelCC = new Column(207, $loyerAnnuelCC);
$this->loyerAnnuelHT = new Column(208, $loyerAnnuelHT);
$this->chargesAnnuellesHT = new Column(209, $chargesAnnuellesHT);
$this->loyerAnnuelM2CC = new Column(210, $loyerAnnuelM2CC);
$this->loyerAnnuelM2HT = new Column(211, $loyerAnnuelM2HT);
$this->chargesAnnuellesM2HT = new Column(212, $chargesAnnuellesM2HT);
$this->divisible = new Column(213, $divisible);
$this->surfaceDivisibleMin = new Column(214, $surfaceDivisibleMin);
$this->surfaceDivisibleMax = new Column(215, $surfaceDivisibleMax);
$this->conditionsFinancieres = new Column(238, $conditionsFinancieres);
$this->prestationsDiverses = new Column(239, $prestationsDiverses);
$this->immeubleBureaux = new Column(249, $immeubleBureaux);
$this->surfaceMaxBureau = new Column(255, $surfaceMaxBureau);
}
public function getLoyerAnnuelGlobal(): Column
{
return $this->loyerAnnuelGlobal;
}
public function getLoyerAnnuelM2(): Column
{
return $this->loyerAnnuelM2;
}
public function getLoyerAnnuelCC(): Column
{
return $this->loyerAnnuelCC;
}
public function getLoyerAnnuelM2CC(): Column
{
return $this->loyerAnnuelM2CC;
}
public function getLoyerAnnuelHT(): Column
{
return $this->loyerAnnuelHT;
}
public function getLoyerAnnuelM2HT(): Column
{
return $this->loyerAnnuelM2HT;
}
public function getChargesAnnuellesGlobales(): Column
{
return $this->chargesAnnuellesGlobales;
}
public function getChargesAnnuellesM2(): Column
{
return $this->chargesAnnuellesM2;
}
public function getChargesMensuellesHT(): Column
{
return $this->chargesMensuellesHT;
}
public function getChargesAnnuellesM2HT(): Column
{
return $this->chargesAnnuellesM2HT;
}
public function getChargesAnnuellesHT(): Column
{
return $this->chargesAnnuellesHT;
}
public function getDivisible(): Column
{
return $this->divisible;
}
public function getSurfaceDivisibleMin(): Column
{
return $this->surfaceDivisibleMin;
}
public function getSurfaceDivisibleMax(): Column
{
return $this->surfaceDivisibleMax;
}
public function getConditionsFinancieres(): Column
{
return $this->conditionsFinancieres;
}
public function getPrestationsDiverses(): Column
{
return $this->prestationsDiverses;
}
public function getImmeubleBureaux(): Column
{
return $this->immeubleBureaux;
}
public function getSurfaceMaxBureau(): Column
{
return $this->surfaceMaxBureau;
}
public function toArray(): array
{
return [
$this->getLoyerAnnuelGlobal(),
$this->getLoyerAnnuelM2(),
$this->getLoyerAnnuelCC(),
$this->getLoyerAnnuelM2CC(),
$this->getLoyerAnnuelHT(),
$this->getLoyerAnnuelM2HT(),
$this->getChargesAnnuellesGlobales(),
$this->getChargesAnnuellesM2(),
$this->getChargesMensuellesHT(),
$this->getChargesAnnuellesM2HT(),
$this->getChargesAnnuellesHT(),
$this->getDivisible(),
$this->getSurfaceDivisibleMin(),
$this->getSurfaceDivisibleMax(),
$this->getConditionsFinancieres(),
$this->getPrestationsDiverses(),
$this->getImmeubleBureaux(),
$this->getSurfaceMaxBureau(),
];
}
}
<file_sep>/Models/Annonce/Contact.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Contact
{
private Column $tel;
private Column $fullName;
private Column $email;
private Column $interCabinet;
private Column $interCabinetPrive;
private Column $codeNego;
private Column $agenceTerrain;
public function __construct(
$tel,
$fullName,
$email,
$interCabinet,
$interCabinetPrive,
$codeNego,
$agenceTerrain
) {
$this->tel = new Column(105, $tel);
$this->fullName = new Column(106, $fullName);
$this->email = new Column(107, $email);
$this->interCabinet = new Column(110, $interCabinet);
$this->interCabinetPrive = new Column(111, $interCabinetPrive);
$this->codeNego = new Column(123, $codeNego);
$this->agenceTerrain = new Column(297, $agenceTerrain);
}
public function getTel(): Column
{
return $this->tel;
}
public function getFullName(): Column
{
return $this->fullName;
}
public function getEmail(): Column
{
return $this->email;
}
public function getInterCabinet(): Column
{
return $this->interCabinet;
}
public function getInterCabinetPrive(): Column
{
return $this->interCabinetPrive;
}
public function getCodeNego(): Column
{
return $this->codeNego;
}
public function getAgenceTerrain(): Column
{
return $this->agenceTerrain;
}
public function toArray(): array
{
return [
$this->getTel(),
$this->getFullName(),
$this->getEmail(),
$this->getInterCabinet(),
$this->getInterCabinetPrive(),
$this->getCodeNego(),
$this->getAgenceTerrain(),
];
}
}
<file_sep>/Models/Annonce/Langue.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Langue
{
private Column $code1;
private Column $code2;
private Column $code3;
private Column $proximite1;
private Column $proximite2;
private Column $proximite3;
private Column $label1;
private Column $label2;
private Column $label3;
private Column $descriptif1;
private Column $descriptif2;
private Column $descriptif3;
public function __construct(
$code1,
$code2,
$code3,
$proximite1,
$proximite2,
$proximite3,
$label1,
$label2,
$label3,
$descriptif1,
$descriptif2,
$descriptif3
) {
$this->code1 = new Column(124, $code1);
$this->code2 = new Column(128, $code2);
$this->code3 = new Column(132, $code3);
$this->proximite1 = new Column(125, $proximite1);
$this->proximite2 = new Column(129, $proximite2);
$this->proximite3 = new Column(133, $proximite3);
$this->label1 = new Column(126, $label1);
$this->label2 = new Column(130, $label2);
$this->label3 = new Column(134, $label3);
$this->descriptif1 = new Column(127, $descriptif1);
$this->descriptif2 = new Column(131, $descriptif2);
$this->descriptif3 = new Column(135, $descriptif3);
}
public function getCode1(): Column
{
return $this->code1;
}
public function getCode2(): Column
{
return $this->code2;
}
public function getCode3(): Column
{
return $this->code3;
}
public function getProximite1(): Column
{
return $this->proximite1;
}
public function getProximite2(): Column
{
return $this->proximite2;
}
public function getProximite3(): Column
{
return $this->proximite3;
}
public function getLabel1(): Column
{
return $this->label1;
}
public function getLabel2(): Column
{
return $this->label2;
}
public function getLabel3(): Column
{
return $this->label3;
}
public function getDescriptif1(): Column
{
return $this->descriptif1;
}
public function getDescriptif2(): Column
{
return $this->descriptif2;
}
public function getDescriptif3(): Column
{
return $this->descriptif3;
}
public function toArray(): array
{
return [
$this->getCode1(),
$this->getCode2(),
$this->getCode3(),
$this->getProximite1(),
$this->getProximite2(),
$this->getProximite3(),
$this->getLabel1(),
$this->getLabel2(),
$this->getLabel3(),
$this->getDescriptif1(),
$this->getDescriptif2(),
$this->getDescriptif3(),
];
}
}
<file_sep>/tests/Models/Annonce/SecuriteTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Securite;
class SecuriteTest extends TestCase
{
/**
* @test
*/
public function it_must_create_securite_test()
{
$securite = new Securite(
$digicode = true,
$interphone = false,
$gardien = true,
$alarme = false
);
self::assertEquals($digicode, $securite->getDigicode()->getVal());
self::assertEquals($interphone, $securite->getInterphone()->getVal());
self::assertEquals($gardien, $securite->getGardien()->getVal());
self::assertEquals($alarme, $securite->getAlarme()->getVal());
$expectedArray = [
$securite->getDigicode(),
$securite->getInterphone(),
$securite->getGardien(),
$securite->getAlarme(),
];
self::assertEquals($expectedArray, $securite->toArray());
}
}
<file_sep>/tests/Builders/AnnonceExportBuilderTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Builders;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Builders\AnnonceExportBuilder;
use Spiriit\PolirisBundle\Models\AnnonceExport;
class AnnonceExportBuilderTest extends TestCase
{
/**
* @test
*/
public function it_must_build_annonce()
{
$annonceBuilder = new AnnonceExportBuilder();
$annonceBuilder
->startLine()
->withIdentifiant('test', 'test', 'test', 'test')
->withType('test', 'test')
->endLine();
$this->assertInstanceOf(AnnonceExport::class, $annonceBuilder->build());
}
}
<file_sep>/tests/Models/Annonce/ContactTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Contact;
class ContactTest extends TestCase
{
/**
* @test
*/
public function it_must_create_contact()
{
$contact = new Contact(
$tel = '0123456789',
$fullName = '<NAME>',
$email = '<EMAIL>',
$interCabinet = true,
$interCabinetPrive = false,
$codeNego = 'MARTIN',
$agenceTerrain = 'Agence terra nova'
);
self::assertEquals($tel, $contact->getTel()->getVal());
self::assertEquals($fullName, $contact->getFullName()->getVal());
self::assertEquals($email, $contact->getEmail()->getVal());
self::assertEquals($interCabinet, $contact->getInterCabinet()->getVal());
self::assertEquals($interCabinetPrive, $contact->getInterCabinetPrive()->getVal());
self::assertEquals($codeNego, $contact->getCodeNego()->getVal());
self::assertEquals($agenceTerrain, $contact->getAgenceTerrain()->getVal());
$expectedArray = [
$contact->getTel(),
$contact->getFullName(),
$contact->getEmail(),
$contact->getInterCabinet(),
$contact->getInterCabinetPrive(),
$contact->getCodeNego(),
$contact->getAgenceTerrain(),
];
self::assertEquals($expectedArray, $contact->toArray());
}
}
<file_sep>/Models/Annonce/Detail.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Detail
{
private Column $activitesCommerciales;
private Column $label;
private Column $description;
private Column $dateDispo;
private Column $amenagementHandicapes;
private Column $animauxAcceptes;
private Column $duplex;
private Column $commPrives;
private Column $logementADisposition;
private Column $nomModele;
public function __construct(
$activitesCommerciales,
$label,
$description,
$dateDispo,
$amenagementHandicapes,
$animauxAcceptes,
$duplex,
$commPrives,
$logementADisposition,
$nomModele
) {
$this->activitesCommerciales = new Column(10, $activitesCommerciales);
$this->label = new Column(20, $label);
$this->description = new Column(21, $description);
$this->dateDispo = new Column(22, $dateDispo);
$this->amenagementHandicapes = new Column(66, $amenagementHandicapes);
$this->animauxAcceptes = new Column(67, $animauxAcceptes);
$this->duplex = new Column(81, $duplex);
$this->commPrives = new Column(122, $commPrives);
$this->logementADisposition = new Column(230, $logementADisposition);
$this->nomModele = new Column(323, $nomModele);
}
public function getActivitesCommerciales(): Column
{
return $this->activitesCommerciales;
}
public function getLabel(): Column
{
return $this->label;
}
public function getDescription(): Column
{
return $this->description;
}
public function getDateDispo(): Column
{
return $this->dateDispo;
}
public function getAmenagementHandicapes(): Column
{
return $this->amenagementHandicapes;
}
public function getAnimauxAcceptes(): Column
{
return $this->animauxAcceptes;
}
public function getDuplex(): Column
{
return $this->duplex;
}
public function getCommPrives(): Column
{
return $this->commPrives;
}
public function getLogementADisposition(): Column
{
return $this->logementADisposition;
}
public function getNomModele(): Column
{
return $this->nomModele;
}
public function toArray(): array
{
return [
$this->getActivitesCommerciales(),
$this->getLabel(),
$this->getDescription(),
$this->getDateDispo(),
$this->getAmenagementHandicapes(),
$this->getAnimauxAcceptes(),
$this->getDuplex(),
$this->getCommPrives(),
$this->getLogementADisposition(),
$this->getNomModele(),
];
}
}
<file_sep>/tests/Models/Annonce/SurfaceTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Surface;
class SurfaceTest extends TestCase
{
/**
* @test
*/
public function it_must_create_surface()
{
$surface = new Surface(
$surf = 1,
$surfaceTerrain = 2,
$nbPieces = 3,
$nbChambres = 4,
$nbSdb = 5,
$nbSalleEau = 6,
$nbWc = 7,
$nbBalcons = 8,
$surfaceBalcon = 26,
$nbParkings = 9,
$nbBoxes = 10,
$terrasse = true,
$longueurFacade = 11,
$placesEnSalle = 12,
$nbBureaux = 13,
$surfaceSejour = 14,
$nbTerrasses = 15,
$surfaceCave = 16,
$surfaceSalleManger = 17,
$surfaceMin = 18,
$surfaceMax = 19,
$nbPiecesMin = 20,
$nbPiecesMax = 21,
$nbChambresMin = 22,
$nbChambresMax = 23,
$comblesAmenageables = false,
$surfaceTerrainNecessaire = 24,
$surfaceTerrasse = 25
);
self::assertEquals($surf, $surface->getSurface()->getVal());
self::assertEquals($surfaceTerrain, $surface->getSurfaceTerrain()->getVal());
self::assertEquals($nbPieces, $surface->getNbPieces()->getVal());
self::assertEquals($nbChambres, $surface->getNbChambres()->getVal());
self::assertEquals($nbSdb, $surface->getNbSdb()->getVal());
self::assertEquals($nbSalleEau, $surface->getNbSalleEau()->getVal());
self::assertEquals($nbWc, $surface->getNbWc()->getVal());
self::assertEquals($nbBalcons, $surface->getNbBalcons()->getVal());
self::assertEquals($surfaceBalcon, $surface->getSurfaceBalcon()->getVal());
self::assertEquals($nbParkings, $surface->getNbParkings()->getVal());
self::assertEquals($nbBoxes, $surface->getNbBoxes()->getVal());
self::assertEquals($terrasse, $surface->getTerrasse()->getVal());
self::assertEquals($longueurFacade, $surface->getLongueurFacade()->getVal());
self::assertEquals($placesEnSalle, $surface->getPlacesEnSalle()->getVal());
self::assertEquals($nbBureaux, $surface->getNbBureaux()->getVal());
self::assertEquals($surfaceSejour, $surface->getSurfaceSejour()->getVal());
self::assertEquals($nbTerrasses, $surface->getNbTerrasses()->getVal());
self::assertEquals($surfaceCave, $surface->getSurfaceCave()->getVal());
self::assertEquals($surfaceSalleManger, $surface->getSurfaceSalleManger()->getVal());
self::assertEquals($surfaceMin, $surface->getSurfaceMin()->getVal());
self::assertEquals($surfaceMax, $surface->getSurfaceMax()->getVal());
self::assertEquals($nbPiecesMin, $surface->getNbPiecesMin()->getVal());
self::assertEquals($nbPiecesMax, $surface->getNbPiecesMax()->getVal());
self::assertEquals($nbChambresMin, $surface->getNbChambresMin()->getVal());
self::assertEquals($nbChambresMax, $surface->getNbChambresMax()->getVal());
self::assertEquals($comblesAmenageables, $surface->getComblesAmenageables()->getVal());
self::assertEquals($surfaceTerrainNecessaire, $surface->getSurfaceTerrainNecessaire()->getVal());
self::assertEquals($surfaceTerrasse, $surface->getSurfaceTerrasse()->getVal());
$expectedArray = [
$surface->getSurface(),
$surface->getSurfaceTerrain(),
$surface->getNbPieces(),
$surface->getNbChambres(),
$surface->getNbSdb(),
$surface->getNbSalleEau(),
$surface->getNbWc(),
$surface->getNbBalcons(),
$surface->getSurfaceBalcon(),
$surface->getNbParkings(),
$surface->getNbBoxes(),
$surface->getTerrasse(),
$surface->getLongueurFacade(),
$surface->getPlacesEnSalle(),
$surface->getNbBureaux(),
$surface->getSurfaceSejour(),
$surface->getNbTerrasses(),
$surface->getSurfaceCave(),
$surface->getSurfaceSalleManger(),
$surface->getSurfaceMin(),
$surface->getSurfaceMax(),
$surface->getNbPiecesMin(),
$surface->getNbPiecesMax(),
$surface->getNbChambresMin(),
$surface->getNbChambresMax(),
$surface->getComblesAmenageables(),
$surface->getSurfaceTerrainNecessaire(),
$surface->getSurfaceTerrasse(),
];
self::assertEquals($expectedArray, $surface->toArray());
}
}
<file_sep>/Models/Annonce/Securite.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Securite
{
private Column $digicode;
private Column $interphone;
private Column $gardien;
private Column $alarme;
public function __construct(
$digicode,
$interphone,
$gardien,
$alarme
) {
$this->digicode = new Column(45, $digicode);
$this->interphone = new Column(46, $interphone);
$this->gardien = new Column(47, $gardien);
$this->alarme = new Column(61, $alarme);
}
public function getDigicode(): Column
{
return $this->digicode;
}
public function getInterphone(): Column
{
return $this->interphone;
}
public function getGardien(): Column
{
return $this->gardien;
}
public function getAlarme(): Column
{
return $this->alarme;
}
public function toArray(): array
{
return [
$this->getDigicode(),
$this->getInterphone(),
$this->getGardien(),
$this->getAlarme(),
];
}
}
<file_sep>/Models/Annonce/Viager.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Viager
{
private Column $prixBouquet;
private Column $renteMensuelle;
private Column $ageHomme;
private Column $ageFemme;
private Column $venduLibre;
public function __construct(
$prixBouquet,
$renteMensuelle,
$ageHomme,
$ageFemme,
$venduLibre
) {
$this->prixBouquet = new Column(185, $prixBouquet);
$this->renteMensuelle = new Column(186, $renteMensuelle);
$this->ageHomme = new Column(187, $ageHomme);
$this->ageFemme = new Column(188, $ageFemme);
$this->venduLibre = new Column(229, $venduLibre);
}
public function getPrixBouquet(): Column
{
return $this->prixBouquet;
}
public function getRenteMensuelle(): Column
{
return $this->renteMensuelle;
}
public function getAgeHomme(): Column
{
return $this->ageHomme;
}
public function getAgeFemme(): Column
{
return $this->ageFemme;
}
public function getVenduLibre(): Column
{
return $this->venduLibre;
}
public function toArray(): array
{
return [
$this->getPrixBouquet(),
$this->getRenteMensuelle(),
$this->getAgeHomme(),
$this->getAgeFemme(),
$this->getVenduLibre(),
];
}
}
<file_sep>/Models/Annonce/FondsCommerce.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class FondsCommerce
{
private Column $ca;
private Column $repartitionCa;
private Column $natureBailCommercial;
private Column $resultatAnneeN2;
private Column $resultatAnneeN1;
private Column $resultatActuel;
private Column $caAnneeN2;
private Column $caAnneeN1;
public function __construct(
$ca,
$repartitionCa,
$natureBailCommercial,
$resultatAnneeN2,
$resultatAnneeN1,
$resultatActuel,
$caAnneeN2,
$caAnneeN1
) {
$this->ca = new Column(79, $ca);
$this->repartitionCa = new Column(220, $repartitionCa);
$this->natureBailCommercial = new Column(243, $natureBailCommercial);
$this->resultatAnneeN2 = new Column(224, $resultatAnneeN2);
$this->resultatAnneeN1 = new Column(225, $resultatAnneeN1);
$this->resultatActuel = new Column(226, $resultatActuel);
$this->caAnneeN2 = new Column(236, $caAnneeN2);
$this->caAnneeN1 = new Column(237, $caAnneeN1);
}
public function getCa(): Column
{
return $this->ca;
}
public function getRepartitionCa(): Column
{
return $this->repartitionCa;
}
public function getNatureBailCommercial(): Column
{
return $this->natureBailCommercial;
}
public function getResultatAnneeN2(): Column
{
return $this->resultatAnneeN2;
}
public function getResultatAnneeN1(): Column
{
return $this->resultatAnneeN1;
}
public function getResultatActuel(): Column
{
return $this->resultatActuel;
}
public function getCaAnneeN2(): Column
{
return $this->caAnneeN2;
}
public function getCaAnneeN1(): Column
{
return $this->caAnneeN1;
}
public function toArray(): array
{
return [
$this->getCa(),
$this->getRepartitionCa(),
$this->getNatureBailCommercial(),
$this->getResultatAnneeN2(),
$this->getResultatAnneeN1(),
$this->getResultatActuel(),
$this->getCaAnneeN2(),
$this->getCaAnneeN1(),
];
}
}
<file_sep>/tests/Models/Annonce/LangueTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Langue;
class LangueTest extends TestCase
{
/**
* @test
*/
public function it_must_create_langue()
{
$langue = new Langue(
$code1 = 'code 1',
$code2 = 'code 2',
$code3 = 'code 3',
$proximite1 = 'proximite 1',
$proximite2 = 'proximite 2',
$proximite3 = 'proximite 3',
$label1 = 'label 1',
$label2 = 'label 2',
$label3 = 'label 3',
$descriptif1 = 'descriptif 1',
$descriptif2 = 'descriptif 2',
$descriptif3 = 'descriptif 3',
);
self::assertEquals($code1, $langue->getCode1()->getVal());
self::assertEquals($code2, $langue->getCode2()->getVal());
self::assertEquals($code3, $langue->getCode3()->getVal());
self::assertEquals($proximite1, $langue->getProximite1()->getVal());
self::assertEquals($proximite2, $langue->getProximite2()->getVal());
self::assertEquals($proximite3, $langue->getProximite3()->getVal());
self::assertEquals($label1, $langue->getLabel1()->getVal());
self::assertEquals($label2, $langue->getLabel2()->getVal());
self::assertEquals($label3, $langue->getLabel3()->getVal());
self::assertEquals($descriptif1, $langue->getDescriptif1()->getVal());
self::assertEquals($descriptif2, $langue->getDescriptif2()->getVal());
self::assertEquals($descriptif3, $langue->getDescriptif3()->getVal());
$expectedArray = [
$langue->getCode1(),
$langue->getCode2(),
$langue->getCode3(),
$langue->getProximite1(),
$langue->getProximite2(),
$langue->getProximite3(),
$langue->getLabel1(),
$langue->getLabel2(),
$langue->getLabel3(),
$langue->getDescriptif1(),
$langue->getDescriptif2(),
$langue->getDescriptif3(),
];
self::assertEquals($expectedArray, $langue->toArray());
}
}
<file_sep>/Models/Annonce/Annonce.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Annonce
{
public const ANNONCE_TYPE_VENTE = 'vente';
public const ANNONCE_TYPE_LOCATION = 'location';
public const ANNONCE_TYPE_MODELE_MAISON = 'modèle de maison';
private Identifiant $identifiant;
private Type $type;
private Photo $photo;
private ChampCustom $champCustom;
private Langue $langue;
private Mandat $mandat;
private LocationVacances $locationVacances;
private Viager $viager;
private Terrain $terrain;
private Bureau $bureau;
private Diagnostic $diagnostic;
private Parking $parking;
private Boutique $boutique;
private Prix $prix;
private Location $location;
private ProduitInvestissement $produitInvestissement;
private FondsCommerce $fondsCommerce;
private HonoraireCharge $honoraireCharge;
private Localisation $localisation;
private Surface $surface;
private Contact $contact;
private Etage $etage;
private Interieur $interieur;
private PartieJour $partieJour;
private Exterieur $exterieur;
private Garage $garage;
private Securite $securite;
private ChauffageClim $chauffageClim;
private Detail $detail;
private Publication $publication;
public function isTypeVente(): bool
{
return self::ANNONCE_TYPE_VENTE === $this->getIdentifiant()->getAnnonceType()->getVal();
}
public function isTypeLocation(): bool
{
return self::ANNONCE_TYPE_LOCATION === $this->getIdentifiant()->getAnnonceType()->getVal();
}
public function isModeleMaison(): bool
{
return self::ANNONCE_TYPE_MODELE_MAISON === $this->getType()->getType()->getVal();
}
public function getIdentifiant(): Identifiant
{
return $this->identifiant;
}
public function getType(): Type
{
return $this->type;
}
public function getPhoto(): Photo
{
return $this->photo;
}
public function getChampCustom(): ChampCustom
{
return $this->champCustom;
}
public function getLangue(): Langue
{
return $this->langue;
}
public function getMandat(): Mandat
{
return $this->mandat;
}
public function getLocationVacances(): LocationVacances
{
return $this->locationVacances;
}
public function getViager(): Viager
{
return $this->viager;
}
public function getTerrain(): Terrain
{
return $this->terrain;
}
public function getBureau(): Bureau
{
return $this->bureau;
}
public function getDiagnostic(): Diagnostic
{
return $this->diagnostic;
}
public function getParking(): Parking
{
return $this->parking;
}
public function getBoutique(): Boutique
{
return $this->boutique;
}
public function getPrix(): Prix
{
return $this->prix;
}
public function getLocation(): Location
{
return $this->location;
}
public function getProduitInvestissement(): ProduitInvestissement
{
return $this->produitInvestissement;
}
public function getFondsCommerce(): FondsCommerce
{
return $this->fondsCommerce;
}
public function getHonoraireCharge(): HonoraireCharge
{
return $this->honoraireCharge;
}
public function getLocalisation(): Localisation
{
return $this->localisation;
}
public function getSurface(): Surface
{
return $this->surface;
}
public function getContact(): Contact
{
return $this->contact;
}
public function getEtage(): Etage
{
return $this->etage;
}
public function getInterieur(): Interieur
{
return $this->interieur;
}
public function getPartieJour(): PartieJour
{
return $this->partieJour;
}
public function getExterieur(): Exterieur
{
return $this->exterieur;
}
public function getGarage(): Garage
{
return $this->garage;
}
public function getSecurite(): Securite
{
return $this->securite;
}
public function getChauffageClim(): ChauffageClim
{
return $this->chauffageClim;
}
public function getDetail(): Detail
{
return $this->detail;
}
public function getPublication(): Publication
{
return $this->publication;
}
public function setIdentifiant(Identifiant $identifiant): void
{
$this->identifiant = $identifiant;
}
public function setType(Type $type): void
{
$this->type = $type;
}
public function setPhoto(Photo $photo): void
{
$this->photo = $photo;
}
public function setChampCustom(ChampCustom $champCustom): void
{
$this->champCustom = $champCustom;
}
public function setLangue(Langue $langue): void
{
$this->langue = $langue;
}
public function setMandat(Mandat $mandat): void
{
$this->mandat = $mandat;
}
public function setLocationVacances(LocationVacances $locationVacances): void
{
$this->locationVacances = $locationVacances;
}
public function setViager(Viager $viager): void
{
$this->viager = $viager;
}
public function setTerrain(Terrain $terrain): void
{
$this->terrain = $terrain;
}
public function setBureau(Bureau $bureau): void
{
$this->bureau = $bureau;
}
public function setDiagnostic(Diagnostic $diagnostic): void
{
$this->diagnostic = $diagnostic;
}
public function setParking(Parking $parking): void
{
$this->parking = $parking;
}
public function setBoutique(Boutique $boutique): void
{
$this->boutique = $boutique;
}
public function setPrix(Prix $prix): void
{
$this->prix = $prix;
}
public function setLocation(Location $location): void
{
$this->location = $location;
}
public function setProduitInvestissement(ProduitInvestissement $produitInvestissement): void
{
$this->produitInvestissement = $produitInvestissement;
}
public function setFondsCommerce(FondsCommerce $fondsCommerce): void
{
$this->fondsCommerce = $fondsCommerce;
}
public function setHonoraireCharge(HonoraireCharge $honoraireCharge): void
{
$this->honoraireCharge = $honoraireCharge;
}
public function setLocalisation(Localisation $localisation): void
{
$this->localisation = $localisation;
}
public function setSurface(Surface $surface): void
{
$this->surface = $surface;
}
public function setContact(Contact $contact): void
{
$this->contact = $contact;
}
public function setEtage(Etage $etage): void
{
$this->etage = $etage;
}
public function setInterieur(Interieur $interieur): void
{
$this->interieur = $interieur;
}
public function setPartieJour(PartieJour $partieJour): void
{
$this->partieJour = $partieJour;
}
public function setExterieur(Exterieur $exterieur): void
{
$this->exterieur = $exterieur;
}
public function setGarage(Garage $garage): void
{
$this->garage = $garage;
}
public function setSecurite(Securite $securite): void
{
$this->securite = $securite;
}
public function setChauffageClim(ChauffageClim $chauffageClim): void
{
$this->chauffageClim = $chauffageClim;
}
public function setDetail(Detail $detail): void
{
$this->detail = $detail;
}
public function setPublication(Publication $publication): void
{
$this->publication = $publication;
}
public function toArray(): array
{
$results = [];
$columns = [
...$this->getIdentifiant()->toArray(),
...$this->getType()->toArray(),
...$this->getPhoto()->toArray(),
...$this->getChampCustom()->toArray(),
...$this->getLangue()->toArray(),
...$this->getMandat()->toArray(),
...$this->getLocationVacances()->toArray(),
...$this->getViager()->toArray(),
...$this->getTerrain()->toArray(),
...$this->getBureau()->toArray(),
...$this->getDiagnostic()->toArray(),
...$this->getParking()->toArray(),
...$this->getBoutique()->toArray(),
...$this->getPrix()->toArray(),
...$this->getLocation()->toArray(),
...$this->getProduitInvestissement()->toArray(),
...$this->getFondsCommerce()->toArray(),
...$this->getHonoraireCharge()->toArray(),
...$this->getLocalisation()->toArray(),
...$this->getSurface()->toArray(),
...$this->getContact()->toArray(),
...$this->getEtage()->toArray(),
...$this->getInterieur()->toArray(),
...$this->getPartieJour()->toArray(),
...$this->getExterieur()->toArray(),
...$this->getGarage()->toArray(),
...$this->getSecurite()->toArray(),
...$this->getChauffageClim()->toArray(),
...$this->getDetail()->toArray(),
...$this->getPublication()->toArray(),
];
/** @var Column $column */
foreach ($columns as $column) {
$results[$column->getPos()] = $column->getTransformedVal();
}
ksort($results);
return $results;
}
}
<file_sep>/tests/Models/Annonce/BureauTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Bureau;
class BureauTest extends TestCase
{
/**
* @test
*/
public function it_must_create_bureau()
{
$bureau = new Bureau(
$loyerAnnuelGlobal = 0,
$loyerAnnuelM2 = 1,
$loyerAnnuelCC = 2,
$loyerAnnuelM2CC = 3,
$loyerAnnuelHT = 4,
$loyerAnnuelM2HT = 5,
$chargesAnnuellesGlobales = 6,
$chargesAnnuellesM2 = 7,
$chargesMensuellesHT = 8,
$chargesAnnuellesM2HT = 9,
$chargesAnnuellesHT = 10,
$divisible = true,
$surfaceDivisibleMin = 11,
$surfaceDivisibleMax = 12,
$conditionsFinancieres = 'conditions',
$prestationsDiverses = 'prestations',
$immeubleBureaux = true,
$surfaceMaxBureau = 13
);
self::assertEquals($loyerAnnuelGlobal, $bureau->getLoyerAnnuelGlobal()->getVal());
self::assertEquals($loyerAnnuelM2, $bureau->getLoyerAnnuelM2()->getVal());
self::assertEquals($loyerAnnuelCC, $bureau->getLoyerAnnuelCC()->getVal());
self::assertEquals($loyerAnnuelM2CC, $bureau->getLoyerAnnuelM2CC()->getVal());
self::assertEquals($loyerAnnuelHT, $bureau->getLoyerAnnuelHT()->getVal());
self::assertEquals($loyerAnnuelM2HT, $bureau->getLoyerAnnuelM2HT()->getVal());
self::assertEquals($chargesAnnuellesGlobales, $bureau->getChargesAnnuellesGlobales()->getVal());
self::assertEquals($chargesAnnuellesM2, $bureau->getChargesAnnuellesM2()->getVal());
self::assertEquals($chargesMensuellesHT, $bureau->getChargesMensuellesHT()->getVal());
self::assertEquals($chargesAnnuellesM2HT, $bureau->getChargesAnnuellesM2HT()->getVal());
self::assertEquals($chargesAnnuellesHT, $bureau->getChargesAnnuellesHT()->getVal());
self::assertEquals($divisible, $bureau->getDivisible()->getVal());
self::assertEquals($surfaceDivisibleMin, $bureau->getSurfaceDivisibleMin()->getVal());
self::assertEquals($surfaceDivisibleMax, $bureau->getSurfaceDivisibleMax()->getVal());
self::assertEquals($conditionsFinancieres, $bureau->getConditionsFinancieres()->getVal());
self::assertEquals($prestationsDiverses, $bureau->getPrestationsDiverses()->getVal());
self::assertEquals($immeubleBureaux, $bureau->getImmeubleBureaux()->getVal());
self::assertEquals($surfaceMaxBureau, $bureau->getSurfaceMaxBureau()->getVal());
$expectedArray = [
$bureau->getLoyerAnnuelGlobal(),
$bureau->getLoyerAnnuelM2(),
$bureau->getLoyerAnnuelCC(),
$bureau->getLoyerAnnuelM2CC(),
$bureau->getLoyerAnnuelHT(),
$bureau->getLoyerAnnuelM2HT(),
$bureau->getChargesAnnuellesGlobales(),
$bureau->getChargesAnnuellesM2(),
$bureau->getChargesMensuellesHT(),
$bureau->getChargesAnnuellesM2HT(),
$bureau->getChargesAnnuellesHT(),
$bureau->getDivisible(),
$bureau->getSurfaceDivisibleMin(),
$bureau->getSurfaceDivisibleMax(),
$bureau->getConditionsFinancieres(),
$bureau->getPrestationsDiverses(),
$bureau->getImmeubleBureaux(),
$bureau->getSurfaceMaxBureau(),
];
self::assertEquals($expectedArray, $bureau->toArray());
}
}
<file_sep>/Models/Annonce/Mandat.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Mandat
{
private Column $exclusif;
private Column $numero;
private Column $date;
private Column $nomMandataire;
private Column $prenomMandataire;
private Column $raisonSocialeMandataire;
private Column $adresseMandataire;
private Column $codePostalMandataire;
private Column $villeMandataire;
private Column $telMandataire;
private Column $commMandataire;
public function __construct(
$exclusif,
$numero,
$date,
$nomMandataire,
$prenomMandataire,
$raisonSocialeMandataire,
$adresseMandataire,
$codePostalMandataire,
$villeMandataire,
$telMandataire,
$commMandataire
) {
$this->exclusif = new Column(83, $exclusif);
$this->numero = new Column(112, $numero);
$this->date = new Column(113, $date);
$this->nomMandataire = new Column(114, $nomMandataire);
$this->prenomMandataire = new Column(115, $prenomMandataire);
$this->raisonSocialeMandataire = new Column(116, $raisonSocialeMandataire);
$this->adresseMandataire = new Column(117, $adresseMandataire);
$this->codePostalMandataire = new Column(118, $codePostalMandataire);
$this->villeMandataire = new Column(119, $villeMandataire);
$this->telMandataire = new Column(120, $telMandataire);
$this->commMandataire = new Column(121, $commMandataire);
}
public function getExclusif(): Column
{
return $this->exclusif;
}
public function getNumero(): Column
{
return $this->numero;
}
public function getDate(): Column
{
return $this->date;
}
public function getNomMandataire(): Column
{
return $this->nomMandataire;
}
public function getPrenomMandataire(): Column
{
return $this->prenomMandataire;
}
public function getRaisonSocialeMandataire(): Column
{
return $this->raisonSocialeMandataire;
}
public function getAdresseMandataire(): Column
{
return $this->adresseMandataire;
}
public function getCodePostalMandataire(): Column
{
return $this->codePostalMandataire;
}
public function getVilleMandataire(): Column
{
return $this->villeMandataire;
}
public function getTelMandataire(): Column
{
return $this->telMandataire;
}
public function getCommMandataire(): Column
{
return $this->commMandataire;
}
public function toArray(): array
{
return [
$this->getExclusif(),
$this->getNumero(),
$this->getDate(),
$this->getNomMandataire(),
$this->getPrenomMandataire(),
$this->getRaisonSocialeMandataire(),
$this->getAdresseMandataire(),
$this->getCodePostalMandataire(),
$this->getVilleMandataire(),
$this->getTelMandataire(),
$this->getCommMandataire(),
];
}
}
<file_sep>/Models/Annonce/Garage.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Garage
{
private Column $garage;
private Column $type;
public function __construct($garage, $type)
{
$this->garage = new Column(318, $garage);
$this->type = new Column(319, $type);
}
public function getGarage(): Column
{
return $this->garage;
}
public function getType(): Column
{
return $this->type;
}
public function toArray(): array
{
return [
$this->getGarage(),
$this->getType(),
];
}
}
<file_sep>/tests/Models/Annonce/ParkingTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Parking;
class ParkingTest extends TestCase
{
/**
* @test
*/
public function it_must_create_parking()
{
$parking = new Parking(
$nbVehicules = 1,
$immeuble = true,
$isole = false
);
self::assertEquals($nbVehicules, $parking->getNbVehicules()->getVal());
self::assertEquals($immeuble, $parking->getImmeuble()->getVal());
self::assertEquals($isole, $parking->getIsole()->getVal());
}
}
<file_sep>/tests/Models/Annonce/FondsCommerceTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\FondsCommerce;
class FondsCommerceTest extends TestCase
{
/**
* @test
*/
public function it_must_create_fonds_commerce()
{
$fondsCommerce = new FondsCommerce(
$ca = 1,
$repartitionCa = '70 % bar / 30 % restaurant',
$natureBailCommercial = 'Tous commerces sauf restauration',
$resultatAnneeN2 = 2,
$resultatAnneeN1 = 3,
$resultatActuel = 4,
$caAnneeN2 = 5,
$caAnneeN1 = 6,
);
self::assertEquals($ca, $fondsCommerce->getCa()->getVal());
self::assertEquals($repartitionCa, $fondsCommerce->getRepartitionCa()->getVal());
self::assertEquals($natureBailCommercial, $fondsCommerce->getNatureBailCommercial()->getVal());
self::assertEquals($resultatAnneeN2, $fondsCommerce->getResultatAnneeN2()->getVal());
self::assertEquals($resultatAnneeN1, $fondsCommerce->getResultatAnneeN1()->getVal());
self::assertEquals($resultatActuel, $fondsCommerce->getResultatActuel()->getVal());
self::assertEquals($caAnneeN2, $fondsCommerce->getCaAnneeN2()->getVal());
self::assertEquals($caAnneeN1, $fondsCommerce->getCaAnneeN1()->getVal());
$expectedArray = [
$fondsCommerce->getCa(),
$fondsCommerce->getRepartitionCa(),
$fondsCommerce->getNatureBailCommercial(),
$fondsCommerce->getResultatAnneeN2(),
$fondsCommerce->getResultatAnneeN1(),
$fondsCommerce->getResultatActuel(),
$fondsCommerce->getCaAnneeN2(),
$fondsCommerce->getCaAnneeN1(),
];
self::assertEquals($expectedArray, $fondsCommerce->toArray());
}
}
<file_sep>/Models/Annonce/Terrain.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Terrain
{
private Column $agricole;
private Column $constructible;
private Column $pente;
private Column $planEau;
private Column $longueurFacade;
private Column $donneSurLaRue;
private Column $viabilise;
public function __construct(
$agricole,
$constructible,
$pente,
$planEau,
$longueurFacade,
$donneSurLaRue,
$viabilise
) {
$this->agricole = new Column(221, $agricole);
$this->constructible = new Column(223, $constructible);
$this->pente = new Column(231, $pente);
$this->planEau = new Column(232, $planEau);
$this->longueurFacade = new Column(240, $longueurFacade);
$this->donneSurLaRue = new Column(248, $donneSurLaRue);
$this->viabilise = new Column(250, $viabilise);
}
public function getAgricole(): Column
{
return $this->agricole;
}
public function getConstructible(): Column
{
return $this->constructible;
}
public function getPente(): Column
{
return $this->pente;
}
public function getPlanEau(): Column
{
return $this->planEau;
}
public function getLongueurFacade(): Column
{
return $this->longueurFacade;
}
public function getDonneSurLaRue(): Column
{
return $this->donneSurLaRue;
}
public function getViabilise(): Column
{
return $this->viabilise;
}
public function toArray(): array
{
return [
$this->getAgricole(),
$this->getConstructible(),
$this->getPente(),
$this->getPlanEau(),
$this->getLongueurFacade(),
$this->getDonneSurLaRue(),
$this->getViabilise(),
];
}
}
<file_sep>/tests/Models/Annonce/PartieJourTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\PartieJour;
class PartieJourTest extends TestCase
{
/**
* @test
*/
public function it_must_create_partie_jour()
{
$partieJour = new PartieJour(
$typeCuisine = 'type',
$congelateur = false,
$four = true,
$laveVaisselle = false,
$microOndes = true,
$laveLinge = false,
$secheLinge = true,
$salleManger = false,
$sejour = true
);
self::assertEquals($typeCuisine, $partieJour->getTypeCuisine()->getVal());
self::assertEquals($congelateur, $partieJour->getCongelateur()->getVal());
self::assertEquals($four, $partieJour->getFour()->getVal());
self::assertEquals($laveVaisselle, $partieJour->getLaveVaisselle()->getVal());
self::assertEquals($microOndes, $partieJour->getMicroOndes()->getVal());
self::assertEquals($laveLinge, $partieJour->getLaveLinge()->getVal());
self::assertEquals($secheLinge, $partieJour->getSecheLinge()->getVal());
self::assertEquals($salleManger, $partieJour->getSalleManger()->getVal());
self::assertEquals($sejour, $partieJour->getSejour()->getVal());
$expectedArray = [
$partieJour->getTypeCuisine(),
$partieJour->getCongelateur(),
$partieJour->getFour(),
$partieJour->getLaveVaisselle(),
$partieJour->getMicroOndes(),
$partieJour->getLaveLinge(),
$partieJour->getSecheLinge(),
$partieJour->getSalleManger(),
$partieJour->getSejour(),
];
self::assertEquals($expectedArray, $partieJour->toArray());
}
}
<file_sep>/Models/Annonce/Surface.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Surface
{
private Column $surface;
private Column $surfaceTerrain;
private Column $nbPieces;
private Column $nbChambres;
private Column $nbSdb;
private Column $nbSalleEau;
private Column $nbWc;
private Column $nbBalcons;
private Column $surfaceBalcon;
private Column $nbParkings;
private Column $nbBoxes;
private Column $terrasse;
private Column $longueurFacade;
private Column $placesEnSalle;
private Column $nbBureaux;
private Column $surfaceSejour;
private Column $nbTerrasses;
private Column $surfaceCave;
private Column $surfaceSalleManger;
private Column $surfaceMin;
private Column $surfaceMax;
private Column $nbPiecesMin;
private Column $nbPiecesMax;
private Column $nbChambresMin;
private Column $nbChambresMax;
private Column $comblesAmenageables;
private Column $surfaceTerrainNecessaire;
private Column $surfaceTerrasse;
public function __construct(
$surface,
$surfaceTerrain,
$nbPieces,
$nbChambres,
$nbSdb,
$nbSalleEau,
$nbWc,
$nbBalcons,
$surfaceBalcon,
$nbParkings,
$nbBoxes,
$terrasse,
$longueurFacade,
$placesEnSalle,
$nbBureaux,
$surfaceSejour,
$nbTerrasses,
$surfaceCave,
$surfaceSalleManger,
$surfaceMin,
$surfaceMax,
$nbPiecesMin,
$nbPiecesMax,
$nbChambresMin,
$nbChambresMax,
$comblesAmenageables,
$surfaceTerrainNecessaire,
$surfaceTerrasse
) {
$this->surface = new Column(16, $surface);
$this->surfaceTerrain = new Column(17, $surfaceTerrain);
$this->nbPieces = new Column(18, $nbPieces);
$this->nbChambres = new Column(19, $nbChambres);
$this->nbSdb = new Column(29, $nbSdb);
$this->nbSalleEau = new Column(30, $nbSalleEau);
$this->nbWc = new Column(31, $nbWc);
$this->nbBalcons = new Column(39, $nbBalcons);
$this->surfaceBalcon = new Column(40, $surfaceBalcon);
$this->nbParkings = new Column(43, $nbParkings);
$this->nbBoxes = new Column(44, $nbBoxes);
$this->terrasse = new Column(48, $terrasse);
$this->longueurFacade = new Column(80, $longueurFacade);
$this->placesEnSalle = new Column(196, $placesEnSalle);
$this->nbBureaux = new Column(199, $nbBureaux);
$this->surfaceSejour = new Column(216, $surfaceSejour);
$this->nbTerrasses = new Column(244, $nbTerrasses);
$this->surfaceCave = new Column(252, $surfaceCave);
$this->surfaceSalleManger = new Column(253, $surfaceSalleManger);
$this->surfaceMin = new Column(310, $surfaceMin);
$this->surfaceMax = new Column(311, $surfaceMax);
$this->nbPiecesMin = new Column(312, $nbPiecesMin);
$this->nbPiecesMax = new Column(313, $nbPiecesMax);
$this->nbChambresMin = new Column(314, $nbChambresMin);
$this->nbChambresMax = new Column(315, $nbChambresMax);
$this->comblesAmenageables = new Column(317, $comblesAmenageables);
$this->surfaceTerrainNecessaire = new Column(321, $surfaceTerrainNecessaire);
$this->surfaceTerrasse = new Column(329, $surfaceTerrasse);
}
public function getSurface(): Column
{
return $this->surface;
}
public function getSurfaceTerrain(): Column
{
return $this->surfaceTerrain;
}
public function getNbPieces(): Column
{
return $this->nbPieces;
}
public function getNbChambres(): Column
{
return $this->nbChambres;
}
public function getNbSdb(): Column
{
return $this->nbSdb;
}
public function getNbSalleEau(): Column
{
return $this->nbSalleEau;
}
public function getNbWc(): Column
{
return $this->nbWc;
}
public function getNbBalcons(): Column
{
return $this->nbBalcons;
}
public function getSurfaceBalcon(): Column
{
return $this->surfaceBalcon;
}
public function getNbParkings(): Column
{
return $this->nbParkings;
}
public function getNbBoxes(): Column
{
return $this->nbBoxes;
}
public function getTerrasse(): Column
{
return $this->terrasse;
}
public function getLongueurFacade(): Column
{
return $this->longueurFacade;
}
public function getPlacesEnSalle(): Column
{
return $this->placesEnSalle;
}
public function getNbBureaux(): Column
{
return $this->nbBureaux;
}
public function getSurfaceSejour(): Column
{
return $this->surfaceSejour;
}
public function getNbTerrasses(): Column
{
return $this->nbTerrasses;
}
public function getSurfaceCave(): Column
{
return $this->surfaceCave;
}
public function getSurfaceSalleManger(): Column
{
return $this->surfaceSalleManger;
}
public function getSurfaceMin(): Column
{
return $this->surfaceMin;
}
public function getSurfaceMax(): Column
{
return $this->surfaceMax;
}
public function getNbPiecesMin(): Column
{
return $this->nbPiecesMin;
}
public function getNbPiecesMax(): Column
{
return $this->nbPiecesMax;
}
public function getNbChambresMin(): Column
{
return $this->nbChambresMin;
}
public function getNbChambresMax(): Column
{
return $this->nbChambresMax;
}
public function getComblesAmenageables(): Column
{
return $this->comblesAmenageables;
}
public function getSurfaceTerrainNecessaire(): Column
{
return $this->surfaceTerrainNecessaire;
}
public function getSurfaceTerrasse(): Column
{
return $this->surfaceTerrasse;
}
public function toArray(): array
{
return [
$this->getSurface(),
$this->getSurfaceTerrain(),
$this->getNbPieces(),
$this->getNbChambres(),
$this->getNbSdb(),
$this->getNbSalleEau(),
$this->getNbWc(),
$this->getNbBalcons(),
$this->getSurfaceBalcon(),
$this->getNbParkings(),
$this->getNbBoxes(),
$this->getTerrasse(),
$this->getLongueurFacade(),
$this->getPlacesEnSalle(),
$this->getNbBureaux(),
$this->getSurfaceSejour(),
$this->getNbTerrasses(),
$this->getSurfaceCave(),
$this->getSurfaceSalleManger(),
$this->getSurfaceMin(),
$this->getSurfaceMax(),
$this->getNbPiecesMin(),
$this->getNbPiecesMax(),
$this->getNbChambresMin(),
$this->getNbChambresMax(),
$this->getComblesAmenageables(),
$this->getSurfaceTerrainNecessaire(),
$this->getSurfaceTerrasse(),
];
}
}
<file_sep>/tests/Models/Annonce/InterieurTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Interieur;
class InterieurTest extends TestCase
{
/**
* @test
*/
public function it_must_create_interieur()
{
$interieur = new Interieur(
$meuble = true,
$anneeConstruction = '1985',
$refaitNeuf = true,
$wcSepares = false,
$orientationSud = true,
$orientationEst = false,
$orientationOuest = false,
$orientationNord = false,
$cave = true,
$nbCouverts = 1,
$nbLitsDoubles = 2,
$nbLitsSimples = 3,
$cableTv = false,
$cheminee = true,
$placards = false,
$tel = true,
$parquet = false,
$equipementBebe = false,
$connexionInternet = false,
$equipementVideo = true,
$mitoyennete = true
);
self::assertEquals($meuble, $interieur->getMeuble()->getVal());
self::assertEquals($anneeConstruction, $interieur->getAnneeConstruction()->getVal());
self::assertEquals($refaitNeuf, $interieur->getRefaitNeuf()->getVal());
self::assertEquals($wcSepares, $interieur->getWcSepares()->getVal());
self::assertEquals($orientationSud, $interieur->getOrientationSud()->getVal());
self::assertEquals($orientationEst, $interieur->getOrientationEst()->getVal());
self::assertEquals($orientationOuest, $interieur->getOrientationOuest()->getVal());
self::assertEquals($orientationNord, $interieur->getOrientationNord()->getVal());
self::assertEquals($cave, $interieur->getCave()->getVal());
self::assertEquals($nbCouverts, $interieur->getNbCouverts()->getVal());
self::assertEquals($nbLitsDoubles, $interieur->getNbLitsDoubles()->getVal());
self::assertEquals($nbLitsSimples, $interieur->getNbLitsSimples()->getVal());
self::assertEquals($cableTv, $interieur->getCableTv()->getVal());
self::assertEquals($cheminee, $interieur->getCheminee()->getVal());
self::assertEquals($placards, $interieur->getPlacards()->getVal());
self::assertEquals($tel, $interieur->getTel()->getVal());
self::assertEquals($parquet, $interieur->getParquet()->getVal());
self::assertEquals($equipementBebe, $interieur->getEquipementBebe()->getVal());
self::assertEquals($connexionInternet, $interieur->getConnexionInternet()->getVal());
self::assertEquals($equipementVideo, $interieur->getEquipementVideo()->getVal());
self::assertEquals($mitoyennete, $interieur->getMitoyennete()->getVal());
}
}
<file_sep>/Models/Annonce/PartieJour.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class PartieJour
{
public const TYPE_CUISINE_AUCUNE = 1;
public const TYPE_CUISINE_AMERICAINE = 2;
public const TYPE_CUISINE_SEPAREE = 3;
public const TYPE_CUISINE_COIN_CUISINE = 5;
public const TYPE_CUISINE_AMERICAINE_EQUIPEE = 6;
public const TYPE_CUISINE_SEPAREE_EQUIPEE = 7;
public const TYPE_CUISINE_COIN_CUISINE_EQUIPE = 8;
public const TYPE_CUISINE_EQUIPEE = 9;
private Column $typeCuisine;
private Column $congelateur;
private Column $four;
private Column $laveVaisselle;
private Column $microOndes;
private Column $laveLinge;
private Column $secheLinge;
private Column $salleManger;
private Column $sejour;
public function __construct(
$typeCuisine,
$congelateur,
$four,
$laveVaisselle,
$microOndes,
$laveLinge,
$secheLinge,
$salleManger,
$sejour
) {
$this->typeCuisine = new Column(34, $typeCuisine);
$this->congelateur = new Column(69, $congelateur);
$this->four = new Column(70, $four);
$this->laveVaisselle = new Column(71, $laveVaisselle);
$this->microOndes = new Column(72, $microOndes);
$this->laveLinge = new Column(233, $laveLinge);
$this->secheLinge = new Column(234, $secheLinge);
$this->salleManger = new Column(246, $salleManger);
$this->sejour = new Column(247, $sejour);
}
public function getTypeCuisine(): Column
{
return $this->typeCuisine;
}
public function getCongelateur(): Column
{
return $this->congelateur;
}
public function getFour(): Column
{
return $this->four;
}
public function getLaveVaisselle(): Column
{
return $this->laveVaisselle;
}
public function getMicroOndes(): Column
{
return $this->microOndes;
}
public function getLaveLinge(): Column
{
return $this->laveLinge;
}
public function getSecheLinge(): Column
{
return $this->secheLinge;
}
public function getSalleManger(): Column
{
return $this->salleManger;
}
public function getSejour(): Column
{
return $this->sejour;
}
public function toArray(): array
{
return [
$this->getTypeCuisine(),
$this->getCongelateur(),
$this->getFour(),
$this->getLaveVaisselle(),
$this->getMicroOndes(),
$this->getLaveLinge(),
$this->getSecheLinge(),
$this->getSalleManger(),
$this->getSejour(),
];
}
}
<file_sep>/Models/Annonce/Identifiant.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Identifiant
{
public const ID_TECHNIQUE_COLUMN = 175;
private Column $agenceId;
private Column $agencePropertyRef;
private Column $annonceType;
private Column $annonceIdTechnique;
public function __construct(
$agenceId,
$agencePropertyRef,
$annonceType,
$annonceIdTechnique
) {
$this->agenceId = new Column(1, $agenceId);
$this->agencePropertyRef = new Column(2, $agencePropertyRef);
$this->annonceType = new Column(3, $annonceType);
$this->annonceIdTechnique = new Column(self::ID_TECHNIQUE_COLUMN, $annonceIdTechnique);
}
public function getAgenceId(): Column
{
return $this->agenceId;
}
public function getAgencePropertyRef(): Column
{
return $this->agencePropertyRef;
}
public function getAnnonceType(): Column
{
return $this->annonceType;
}
public function getAnnonceIdTechnique(): Column
{
return $this->annonceIdTechnique;
}
public function toArray(): array
{
return [
$this->getAgenceId(),
$this->getAgencePropertyRef(),
$this->getAnnonceType(),
$this->getAnnonceIdTechnique(),
];
}
}
<file_sep>/tests/Models/Annonce/BoutiqueTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Boutique;
class BoutiqueTest extends TestCase
{
/**
* @test
*/
public function it_must_create_boutique()
{
$boutique = new Boutique(
$quai = true,
$situationCommerciale = 'situation'
);
self::assertEquals($quai, $boutique->getQuai()->getVal());
self::assertEquals($situationCommerciale, $boutique->getSituationCommerciale()->getVal());
$expectedArray = [
$boutique->getQuai(),
$boutique->getSituationCommerciale(),
];
self::assertEquals($expectedArray, $boutique->toArray());
}
}
<file_sep>/Models/Annonce/LocationVacances.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class LocationVacances
{
private Column $periodesDispo;
private Column $periodesBasseSaison;
private Column $prixSemaineBasseSaison;
private Column $prixQuinzaineBasseSaison;
private Column $prixMoisBasseSaison;
private Column $periodesHauteSaison;
private Column $prixSemaineHauteSaison;
private Column $prixQuinzaineHauteSaison;
private Column $prixMoisHauteSaison;
private Column $nbPersonnes;
private Column $residence;
private Column $typeResidence;
public function __construct(
$periodesDispo,
$periodesBasseSaison,
$prixSemaineBasseSaison,
$prixQuinzaineBasseSaison,
$prixMoisBasseSaison,
$periodesHauteSaison,
$prixSemaineHauteSaison,
$prixQuinzaineHauteSaison,
$prixMoisHauteSaison,
$nbPersonnes,
$residence,
$typeResidence
) {
$this->periodesDispo = new Column(182, $periodesDispo);
$this->periodesBasseSaison = new Column(183, $periodesBasseSaison);
$this->prixSemaineBasseSaison = new Column(49, $prixSemaineBasseSaison);
$this->prixQuinzaineBasseSaison = new Column(50, $prixQuinzaineBasseSaison);
$this->prixMoisBasseSaison = new Column(51, $prixMoisBasseSaison);
$this->periodesHauteSaison = new Column(184, $periodesHauteSaison);
$this->prixSemaineHauteSaison = new Column(52, $prixSemaineHauteSaison);
$this->prixQuinzaineHauteSaison = new Column(53, $prixQuinzaineHauteSaison);
$this->prixMoisHauteSaison = new Column(54, $prixMoisHauteSaison);
$this->nbPersonnes = new Column(55, $nbPersonnes);
$this->residence = new Column(190, $residence);
$this->typeResidence = new Column(56, $typeResidence);
}
public function getPeriodesDispo(): Column
{
return $this->periodesDispo;
}
public function getPeriodesBasseSaison(): Column
{
return $this->periodesBasseSaison;
}
public function getPrixSemaineBasseSaison(): Column
{
return $this->prixSemaineBasseSaison;
}
public function getPrixQuinzaineBasseSaison(): Column
{
return $this->prixQuinzaineBasseSaison;
}
public function getPrixMoisBasseSaison(): Column
{
return $this->prixMoisBasseSaison;
}
public function getPeriodesHauteSaison(): Column
{
return $this->periodesHauteSaison;
}
public function getPrixSemaineHauteSaison(): Column
{
return $this->prixSemaineHauteSaison;
}
public function getPrixQuinzaineHauteSaison(): Column
{
return $this->prixQuinzaineHauteSaison;
}
public function getPrixMoisHauteSaison(): Column
{
return $this->prixMoisHauteSaison;
}
public function getNbPersonnes(): Column
{
return $this->nbPersonnes;
}
public function getResidence(): Column
{
return $this->residence;
}
public function getTypeResidence(): Column
{
return $this->typeResidence;
}
public function toArray(): array
{
return [
$this->getPeriodesDispo(),
$this->getPeriodesBasseSaison(),
$this->getPrixSemaineBasseSaison(),
$this->getPrixQuinzaineBasseSaison(),
$this->getPrixMoisBasseSaison(),
$this->getPeriodesHauteSaison(),
$this->getPrixSemaineHauteSaison(),
$this->getPrixQuinzaineHauteSaison(),
$this->getPrixMoisHauteSaison(),
$this->getNbPersonnes(),
$this->getResidence(),
$this->getTypeResidence(),
];
}
}
<file_sep>/tests/Models/Annonce/PrixTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Prix;
class PrixTest extends TestCase
{
/**
* @test
*/
public function it_must_create_prix()
{
$prix = new Prix(
$p = 1,
$loyerMoisMur = 2,
$loyerCC = 3,
$loyerHT = 4,
$depotGarantie = 6,
$prixMasque = 7,
$prixHT = 8,
$copropriete = 9,
$nbLots = 10,
$syndicatCopro = 11,
$syndicatCoproDetails = 12,
$prixTerrain = 13,
$prixModeleMaison = 14,
$prixMin = 15,
$prixMax = 16
);
self::assertEquals($p, $prix->getPrix()->getVal());
self::assertEquals($loyerMoisMur, $prix->getLoyerMoisMur()->getVal());
self::assertEquals($loyerCC, $prix->getLoyerCC()->getVal());
self::assertEquals($loyerHT, $prix->getLoyerHT()->getVal());
self::assertEquals($depotGarantie, $prix->getDepotGarantie()->getVal());
self::assertEquals($prixMasque, $prix->getPrixMasque()->getVal());
self::assertEquals($prixHT, $prix->getPrixHT()->getVal());
self::assertEquals($copropriete, $prix->getCopropriete()->getVal());
self::assertEquals($nbLots, $prix->getNbLots()->getVal());
self::assertEquals($syndicatCopro, $prix->getSyndicatCopro()->getVal());
self::assertEquals($syndicatCoproDetails, $prix->getSyndicatCoproDetails()->getVal());
self::assertEquals($prixTerrain, $prix->getPrixTerrain()->getVal());
self::assertEquals($prixModeleMaison, $prix->getPrixModeleMaison()->getVal());
self::assertEquals($prixMin, $prix->getPrixMin()->getVal());
self::assertEquals($prixMax, $prix->getPrixMax()->getVal());
}
}
<file_sep>/README.md
PolirisBundle
=============
This bundle provide Poliris generation CSV.
Current version is V4.1.17.
[](https://packagist.org/packages/spiriitlabs/poliris-bundle)
[](https://github.com/spiriitlabs/poliris-bundle/actions/workflows/ci.yml)
[](https://github.com/spiriitlabs/poliris-bundle/actions/workflows/coding-standards.yml)
Installation
--------------
Add
[spiriitlabs/poliris-bundle](https://packagist.org/packages/spiriitlabs/poliris-bundle)
to your ``composer.json`` file:
```bash
$ php composer.phar require "spiriitlabs/poliris-bundle"
```
How to use
----------
A CSV Poliris is very long. More than 333 columns.
Here we propose to use the pattern Builder to create it.
Some classes:
-------------
The `Column` class represents a position in a CSV file by associating an index with a value:
```php
$column1 = new Column(1, 'Agence id'); // a string
$column2 = new Column(2, true); // OUI / NON
$column2 = new Column(2, new \DateTimeImmutable('2023-05-01')); // format d/m/Y
$column2 = new Column(2, object); // return toString on object
$column2 = new Column(2, 1); // 1
```
If a string is used, we remove spaces and EOL.
Exemple:
```php
beautiful house
with garage
```
is transformed into:
```
beautiful house with garage
```
After that we have a lot of classes, exemple "Exterieur"
If we look at the constructor:
```php
public function __construct(
$ascenseur,
$calme,
$piscine,
$vueDegagee,
$entree,
$visAVis,
$monteCharge
) {
$this->ascenseur = new Column(41, $ascenseur);
$this->calme = new Column(63, $calme);
$this->piscine = new Column(65, $piscine);
$this->vueDegagee = new Column(78, $vueDegagee);
$this->entree = new Column(189, $entree);
$this->visAVis = new Column(192, $visAVis);
$this->monteCharge = new Column(197, $monteCharge);
}
```
In this example, the CSV file contains data about Exterior features of a property, which are not sequentially
arranged in consecutive columns. To simplify the handling of this data, we decided to consolidate them using
the `Column` class.
Each property is represented by an instance of `Column`, where the index specifies the column position
in the CSV file, and the value holds the associated data. This approach allows for easier access to the exterior
features of the property, even if they are scattered throughout the CSV file.
There is 31 classes. [models](Models/Annonce/)
Usage
-----
```php
$builder = new AnnonceExportBuilder();
foreach ($lines as $line) {
try {
$this->createLine($builder, $line);
} catch (\Throwable $throwable) {
// log
}
}
return $builder->build();
```
```php
function createLine() {
$builder
->startLine()
->withIdentifiant(
'somewhere',
'agence_id',
Annonce::ANNONCE_TYPE_VENTE,
'REF_BA123'
)
->withType(
getType(),
getSubType()
)
```
Important - No validation
-------------------------
There is no validation on the data. Why? A CSV file can have several thousand rows, multiplied by approximately 300 columns, and PHP struggles to keep up.
Historically, there were validation classes using the Validator component, but it is too memory-intensive.
One solution would be to batch process the CSV and validate only a few rows at a time. However, that is not currently on the agenda.
<file_sep>/tests/Models/Annonce/LocationVacancesTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\LocationVacances;
class LocationVacancesTest extends TestCase
{
/**
* @test
*/
public function it_must_create_location_vacances()
{
$locationVacances = new LocationVacances(
$periodesDispo = 'periodes dispo',
$periodesBS = 'periodes bs',
$prixSemaineBS = 'prix semaine bs',
$prixQuinzaineBS = 'prix quinzaine bs',
$prixMoisBS = 'prix mois bs',
$periodesHS = 'periodes hs',
$prixSemaineHS = 'prix semaine hs',
$prixQuinzaineHS = 'prix quinzaine hs',
$prixMoisHS = 'prix mois hs',
$nbPersonnes = 1,
$residence = true,
$typeResidence = 'type'
);
self::assertEquals($periodesDispo, $locationVacances->getPeriodesDispo()->getVal());
self::assertEquals($periodesBS, $locationVacances->getPeriodesBasseSaison()->getVal());
self::assertEquals($prixSemaineBS, $locationVacances->getPrixSemaineBasseSaison()->getVal());
self::assertEquals($prixQuinzaineBS, $locationVacances->getPrixQuinzaineBasseSaison()->getVal());
self::assertEquals($prixMoisBS, $locationVacances->getPrixMoisBasseSaison()->getVal());
self::assertEquals($periodesHS, $locationVacances->getPeriodesHauteSaison()->getVal());
self::assertEquals($prixSemaineHS, $locationVacances->getPrixSemaineHauteSaison()->getVal());
self::assertEquals($prixQuinzaineHS, $locationVacances->getPrixQuinzaineHauteSaison()->getVal());
self::assertEquals($prixMoisHS, $locationVacances->getPrixMoisHauteSaison()->getVal());
self::assertEquals($nbPersonnes, $locationVacances->getNbPersonnes()->getVal());
self::assertEquals($residence, $locationVacances->getResidence()->getVal());
self::assertEquals($typeResidence, $locationVacances->getTypeResidence()->getVal());
$expectedArray = [
$locationVacances->getPeriodesDispo(),
$locationVacances->getPeriodesBasseSaison(),
$locationVacances->getPrixSemaineBasseSaison(),
$locationVacances->getPrixQuinzaineBasseSaison(),
$locationVacances->getPrixMoisBasseSaison(),
$locationVacances->getPeriodesHauteSaison(),
$locationVacances->getPrixSemaineHauteSaison(),
$locationVacances->getPrixQuinzaineHauteSaison(),
$locationVacances->getPrixMoisHauteSaison(),
$locationVacances->getNbPersonnes(),
$locationVacances->getResidence(),
$locationVacances->getTypeResidence(),
];
self::assertEquals($expectedArray, $locationVacances->toArray());
}
}
<file_sep>/tests/Models/AnnonceExportTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Annonce;
use Spiriit\PolirisBundle\Models\Annonce\Boutique;
use Spiriit\PolirisBundle\Models\Annonce\Bureau;
use Spiriit\PolirisBundle\Models\Annonce\ChampCustom;
use Spiriit\PolirisBundle\Models\Annonce\ChauffageClim;
use Spiriit\PolirisBundle\Models\Annonce\Contact;
use Spiriit\PolirisBundle\Models\Annonce\Detail;
use Spiriit\PolirisBundle\Models\Annonce\Diagnostic;
use Spiriit\PolirisBundle\Models\Annonce\Etage;
use Spiriit\PolirisBundle\Models\Annonce\Exterieur;
use Spiriit\PolirisBundle\Models\Annonce\FondsCommerce;
use Spiriit\PolirisBundle\Models\Annonce\Garage;
use Spiriit\PolirisBundle\Models\Annonce\HonoraireCharge;
use Spiriit\PolirisBundle\Models\Annonce\Identifiant;
use Spiriit\PolirisBundle\Models\Annonce\Interieur;
use Spiriit\PolirisBundle\Models\Annonce\Langue;
use Spiriit\PolirisBundle\Models\Annonce\Localisation;
use Spiriit\PolirisBundle\Models\Annonce\Location;
use Spiriit\PolirisBundle\Models\Annonce\LocationVacances;
use Spiriit\PolirisBundle\Models\Annonce\Mandat;
use Spiriit\PolirisBundle\Models\Annonce\Parking;
use Spiriit\PolirisBundle\Models\Annonce\PartieJour;
use Spiriit\PolirisBundle\Models\Annonce\Photo;
use Spiriit\PolirisBundle\Models\Annonce\Prix;
use Spiriit\PolirisBundle\Models\Annonce\ProduitInvestissement;
use Spiriit\PolirisBundle\Models\Annonce\Publication;
use Spiriit\PolirisBundle\Models\Annonce\Securite;
use Spiriit\PolirisBundle\Models\Annonce\Surface;
use Spiriit\PolirisBundle\Models\Annonce\Terrain;
use Spiriit\PolirisBundle\Models\Annonce\Type;
use Spiriit\PolirisBundle\Models\Annonce\Viager;
use Spiriit\PolirisBundle\Models\AnnonceExport;
class AnnonceExportTest extends TestCase
{
/**
* @test
*/
public function it_must_create_annonce_export()
{
$annonceExport = new AnnonceExport();
$annonce = new Annonce();
$identifiant = new Identifiant(null, 'ref', 'type', 'id_tech');
$annonce->setIdentifiant($identifiant);
$type = new Type('type', 'sous_type');
$annonce->setType($type);
$photo = new Photo(
'https://url.photo_1',
'https://url.photo_2',
'https://url.photo_3',
'https://url.photo_4',
'https://url.photo_5',
'https://url.photo_6',
'https://url.photo_7',
'https://url.photo_8',
'https://url.photo_9',
'https://url.photo_10',
'https://url.photo_11',
'https://url.photo_12',
'https://url.photo_13',
'https://url.photo_14',
'https://url.photo_15',
'https://url.photo_16',
'https://url.photo_17',
'https://url.photo_18',
'https://url.photo_19',
'https://url.photo_20',
'https://url.photo_21',
'https://url.photo_22',
'https://url.photo_23',
'https://url.photo_24',
'https://url.photo_25',
'https://url.photo_26',
'https://url.photo_27',
'https://url.photo_28',
'https://url.photo_29',
'https://url.photo_30',
'titre 1',
'titre 2',
'titre 3',
'titre 4',
'titre 5',
'titre 6',
'titre 7',
'titre 8',
'titre 9',
'titre 10',
'titre 11',
'titre 12',
'titre 13',
'titre 14',
'titre 15',
'titre 16',
'titre 17',
'titre 18',
'titre 19',
'titre 20',
'titre 21',
'titre 22',
'titre 23',
'titre 24',
'titre 25',
'titre 26',
'titre 27',
'titre 28',
'titre 29',
'titre 30',
'panorama',
'visite'
);
$annonce->setPhoto($photo);
$champCustom = new ChampCustom(
'champ 1',
'champ 2',
'champ 3',
'champ 4',
'champ 5',
'champ 6',
'champ 7',
'champ 8',
'champ 9',
'champ 10',
'champ 11',
'champ 12',
'champ 13',
'champ 14',
'champ 15',
'champ 16',
'champ 17',
'champ 18',
'champ 19',
'champ 20',
'champ 21',
'champ 22',
'champ 23',
'champ 24',
'champ 25',
'champ 26',
);
$annonce->setChampCustom($champCustom);
$langue = new Langue(
'code',
'code',
'code',
'prox',
'prox',
'prox',
'label',
'label',
'label',
'desc',
'desc',
'desc',
);
$annonce->setLangue($langue);
$mandat = new Mandat(
true,
'01',
new \DateTimeImmutable(),
'nom',
'prenom',
'raison',
'adresse',
'34000',
'Montpellier',
'0123456789',
'commentaire'
);
$annonce->setMandat($mandat);
$locationVacances = new LocationVacances(
'periodes dispo',
'periodes bs',
'prix semaine bs',
'prix quinzaine bs',
'prix mois bs',
'periodes hs',
'prix semaine hs',
'prix quinzaine hs',
'prix mois hs',
1,
true,
'type'
);
$annonce->setLocationVacances($locationVacances);
$viager = new Viager(
2000,
500,
50,
52,
true,
);
$annonce->setViager($viager);
$terrain = new Terrain(
true,
true,
true,
true,
100,
true,
true
);
$annonce->setTerrain($terrain);
$bureau = new Bureau(
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
true,
11,
12,
'conditions',
'prestations',
true,
13
);
$annonce->setBureau($bureau);
$diagnostic = new Diagnostic(
true,
false,
1,
'D',
3,
'E',
new \DateTimeImmutable(),
'1',
0,
10,
'2021',
null
);
$annonce->setDiagnostic($diagnostic);
$parking = new Parking(1, true, false);
$annonce->setParking($parking);
$boutique = new Boutique(true, 'situation');
$annonce->setBoutique($boutique);
$prix = new Prix(
1,
2,
3,
4,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
);
$annonce->setPrix($prix);
$location = new Location(
1,
2,
3,
'location meublée',
4,
10,
15,
20
);
$annonce->setLocation($location);
$produitInvestissement = new ProduitInvestissement(
1,
2,
);
$annonce->setProduitInvestissement($produitInvestissement);
$fondsCommerce = new FondsCommerce(
1,
'70 % bar / 30 % restaurant',
'Tous commerces sauf restauration',
2,
3,
4,
5,
6,
);
$annonce->setFondsCommerce($fondsCommerce);
$honoraireCharge = new HonoraireCharge(
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
);
$annonce->setHonoraireCharge($honoraireCharge);
$localisation = new Localisation(
'34000',
'MTP',
'France',
'425 Rue <NAME>',
'Commerces',
'ville',
false,
false,
false,
'34000',
'MONTPELLIER',
null,
'8',
'Opera',
22.1,
23.4,
1,
'75,92,93,94,95'
);
$annonce->setLocalisation($localisation);
$surface = new Surface(
1,
2,
3,
4,
5,
6,
7,
8,
9,
26,
10,
true,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
false,
24,
25
);
$annonce->setSurface($surface);
$contact = new Contact(
'0123456789',
'<NAME>',
'<EMAIL>',
true,
false,
'MARTIN',
'Agence'
);
$annonce->setContact($contact);
$etage = new Etage(
0,
1,
3
);
$annonce->setEtage($etage);
$interieur = new Interieur(
true,
'1985',
true,
false,
true,
false,
false,
false,
true,
1,
2,
3,
false,
true,
false,
true,
false,
false,
false,
true,
true
);
$annonce->setInterieur($interieur);
$partieJour = new PartieJour(
'type',
false,
true,
false,
true,
false,
true,
false,
true
);
$annonce->setPartieJour($partieJour);
$exterieur = new Exterieur(
true,
false,
true,
false,
true,
false,
true
);
$annonce->setExterieur($exterieur);
$garage = new Garage(
true,
1
);
$annonce->setGarage($garage);
$securite = new Securite(
true,
false,
true,
false
);
$annonce->setSecurite($securite);
$chauffageClim = new ChauffageClim(1, true);
$annonce->setChauffageClim($chauffageClim);
$detail = new Detail(
'<NAME>',
'Maison 3 pièces',
'Très belle maison',
new \DateTimeImmutable(),
true,
false,
true,
'Clefs à prendre chez le gardien',
false,
'Tradition'
);
$annonce->setDetail($detail);
$publication = new Publication(
'SL,BD,WA',
true,
'4.11'
);
$annonce->setPublication($publication);
$annonceExport->addLine($annonce);
self::assertCount(1, $annonceExport->getAnnonces());
$expectedArray = [
[
$identifiant->getAgenceId()->getPos() => $identifiant->getAgenceId()->getTransformedVal(),
$identifiant->getAnnonceType()->getPos() => $identifiant->getAnnonceType()->getTransformedVal(),
$identifiant->getAnnonceIdTechnique()->getPos() => $identifiant->getAnnonceIdTechnique(
)->getTransformedVal(),
$identifiant->getAgencePropertyRef()->getPos() => $identifiant->getAgencePropertyRef(
)->getTransformedVal(),
$type->getType()->getPos() => $type->getType()->getTransformedVal(),
$type->getSousType()->getPos() => $type->getSousType()->getTransformedVal(),
$photo->getPhoto1()->getPos() => $photo->getPhoto1()->getTransformedVal(),
$photo->getPhoto2()->getPos() => $photo->getPhoto2()->getTransformedVal(),
$photo->getPhoto3()->getPos() => $photo->getPhoto3()->getTransformedVal(),
$photo->getPhoto4()->getPos() => $photo->getPhoto4()->getTransformedVal(),
$photo->getPhoto5()->getPos() => $photo->getPhoto5()->getTransformedVal(),
$photo->getPhoto6()->getPos() => $photo->getPhoto6()->getTransformedVal(),
$photo->getPhoto7()->getPos() => $photo->getPhoto7()->getTransformedVal(),
$photo->getPhoto8()->getPos() => $photo->getPhoto8()->getTransformedVal(),
$photo->getPhoto9()->getPos() => $photo->getPhoto9()->getTransformedVal(),
$photo->getPhoto10()->getPos() => $photo->getPhoto10()->getTransformedVal(),
$photo->getPhoto11()->getPos() => $photo->getPhoto11()->getTransformedVal(),
$photo->getPhoto12()->getPos() => $photo->getPhoto12()->getTransformedVal(),
$photo->getPhoto13()->getPos() => $photo->getPhoto13()->getTransformedVal(),
$photo->getPhoto14()->getPos() => $photo->getPhoto14()->getTransformedVal(),
$photo->getPhoto15()->getPos() => $photo->getPhoto15()->getTransformedVal(),
$photo->getPhoto16()->getPos() => $photo->getPhoto16()->getTransformedVal(),
$photo->getPhoto17()->getPos() => $photo->getPhoto17()->getTransformedVal(),
$photo->getPhoto18()->getPos() => $photo->getPhoto18()->getTransformedVal(),
$photo->getPhoto19()->getPos() => $photo->getPhoto19()->getTransformedVal(),
$photo->getPhoto20()->getPos() => $photo->getPhoto20()->getTransformedVal(),
$photo->getPhoto21()->getPos() => $photo->getPhoto21()->getTransformedVal(),
$photo->getPhoto22()->getPos() => $photo->getPhoto22()->getTransformedVal(),
$photo->getPhoto23()->getPos() => $photo->getPhoto23()->getTransformedVal(),
$photo->getPhoto24()->getPos() => $photo->getPhoto24()->getTransformedVal(),
$photo->getPhoto25()->getPos() => $photo->getPhoto25()->getTransformedVal(),
$photo->getPhoto26()->getPos() => $photo->getPhoto26()->getTransformedVal(),
$photo->getPhoto27()->getPos() => $photo->getPhoto27()->getTransformedVal(),
$photo->getPhoto28()->getPos() => $photo->getPhoto28()->getTransformedVal(),
$photo->getPhoto29()->getPos() => $photo->getPhoto29()->getTransformedVal(),
$photo->getPhoto30()->getPos() => $photo->getPhoto30()->getTransformedVal(),
$photo->getTitre1()->getPos() => $photo->getTitre1()->getTransformedVal(),
$photo->getTitre2()->getPos() => $photo->getTitre2()->getTransformedVal(),
$photo->getTitre3()->getPos() => $photo->getTitre3()->getTransformedVal(),
$photo->getTitre4()->getPos() => $photo->getTitre4()->getTransformedVal(),
$photo->getTitre5()->getPos() => $photo->getTitre5()->getTransformedVal(),
$photo->getTitre6()->getPos() => $photo->getTitre6()->getTransformedVal(),
$photo->getTitre7()->getPos() => $photo->getTitre7()->getTransformedVal(),
$photo->getTitre8()->getPos() => $photo->getTitre8()->getTransformedVal(),
$photo->getTitre9()->getPos() => $photo->getTitre9()->getTransformedVal(),
$photo->getTitre10()->getPos() => $photo->getTitre10()->getTransformedVal(),
$photo->getTitre11()->getPos() => $photo->getTitre11()->getTransformedVal(),
$photo->getTitre12()->getPos() => $photo->getTitre12()->getTransformedVal(),
$photo->getTitre13()->getPos() => $photo->getTitre13()->getTransformedVal(),
$photo->getTitre14()->getPos() => $photo->getTitre14()->getTransformedVal(),
$photo->getTitre15()->getPos() => $photo->getTitre15()->getTransformedVal(),
$photo->getTitre16()->getPos() => $photo->getTitre16()->getTransformedVal(),
$photo->getTitre17()->getPos() => $photo->getTitre17()->getTransformedVal(),
$photo->getTitre18()->getPos() => $photo->getTitre18()->getTransformedVal(),
$photo->getTitre19()->getPos() => $photo->getTitre19()->getTransformedVal(),
$photo->getTitre20()->getPos() => $photo->getTitre20()->getTransformedVal(),
$photo->getTitre21()->getPos() => $photo->getTitre21()->getTransformedVal(),
$photo->getTitre22()->getPos() => $photo->getTitre22()->getTransformedVal(),
$photo->getTitre23()->getPos() => $photo->getTitre23()->getTransformedVal(),
$photo->getTitre24()->getPos() => $photo->getTitre24()->getTransformedVal(),
$photo->getTitre25()->getPos() => $photo->getTitre25()->getTransformedVal(),
$photo->getTitre26()->getPos() => $photo->getTitre26()->getTransformedVal(),
$photo->getTitre27()->getPos() => $photo->getTitre27()->getTransformedVal(),
$photo->getTitre28()->getPos() => $photo->getTitre28()->getTransformedVal(),
$photo->getTitre29()->getPos() => $photo->getTitre29()->getTransformedVal(),
$photo->getTitre30()->getPos() => $photo->getTitre30()->getTransformedVal(),
$photo->getPhotoPanoramique()->getPos() => $photo->getPhotoPanoramique()->getTransformedVal(),
$photo->getUrlVisiteVirtuelle()->getPos() => $photo->getUrlVisiteVirtuelle()->getTransformedVal(),
$champCustom->getChamp1()->getPos() => $champCustom->getChamp1()->getTransformedVal(),
$champCustom->getChamp2()->getPos() => $champCustom->getChamp2()->getTransformedVal(),
$champCustom->getChamp3()->getPos() => $champCustom->getChamp3()->getTransformedVal(),
$champCustom->getChamp4()->getPos() => $champCustom->getChamp4()->getTransformedVal(),
$champCustom->getChamp5()->getPos() => $champCustom->getChamp5()->getTransformedVal(),
$champCustom->getChamp6()->getPos() => $champCustom->getChamp6()->getTransformedVal(),
$champCustom->getChamp7()->getPos() => $champCustom->getChamp7()->getTransformedVal(),
$champCustom->getChamp8()->getPos() => $champCustom->getChamp8()->getTransformedVal(),
$champCustom->getChamp9()->getPos() => $champCustom->getChamp9()->getTransformedVal(),
$champCustom->getChamp10()->getPos() => $champCustom->getChamp10()->getTransformedVal(),
$champCustom->getChamp11()->getPos() => $champCustom->getChamp11()->getTransformedVal(),
$champCustom->getChamp12()->getPos() => $champCustom->getChamp12()->getTransformedVal(),
$champCustom->getChamp13()->getPos() => $champCustom->getChamp13()->getTransformedVal(),
$champCustom->getChamp14()->getPos() => $champCustom->getChamp14()->getTransformedVal(),
$champCustom->getChamp15()->getPos() => $champCustom->getChamp15()->getTransformedVal(),
$champCustom->getChamp16()->getPos() => $champCustom->getChamp16()->getTransformedVal(),
$champCustom->getChamp17()->getPos() => $champCustom->getChamp17()->getTransformedVal(),
$champCustom->getChamp18()->getPos() => $champCustom->getChamp18()->getTransformedVal(),
$champCustom->getChamp19()->getPos() => $champCustom->getChamp19()->getTransformedVal(),
$champCustom->getChamp20()->getPos() => $champCustom->getChamp20()->getTransformedVal(),
$champCustom->getChamp21()->getPos() => $champCustom->getChamp21()->getTransformedVal(),
$champCustom->getChamp22()->getPos() => $champCustom->getChamp22()->getTransformedVal(),
$champCustom->getChamp23()->getPos() => $champCustom->getChamp23()->getTransformedVal(),
$champCustom->getChamp24()->getPos() => $champCustom->getChamp24()->getTransformedVal(),
$champCustom->getChamp25()->getPos() => $champCustom->getChamp25()->getTransformedVal(),
$champCustom->getChamp26()->getPos() => $champCustom->getChamp26()->getTransformedVal(),
$langue->getCode1()->getPos() => $langue->getCode1()->getTransformedVal(),
$langue->getCode2()->getPos() => $langue->getCode2()->getTransformedVal(),
$langue->getCode3()->getPos() => $langue->getCode3()->getTransformedVal(),
$langue->getProximite1()->getPos() => $langue->getProximite1()->getTransformedVal(),
$langue->getProximite2()->getPos() => $langue->getProximite2()->getTransformedVal(),
$langue->getProximite3()->getPos() => $langue->getProximite3()->getTransformedVal(),
$langue->getLabel1()->getPos() => $langue->getLabel1()->getTransformedVal(),
$langue->getLabel2()->getPos() => $langue->getLabel2()->getTransformedVal(),
$langue->getLabel3()->getPos() => $langue->getLabel3()->getTransformedVal(),
$langue->getDescriptif1()->getPos() => $langue->getDescriptif1()->getTransformedVal(),
$langue->getDescriptif2()->getPos() => $langue->getDescriptif2()->getTransformedVal(),
$langue->getDescriptif3()->getPos() => $langue->getDescriptif3()->getTransformedVal(),
$mandat->getExclusif()->getPos() => $mandat->getExclusif()->getTransformedVal(),
$mandat->getNumero()->getPos() => $mandat->getNumero()->getTransformedVal(),
$mandat->getDate()->getPos() => $mandat->getDate()->getTransformedVal(),
$mandat->getNomMandataire()->getPos() => $mandat->getNomMandataire()->getTransformedVal(),
$mandat->getPrenomMandataire()->getPos() => $mandat->getPrenomMandataire()->getTransformedVal(),
$mandat->getRaisonSocialeMandataire()->getPos() => $mandat->getRaisonSocialeMandataire(
)->getTransformedVal(),
$mandat->getAdresseMandataire()->getPos() => $mandat->getAdresseMandataire()->getTransformedVal(),
$mandat->getCodePostalMandataire()->getPos() => $mandat->getCodePostalMandataire()->getTransformedVal(),
$mandat->getVilleMandataire()->getPos() => $mandat->getVilleMandataire()->getTransformedVal(),
$mandat->getTelMandataire()->getPos() => $mandat->getTelMandataire()->getTransformedVal(),
$mandat->getCommMandataire()->getPos() => $mandat->getCommMandataire()->getTransformedVal(),
$locationVacances->getPeriodesDispo()->getPos() => $locationVacances->getPeriodesDispo(
)->getTransformedVal(),
$locationVacances->getPeriodesBasseSaison()->getPos() => $locationVacances->getPeriodesBasseSaison(
)->getTransformedVal(),
$locationVacances->getPrixSemaineBasseSaison()->getPos(
) => $locationVacances->getPrixSemaineBasseSaison()->getTransformedVal(),
$locationVacances->getPrixQuinzaineBasseSaison()->getPos(
) => $locationVacances->getPrixQuinzaineBasseSaison()->getTransformedVal(),
$locationVacances->getPrixMoisBasseSaison()->getPos() => $locationVacances->getPrixMoisBasseSaison(
)->getTransformedVal(),
$locationVacances->getPeriodesHauteSaison()->getPos() => $locationVacances->getPeriodesHauteSaison(
)->getTransformedVal(),
$locationVacances->getPrixSemaineHauteSaison()->getPos(
) => $locationVacances->getPrixSemaineHauteSaison()->getTransformedVal(),
$locationVacances->getPrixQuinzaineHauteSaison()->getPos(
) => $locationVacances->getPrixQuinzaineHauteSaison()->getTransformedVal(),
$locationVacances->getPrixMoisHauteSaison()->getPos() => $locationVacances->getPrixMoisHauteSaison(
)->getTransformedVal(),
$locationVacances->getNbPersonnes()->getPos() => $locationVacances->getNbPersonnes()->getTransformedVal(
),
$locationVacances->getResidence()->getPos() => $locationVacances->getResidence()->getTransformedVal(),
$locationVacances->getTypeResidence()->getPos() => $locationVacances->getTypeResidence(
)->getTransformedVal(),
$viager->getPrixBouquet()->getPos() => $viager->getPrixBouquet()->getTransformedVal(),
$viager->getRenteMensuelle()->getPos() => $viager->getRenteMensuelle()->getTransformedVal(),
$viager->getAgeHomme()->getPos() => $viager->getAgeHomme()->getTransformedVal(),
$viager->getAgeFemme()->getPos() => $viager->getAgeFemme()->getTransformedVal(),
$viager->getVenduLibre()->getPos() => $viager->getVenduLibre()->getTransformedVal(),
$terrain->getAgricole()->getPos() => $terrain->getAgricole()->getTransformedVal(),
$terrain->getConstructible()->getPos() => $terrain->getConstructible()->getTransformedVal(),
$terrain->getPente()->getPos() => $terrain->getPente()->getTransformedVal(),
$terrain->getPlanEau()->getPos() => $terrain->getPlanEau()->getTransformedVal(),
$terrain->getViabilise()->getPos() => $terrain->getViabilise()->getTransformedVal(),
$terrain->getDonneSurLaRue()->getPos() => $terrain->getDonneSurLaRue()->getTransformedVal(),
$terrain->getLongueurFacade()->getPos() => $terrain->getLongueurFacade()->getTransformedVal(),
$bureau->getLoyerAnnuelGlobal()->getPos() => $bureau->getLoyerAnnuelGlobal()->getTransformedVal(),
$bureau->getLoyerAnnuelM2()->getPos() => $bureau->getLoyerAnnuelM2()->getTransformedVal(),
$bureau->getLoyerAnnuelCC()->getPos() => $bureau->getLoyerAnnuelCC()->getTransformedVal(),
$bureau->getLoyerAnnuelM2CC()->getPos() => $bureau->getLoyerAnnuelM2CC()->getTransformedVal(),
$bureau->getLoyerAnnuelHT()->getPos() => $bureau->getLoyerAnnuelHT()->getTransformedVal(),
$bureau->getLoyerAnnuelM2HT()->getPos() => $bureau->getLoyerAnnuelM2HT()->getTransformedVal(),
$bureau->getChargesAnnuellesGlobales()->getPos() => $bureau->getChargesAnnuellesGlobales(
)->getTransformedVal(),
$bureau->getChargesAnnuellesM2()->getPos() => $bureau->getChargesAnnuellesM2()->getTransformedVal(),
$bureau->getChargesMensuellesHT()->getPos() => $bureau->getChargesMensuellesHT()->getTransformedVal(),
$bureau->getChargesAnnuellesM2HT()->getPos() => $bureau->getChargesAnnuellesM2HT()->getTransformedVal(),
$bureau->getChargesAnnuellesHT()->getPos() => $bureau->getChargesAnnuellesHT()->getTransformedVal(),
$bureau->getDivisible()->getPos() => $bureau->getDivisible()->getTransformedVal(),
$bureau->getSurfaceDivisibleMin()->getPos() => $bureau->getSurfaceDivisibleMin()->getTransformedVal(),
$bureau->getSurfaceDivisibleMax()->getPos() => $bureau->getSurfaceDivisibleMax()->getTransformedVal(),
$bureau->getConditionsFinancieres()->getPos() => $bureau->getConditionsFinancieres()->getTransformedVal(
),
$bureau->getPrestationsDiverses()->getPos() => $bureau->getPrestationsDiverses()->getTransformedVal(),
$bureau->getImmeubleBureaux()->getPos() => $bureau->getImmeubleBureaux()->getTransformedVal(),
$bureau->getSurfaceMaxBureau()->getPos() => $bureau->getSurfaceMaxBureau()->getTransformedVal(),
$diagnostic->getRecent()->getPos() => $diagnostic->getRecent()->getTransformedVal(),
$diagnostic->getTravaux()->getPos() => $diagnostic->getTravaux()->getTransformedVal(),
$diagnostic->getConsoEnergie()->getPos() => $diagnostic->getConsoEnergie()->getTransformedVal(),
$diagnostic->getBilanConsoEnergie()->getPos() => $diagnostic->getBilanConsoEnergie()->getTransformedVal(
),
$diagnostic->getGes()->getPos() => $diagnostic->getGes()->getTransformedVal(),
$diagnostic->getBilanGes()->getPos() => $diagnostic->getBilanGes()->getTransformedVal(),
$diagnostic->getDpeAt()->getPos() => $diagnostic->getDpeAt()->getTransformedVal(),
$diagnostic->getDpeVersion()->getPos() => $diagnostic->getDpeVersion()->getTransformedVal(),
$diagnostic->getDpeMin()->getPos() => $diagnostic->getDpeMin()->getTransformedVal(),
$diagnostic->getDpeMax()->getPos() => $diagnostic->getDpeMax()->getTransformedVal(),
$diagnostic->getDpeAnneeRef()->getPos() => $diagnostic->getDpeAnneeRef()->getTransformedVal(),
$diagnostic->getDpeCoutConsoAnnuelle()->getPos() => $diagnostic->getDpeCoutConsoAnnuelle(
)->getTransformedVal(),
$parking->getNbVehicules()->getPos() => $parking->getNbVehicules()->getTransformedVal(),
$parking->getImmeuble()->getPos() => $parking->getImmeuble()->getTransformedVal(),
$parking->getIsole()->getPos() => $parking->getIsole()->getTransformedVal(),
$boutique->getQuai()->getPos() => $boutique->getQuai()->getTransformedVal(),
$boutique->getSituationCommerciale()->getPos() => $boutique->getSituationCommerciale(
)->getTransformedVal(),
$prix->getPrix()->getPos() => $prix->getPrix()->getTransformedVal(),
$prix->getLoyerMoisMur()->getPos() => $prix->getLoyerMoisMur()->getTransformedVal(),
$prix->getLoyerCC()->getPos() => $prix->getLoyerCC()->getTransformedVal(),
$prix->getLoyerHT()->getPos() => $prix->getLoyerHT()->getTransformedVal(),
$prix->getDepotGarantie()->getPos() => $prix->getDepotGarantie()->getTransformedVal(),
$prix->getPrixMasque()->getPos() => $prix->getPrixMasque()->getTransformedVal(),
$prix->getPrixHT()->getPos() => $prix->getPrixHT()->getTransformedVal(),
$prix->getCopropriete()->getPos() => $prix->getCopropriete()->getTransformedVal(),
$prix->getNbLots()->getPos() => $prix->getNbLots()->getTransformedVal(),
$prix->getSyndicatCopro()->getPos() => $prix->getSyndicatCopro()->getTransformedVal(),
$prix->getSyndicatCoproDetails()->getPos() => $prix->getSyndicatCoproDetails()->getTransformedVal(),
$prix->getPrixTerrain()->getPos() => $prix->getPrixTerrain()->getTransformedVal(),
$prix->getPrixModeleMaison()->getPos() => $prix->getPrixModeleMaison()->getTransformedVal(),
$prix->getPrixMin()->getPos() => $prix->getPrixMin()->getTransformedVal(),
$prix->getPrixMax()->getPos() => $prix->getPrixMax()->getTransformedVal(),
$location->getDureeBail()->getPos() => $location->getDureeBail()->getTransformedVal(),
$location->getPrixDroitEntree()->getPos() => $location->getPrixDroitEntree()->getTransformedVal(),
$location->getPrixDroitBail()->getPos() => $location->getPrixDroitBail()->getTransformedVal(),
$location->getNatureBail()->getPos() => $location->getNatureBail()->getTransformedVal(),
$location->getComplementLoyer()->getPos() => $location->getComplementLoyer()->getTransformedVal(),
$location->getLoyerBase()->getPos() => $location->getLoyerBase()->getTransformedVal(),
$location->getLoyerReferenceMajore()->getPos() => $location->getLoyerReferenceMajore(
)->getTransformedVal(),
$location->getEncadrementLoyers()->getPos() => $location->getEncadrementLoyers()->getTransformedVal(),
$produitInvestissement->getValeurAchat()->getPos() => $produitInvestissement->getValeurAchat(
)->getTransformedVal(),
$produitInvestissement->getMontantRapport()->getPos() => $produitInvestissement->getMontantRapport(
)->getTransformedVal(),
$fondsCommerce->getCa()->getPos() => $fondsCommerce->getCa()->getTransformedVal(),
$fondsCommerce->getRepartitionCa()->getPos() => $fondsCommerce->getRepartitionCa()->getTransformedVal(),
$fondsCommerce->getNatureBailCommercial()->getPos() => $fondsCommerce->getNatureBailCommercial(
)->getTransformedVal(),
$fondsCommerce->getResultatAnneeN2()->getPos() => $fondsCommerce->getResultatAnneeN2(
)->getTransformedVal(),
$fondsCommerce->getResultatAnneeN1()->getPos() => $fondsCommerce->getResultatAnneeN1(
)->getTransformedVal(),
$fondsCommerce->getResultatActuel()->getPos() => $fondsCommerce->getResultatActuel()->getTransformedVal(
),
$fondsCommerce->getCaAnneeN2()->getPos() => $fondsCommerce->getCaAnneeN2()->getTransformedVal(),
$fondsCommerce->getCaAnneeN1()->getPos() => $fondsCommerce->getCaAnneeN1()->getTransformedVal(),
$honoraireCharge->getHonoraires()->getPos() => $honoraireCharge->getHonoraires()->getTransformedVal(),
$honoraireCharge->getHonorairesCharge()->getPos() => $honoraireCharge->getHonorairesCharge(
)->getTransformedVal(),
$honoraireCharge->getCharges()->getPos() => $honoraireCharge->getCharges()->getTransformedVal(),
$honoraireCharge->getUrlBaremeHonorairesAgence()->getPos(
) => $honoraireCharge->getUrlBaremeHonorairesAgence()->getTransformedVal(),
$honoraireCharge->getPartHonorairesEtatLieux()->getPos(
) => $honoraireCharge->getPartHonorairesEtatLieux()->getTransformedVal(),
$honoraireCharge->getPrixHorsHonorairesAcquereur()->getPos(
) => $honoraireCharge->getPrixHorsHonorairesAcquereur()->getTransformedVal(),
$honoraireCharge->getHonorairesChargeAcquereur()->getPos(
) => $honoraireCharge->getHonorairesChargeAcquereur()->getTransformedVal(),
$honoraireCharge->getPourcentageHonorairesTTC()->getPos(
) => $honoraireCharge->getPourcentageHonorairesTTC()->getTransformedVal(),
$honoraireCharge->getModalitesChargesLocataire()->getPos(
) => $honoraireCharge->getModalitesChargesLocataire()->getTransformedVal(),
$honoraireCharge->getChargesAnnuelles()->getPos() => $honoraireCharge->getChargesAnnuelles(
)->getTransformedVal(),
$localisation->getCp()->getPos() => $localisation->getCp()->getTransformedVal(),
$localisation->getVille()->getPos() => $localisation->getVille()->getTransformedVal(),
$localisation->getPays()->getPos() => $localisation->getPays()->getTransformedVal(),
$localisation->getAdresse()->getPos() => $localisation->getAdresse()->getTransformedVal(),
$localisation->getQuartierProximite()->getPos() => $localisation->getQuartierProximite(
)->getTransformedVal(),
$localisation->getSituation()->getPos() => $localisation->getSituation()->getTransformedVal(),
$localisation->getProcheLac()->getPos() => $localisation->getProcheLac()->getTransformedVal(),
$localisation->getProcheTennis()->getPos() => $localisation->getProcheTennis()->getTransformedVal(),
$localisation->getProcheSki()->getPos() => $localisation->getProcheSki()->getTransformedVal(),
$localisation->getCpReel()->getPos() => $localisation->getCpReel()->getTransformedVal(),
$localisation->getVilleReelle()->getPos() => $localisation->getVilleReelle()->getTransformedVal(),
$localisation->getIdQuartier()->getPos() => $localisation->getIdQuartier()->getTransformedVal(),
$localisation->getTransportLigne()->getPos() => $localisation->getTransportLigne()->getTransformedVal(),
$localisation->getTransportStation()->getPos() => $localisation->getTransportStation(
)->getTransformedVal(),
$localisation->getLatitude()->getPos() => $localisation->getLatitude()->getTransformedVal(),
$localisation->getLongitude()->getPos() => $localisation->getLongitude()->getTransformedVal(),
$localisation->getPrecisionGps()->getPos() => $localisation->getPrecisionGps()->getTransformedVal(),
$localisation->getLocalisation()->getPos() => $localisation->getLocalisation()->getTransformedVal(),
$surface->getSurface()->getPos() => $surface->getSurface()->getTransformedVal(),
$surface->getSurfaceTerrain()->getPos() => $surface->getSurfaceTerrain()->getTransformedVal(),
$surface->getNbPieces()->getPos() => $surface->getNbPieces()->getTransformedVal(),
$surface->getNbChambres()->getPos() => $surface->getNbChambres()->getTransformedVal(),
$surface->getNbSdb()->getPos() => $surface->getNbSdb()->getTransformedVal(),
$surface->getNbSalleEau()->getPos() => $surface->getNbSalleEau()->getTransformedVal(),
$surface->getNbWc()->getPos() => $surface->getNbWc()->getTransformedVal(),
$surface->getNbBalcons()->getPos() => $surface->getNbBalcons()->getTransformedVal(),
$surface->getSurfaceBalcon()->getPos() => $surface->getSurfaceBalcon()->getTransformedVal(),
$surface->getNbParkings()->getPos() => $surface->getNbParkings()->getTransformedVal(),
$surface->getNbBoxes()->getPos() => $surface->getNbBoxes()->getTransformedVal(),
$surface->getTerrasse()->getPos() => $surface->getTerrasse()->getTransformedVal(),
$surface->getLongueurFacade()->getPos() => $surface->getLongueurFacade()->getTransformedVal(),
$surface->getPlacesEnSalle()->getPos() => $surface->getPlacesEnSalle()->getTransformedVal(),
$surface->getNbBureaux()->getPos() => $surface->getNbBureaux()->getTransformedVal(),
$surface->getSurfaceSejour()->getPos() => $surface->getSurfaceSejour()->getTransformedVal(),
$surface->getNbTerrasses()->getPos() => $surface->getNbTerrasses()->getTransformedVal(),
$surface->getSurfaceCave()->getPos() => $surface->getSurfaceCave()->getTransformedVal(),
$surface->getSurfaceSalleManger()->getPos() => $surface->getSurfaceSalleManger()->getTransformedVal(),
$surface->getSurfaceMin()->getPos() => $surface->getSurfaceMin()->getTransformedVal(),
$surface->getSurfaceMax()->getPos() => $surface->getSurfaceMax()->getTransformedVal(),
$surface->getNbPiecesMin()->getPos() => $surface->getNbPiecesMin()->getTransformedVal(),
$surface->getNbPiecesMax()->getPos() => $surface->getNbPiecesMax()->getTransformedVal(),
$surface->getNbChambresMin()->getPos() => $surface->getNbChambresMin()->getTransformedVal(),
$surface->getNbChambresMax()->getPos() => $surface->getNbChambresMax()->getTransformedVal(),
$surface->getComblesAmenageables()->getPos() => $surface->getComblesAmenageables()->getTransformedVal(),
$surface->getSurfaceTerrainNecessaire()->getPos() => $surface->getSurfaceTerrainNecessaire(
)->getTransformedVal(),
$surface->getSurfaceTerrasse()->getPos() => $surface->getSurfaceTerrasse()->getTransformedVal(),
$contact->getTel()->getPos() => $contact->getTel()->getTransformedVal(),
$contact->getFullName()->getPos() => $contact->getFullName()->getTransformedVal(),
$contact->getEmail()->getPos() => $contact->getEmail()->getTransformedVal(),
$contact->getInterCabinet()->getPos() => $contact->getInterCabinet()->getTransformedVal(),
$contact->getInterCabinetPrive()->getPos() => $contact->getInterCabinetPrive()->getTransformedVal(),
$contact->getCodeNego()->getPos() => $contact->getCodeNego()->getTransformedVal(),
$contact->getAgenceTerrain()->getPos() => $contact->getAgenceTerrain()->getTransformedVal(),
$etage->getEtage()->getPos() => $etage->getEtage()->getTransformedVal(),
$etage->getNbEtages()->getPos() => $etage->getNbEtages()->getTransformedVal(),
$etage->getIdTypeEtage()->getPos() => $etage->getIdTypeEtage()->getTransformedVal(),
$interieur->getMeuble()->getPos() => $interieur->getMeuble()->getTransformedVal(),
$interieur->getAnneeConstruction()->getPos() => $interieur->getAnneeConstruction()->getTransformedVal(),
$interieur->getRefaitNeuf()->getPos() => $interieur->getRefaitNeuf()->getTransformedVal(),
$interieur->getWcSepares()->getPos() => $interieur->getWcSepares()->getTransformedVal(),
$interieur->getOrientationSud()->getPos() => $interieur->getOrientationSud()->getTransformedVal(),
$interieur->getOrientationEst()->getPos() => $interieur->getOrientationEst()->getTransformedVal(),
$interieur->getOrientationOuest()->getPos() => $interieur->getOrientationOuest()->getTransformedVal(),
$interieur->getOrientationNord()->getPos() => $interieur->getOrientationNord()->getTransformedVal(),
$interieur->getCave()->getPos() => $interieur->getCave()->getTransformedVal(),
$interieur->getNbCouverts()->getPos() => $interieur->getNbCouverts()->getTransformedVal(),
$interieur->getNbLitsDoubles()->getPos() => $interieur->getNbLitsDoubles()->getTransformedVal(),
$interieur->getNbLitsSimples()->getPos() => $interieur->getNbLitsSimples()->getTransformedVal(),
$interieur->getCableTv()->getPos() => $interieur->getCableTv()->getTransformedVal(),
$interieur->getCheminee()->getPos() => $interieur->getCheminee()->getTransformedVal(),
$interieur->getPlacards()->getPos() => $interieur->getPlacards()->getTransformedVal(),
$interieur->getTel()->getPos() => $interieur->getTel()->getTransformedVal(),
$interieur->getParquet()->getPos() => $interieur->getParquet()->getTransformedVal(),
$interieur->getEquipementBebe()->getPos() => $interieur->getEquipementBebe()->getTransformedVal(),
$interieur->getConnexionInternet()->getPos() => $interieur->getConnexionInternet()->getTransformedVal(),
$interieur->getEquipementVideo()->getPos() => $interieur->getEquipementVideo()->getTransformedVal(),
$interieur->getMitoyennete()->getPos() => $interieur->getMitoyennete()->getTransformedVal(),
$partieJour->getTypeCuisine()->getPos() => $partieJour->getTypeCuisine()->getTransformedVal(),
$partieJour->getCongelateur()->getPos() => $partieJour->getCongelateur()->getTransformedVal(),
$partieJour->getFour()->getPos() => $partieJour->getFour()->getTransformedVal(),
$partieJour->getMicroOndes()->getPos() => $partieJour->getMicroOndes()->getTransformedVal(),
$partieJour->getLaveLinge()->getPos() => $partieJour->getLaveLinge()->getTransformedVal(),
$partieJour->getLaveVaisselle()->getPos() => $partieJour->getLaveVaisselle()->getTransformedVal(),
$partieJour->getSecheLinge()->getPos() => $partieJour->getSecheLinge()->getTransformedVal(),
$partieJour->getSalleManger()->getPos() => $partieJour->getSalleManger()->getTransformedVal(),
$partieJour->getSejour()->getPos() => $partieJour->getSejour()->getTransformedVal(),
$exterieur->getAscenseur()->getPos() => $exterieur->getAscenseur()->getTransformedVal(),
$exterieur->getCalme()->getPos() => $exterieur->getCalme()->getTransformedVal(),
$exterieur->getPiscine()->getPos() => $exterieur->getPiscine()->getTransformedVal(),
$exterieur->getVueDegagee()->getPos() => $exterieur->getVueDegagee()->getTransformedVal(),
$exterieur->getEntree()->getPos() => $exterieur->getEntree()->getTransformedVal(),
$exterieur->getVisAVis()->getPos() => $exterieur->getVisAVis()->getTransformedVal(),
$exterieur->getMonteCharge()->getPos() => $exterieur->getMonteCharge()->getTransformedVal(),
$garage->getGarage()->getPos() => $garage->getGarage()->getTransformedVal(),
$garage->getType()->getPos() => $garage->getType()->getTransformedVal(),
$securite->getAlarme()->getPos() => $securite->getAlarme()->getTransformedVal(),
$securite->getDigicode()->getPos() => $securite->getDigicode()->getTransformedVal(),
$securite->getGardien()->getPos() => $securite->getGardien()->getTransformedVal(),
$securite->getInterphone()->getPos() => $securite->getInterphone()->getTransformedVal(),
$chauffageClim->getTypeChauffage()->getPos() => $chauffageClim->getTypeChauffage()->getTransformedVal(),
$chauffageClim->getClim()->getPos() => $chauffageClim->getClim()->getTransformedVal(),
$detail->getNomModele()->getPos() => $detail->getNomModele()->getTransformedVal(),
$detail->getLogementADisposition()->getPos() => $detail->getLogementADisposition()->getTransformedVal(),
$detail->getCommPrives()->getPos() => $detail->getCommPrives()->getTransformedVal(),
$detail->getDuplex()->getPos() => $detail->getDuplex()->getTransformedVal(),
$detail->getAnimauxAcceptes()->getPos() => $detail->getAnimauxAcceptes()->getTransformedVal(),
$detail->getAmenagementHandicapes()->getPos() => $detail->getAmenagementHandicapes()->getTransformedVal(
),
$detail->getDateDispo()->getPos() => $detail->getDateDispo()->getTransformedVal(),
$detail->getDescription()->getPos() => $detail->getDescription()->getTransformedVal(),
$detail->getLabel()->getPos() => $detail->getLabel()->getTransformedVal(),
$detail->getActivitesCommerciales()->getPos() => $detail->getActivitesCommerciales()->getTransformedVal(
),
$publication->getPublications()->getPos() => $publication->getPublications()->getTransformedVal(),
$publication->getCoupDeCoeur()->getPos() => $publication->getCoupDeCoeur()->getTransformedVal(),
$publication->getVersionFormat()->getPos() => $publication->getVersionFormat()->getTransformedVal(),
],
];
ksort($expectedArray);
self::assertEquals($expectedArray, $annonceExport->toArray());
self::assertCount(333, $annonceExport->toArray()[0]);
self::assertEquals(range(1, 333), array_keys($annonceExport->toArray()[0]));
$annonceExport->removeLines([1]);
self::assertEmpty($annonceExport->toArray());
}
}
<file_sep>/tests/Models/Annonce/ChauffageClimTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\ChauffageClim;
class ChauffageClimTest extends TestCase
{
/**
* @test
*/
public function it_must_create_chauffage_clim()
{
$chauffageClim = new ChauffageClim($typeChauffage = 1, $clim = true);
self::assertEquals($typeChauffage, $chauffageClim->getTypeChauffage()->getVal());
self::assertEquals($clim, $chauffageClim->getClim()->getVal());
$expectedArray = [
$chauffageClim->getTypeChauffage(),
$chauffageClim->getClim(),
];
self::assertEquals($expectedArray, $chauffageClim->toArray());
}
}
<file_sep>/Models/Annonce/ChauffageClim.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class ChauffageClim
{
// clim
public const TYPE_CLIM_REVERSIBLE = 16384;
// ***********************************************
// individuel
public const TYPE_INDIVIDUEL = 8192;
public const TYPE_INDIVIDUEL_SOL = 8448;
public const TYPE_INDIVIDUEL_RADIATEUR = 8320;
// électricité
public const TYPE_INDIVIDUEL_ELECTRIQUE = 10240;
public const TYPE_INDIVIDUEL_ELECTRIQUE_SOL = 10496;
public const TYPE_INDIVIDUEL_ELECTRIQUE_RADIATEUR = 10368;
// fuel
public const TYPE_INDIVIDUEL_FUEL = 9216;
public const TYPE_INDIVIDUEL_FUEL_SOL = 9472;
public const TYPE_INDIVIDUEL_FUEL_RADIATEUR = 9344;
// gaz
public const TYPE_INDIVIDUEL_GAZ = 8704;
public const TYPE_INDIVIDUEL_GAZ_SOL = 8960;
public const TYPE_INDIVIDUEL_GAZ_RADIATEUR = 8832;
// ***********************************************
// collectif
public const TYPE_COLLECTIF = 4096;
public const TYPE_COLLECTIF_SOL = 4352;
public const TYPE_COLLECTIF_RADIATEUR = 4224;
// électricité
public const TYPE_COLLECTIF_ELECTRIQUE = 6144;
public const TYPE_COLLECTIF_ELECTRIQUE_SOL = 6400;
public const TYPE_COLLECTIF_ELECTRIQUE_RADIATEUR = 6272;
// gaz
public const TYPE_COLLECTIF_GAZ = 4608;
public const TYPE_COLLECTIF_GAZ_SOL = 4864;
public const TYPE_COLLECTIF_GAZ_RADIATEUR = 4736;
// fuel
public const TYPE_COLLECTIF_FUEL = 5120;
public const TYPE_COLLECTIF_FUEL_SOL = 5376;
public const TYPE_COLLECTIF_FUEL_RADIATEUR = 5248;
// ***********************************************
// urbain
public const TYPE_RADIATEUR = 128;
public const TYPE_SOL = 256;
// gaz
public const TYPE_GAZ = 512;
public const TYPE_GAZ_RADIATEUR = 640;
public const TYPE_GAZ_SOL = 768;
// fuel
public const TYPE_FUEL = 1024;
public const TYPE_FUEL_SOL = 1280;
public const TYPE_FUEL_RADIATEUR = 1152;
// électricité
public const TYPE_ELECTRIQUE = 2048;
public const TYPE_ELECTRIQUE_SOL = 2304;
public const TYPE_ELECTRIQUE_RADIATEUR = 2176;
private Column $typeChauffage;
private Column $clim;
public function __construct($typeChauffage, $clim)
{
$this->typeChauffage = new Column(33, $typeChauffage);
$this->clim = new Column(64, $clim);
}
public function getTypeChauffage(): Column
{
return $this->typeChauffage;
}
public function getClim(): Column
{
return $this->clim;
}
public function toArray(): array
{
return [
$this->getTypeChauffage(),
$this->getClim(),
];
}
}
<file_sep>/Models/Annonce/Location.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Location
{
private Column $dureeBail;
private Column $prixDroitEntree;
private Column $prixDroitBail;
private Column $natureBail;
private Column $complementLoyer;
private Column $loyerBase;
private Column $loyerReferenceMajore;
private Column $encadrementLoyers;
public function __construct(
$dureeBail,
$prixDroitEntree,
$prixDroitBail,
$natureBail,
$complementLoyer,
$loyerBase,
$loyerReferenceMajore,
$encadrementLoyers
) {
$this->dureeBail = new Column(195, $dureeBail);
$this->prixDroitEntree = new Column(200, $prixDroitEntree);
$this->prixDroitBail = new Column(218, $prixDroitBail);
$this->natureBail = new Column(242, $natureBail);
$this->complementLoyer = new Column(305, $complementLoyer);
$this->loyerBase = new Column(331, $loyerBase);
$this->loyerReferenceMajore = new Column(332, $loyerReferenceMajore);
$this->encadrementLoyers = new Column(333, $encadrementLoyers);
}
public function getDureeBail(): Column
{
return $this->dureeBail;
}
public function getPrixDroitEntree(): Column
{
return $this->prixDroitEntree;
}
public function getPrixDroitBail(): Column
{
return $this->prixDroitBail;
}
public function getNatureBail(): Column
{
return $this->natureBail;
}
public function getComplementLoyer(): Column
{
return $this->complementLoyer;
}
public function getLoyerBase(): Column
{
return $this->loyerBase;
}
public function getLoyerReferenceMajore(): Column
{
return $this->loyerReferenceMajore;
}
public function getEncadrementLoyers(): Column
{
return $this->encadrementLoyers;
}
public function toArray(): array
{
return [
$this->getDureeBail(),
$this->getPrixDroitEntree(),
$this->getPrixDroitBail(),
$this->getNatureBail(),
$this->getComplementLoyer(),
$this->getLoyerBase(),
$this->getLoyerReferenceMajore(),
$this->getEncadrementLoyers(),
];
}
}
<file_sep>/tests/Models/Annonce/ChampCustomTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\ChampCustom;
class ChampCustomTest extends TestCase
{
/**
* @test
*/
public function it_must_create_champ_custom()
{
$champCustom = new ChampCustom(
$champ1 = 'champ 1',
$champ2 = 'champ 2',
$champ3 = 'champ 3',
$champ4 = 'champ 4',
$champ5 = 'champ 5',
$champ6 = 'champ 6',
$champ7 = 'champ 7',
$champ8 = 'champ 8',
$champ9 = 'champ 9',
$champ10 = 'champ 10',
$champ11 = 'champ 11',
$champ12 = 'champ 12',
$champ13 = 'champ 13',
$champ14 = 'champ 14',
$champ15 = 'champ 15',
$champ16 = 'champ 16',
$champ17 = 'champ 17',
$champ18 = 'champ 18',
$champ19 = 'champ 19',
$champ20 = 'champ 20',
$champ21 = 'champ 21',
$champ22 = 'champ 22',
$champ23 = 'champ 23',
$champ24 = 'champ 24',
$champ25 = 'champ 25',
$champ26 = 'champ 26',
);
self::assertEquals($champ1, $champCustom->getChamp1()->getVal());
self::assertEquals($champ2, $champCustom->getChamp2()->getVal());
self::assertEquals($champ3, $champCustom->getChamp3()->getVal());
self::assertEquals($champ4, $champCustom->getChamp4()->getVal());
self::assertEquals($champ5, $champCustom->getChamp5()->getVal());
self::assertEquals($champ6, $champCustom->getChamp6()->getVal());
self::assertEquals($champ7, $champCustom->getChamp7()->getVal());
self::assertEquals($champ8, $champCustom->getChamp8()->getVal());
self::assertEquals($champ9, $champCustom->getChamp9()->getVal());
self::assertEquals($champ10, $champCustom->getChamp10()->getVal());
self::assertEquals($champ11, $champCustom->getChamp11()->getVal());
self::assertEquals($champ12, $champCustom->getChamp12()->getVal());
self::assertEquals($champ13, $champCustom->getChamp13()->getVal());
self::assertEquals($champ14, $champCustom->getChamp14()->getVal());
self::assertEquals($champ15, $champCustom->getChamp15()->getVal());
self::assertEquals($champ16, $champCustom->getChamp16()->getVal());
self::assertEquals($champ17, $champCustom->getChamp17()->getVal());
self::assertEquals($champ18, $champCustom->getChamp18()->getVal());
self::assertEquals($champ19, $champCustom->getChamp19()->getVal());
self::assertEquals($champ20, $champCustom->getChamp20()->getVal());
self::assertEquals($champ21, $champCustom->getChamp21()->getVal());
self::assertEquals($champ22, $champCustom->getChamp22()->getVal());
self::assertEquals($champ23, $champCustom->getChamp23()->getVal());
self::assertEquals($champ24, $champCustom->getChamp24()->getVal());
self::assertEquals($champ25, $champCustom->getChamp25()->getVal());
self::assertEquals($champ26, $champCustom->getChamp26()->getVal());
$expectedArray = [
$champCustom->getChamp1(),
$champCustom->getChamp2(),
$champCustom->getChamp3(),
$champCustom->getChamp4(),
$champCustom->getChamp5(),
$champCustom->getChamp6(),
$champCustom->getChamp7(),
$champCustom->getChamp8(),
$champCustom->getChamp9(),
$champCustom->getChamp10(),
$champCustom->getChamp11(),
$champCustom->getChamp12(),
$champCustom->getChamp13(),
$champCustom->getChamp14(),
$champCustom->getChamp15(),
$champCustom->getChamp16(),
$champCustom->getChamp17(),
$champCustom->getChamp18(),
$champCustom->getChamp19(),
$champCustom->getChamp20(),
$champCustom->getChamp21(),
$champCustom->getChamp22(),
$champCustom->getChamp23(),
$champCustom->getChamp24(),
$champCustom->getChamp25(),
$champCustom->getChamp26(),
];
self::assertEquals($expectedArray, $champCustom->toArray());
}
}
<file_sep>/tests/Models/Annonce/LocalisationTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Localisation;
class LocalisationTest extends TestCase
{
/**
* @test
*/
public function it_must_create_localisation()
{
$localisation = new Localisation(
$cp = '34000',
$ville = 'MTP',
$pays = 'France',
$adresse = '425 Rue <NAME>',
$quartierProximite = 'Commerces',
$situation = 'ville',
$procheLac = false,
$procheTennis = false,
$procheSki = false,
$cpReel = '34000',
$villeReelle = 'MONTPELLIER',
$idQuartier = null,
$transportLigne = '8',
$transportStation = 'Opera',
$latitude = 22.1,
$longitude = 23.4,
$precisionGps = 1,
$loc = '75,92,93,94,95'
);
self::assertEquals($cp, $localisation->getCp()->getVal());
self::assertEquals($ville, $localisation->getVille()->getVal());
self::assertEquals($pays, $localisation->getPays()->getVal());
self::assertEquals($adresse, $localisation->getAdresse()->getVal());
self::assertEquals($quartierProximite, $localisation->getQuartierProximite()->getVal());
self::assertEquals($situation, $localisation->getSituation()->getVal());
self::assertEquals($procheLac, $localisation->getProcheLac()->getVal());
self::assertEquals($procheTennis, $localisation->getProcheTennis()->getVal());
self::assertEquals($procheSki, $localisation->getProcheSki()->getVal());
self::assertEquals($cpReel, $localisation->getCpReel()->getVal());
self::assertEquals($villeReelle, $localisation->getVilleReelle()->getVal());
self::assertEquals($idQuartier, $localisation->getIdQuartier()->getVal());
self::assertEquals($transportLigne, $localisation->getTransportLigne()->getVal());
self::assertEquals($transportStation, $localisation->getTransportStation()->getVal());
self::assertEquals($latitude, $localisation->getLatitude()->getVal());
self::assertEquals($longitude, $localisation->getLongitude()->getVal());
self::assertEquals($precisionGps, $localisation->getPrecisionGps()->getVal());
self::assertEquals($loc, $localisation->getLocalisation()->getVal());
$expectedArray = [
$localisation->getCp(),
$localisation->getVille(),
$localisation->getPays(),
$localisation->getAdresse(),
$localisation->getQuartierProximite(),
$localisation->getSituation(),
$localisation->getProcheLac(),
$localisation->getProcheTennis(),
$localisation->getProcheSki(),
$localisation->getCpReel(),
$localisation->getVilleReelle(),
$localisation->getIdQuartier(),
$localisation->getTransportLigne(),
$localisation->getTransportStation(),
$localisation->getLatitude(),
$localisation->getLongitude(),
$localisation->getPrecisionGps(),
$localisation->getLocalisation(),
];
self::assertEquals($expectedArray, $localisation->toArray());
}
}
<file_sep>/tests/Models/ColumnTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Column;
class ColumnTest extends TestCase
{
/**
* @test
*/
public function it_must_create_column()
{
$column = new Column(1, 'value');
self::assertEquals(1, $column->getPos());
self::assertEquals('value', $column->getVal());
$arrayExpected = [
'pos' => 1,
'val' => 'value',
];
self::assertEquals($arrayExpected, $column->toArray());
}
/**
* @test
*/
public function it_must_transform_boolean_value()
{
$column = new Column(1, true);
self::assertEquals('OUI', $column->getTransformedVal());
$column = new Column(1, false);
self::assertEquals('NON', $column->getTransformedVal());
}
/**
* @test
*/
public function it_must_transform_string_with_quotes_value()
{
$column = new Column(1, 'Camping "Les flots bleus"');
self::assertEquals("Camping 'Les flots bleus'", $column->getTransformedVal());
}
/**
* @test
*/
public function it_must_transform_string_with_new_line_value()
{
$column = new Column(1, 'new' . \PHP_EOL . 'line');
self::assertEquals('new line', $column->getTransformedVal());
}
/**
* @test
*/
public function it_must_transform_date_value()
{
$column = new Column(1, new \DateTimeImmutable('2021-12-30'));
self::assertEquals('30/12/2021', $column->getTransformedVal());
$column = new Column(1, new \DateTime('2021-12-31'));
self::assertEquals('31/12/2021', $column->getTransformedVal());
}
}
<file_sep>/tests/Models/Annonce/MandatTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Mandat;
class MandatTest extends TestCase
{
/**
* @test
*/
public function it_must_create_mandat()
{
$mandat = new Mandat(
$exclusif = true,
$numero = '01',
$date = new \DateTimeImmutable(),
$nomMandataire = 'nom',
$prenomMandataire = 'prénom',
$raisonSocialeMandataire = 'raison',
$adresseMandataire = 'adresse',
$cpMandataire = 'cp',
$villeMandataire = 'ville',
$telMandataire = '0123456789',
$commMandataire = 'comm',
);
self::assertEquals($exclusif, $mandat->getExclusif()->getVal());
self::assertEquals($numero, $mandat->getNumero()->getVal());
self::assertEquals($date, $mandat->getDate()->getVal());
self::assertEquals($nomMandataire, $mandat->getNomMandataire()->getVal());
self::assertEquals($prenomMandataire, $mandat->getPrenomMandataire()->getVal());
self::assertEquals($raisonSocialeMandataire, $mandat->getRaisonSocialeMandataire()->getVal());
self::assertEquals($adresseMandataire, $mandat->getAdresseMandataire()->getVal());
self::assertEquals($cpMandataire, $mandat->getCodePostalMandataire()->getVal());
self::assertEquals($villeMandataire, $mandat->getVilleMandataire()->getVal());
self::assertEquals($telMandataire, $mandat->getTelMandataire()->getVal());
self::assertEquals($commMandataire, $mandat->getCommMandataire()->getVal());
$expectedArray = [
$mandat->getExclusif(),
$mandat->getNumero(),
$mandat->getDate(),
$mandat->getNomMandataire(),
$mandat->getPrenomMandataire(),
$mandat->getRaisonSocialeMandataire(),
$mandat->getAdresseMandataire(),
$mandat->getCodePostalMandataire(),
$mandat->getVilleMandataire(),
$mandat->getTelMandataire(),
$mandat->getCommMandataire(),
];
self::assertEquals($expectedArray, $mandat->toArray());
}
}
<file_sep>/Models/Annonce/ProduitInvestissement.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class ProduitInvestissement
{
private Column $valeurAchat;
private Column $montantRapport;
public function __construct($valeurAchat, $montantRapport)
{
$this->valeurAchat = new Column(219, $valeurAchat);
$this->montantRapport = new Column(241, $montantRapport);
}
public function getValeurAchat(): Column
{
return $this->valeurAchat;
}
public function getMontantRapport(): Column
{
return $this->montantRapport;
}
public function toArray(): array
{
return [
$this->getValeurAchat(),
$this->getMontantRapport(),
];
}
}
<file_sep>/Models/Annonce/HonoraireCharge.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class HonoraireCharge
{
public const CHARGE_ACQUEREUR = 1;
public const CHARGE_VENDEUR = 2;
private Column $honoraires;
private Column $charges;
private Column $honorairesChargeAcquereur;
private Column $pourcentageHonorairesTTC;
private Column $chargesAnnuelles;
private Column $honorairesCharge;
private Column $prixHorsHonorairesAcquereur;
private Column $modalitesChargesLocataire;
private Column $partHonorairesEtatLieux;
private Column $urlBaremeHonorairesAgence;
public function __construct(
$honoraires,
$charges,
$honorairesChargeAcquereur,
$pourcentageHonorairesTTC,
$chargesAnnuelles,
$honorairesCharge,
$prixHorsHonorairesAcquereur,
$modalitesChargesLocataire,
$partHonorairesEtatLieux,
$urlBaremeHonorairesAgence
) {
$this->honoraires = new Column(15, $honoraires);
$this->charges = new Column(23, $charges);
$this->honorairesChargeAcquereur = new Column(256, $honorairesChargeAcquereur);
$this->pourcentageHonorairesTTC = new Column(257, $pourcentageHonorairesTTC);
$this->chargesAnnuelles = new Column(260, $chargesAnnuelles);
$this->honorairesCharge = new Column(302, $honorairesCharge);
$this->prixHorsHonorairesAcquereur = new Column(303, $prixHorsHonorairesAcquereur);
$this->modalitesChargesLocataire = new Column(304, $modalitesChargesLocataire);
$this->partHonorairesEtatLieux = new Column(306, $partHonorairesEtatLieux);
$this->urlBaremeHonorairesAgence = new Column(307, $urlBaremeHonorairesAgence);
}
public function getHonoraires(): Column
{
return $this->honoraires;
}
public function getCharges(): Column
{
return $this->charges;
}
public function getHonorairesChargeAcquereur(): Column
{
return $this->honorairesChargeAcquereur;
}
public function getPourcentageHonorairesTTC(): Column
{
return $this->pourcentageHonorairesTTC;
}
public function getChargesAnnuelles(): Column
{
return $this->chargesAnnuelles;
}
public function getHonorairesCharge(): Column
{
return $this->honorairesCharge;
}
public function getPrixHorsHonorairesAcquereur(): Column
{
return $this->prixHorsHonorairesAcquereur;
}
public function getModalitesChargesLocataire(): Column
{
return $this->modalitesChargesLocataire;
}
public function getPartHonorairesEtatLieux(): Column
{
return $this->partHonorairesEtatLieux;
}
public function getUrlBaremeHonorairesAgence(): Column
{
return $this->urlBaremeHonorairesAgence;
}
public function toArray(): array
{
return [
$this->getHonoraires(),
$this->getCharges(),
$this->getHonorairesChargeAcquereur(),
$this->getPourcentageHonorairesTTC(),
$this->getChargesAnnuelles(),
$this->getHonorairesCharge(),
$this->getPrixHorsHonorairesAcquereur(),
$this->getModalitesChargesLocataire(),
$this->getPartHonorairesEtatLieux(),
$this->getUrlBaremeHonorairesAgence(),
];
}
}
<file_sep>/tests/Models/Annonce/DetailTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Detail;
class DetailTest extends TestCase
{
/**
* @test
*/
public function it_must_create_detail()
{
$detail = new Detail(
$activitesCommerciales = 'BAR, TABAC, PMU',
$label = 'Maison 3 pièces',
$description = 'Très belle maison',
$dateDispo = new \DateTimeImmutable(),
$amenagementHandicapes = true,
$animauxAcceptes = false,
$duplex = true,
$commPrives = 'Clefs à prendre chez le gardien',
$logementADisposition = false,
$nomModele = 'Tradition'
);
self::assertEquals($activitesCommerciales, $detail->getActivitesCommerciales()->getVal());
self::assertEquals($label, $detail->getLabel()->getVal());
self::assertEquals($description, $detail->getDescription()->getVal());
self::assertEquals($dateDispo, $detail->getDateDispo()->getVal());
self::assertEquals($amenagementHandicapes, $detail->getAmenagementHandicapes()->getVal());
self::assertEquals($animauxAcceptes, $detail->getAnimauxAcceptes()->getVal());
self::assertEquals($duplex, $detail->getDuplex()->getVal());
self::assertEquals($commPrives, $detail->getCommPrives()->getVal());
self::assertEquals($logementADisposition, $detail->getLogementADisposition()->getVal());
self::assertEquals($nomModele, $detail->getNomModele()->getVal());
$expectedArray = [
$detail->getActivitesCommerciales(),
$detail->getLabel(),
$detail->getDescription(),
$detail->getDateDispo(),
$detail->getAmenagementHandicapes(),
$detail->getAnimauxAcceptes(),
$detail->getDuplex(),
$detail->getCommPrives(),
$detail->getLogementADisposition(),
$detail->getNomModele(),
];
self::assertEquals($expectedArray, $detail->toArray());
}
}
<file_sep>/tests/Functional/app/AppKernel.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Functional\app;
use Psr\Log\NullLogger;
use Spiriit\PolirisBundle\PolirisBundle;
use Spiriit\PolirisBundle\Tests\Functional\Bundle\Bundle;
use Symfony\Bundle\FrameworkBundle\FrameworkBundle;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\HttpKernel\Kernel;
class AppKernel extends Kernel
{
private string $config;
public function __construct(string $environment, bool $debug, string $config = 'base')
{
parent::__construct($environment, $debug);
$this->config = $config;
}
/**
* {@inheritdoc}
*/
public function registerBundles(): iterable
{
return [
new FrameworkBundle(),
new PolirisBundle(),
new Bundle(),
];
}
/**
* {@inheritdoc}
*/
public function getCacheDir(): string
{
return sys_get_temp_dir() . '/PolirisBundle/cache';
}
/**
* {@inheritdoc}
*/
public function getLogDir(): string
{
return sys_get_temp_dir() . '/PolirisBundle/logs';
}
protected function build(ContainerBuilder $container): void
{
$container->register('logger', NullLogger::class);
}
/**
* Loads the container configuration.
*/
public function registerContainerConfiguration(LoaderInterface $loader): void
{
$loader->load(sprintf(__DIR__ . '/config/%s_config.yml', $this->config));
}
}
<file_sep>/Models/Annonce/Interieur.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Interieur
{
private Column $meuble;
private Column $anneeConstruction;
private Column $refaitNeuf;
private Column $wcSepares;
private Column $orientationSud;
private Column $orientationEst;
private Column $orientationOuest;
private Column $orientationNord;
private Column $cave;
private Column $nbCouverts;
private Column $nbLitsDoubles;
private Column $nbLitsSimples;
private Column $cableTv;
private Column $cheminee;
private Column $placards;
private Column $tel;
private Column $parquet;
private Column $equipementBebe;
private Column $connexionInternet;
private Column $equipementVideo;
private Column $mitoyennete;
public function __construct(
$meuble,
$anneeConstruction,
$refaitNeuf,
$wcSepares,
$orientationSud,
$orientationEst,
$orientationOuest,
$orientationNord,
$cave,
$nbCouverts,
$nbLitsDoubles,
$nbLitsSimples,
$cableTv,
$cheminee,
$placards,
$tel,
$parquet,
$equipementBebe,
$connexionInternet,
$equipementVideo,
$mitoyennete
) {
$this->meuble = new Column(26, $meuble);
$this->anneeConstruction = new Column(27, $anneeConstruction);
$this->refaitNeuf = new Column(28, $refaitNeuf);
$this->wcSepares = new Column(32, $wcSepares);
$this->orientationSud = new Column(35, $orientationSud);
$this->orientationEst = new Column(36, $orientationEst);
$this->orientationOuest = new Column(37, $orientationOuest);
$this->orientationNord = new Column(38, $orientationNord);
$this->cave = new Column(42, $cave);
$this->nbCouverts = new Column(58, $nbCouverts);
$this->nbLitsDoubles = new Column(59, $nbLitsDoubles);
$this->nbLitsSimples = new Column(60, $nbLitsSimples);
$this->cableTv = new Column(62, $cableTv);
$this->cheminee = new Column(68, $cheminee);
$this->placards = new Column(73, $placards);
$this->tel = new Column(74, $tel);
$this->parquet = new Column(191, $parquet);
$this->equipementBebe = new Column(222, $equipementBebe);
$this->connexionInternet = new Column(235, $connexionInternet);
$this->equipementVideo = new Column(251, $equipementVideo);
$this->mitoyennete = new Column(320, $mitoyennete);
}
public function getMeuble(): Column
{
return $this->meuble;
}
public function getAnneeConstruction(): Column
{
return $this->anneeConstruction;
}
public function getRefaitNeuf(): Column
{
return $this->refaitNeuf;
}
public function getWcSepares(): Column
{
return $this->wcSepares;
}
public function getOrientationSud(): Column
{
return $this->orientationSud;
}
public function getOrientationEst(): Column
{
return $this->orientationEst;
}
public function getOrientationOuest(): Column
{
return $this->orientationOuest;
}
public function getOrientationNord(): Column
{
return $this->orientationNord;
}
public function getCave(): Column
{
return $this->cave;
}
public function getNbCouverts(): Column
{
return $this->nbCouverts;
}
public function getNbLitsDoubles(): Column
{
return $this->nbLitsDoubles;
}
public function getNbLitsSimples(): Column
{
return $this->nbLitsSimples;
}
public function getCableTv(): Column
{
return $this->cableTv;
}
public function getCheminee(): Column
{
return $this->cheminee;
}
public function getPlacards(): Column
{
return $this->placards;
}
public function getTel(): Column
{
return $this->tel;
}
public function getParquet(): Column
{
return $this->parquet;
}
public function getEquipementBebe(): Column
{
return $this->equipementBebe;
}
public function getConnexionInternet(): Column
{
return $this->connexionInternet;
}
public function getEquipementVideo(): Column
{
return $this->equipementVideo;
}
public function getMitoyennete(): Column
{
return $this->mitoyennete;
}
public function toArray()
{
return [
$this->getMeuble(),
$this->getAnneeConstruction(),
$this->getRefaitNeuf(),
$this->getWcSepares(),
$this->getOrientationSud(),
$this->getOrientationEst(),
$this->getOrientationOuest(),
$this->getOrientationNord(),
$this->getCave(),
$this->getNbCouverts(),
$this->getNbLitsDoubles(),
$this->getNbLitsSimples(),
$this->getCableTv(),
$this->getCheminee(),
$this->getPlacards(),
$this->getTel(),
$this->getParquet(),
$this->getEquipementBebe(),
$this->getConnexionInternet(),
$this->getEquipementVideo(),
$this->getMitoyennete(),
];
}
}
<file_sep>/tests/Models/Annonce/GarageTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Garage;
class GarageTest extends TestCase
{
/**
* @test
*/
public function it_must_create_garage()
{
$garage = new Garage(
$g = true,
$type = 1
);
self::assertEquals($g, $garage->getGarage()->getVal());
self::assertEquals($type, $garage->getType()->getVal());
$expectedArray = [
$garage->getGarage(),
$garage->getType(),
];
self::assertEquals($expectedArray, $garage->toArray());
}
}
<file_sep>/Models/Annonce/Boutique.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Boutique
{
private Column $quai;
private Column $situationCommerciale;
public function __construct(
$quai,
$situationCommerciale
) {
$this->quai = new Column(198, $quai);
$this->situationCommerciale = new Column(254, $situationCommerciale);
}
public function getQuai(): Column
{
return $this->quai;
}
public function getSituationCommerciale(): Column
{
return $this->situationCommerciale;
}
public function toArray(): array
{
return [
$this->getQuai(),
$this->getSituationCommerciale(),
];
}
}
<file_sep>/tests/Models/Annonce/IdentifiantTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Identifiant;
class IdentifiantTest extends TestCase
{
/**
* @test
*/
public function it_must_create_identifiant()
{
$identifiant = new Identifiant(
$id = 'id',
$ref = 'ref',
$annonceType = 'type annonce',
$annonceIdTechnique = 'annonce id technique',
);
self::assertEquals($id, $identifiant->getAgenceId()->getVal());
self::assertEquals($ref, $identifiant->getAgencePropertyRef()->getVal());
self::assertEquals($annonceType, $identifiant->getAnnonceType()->getVal());
self::assertEquals($annonceIdTechnique, $identifiant->getAnnonceIdTechnique()->getVal());
$expectedArray = [
$identifiant->getAgenceId(),
$identifiant->getAgencePropertyRef(),
$identifiant->getAnnonceType(),
$identifiant->getAnnonceIdTechnique(),
];
self::assertEquals($expectedArray, $identifiant->toArray());
}
}
<file_sep>/tests/Models/Annonce/DiagnosticTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Diagnostic;
class DiagnosticTest extends TestCase
{
/**
* @test
*/
public function it_must_create_diagnostic()
{
$diagnostic = new Diagnostic(
$recent = true,
$travaux = false,
$consoEnergie = 1,
$bilanConsoEnergie = 'D',
$ges = 3,
$bilanGes = 'E',
$dpeAt = new \DateTimeImmutable(),
$dpeVersion = '1',
$dpeMin = 0,
$dpeMax = 10,
$dpeAnneeRef = '2021',
$depCoutAnnuelle = 250
);
self::assertEquals($recent, $diagnostic->getRecent()->getVal());
self::assertEquals($travaux, $diagnostic->getTravaux()->getVal());
self::assertEquals($consoEnergie, $diagnostic->getConsoEnergie()->getVal());
self::assertEquals($bilanConsoEnergie, $diagnostic->getBilanConsoEnergie()->getVal());
self::assertEquals($ges, $diagnostic->getGes()->getVal());
self::assertEquals($bilanGes, $diagnostic->getBilanGes()->getVal());
self::assertEquals($dpeAt, $diagnostic->getDpeAt()->getVal());
self::assertEquals($dpeVersion, $diagnostic->getDpeVersion()->getVal());
self::assertEquals($dpeMin, $diagnostic->getDpeMin()->getVal());
self::assertEquals($dpeMax, $diagnostic->getDpeMax()->getVal());
self::assertEquals($dpeAnneeRef, $diagnostic->getDpeAnneeRef()->getVal());
self::assertEquals($depCoutAnnuelle, $diagnostic->getDpeCoutConsoAnnuelle()->getVal());
$expectedArray = [
$diagnostic->getRecent(),
$diagnostic->getTravaux(),
$diagnostic->getConsoEnergie(),
$diagnostic->getBilanConsoEnergie(),
$diagnostic->getGes(),
$diagnostic->getBilanGes(),
$diagnostic->getDpeAt(),
$diagnostic->getDpeVersion(),
$diagnostic->getDpeMin(),
$diagnostic->getDpeMax(),
$diagnostic->getDpeAnneeRef(),
$diagnostic->getDpeCoutConsoAnnuelle(),
];
self::assertEquals($expectedArray, $diagnostic->toArray());
}
}
<file_sep>/Models/ExportInterface.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models;
interface ExportInterface
{
public function toArray();
}
<file_sep>/tests/Models/Annonce/LocationTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Location;
class LocationTest extends TestCase
{
/**
* @test
*/
public function it_must_create_location()
{
$location = new Location(
$dureeBail = 1,
$prixDroitEntree = 2,
$prixDroitBail = 3,
$natureBail = 'location meublée',
$complementLoyer = 4,
$loyerBase = 10,
$loyerReferenceMajore = 15,
$encadrementLoyer = 10
);
self::assertEquals($dureeBail, $location->getDureeBail()->getVal());
self::assertEquals($prixDroitEntree, $location->getPrixDroitEntree()->getVal());
self::assertEquals($prixDroitBail, $location->getPrixDroitBail()->getVal());
self::assertEquals($natureBail, $location->getNatureBail()->getVal());
self::assertEquals($complementLoyer, $location->getComplementLoyer()->getVal());
self::assertEquals($loyerBase, $location->getLoyerBase()->getVal());
self::assertEquals($loyerReferenceMajore, $location->getLoyerReferenceMajore()->getVal());
self::assertEquals($encadrementLoyer, $location->getEncadrementLoyers()->getVal());
$expectedArray = [
$location->getDureeBail(),
$location->getPrixDroitEntree(),
$location->getPrixDroitBail(),
$location->getNatureBail(),
$location->getComplementLoyer(),
$location->getLoyerBase(),
$location->getLoyerReferenceMajore(),
$location->getEncadrementLoyers(),
];
self::assertEquals($expectedArray, $location->toArray());
}
}
<file_sep>/Builders/AnnonceBuilder.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Builders;
use Spiriit\PolirisBundle\Models\Annonce\Annonce;
use Spiriit\PolirisBundle\Models\Annonce\Boutique;
use Spiriit\PolirisBundle\Models\Annonce\Bureau;
use Spiriit\PolirisBundle\Models\Annonce\ChampCustom;
use Spiriit\PolirisBundle\Models\Annonce\ChauffageClim;
use Spiriit\PolirisBundle\Models\Annonce\Contact;
use Spiriit\PolirisBundle\Models\Annonce\Detail;
use Spiriit\PolirisBundle\Models\Annonce\Diagnostic;
use Spiriit\PolirisBundle\Models\Annonce\Etage;
use Spiriit\PolirisBundle\Models\Annonce\Exterieur;
use Spiriit\PolirisBundle\Models\Annonce\FondsCommerce;
use Spiriit\PolirisBundle\Models\Annonce\Garage;
use Spiriit\PolirisBundle\Models\Annonce\HonoraireCharge;
use Spiriit\PolirisBundle\Models\Annonce\Identifiant;
use Spiriit\PolirisBundle\Models\Annonce\Interieur;
use Spiriit\PolirisBundle\Models\Annonce\Langue;
use Spiriit\PolirisBundle\Models\Annonce\Localisation;
use Spiriit\PolirisBundle\Models\Annonce\Location;
use Spiriit\PolirisBundle\Models\Annonce\LocationVacances;
use Spiriit\PolirisBundle\Models\Annonce\Mandat;
use Spiriit\PolirisBundle\Models\Annonce\Parking;
use Spiriit\PolirisBundle\Models\Annonce\PartieJour;
use Spiriit\PolirisBundle\Models\Annonce\Photo;
use Spiriit\PolirisBundle\Models\Annonce\Prix;
use Spiriit\PolirisBundle\Models\Annonce\ProduitInvestissement;
use Spiriit\PolirisBundle\Models\Annonce\Publication;
use Spiriit\PolirisBundle\Models\Annonce\Securite;
use Spiriit\PolirisBundle\Models\Annonce\Surface;
use Spiriit\PolirisBundle\Models\Annonce\Terrain;
use Spiriit\PolirisBundle\Models\Annonce\Type;
use Spiriit\PolirisBundle\Models\Annonce\Viager;
class AnnonceBuilder
{
private Annonce $annonce;
public function __construct()
{
$this->annonce = new Annonce();
}
public function withIdentifiant(
$agenceId = null,
$agencePropertyRef = null,
$annonceType = null,
$annonceIdTechnique = null
): self {
$this->annonce->setIdentifiant(new Identifiant($agenceId, $agencePropertyRef, $annonceType, $annonceIdTechnique));
return $this;
}
public function withType(
$type = null,
$sousType = null
): self {
$this->annonce->setType(new Type($type, $sousType));
return $this;
}
public function withPhoto(
$photo1 = null,
$photo2 = null,
$photo3 = null,
$photo4 = null,
$photo5 = null,
$photo6 = null,
$photo7 = null,
$photo8 = null,
$photo9 = null,
$photo10 = null,
$photo11 = null,
$photo12 = null,
$photo13 = null,
$photo14 = null,
$photo15 = null,
$photo16 = null,
$photo17 = null,
$photo18 = null,
$photo19 = null,
$photo20 = null,
$photo21 = null,
$photo22 = null,
$photo23 = null,
$photo24 = null,
$photo25 = null,
$photo26 = null,
$photo27 = null,
$photo28 = null,
$photo29 = null,
$photo30 = null,
$titre1 = null,
$titre2 = null,
$titre3 = null,
$titre4 = null,
$titre5 = null,
$titre6 = null,
$titre7 = null,
$titre8 = null,
$titre9 = null,
$titre10 = null,
$titre11 = null,
$titre12 = null,
$titre13 = null,
$titre14 = null,
$titre15 = null,
$titre16 = null,
$titre17 = null,
$titre18 = null,
$titre19 = null,
$titre20 = null,
$titre21 = null,
$titre22 = null,
$titre23 = null,
$titre24 = null,
$titre25 = null,
$titre26 = null,
$titre27 = null,
$titre28 = null,
$titre29 = null,
$titre30 = null,
$photoPanoramique = null,
$urlVisiteVirtuelle = null
): self {
$photo = new Photo(
$photo1,
$photo2,
$photo3,
$photo4,
$photo5,
$photo6,
$photo7,
$photo8,
$photo9,
$photo10,
$photo11,
$photo12,
$photo13,
$photo14,
$photo15,
$photo16,
$photo17,
$photo18,
$photo19,
$photo20,
$photo21,
$photo22,
$photo23,
$photo24,
$photo25,
$photo26,
$photo27,
$photo28,
$photo29,
$photo30,
$titre1,
$titre2,
$titre3,
$titre4,
$titre5,
$titre6,
$titre7,
$titre8,
$titre9,
$titre10,
$titre11,
$titre12,
$titre13,
$titre14,
$titre15,
$titre16,
$titre17,
$titre18,
$titre19,
$titre20,
$titre21,
$titre22,
$titre23,
$titre24,
$titre25,
$titre26,
$titre27,
$titre28,
$titre29,
$titre30,
$photoPanoramique,
$urlVisiteVirtuelle
);
$this->annonce->setPhoto($photo);
return $this;
}
public function withChampCustom(
$champ1 = null,
$champ2 = null,
$champ3 = null,
$champ4 = null,
$champ5 = null,
$champ6 = null,
$champ7 = null,
$champ8 = null,
$champ9 = null,
$champ10 = null,
$champ11 = null,
$champ12 = null,
$champ13 = null,
$champ14 = null,
$champ15 = null,
$champ16 = null,
$champ17 = null,
$champ18 = null,
$champ19 = null,
$champ20 = null,
$champ21 = null,
$champ22 = null,
$champ23 = null,
$champ24 = null,
$champ25 = null,
$champ26 = null
): self {
$champCustom = new ChampCustom(
$champ1,
$champ2,
$champ3,
$champ4,
$champ5,
$champ6,
$champ7,
$champ8,
$champ9,
$champ10,
$champ11,
$champ12,
$champ13,
$champ14,
$champ15,
$champ16,
$champ17,
$champ18,
$champ19,
$champ20,
$champ21,
$champ22,
$champ23,
$champ24,
$champ25,
$champ26
);
$this->annonce->setChampCustom($champCustom);
return $this;
}
public function withLangue(
$code1 = null,
$code2 = null,
$code3 = null,
$proximite1 = null,
$proximite2 = null,
$proximite3 = null,
$label1 = null,
$label2 = null,
$label3 = null,
$descriptif1 = null,
$descriptif2 = null,
$descriptif3 = null
): self {
$langue = new Langue(
$code1,
$code2,
$code3,
$proximite1,
$proximite2,
$proximite3,
$label1,
$label2,
$label3,
$descriptif1,
$descriptif2,
$descriptif3
);
$this->annonce->setLangue($langue);
return $this;
}
public function withMandat(
$exclusif = null,
$numero = null,
$date = null,
$nomMandataire = null,
$prenomMandataire = null,
$raisonSocialeMandataire = null,
$adresseMandataire = null,
$codePostalMandataire = null,
$villeMandataire = null,
$telMandataire = null,
$commMandataire = null
): self {
$mandat = new Mandat(
$exclusif,
$numero,
$date,
$nomMandataire,
$prenomMandataire,
$raisonSocialeMandataire,
$adresseMandataire,
$codePostalMandataire,
$villeMandataire,
$telMandataire,
$commMandataire
);
$this->annonce->setMandat($mandat);
return $this;
}
public function withLocationVacances(
$periodesDispo = null,
$periodesBasseSaison = null,
$prixSemaineBasseSaison = null,
$prixQuinzaineBasseSaison = null,
$prixMoisBasseSaison = null,
$periodesHauteSaison = null,
$prixSemaineHauteSaison = null,
$prixQuinzaineHauteSaison = null,
$prixMoisHauteSaison = null,
$nbPersonnes = null,
$residence = null,
$typeResidence = null
): self {
$locationVacances = new LocationVacances(
$periodesDispo,
$periodesBasseSaison,
$prixSemaineBasseSaison,
$prixQuinzaineBasseSaison,
$prixMoisBasseSaison,
$periodesHauteSaison,
$prixSemaineHauteSaison,
$prixQuinzaineHauteSaison,
$prixMoisHauteSaison,
$nbPersonnes,
$residence,
$typeResidence
);
$this->annonce->setLocationVacances($locationVacances);
return $this;
}
public function withViager(
$prixBouquet = null,
$renteMensuelle = null,
$ageHomme = null,
$ageFemme = null,
$venduLibre = null
): self {
$viager = new Viager(
$prixBouquet,
$renteMensuelle,
$ageHomme,
$ageFemme,
$venduLibre
);
$this->annonce->setViager($viager);
return $this;
}
public function withTerrain(
$agricole = null,
$constructible = null,
$pente = null,
$planEau = null,
$longueurFacade = null,
$donneSurLaRue = null,
$viabilise = null
): self {
$terrain = new Terrain(
$agricole,
$constructible,
$pente,
$planEau,
$longueurFacade,
$donneSurLaRue,
$viabilise
);
$this->annonce->setTerrain($terrain);
return $this;
}
public function withBureau(
$loyerAnnuelGlobal = null,
$loyerAnnuelM2 = null,
$loyerAnnuelCC = null,
$loyerAnnuelM2CC = null,
$loyerAnnuelHT = null,
$loyerAnnuelM2HT = null,
$chargesAnnuellesGlobales = null,
$chargesAnnuellesM2 = null,
$chargesMensuellesHT = null,
$chargesAnnuellesM2HT = null,
$chargesAnnuellesHT = null,
$divisible = null,
$surfaceDivisibleMin = null,
$surfaceDivisibleMax = null,
$conditionsFinancieres = null,
$prestationsDiverses = null,
$immeubleBureaux = null,
$surfaceMaxBureau = null
): self {
$bureau = new Bureau(
$loyerAnnuelGlobal,
$loyerAnnuelM2,
$loyerAnnuelCC,
$loyerAnnuelM2CC,
$loyerAnnuelHT,
$loyerAnnuelM2HT,
$chargesAnnuellesGlobales,
$chargesAnnuellesM2,
$chargesMensuellesHT,
$chargesAnnuellesM2HT,
$chargesAnnuellesHT,
$divisible,
$surfaceDivisibleMin,
$surfaceDivisibleMax,
$conditionsFinancieres,
$prestationsDiverses,
$immeubleBureaux,
$surfaceMaxBureau
);
$this->annonce->setBureau($bureau);
return $this;
}
public function withDiagnostic(
$recent = null,
$travaux = null,
$consoEnergie = null,
$bilanConsoEnergie = null,
$ges = null,
$bilanGes = null,
$dpeAt = null,
$dpeVersion = null,
$dpeMin = null,
$dpeMax = null,
$dpeAnneeRef = null,
$dpeCoutConsoAnnuelle = null
): self {
$diagnostic = new Diagnostic(
$recent,
$travaux,
$consoEnergie,
$bilanConsoEnergie,
$ges,
$bilanGes,
$dpeAt,
$dpeVersion,
$dpeMin,
$dpeMax,
$dpeAnneeRef,
$dpeCoutConsoAnnuelle
);
$this->annonce->setDiagnostic($diagnostic);
return $this;
}
public function withParking(
$nbVehicules = null,
$immeuble = null,
$isole = null
): self {
$this->annonce->setParking(new Parking($nbVehicules, $immeuble, $isole));
return $this;
}
public function withBoutique(
$quai = null,
$situationCommerciale = null
): self {
$this->annonce->setBoutique(new Boutique($quai, $situationCommerciale));
return $this;
}
public function withPrix(
$prix = null,
$loyerMoisMur = null,
$loyerCC = null,
$loyerHT = null,
$depotGarantie = null,
$prixMasque = null,
$prixHT = null,
$copropriete = null,
$nbLots = null,
$syndicatCopro = null,
$syndicatCoproDetails = null,
$prixTerrain = null,
$prixModeleMaison = null,
$prixMin = null,
$prixMax = null
) {
$prix = new Prix(
$prix,
$loyerMoisMur,
$loyerCC,
$loyerHT,
$depotGarantie,
$prixMasque,
$prixHT,
$copropriete,
$nbLots,
$syndicatCopro,
$syndicatCoproDetails,
$prixTerrain,
$prixModeleMaison,
$prixMin,
$prixMax
);
$this->annonce->setPrix($prix);
return $this;
}
public function withLocation(
$dureeBail = null,
$prixDroitEntree = null,
$prixDroitBail = null,
$natureBail = null,
$complementLoyer = null,
$loyerBase = null,
$loyerReferenceMajore = null,
$encadrementLoyers = null
): self {
$location = new Location(
$dureeBail,
$prixDroitEntree,
$prixDroitBail,
$natureBail,
$complementLoyer,
$loyerBase,
$loyerReferenceMajore,
$encadrementLoyers
);
$this->annonce->setLocation($location);
return $this;
}
public function withProduitInvestissement($valeurAchat = null, $montantRapport = null): self
{
$this->annonce->setProduitInvestissement(new ProduitInvestissement($valeurAchat, $montantRapport));
return $this;
}
public function withFondsCommerce(
$ca = null,
$repartitionCa = null,
$natureBailCommercial = null,
$resultatAnneeN2 = null,
$resultatAnneeN1 = null,
$resultatActuel = null,
$caAnneeN2 = null,
$caAnneeN1 = null
): self {
$fondsCommerce = new FondsCommerce(
$ca,
$repartitionCa,
$natureBailCommercial,
$resultatAnneeN2,
$resultatAnneeN1,
$resultatActuel,
$caAnneeN2,
$caAnneeN1
);
$this->annonce->setFondsCommerce($fondsCommerce);
return $this;
}
public function withHonoraireCharge(
$honoraires = null,
$charges = null,
$honorairesChargeAcquereur = null,
$pourcentageHonorairesTTC = null,
$chargesAnnuelles = null,
$honorairesCharge = null,
$prixHonorairesAcquereur = null,
$modalitesChargesLocataire = null,
$partHonorairesEtatLieux = null,
$urlBaremeHonorairesAgence = null
): self {
$honoraireCharge = new HonoraireCharge(
$honoraires,
$charges,
$honorairesChargeAcquereur,
$pourcentageHonorairesTTC,
$chargesAnnuelles,
$honorairesCharge,
$prixHonorairesAcquereur,
$modalitesChargesLocataire,
$partHonorairesEtatLieux,
$urlBaremeHonorairesAgence
);
$this->annonce->setHonoraireCharge($honoraireCharge);
return $this;
}
public function withLocalisation(
$cp = null,
$ville = null,
$pays = null,
$adresse = null,
$quartierProximite = null,
$situation = null,
$procheLac = null,
$procheTennis = null,
$procheSki = null,
$cpReel = null,
$villeReelle = null,
$idQuartier = null,
$transportLigne = null,
$transportStation = null,
$latitude = null,
$longitude = null,
$precisionGps = null,
$localisation = null
): self {
$loc = new Localisation(
$cp,
$ville,
$pays,
$adresse,
$quartierProximite,
$situation,
$procheLac,
$procheTennis,
$procheSki,
$cpReel,
$villeReelle,
$idQuartier,
$transportLigne,
$transportStation,
$latitude,
$longitude,
$precisionGps,
$localisation
);
$this->annonce->setLocalisation($loc);
return $this;
}
public function withSurface(
$surface = null,
$surfaceTerrain = null,
$nbPieces = null,
$nbChambres = null,
$nbSdb = null,
$nbSalleEau = null,
$nbWc = null,
$nbBalcons = null,
$surfaceBalcon = null,
$nbParkings = null,
$nbBoxes = null,
$terrasse = null,
$longueurFacade = null,
$placesEnSalle = null,
$nbBureaux = null,
$surfaceSejour = null,
$nbTerrasses = null,
$surfaceCave = null,
$surfaceSalleManger = null,
$surfaceMin = null,
$surfaceMax = null,
$nbPiecesMin = null,
$nbPiecesMax = null,
$nbChambresMin = null,
$nbChambresMax = null,
$comblesAmenageables = null,
$surfaceTerrainNecessaire = null,
$surfaceTerrasse = null
): self {
$surf = new Surface(
$surface,
$surfaceTerrain,
$nbPieces,
$nbChambres,
$nbSdb,
$nbSalleEau,
$nbWc,
$nbBalcons,
$surfaceBalcon,
$nbParkings,
$nbBoxes,
$terrasse,
$longueurFacade,
$placesEnSalle,
$nbBureaux,
$surfaceSejour,
$nbTerrasses,
$surfaceCave,
$surfaceSalleManger,
$surfaceMin,
$surfaceMax,
$nbPiecesMin,
$nbPiecesMax,
$nbChambresMin,
$nbChambresMax,
$comblesAmenageables,
$surfaceTerrainNecessaire,
$surfaceTerrasse
);
$this->annonce->setSurface($surf);
return $this;
}
public function withContact(
$tel = null,
$fullName = null,
$email = null,
$interCabinet = null,
$interCabinetPrive = null,
$codeNego = null,
$agenceTerrain = null
): self {
$contact = new Contact(
$tel,
$fullName,
$email,
$interCabinet,
$interCabinetPrive,
$codeNego,
$agenceTerrain
);
$this->annonce->setContact($contact);
return $this;
}
public function withEtage(
$etage = null,
$nbEtages = null,
$idTypeEtage = null
): self {
$e = new Etage(
$etage,
$nbEtages,
$idTypeEtage
);
$this->annonce->setEtage($e);
return $this;
}
public function withInterieur(
$meuble = null,
$anneeConstruction = null,
$refaitNeuf = null,
$wcSepares = null,
$orientationSud = null,
$orientationEst = null,
$orientationOuest = null,
$orientationNord = null,
$cave = null,
$nbCouverts = null,
$nbLitsDoubles = null,
$nbLitsSimples = null,
$cableTv = null,
$cheminee = null,
$placards = null,
$tel = null,
$parquet = null,
$equipementBebe = null,
$connexionInternet = null,
$equipementVideo = null,
$mitoyennete = null
): self {
$interieur = new Interieur(
$meuble,
$anneeConstruction,
$refaitNeuf,
$wcSepares,
$orientationSud,
$orientationEst,
$orientationOuest,
$orientationNord,
$cave,
$nbCouverts,
$nbLitsDoubles,
$nbLitsSimples,
$cableTv,
$cheminee,
$placards,
$tel,
$parquet,
$equipementBebe,
$connexionInternet,
$equipementVideo,
$mitoyennete
);
$this->annonce->setInterieur($interieur);
return $this;
}
public function withPartieJour(
$typeCuisine = null,
$congelateur = null,
$four = null,
$laveVaisselle = null,
$microOndes = null,
$laveLinge = null,
$secheLinge = null,
$salleManger = null,
$sejour = null
): self {
$partieJour = new PartieJour(
$typeCuisine,
$congelateur,
$four,
$laveVaisselle,
$microOndes,
$laveLinge,
$secheLinge,
$salleManger,
$sejour
);
$this->annonce->setPartieJour($partieJour);
return $this;
}
public function withExterieur(
$ascenseur = null,
$calme = null,
$piscine = null,
$vueDegagee = null,
$entree = null,
$visAVis = null,
$monteCharge = null
): self {
$exterieur = new Exterieur(
$ascenseur,
$calme,
$piscine,
$vueDegagee,
$entree,
$visAVis,
$monteCharge
);
$this->annonce->setExterieur($exterieur);
return $this;
}
public function withGarage($garage = null, $type = null): self
{
$this->annonce->setGarage(new Garage($garage, $type));
return $this;
}
public function withSecurite(
$digicode = null,
$interphone = null,
$gardien = null,
$alarme = null
): self {
$securite = new Securite(
$digicode,
$interphone,
$gardien,
$alarme
);
$this->annonce->setSecurite($securite);
return $this;
}
public function withChauffageClim($typeChauffage = null, $clim = null): self
{
$this->annonce->setChauffageClim(new ChauffageClim($typeChauffage, $clim));
return $this;
}
public function withDetail(
$activitesCommerciales = null,
$label = null,
$description = null,
$datesDispo = null,
$amenagementHandicapes = null,
$animauxAcceptes = null,
$duplex = null,
$commPrives = null,
$logementADisposition = null,
$nomModele = null
): self {
$detail = new Detail(
$activitesCommerciales,
$label,
$description,
$datesDispo,
$amenagementHandicapes,
$animauxAcceptes,
$duplex,
$commPrives,
$logementADisposition,
$nomModele
);
$this->annonce->setDetail($detail);
return $this;
}
public function withPublication(
$publications = null,
$coupDeCoeur = null,
$versionFormat = null
): self {
$publication = new Publication(
$publications,
$coupDeCoeur,
$versionFormat
);
$this->annonce->setPublication($publication);
return $this;
}
public function endLine(): AnnonceExportBuilder
{
return new AnnonceExportBuilder();
}
public function build(): Annonce
{
return $this->annonce;
}
}
<file_sep>/tests/Models/Annonce/PublicationTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Publication;
class PublicationTest extends TestCase
{
/**
* @test
*/
public function it_must_create_publication()
{
$publication = new Publication(
$publications = 'SL,BD,WA',
$coupDeCoeur = true,
$versionFormat = '4.09'
);
self::assertEquals($publications, $publication->getPublications()->getVal());
self::assertEquals($coupDeCoeur, $publication->getCoupDeCoeur()->getVal());
self::assertEquals($versionFormat, $publication->getVersionFormat()->getVal());
$expectedArray = [
$publication->getPublications(),
$publication->getCoupDeCoeur(),
$publication->getVersionFormat(),
];
self::assertEquals($expectedArray, $publication->toArray());
}
}
<file_sep>/Centers/CsvCenter/CsvCenter.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Centers\CsvCenter;
use Spiriit\PolirisBundle\Models\ExportInterface;
abstract class CsvCenter
{
abstract public function generateCsvFile(ExportInterface $export, string $formatEncodage): string;
/**
* Remove unnecessary $ enclosure.
*/
protected function getCleanedContent(string $content): string
{
return str_replace('$', '', $content);
}
/**
* Create : "contenu du champ1" !# "contenu du champ2" !# "contenu du champ3".
*/
protected function updateDelimiter(array $lines): array
{
$result = [];
foreach ($lines as $line) {
$resultLine = [];
$k = 1;
foreach ($line as $field) {
if ($k === (is_array($line) || $line instanceof \Countable ? \count($line) : 0)) {
$resultLine[] = '"' . $field . '"';
} else {
$resultLine[] = '"' . $field . '"!';
}
++$k;
}
$result[] = $resultLine;
}
return $result;
}
protected function getTransformedContent(array $lines): array
{
return $this->updateDelimiter($lines);
}
}
<file_sep>/DependencyInjection/PolirisExtension.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\DependencyInjection;
use Spiriit\PolirisBundle\Centers\CsvCenter\AnnonceCsvCenter;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
class PolirisExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container): void
{
$loader = new XmlFileLoader($container, new FileLocator(__DIR__ . '/../Resources/config'));
$loader->load('services.xml');
$container->setAlias(AnnonceCsvCenter::class, 'spiriit_poliris.centers_csv_center.annonce_csv_center');
}
}
<file_sep>/tests/Models/Annonce/EtageTest.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Tests\Models\Annonce;
use PHPUnit\Framework\TestCase;
use Spiriit\PolirisBundle\Models\Annonce\Etage;
class EtageTest extends TestCase
{
/**
* @test
*/
public function it_must_create_etage()
{
$etage = new Etage(
$e = 0,
$nbEtages = 1,
$idTypeEtage = 3
);
self::assertEquals($e, $etage->getEtage()->getVal());
self::assertEquals($nbEtages, $etage->getNbEtages()->getVal());
self::assertEquals($idTypeEtage, $etage->getIdTypeEtage()->getVal());
$expectedArray = [
$etage->getEtage(),
$etage->getNbEtages(),
$etage->getIdTypeEtage(),
];
self::assertEquals($expectedArray, $etage->toArray());
}
}
<file_sep>/Models/Annonce/Diagnostic.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Diagnostic
{
public const DPE_VERSION_V01 = 'DPE_v01-2011';
public const DPE_VERSION_V07 = 'DPE_v07-2021';
public const CLASSIFICATION_VI = 'VI';
public const CLASSIFICATION_NS = 'NS';
private Column $recent;
private Column $travaux;
private Column $consoEnergie;
private Column $bilanConsoEnergie;
private Column $ges;
private Column $bilanGes;
private Column $dpeAt;
private Column $dpeVersion;
private Column $dpeMin;
private Column $dpeMax;
private Column $dpeAnneeRef;
private Column $dpeCoutConsoAnnuelle;
public function __construct(
$recent,
$travaux,
$consoEnergie,
$bilanConsoEnergie,
$ges,
$bilanGes,
$dpeAt,
$dpeVersion,
$dpeMin,
$dpeMax,
$dpeAnneeRef,
$dpeCoutConsoAnnuelle
) {
$this->recent = new Column(162, $recent);
$this->travaux = new Column(163, $travaux);
$this->consoEnergie = new Column(176, $consoEnergie);
$this->bilanConsoEnergie = new Column(177, $bilanConsoEnergie);
$this->ges = new Column(178, $ges);
$this->bilanGes = new Column(179, $bilanGes);
$this->dpeAt = new Column(324, $dpeAt);
$this->dpeVersion = new Column(325, $dpeVersion);
$this->dpeMin = new Column(326, $dpeMin);
$this->dpeMax = new Column(327, $dpeMax);
$this->dpeAnneeRef = new Column(328, $dpeAnneeRef);
$this->dpeCoutConsoAnnuelle = new Column(330, $dpeCoutConsoAnnuelle);
}
public function getRecent(): Column
{
return $this->recent;
}
public function getTravaux(): Column
{
return $this->travaux;
}
public function getConsoEnergie(): Column
{
return $this->consoEnergie;
}
public function getBilanConsoEnergie(): Column
{
return $this->bilanConsoEnergie;
}
public function getGes(): Column
{
return $this->ges;
}
public function getBilanGes(): Column
{
return $this->bilanGes;
}
public function getDpeAt(): Column
{
return $this->dpeAt;
}
public function getDpeVersion(): Column
{
return $this->dpeVersion;
}
public function getDpeMin(): Column
{
return $this->dpeMin;
}
public function getDpeMax(): Column
{
return $this->dpeMax;
}
public function getDpeAnneeRef(): Column
{
return $this->dpeAnneeRef;
}
public function getDpeCoutConsoAnnuelle(): Column
{
return $this->dpeCoutConsoAnnuelle;
}
public function toArray(): array
{
return [
$this->getRecent(),
$this->getTravaux(),
$this->getConsoEnergie(),
$this->getBilanConsoEnergie(),
$this->getGes(),
$this->getBilanGes(),
$this->getDpeAt(),
$this->getDpeVersion(),
$this->getDpeMin(),
$this->getDpeMax(),
$this->getDpeAnneeRef(),
$this->getDpeCoutConsoAnnuelle(),
];
}
}
<file_sep>/Models/Annonce/Etage.php
<?php
/*
* This file is part of the composer-write-changelogs project.
*
* (c) <NAME> <<EMAIL>>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Spiriit\PolirisBundle\Models\Annonce;
use Spiriit\PolirisBundle\Models\Column;
class Etage
{
public const TYPE_RDC_RDJ = 0;
public const TYPE_PREMIER_ETAGE = 1;
private Column $etage;
private Column $nbEtages;
private Column $idTypeEtage;
public function __construct(
$etage,
$nbEtages,
$idTypeEtage
) {
$this->etage = new Column(24, $etage);
$this->nbEtages = new Column(25, $nbEtages);
$this->idTypeEtage = new Column(316, $idTypeEtage);
}
public function getEtage(): Column
{
return $this->etage;
}
public function getNbEtages(): Column
{
return $this->nbEtages;
}
public function getIdTypeEtage(): Column
{
return $this->idTypeEtage;
}
public function toArray(): array
{
return [
$this->getEtage(),
$this->getNbEtages(),
$this->getIdTypeEtage(),
];
}
}
|
0dadf6fff957608f75263abfcf900e83d07304c9
|
[
"Markdown",
"PHP"
] | 78
|
PHP
|
SpiriitLabs/poliris-bundle
|
06fe20c10b5d80b5ccb5778f9aafb8a865ad4d71
|
74f5604b6273839e5e393a74554d8e917079ad55
|
refs/heads/master
|
<file_sep>import numpy as np
import pandas as pd
import sys
def topsis_solution(a, b, c):
df=pd.read_csv(a).values
dfbaad=df
df = df.astype(float)
weights=list(map(float,b.split(",")))
impacts=list(map(str,c.split(",")))
(x,y)=df.shape
summation=list()
for j in range(0,y):
temp=0
for i in range(0,x):
temp+=(df[i,j]**2)
summation.append(float((temp)**(0.5)))
for i in range(0,x):
for j in range(0,y):
df[i,j]=(df[i,j]/(summation[j]))*weights[j]
vjplus=list()
vjminus=list()
for j in range(0,y):
if impacts[j]=='-':
vjplus.append(min(df[:,j]))
vjminus.append(max(df[:,j]))
elif impacts[j]=='+':
vjplus.append(max(df[:,j]))
vjminus.append(min(df[:,j]))
siplus=list()
siminus=list()
temp1 = 0
temp2 = 0
for i in range(0,x):
a = np.array(df[i,:])
b = np.array(vjplus)
c = np.array(vjminus)
temp1= np.sum((a-b)**2)
temp1= np.sqrt(temp1)
temp2 = np.sum((a-c)**2)
temp2 = np.sqrt(temp2)
siplus.append(temp1)
siminus.append(temp2)
temp1 = 0
temp2 = 0
pscore=list()
for i in range(0,x):
pscore.append(float(siminus[i]/(siplus[i]+siminus[i])))
output = [0] * x
for i, p in enumerate(sorted(range(x), key=lambda y: pscore[y])):
output[p] = i+1
output = np.array(output)
dftemp=np.zeros(shape=(x,y+1))
dftemp[:,:-1] = dfbaad
dftemp[:,-1] = output
dftemp = dftemp.astype(int)
#df = np.concat(df,output)
#print(dftemp)
outdict={}
outdict['values:']=[i+1 for i in range(0,x)]
outdict["Performance Score:"]=pscore
outdf=pd.DataFrame(outdict)
print(outdf.head())
def main():
topsis_solution(sys.argv[1], sys.argv[2], sys.argv[3])
if __name__ == "__main__":
main()<file_sep>A Python package for topsis analysis
Usage
topsis3317 <dataset> <weights> <impacts>
|
99613ab1b35af41cdd3364ac18893b995a3f0401
|
[
"Markdown",
"Python"
] | 2
|
Python
|
manaskhatri/Topsis
|
e2897630124af247a4afafd519feac7d8dabfe88
|
58f2da0cacefa26ebd9d77bf891c2b2dd06349d2
|
refs/heads/master
|
<repo_name>bbferka/docker<file_sep>/indigo-knowrob/indigo-knowrob-daemon/Dockerfile
FROM knowrob/indigo-knowrob-base
MAINTAINER <NAME> <EMAIL>
USER root
RUN mkdir /home/ros/.ssh/
ADD rs_openease /home/ros/.ssh/id_rsa
RUN touch /home/ros/.ssh/known_hosts && \
ssh-keyscan -T 60 github.com >> /home/ros/.ssh/known_hosts && \
chown -R ros:ros /home/ros/.ssh
USER ros
# set up workspace and setup knowrob
WORKDIR /home/ros/src
RUN /usr/bin/python /opt/ros/indigo/bin/catkin_init_workspace
# dummy 'add' command to always check out the repositories
RUN git clone <EMAIL>:code-iai/robosherlock_demos.git && \
git clone --recursive https://github.com/knowrob/knowrob.git -b master && \
git clone --recursive https://github.com/knowrob/knowrob_addons.git -b master && \
git clone --recursive https://github.com/knowrob/knowrob_tutorials.git -b master && \
git clone --recursive https://github.com/code-iai/knowrob_dev.git && \
git clone https://github.com/code-iai/iai_maps.git && \
git clone https://github.com/code-iai/iai_common_msgs.git && \
git clone https://github.com/code-iai/iai_cad_tools.git && \
git clone https://github.com/code-iai/designator_integration -b openease_comp &&\
git clone https://github.com/bbferka/robosherlock.git && \
git clone https://github.com/bbferka/rs_addons.git && \
git clone https://github.com/bbferka/rs_turn_table.git && \
git clone https://github.com/code-iai/rs_resources.git && \
git clone <EMAIL>:code-iai/rs_kbreasoning.git -b acat_demo && \
/home/ros/local/src/caffe/scripts/download_model_binary.py /home/ros/src/rs_resources/caffe/models/bvlc_reference_caffenet/
WORKDIR /home/ros
ENV OPEN_EASE_APPLICATION true
# build the catkin workspace
RUN /opt/ros/indigo/bin/catkin_make
# ENTRYPOINT /opt/ros/indigo/bin/roslaunch knowrob_roslog_launch knowrob_ease.launch
<file_sep>/flask/webrob/pages/meshes.py
import os
import sys
import traceback
from flask import send_from_directory
from flask_user import login_required
from urllib import urlopen, urlretrieve
from subprocess import call
from webrob.app_and_db import app
from webrob.config.settings import MESH_REPOSITORIES
__author__ = '<EMAIL>'
def is_mesh_url_valid(url):
return urlopen(url).getcode() == 200
def download_mesh_to_local_cache(src, dst):
"""
download mesh file via http from trusted host
that is defined in flask settings.
"""
dstDir = os.path.dirname(dst)
p_src, ext = os.path.splitext(src)
p_dst, ext = os.path.splitext(dst)
if is_mesh_url_valid(src):
if not os.path.exists(dstDir):
os.makedirs(dstDir)
urlretrieve(src,dst)
if ext == ".tif":
call(["/usr/bin/convert", dst, p_dst+".png"])
if ext == ".dae":
call(["/opt/webapp/update-texture-reference", dst])
return True
else:
if ext == ".png":
return download_mesh_to_local_cache(p_src + ".tif", p_dst + ".tif")
else:
return False
@app.route('/meshes/<path:mesh>')
@login_required
def download_mesh(mesh):
meshFile = os.path.join('/home/ros/mesh_data', mesh)
if not os.path.isfile(meshFile):
for repository in MESH_REPOSITORIES:
sourceFile = repository + mesh
try:
if download_mesh_to_local_cache(sourceFile, meshFile):
break
except:
app.logger.error(str(sys.exc_info()[0]))
app.logger.error(str(traceback.format_exc()))
pass
return send_from_directory(
os.path.dirname(meshFile),
os.path.basename(meshFile))
<file_sep>/indigo-knowrob/indigo-knowrob-base/Dockerfile
FROM ubuntu:14.04
MAINTAINER <NAME>
RUN apt-get -qq update && apt-get -qq install -y wget apt-utils
# Use apt-cacher container
RUN echo 'Acquire::http { Proxy "http://172.17.42.1:3142"; };' >> /etc/apt/apt.conf.d/01proxy && \
sh -c '. /etc/lsb-release && echo "deb http://packages.ros.org.ros.informatik.uni-freiburg.de/ros/ubuntu trusty main" > /etc/apt/sources.list.d/ros-latest.list' && \
wget http://packages.ros.org/ros.key -O - | apt-key add - && \
apt-get -y update && apt-get -y install \
curl \
libjson-java \
libjson-glib-dev \
ros-indigo-desktop \
swi-prolog \
swi-prolog-java \
openjdk-7-jdk \
python-pip\
python-yaml \
python-catkin-pkg \
python-twisted-web \
python-twisted-bin \
python-twisted-core \
python-rospkg \
python-wstool \
python-tk \
python-scipy \
python-logutils \
ros-indigo-catkin \
ros-indigo-iai-common-msgs \
ros-indigo-rosjava \
ros-indigo-rosbridge-suite \
ros-indigo-tf2-web-republisher \
ros-indigo-mjpeg-server \
ros-indigo-web-video-server \
ros-indigo-self-test \
ros-indigo-compressed-depth-image-transport \
ros-indigo-compressed-image-transport \
ros-indigo-image-transport \
ros-indigo-pcl-ros \
ros-indigo-pcl-conversions \
ros-indigo-vision-opencv \
ros-indigo-openni-camera \
ros-indigo-openni-launch \
mongodb-clients \
mongodb-dev \
libmongo-client-dev \
ros-indigo-rosauth \
mencoder \
lame \
libavcodec54 \
texlive-latex-base \
imagemagick \
automake \
libxerces-c-dev \
libicu-dev \
libapr1-dev \
libgphoto2-2-dev \
libhdf5-serial-dev \
protobuf-compiler \
libopencv-dev \
libcppnetlib-dev \
scons \
libtool \
xstow \
vim \
emacs \
gdb \
cmake-curses-gui \
libprotobuf-dev \
libleveldb-dev \
libsnappy-dev \
libopencv-dev \
libhdf5-serial-dev \
protobuf-compiler \
libboost-all-dev \
libgflags-dev \
libgoogle-glog-dev \
liblmdb-dev \
libatlas-base-dev \
libatlas-dev \
libatlas3-base \
git \
openssh-client openssh-server && \
useradd -m -d /home/ros -p ros ros && adduser ros sudo && chsh -s /bin/bash ros && \
cp /opt/ros/indigo/setup.sh /etc/profile.d/ros_indigo.sh && rosdep init && \
/usr/bin/pip install pyparsing tabulate psutil==0.4.1
ENV HOME /home/ros
WORKDIR /home/ros
USER ros
RUN mkdir /home/ros/src && chown -R ros:ros /home/ros && rosdep update && \
mkdir -p /home/ros/.m2
ADD mvn-settings.xml /home/ros/.m2/settings.xml
RUN mkdir -p /home/ros/local/src && mkdir -p /home/ros/local/xstow
WORKDIR /home/ros/local/src
RUN git clone https://github.com/RoboSherlock/uima-uimacpp.git uimacpp && \
git clone https://github.com/mongodb/mongo-cxx-driver.git -b 26compat && \
git clone https://github.com/BVLC/caffe.git && \
git clone https://github.com/bbferka/pracmln.git
ENV CMAKE_PREFIX_PATH /home/ros/devel:/opt/ros/indigo
ENV PKG_CONFIG_PATH=/home/ros/local/lib/pkgconfig:/home/ros/devel/lib/pkgconfig:/home/ros/devel/lib/x86_64-linux-gnu/pkgconfig:/opt/ros/indigo/lib/pkgconfig:/opt/ros/indigo/lib/x86_64-linux-gnu/pkgconfig
ENV PYTHONPATH /home/ros/local/src/pracmln:/home/ros/local/src/pracmln/3rdparty/logutils-0.3.3:/home/ros/local/lib/python/site-packages:/home/ros/devel/lib/python2.7/dist-packages:/opt/ros/indigo/lib/python2.7/dist-packages
WORKDIR /home/ros/local/src/uimacpp
RUN ./autogen.sh && ./configure --without-activemq --with-jdk=/usr/lib/jvm/java-7-openjdk-amd64/include --prefix=/home/ros/local/xstow/uimacpp --with-icu=/usr && make install
WORKDIR /home/ros/local/src/mongo-cxx-driver
RUN scons --full --use-system-boost --prefix=/home/ros/local/xstow/mongoclient --ssl --sharedclient install-mongoclient
WORKDIR /home/ros/local/src/caffe
RUN mkdir build && cd build && cmake .. -DCPU_ONLY=ON -DCMAKE_INSTALL_PREFIX=/home/ros/local/xstow/caffe && make install
WORKDIR /home/ros/local/src/pracmln
RUN /usr/bin/python /home/ros/local/src/pracmln/setup.py --cppbindings
WORKDIR /home/ros/local/xstow
RUN xstow uimacpp && xstow mongoclient && xstow caffe && \
echo "export LD_LIBRARY_PATH=/home/ros/local/lib:/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server" >> /home/ros/.bashrc && \
echo "export JAVA_HOME=/usr/lib/jvm/default-java" >> /home/ros/.bashrc && \
echo source /home/ros/devel/setup.bash >> /home/ros/.bashrc && \
echo source /home/ros/local/src/pracmln/env.sh && \
echo source /home/ros/.bashrc >> /home/ros/.bash_profile
# set pre-build variables: only packages in /opt/ros
# set post-build variables:
ENV ROS_ROOT /opt/ros/indigo/share/ros
ENV ROS_PACKAGE_PATH /home/ros/src:/opt/ros/indigo/share:/opt/ros/indigo/stacks
ENV ROS_MASTER_URI http://localhost:11311
ENV ROS_MAVEN_DEPLOYMENT_REPOSITORY /home/ros/devel/share/maven
ENV ROS_MAVEN_PATH /home/ros/devel/share/maven:/opt/ros/indigo/share/maven
EnV ROS_MAVEN_REPOSITORY http://172.17.42.1:8081/nexus/content/groups/public
ENV ROS_DISTRO=indigo
ENV ROS_WORKSPACE /home/ros
ENV ROS_ETC_DIR=/home/ros/etc:/opt/ros/indigo/etc/ros
ENV ROS_IP 127.0.0.1
ENV PYTHON_VERSION python2.7
ENV LD_LIBRARY_PATH /home/ros/local/src/pracmln/libpracmln/install/lib:/home/ros/local/lib:/home/ros/devel/lib:/home/ros/devel/lib/x64_64-linux-gnu:/opt/ros/indigo/lib:/opt/ros/indigo/lib/x86_64-linux-gnu:/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server:/opt/ros/indigo/lib/python2.7/dist-packages
ENV LIBRARY_PATH /home/ros/local/src/pracmln/libpracmln/install/lib:/home/ros/local/lib:/home/ros/devel/lib:/home/ros/devel/lib/x64_64-linux-gnu:/opt/ros/indigo/lib:/opt/ros/indigo/lib/x86_64-linux-gnu:/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server:/opt/ros/indigo/lib/python2.7/dist-packages
ENV CPATH /home/ros/local/src/pracmln/libpracmln/install/include:/home/ros/local/include:/home/ros/devel/include:/opt/ros/indigo/include
ENV PATH /home/ros/local/bin:/home/ros/devel/bin:/opt/ros/indigo/bin:.:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/home/ros/local/src/pracmln/apps
ENV LDFLAGS -L/home/ros/local/lib
ENV CMAKE_INCLUDE_PATH=/home/ros/local/src/pracmln/libpracmln/install/include:/home/ros/local/include:/home/ros/devel/include:/opt/ros/indigo/include
ENV CMAKE_LIBRARY_PATH=/home/ros/local/src/pracmln/libpracmln/install/lib:/home/ros/local/lib:/home/ros/devel/lib:/home/ros/devel/lib/x64_64-linux-gnu:/opt/ros/indigo/lib:/opt/ros/indigo/lib/x86_64-linux-gnu
ENV PRACMLN_HOME /home/ros/local/src/pracmln
ENV PRACMLN_EXPERIMENTS /home/ros/local/src/pracmln/experiments
ENV SWI_HOME_DIR /usr/lib/swi-prolog
ENV APR_HOME /usr
ENV ICU_HOME /usr
ENV XERCES_HOME /usr
ENV USER ros
ENV DOCKER_LINKS mongo_db:mongo
# TODO: Mount mesh_data read only. Note: Meshes can be generated in knowrob_vis and saved in mesh_data
ENV DOCKER_VOLUMES episode_data:ro mesh_data
#ENV DOCKER_VOLUMES knowrob_data:ro mesh_data:ro
USER root
RUN git clone https://github.com/cxhernandez/amd_sdk.git && \
./amd_sdk/amd_sdk.sh
RUN apt-get install opencl-headers && \
echo "export LD_LIBRARY_PATH=/opt/AMDAPP/lib/x86_64:${LD_LIBRARY_PATH}" >> /home/ros/.bashrc
ENV LD_LIBRARY_PATH /opt/AMDAPP/lib/x86_64:/home/ros/local/src/pracmln/libpracmln/install/lib:/home/ros/local/lib:/home/ros/devel/lib:/home/ros/devel/lib/x64_64-linux-gnu:/opt/ros/indigo/lib:/opt/ros/indigo/lib/x86_64-linux-gnu:/usr/lib/jvm/default-java/jre/lib/amd64:/usr/lib/jvm/default-java/jre/lib/amd64/server:/opt/ros/indigo/lib/python2.7/dist-packages
USER ros
# forward ports: KnowRob webserver + rosbridge
EXPOSE 1111 9090
# Volumes for mounting data containers
VOLUME /home/ros/knowrob_data
VOLUME /home/ros/sandbox
<file_sep>/flask/Dockerfile
FROM ubuntu:14.04
MAINTAINER <NAME>, <EMAIL>
# install python and flask
RUN apt-get -qq update
RUN DEBIAN_FRONTEND=noninteractive apt-get -qq install -y -q curl python-all python-pip python-dev wget gcc imagemagick mongodb libffi-dev libpq-dev
RUN easy_install pymongo
# NOTE: At the moment Flask-Misaka==0.3 is incompatible with latest misaka==2.0.0
# @see https://github.com/singingwolfboy/flask-misaka/issues/11
RUN pip install Flask misaka==1.0.2 Flask-Misaka==0.3 Flask-OAuth flask-user flask-babel flask-mail psycopg2 python-jsonrpc tornado
WORKDIR /opt/webapp
# flag used in nginx configuration
ENV OPEN_EASE_WEBAPP true
# work as user 'ros'
RUN useradd -m -d /home/ros -p ros ros && chsh -s /bin/bash ros
ENV HOME /home/ros
## copy this folder to the container
ADD . /opt/webapp/
RUN chown -R ros:ros /opt/webapp/
USER ros
# Expose volumes for maintenance
VOLUME /opt/webapp/
EXPOSE 5000
CMD ["python", "runserver.py"]
<file_sep>/indigo-knowrob/indigo-knowrob-daemon/build.sh
#!/bin/sh
# Author: <NAME>, <NAME>
SCRIPT=`readlink -f "$0"`
DIR=`dirname $SCRIPT`
$DIR/../../scripts/start-apt-cacher
echo "Building knowrob/indigo-knowrob-daemon....";
docker build -t knowrob/indigo-knowrob-daemon .
|
7017a6fe45071562d8c22c08d1a576c31218e73e
|
[
"Python",
"Dockerfile",
"Shell"
] | 5
|
Dockerfile
|
bbferka/docker
|
14ebf75c439a2bd1ee2b245deaa9f30723571210
|
0d2881c2f727539a2351aac4e71fed818bb1a6ba
|
refs/heads/master
|
<repo_name>gre-ory/lite<file_sep>/test.py
#!/usr/bin/python
# ##################################################
# import
import lite
import unittest
import sys
import cgi
import os
# ##################################################
# lite unittest
class LiteUnitTest( unittest.TestCase ):
# ##################################################
# execute
def execute( self, db='test', tb='test', **kwargs ):
if db is not None:
kwargs[ 'db' ] = db
if tb is not None:
kwargs[ 'tb' ] = tb
os.environ[ 'QUERY_STRING' ] = '&'.join( [ '%s=%s' % ( key, kwargs[key] ) for key in kwargs ] )
# print '\n [rq] %s' % os.environ[ 'QUERY_STRING' ]
os.environ[ 'REQUEST_METHOD' ] = 'GET'
try:
with lite.Usecase( lite.Request(), lite.Response() ) as self.usecase:
self.usecase.execute()
except:
pass
self.index = 0
# ##################################################
# assert_query
def assert_query( self, sql=None, parameters=[], fetch_one=False, fetch_all=False, fetch_oid=False, fetch_nb=False, table='test', database='test' ):
self.assertTrue( self.usecase is not None )
self.assertTrue( self.usecase.request is not None )
self.assertEqual( self.usecase.request.database, database )
self.assertEqual( self.usecase.request.table, table )
self.assertEqual( self.usecase.request.multi, len(self.usecase.request.queries) > 1 )
self.assertTrue( self.index < len(self.usecase.request.queries) )
query = self.usecase.request.queries[ self.index ]
self.assertTrue( query is not None )
self.assertEqual( query.sql, sql )
self.assertEqual( len(query.parameters), len(parameters) )
for i, parameter in enumerate(parameters):
self.assertEqual( query.parameters[i], parameter )
self.assertEqual( query.fetch_one, fetch_one )
self.assertEqual( query.fetch_all, fetch_all )
self.assertEqual( query.fetch_oid, fetch_oid )
self.assertEqual( query.fetch_nb, fetch_nb )
self.index = self.index + 1
# ##################################################
# assert_response
def assert_response( self, success, error=None, oid=None, row=None, rows=None, nb=None ):
self.assertEqual( self.usecase.response.success, success )
if error is not None:
self.assertEqual( self.usecase.response.error, error )
if oid is not None:
self.assertEqual( self.usecase.response.oid, oid )
if row is not None:
self.assertEqual( self.usecase.response.row, row )
if rows is not None:
self.assertEqual( self.usecase.response.rows, rows )
if nb is not None:
self.assertEqual( self.usecase.response.nb, nb )
# ##################################################
# test
def test_00_drop( self ):
self.execute( qr='drop' )
self.assert_query( 'DROP TABLE test' )
self.assert_query( 'DROP TABLE tmp' )
self.assert_response( True )
def test_01_create( self ):
self.execute( qr='create' )
self.assert_query( 'CREATE TABLE test ( oid INTEGER PRIMARY KEY, key TEXT NOT NULL, value TEXT )' )
self.assert_query( 'CREATE TABLE tmp ( oid INTEGER PRIMARY KEY, key TEXT NOT NULL, value TEXT )' )
self.assert_response( True )
def test_10_insert( self ):
self.execute( qr='insert', key='one', value='un' )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ 'one', 'un' ], fetch_oid = True )
self.assert_response( True, oid=1 )
def test_11_insert( self ):
self.execute( qr='insert', key='two', value='deux' )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ 'two', 'deux' ], fetch_oid = True )
self.assert_response( True, oid=2 )
def test_12_insert( self ):
self.execute( qr='insert', key='two', value='duo' )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ 'two', 'duo' ], fetch_oid = True )
self.assert_response( True, oid=3 )
def test_13_insert_with_missing_key( self ):
self.execute( qr='insert', value='something' )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ None, 'something' ], fetch_oid = True )
self.assert_response( False, error='test.key may not be NULL', oid=None )
def test_14_upsert( self ):
self.execute( qr='upsert', key='three', value='three' )
self.assert_query( 'DELETE FROM test WHERE key = ?', [ 'three' ] )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ 'three', 'three' ] )
self.assert_response( True )
def test_15_upsert( self ):
self.execute( qr='upsert', key='three', value='trois' )
self.assert_query( 'DELETE FROM test WHERE key = ?', [ 'three' ] )
self.assert_query( 'INSERT INTO test ( key, value ) VALUES ( ?, ? )', [ 'three', 'trois' ] )
self.assert_response( True )
def test_20_missing_parameter( self ):
self.execute( qr='select.one' )
self.assert_query( 'SELECT * FROM test WHERE oid = ?', [ None ], fetch_one = True )
self.assert_response( False, error='row not found' )
def test_21_select_one( self ):
self.execute( qr='select.one', oid='1' )
self.assert_query( 'SELECT * FROM test WHERE oid = ?', [ '1' ], fetch_one = True )
self.assert_response( True, row={'oid': 1, 'value': 'un', 'key': 'one'} )
def test_22_select_one_ignorecase( self ):
self.execute( qr='select.one.ignorecase', oid='1' )
self.assert_query( 'SELECT * FROM test WHERE oid = ?', [ '1' ], fetch_one = True )
self.assert_response( True, row={'oid': 1, 'value': 'un', 'key': 'one'} )
def test_23_select_all( self ):
self.execute( qr='select.all' )
self.assert_query( 'SELECT * FROM test', fetch_all = True )
self.assert_response( True, rows=[{'oid': 1, 'value': u'un', 'key': u'one'}, {'oid': 2, 'value': u'deux', 'key': u'two'}, {'oid': 3, 'value': u'duo', 'key': u'two'}, {'oid': 4, 'value': u'trois', 'key': u'three'}] )
def test_24_count( self ):
self.execute( qr='count', key='one' )
self.assert_query( 'SELECT COUNT(*) AS nb FROM test WHERE key = ?', [ 'one' ], fetch_one = True, fetch_oid = True, fetch_nb = True )
self.assert_response( True, row={'nb': 1} )
def test_25_select_one( self ):
self.execute( qr='select.one', oid='99' )
self.assert_query( 'SELECT * FROM test WHERE oid = ?', [ '99' ], fetch_one = True )
self.assert_response( False, error='row not found' )
def test_30_update( self ):
self.execute( qr='update', key='one', value='uno' )
self.assert_query( 'UPDATE test SET value = ? WHERE key = ?', [ 'uno', 'one' ], fetch_nb = True )
self.assert_response( True, nb=1 )
def test_31_select_one( self ):
self.execute( qr='select.one', oid='1' )
self.assert_query( 'SELECT * FROM test WHERE oid = ?', [ '1' ], fetch_one = True )
self.assert_response( True, row={'oid': 1, 'value': 'uno', 'key': 'one'} )
def test_40_delete( self ):
self.execute( qr='delete', oid='1' )
self.assert_query( 'DELETE FROM test WHERE oid = ?', [ '1' ], fetch_nb = True )
self.assert_response( True, nb=1 )
def test_41_select_all( self ):
self.execute( qr='select.all' )
self.assert_query( 'SELECT * FROM test', fetch_all = True )
self.assert_response( True, rows=[{'oid': 2, 'value': u'deux', 'key': u'two'}, {'oid': 3, 'value': u'duo', 'key': u'two'}, {'oid': 4, 'value': u'trois', 'key': u'three'}] )
def test_42_delete_all( self ):
self.execute( qr='delete.all' )
self.assert_query( 'DELETE FROM test WHERE 1=1', fetch_nb = True )
self.assert_response( True, nb=3 )
def test_43_select_all( self ):
self.execute( qr='select.all' )
self.assert_query( 'SELECT * FROM test', fetch_all = True )
self.assert_response( True, rows=[] )
def test_90_missing_db( self ):
self.execute( db=None, qr='count' )
self.assert_response( False, error='missing parameter db in request' )
def test_91_missing_tb( self ):
self.execute( tb=None, qr='count' )
self.assert_response( False, error='missing option count in section DEFAULT in test.ini' )
def test_92_missing_tb( self ):
self.execute( tb=None, qr='select.all' )
self.assert_response( False, error='missing parameter tb in request' )
def test_93_missing_query( self ):
self.execute()
self.assert_response( False, error='missing parameter qr in request' )
# ##################################################
# main
if __name__ == '__main__':
print 'Content-Type: text/text'
print
if True:
suite = unittest.TestLoader().loadTestsFromTestCase( LiteUnitTest )
unittest.TextTestRunner( stream=sys.stdout, verbosity = 2 ).run( suite )
else:
suite = LiteUnitTest( 'test_15_upsert' )
suite.test_15_upsert()
<file_sep>/lite.py
#!/usr/bin/python
# ##################################################
# import
import sys
import cgi
import sqlite3
import json
import ConfigParser
import re
import traceback
# ##################################################
# class Query
class Query:
# ##################################################
# constructor
def __init__( self, sql=None, parameters=None, fetch_one=None, fetch_all=None, fetch_oid=None, fetch_nb=None ):
self.sql = sql
self.parameters = parameters or []
self.fetch_one = ( fetch_one == True )
self.fetch_all = ( fetch_all == True )
self.fetch_oid = ( fetch_oid == True )
self.fetch_nb = ( fetch_nb == True )
# ##################################################
# execute
def execute( self, database, response ):
# print '[sql] %s %s' % ( self.sql, self.parameters )
# execute query
database.execute_query( self.sql, *self.parameters )
# fetch oid
if self.fetch_oid:
response[ 'oid' ] = database.fetch_oid()
# fetch count
if self.fetch_nb:
response[ 'nb' ] = database.fetch_nb()
# fetch one row
if self.fetch_one:
response[ 'row' ] = database.fetch_one()
# fetch all rows
if self.fetch_all:
response[ 'rows' ] = database.fetch_all()
# ##################################################
# class Database
class Database:
# ##################################################
# constructor
def __init__( self, name ):
self.name = name
self.connection = None
# ##################################################
# set up
def __enter__( self ):
self.connect()
return self
# ##################################################
# tear dow
def __exit__( self, type, value, traceback ):
if self.connection is not None:
if value is not None:
self.rollback()
else:
self.commit()
self.disconnect()
# ##################################################
# connect
def connect( self ):
if self.name is None:
raise Exception( 'missing database name' )
self.connection = sqlite3.connect( '%s.db' % self.name )
# ##################################################
# disconnect
def disconnect( self ):
if self.connection is not None:
self.connection.close()
self.connection = None
# ##################################################
# commit
def commit( self ):
if self.connection is not None:
self.connection.commit()
# ##################################################
# rollback
def rollback( self ):
if self.connection is not None:
self.connection.rollback()
# ##################################################
# execute_query
def execute_query( self, query, *args ):
if self.connection is None:
raise Exception( 'database not connected' )
self.cursor = self.connection.cursor()
if len( args ) > 0:
self.cursor.execute( query, args )
else:
self.cursor.execute( query )
# ##################################################
# execute_script
def execute_script( self, script, *args ):
if self.connection is None:
raise Exception( 'database not connected' )
self.cursor = self.connection.cursor()
if len( args ) > 0:
self.cursor.execute( script, args )
# self.cursor.executescript( script )
else:
self.cursor.executescript( script )
# ##################################################
# fetch_oid
def fetch_oid( self ):
if self.cursor is None:
raise Exception( 'query not executed' )
return self.cursor.lastrowid
# ##################################################
# fetch_nb
def fetch_nb( self ):
if self.cursor is None:
raise Exception( 'query not executed' )
if self.cursor.rowcount >= 0:
return self.cursor.rowcount
return None
# ##################################################
# fetch_one
def fetch_one( self ):
if self.cursor is None:
raise Exception( 'query not executed' )
if self.cursor.description is None:
raise Exception( 'query failed' )
row = self.cursor.fetchone()
if row is None:
raise Exception( 'row not found' )
item = {}
keys = [ column[0] for column in self.cursor.description ]
index = 0
for value in row:
if value is not None:
item[ keys[ index ] ] = value
index = index + 1
return item
# ##################################################
# fetch_all
def fetch_all( self ):
if self.cursor is None:
raise Exception( 'query not executed' )
if self.cursor.description is None:
raise Exception( 'query failed' )
items = []
keys = [ column[0] for column in self.cursor.description ]
for row in self.cursor.fetchall():
item = {}
index = 0
for value in row:
if value is not None:
item[ keys[ index ] ] = value
index = index + 1
items.append( item )
return items
# ##################################################
# class Request
class Request:
# ##################################################
# constructor
def __init__( self ):
self.parameters = cgi.FieldStorage()
self.database = None
self.table = None
self.multi = False
self.queries = []
# ##################################################
# get_parameter
def get_parameter( self, key, mandatory=True ):
if key not in self.parameters:
if mandatory:
raise Exception( 'missing parameter %s in request' % key )
return None
return self.parameters[ key ].value
# ##################################################
# build_query
def build_query( self ):
# extract context
self.database = self.get_parameter( 'db' )
self.table = self.get_parameter( 'tb', False )
sql_query_id = self.get_parameter( 'qr' )
# extract sql_query from config file
config_file = '%s.ini' % self.database
config = ConfigParser.ConfigParser()
config.read( config_file )
section = self.table or 'DEFAULT'
if section.upper() != 'DEFAULT' and not config.has_section( section ):
raise Exception( 'missing section %s in %s' % ( section, config_file ) )
option = sql_query_id
if not config.has_option( section, option ):
raise Exception( 'missing option %s in section %s in %s' % ( option, section, config_file ) )
sql = config.get( section, option )
if sql is None:
raise Exception( 'missing option %s in section %s in %s' % ( option, section, config_file ) )
sql_queries = [ s.strip() for s in sql.split( ';' ) if s.strip() != '' ]
self.multi = ( len( sql_queries ) > 1 )
for sql_query in sql_queries:
# extract sql_parameters from request
sql_parameters = []
regexp = re.compile( '%(\w*)%' )
match = regexp.search( sql_query )
while match:
key = match.group(1)
if key in [ 'db', 'tb' ]:
value = self.get_parameter( key )
sql_query = regexp.sub( value, sql_query, 1 )
else:
value = self.get_parameter( key, False )
sql_parameters.append( value )
sql_query = regexp.sub( '?', sql_query, 1 )
match = regexp.search( sql_query )
# extract sql_fetch
( sql_query, fetch_one ) = self.extract_sql_fetch( sql_query, 'one', [] )
( sql_query, fetch_all ) = self.extract_sql_fetch( sql_query, 'all', [ 'SELECT' ] )
( sql_query, fetch_oid ) = self.extract_sql_fetch( sql_query, 'oid', [ 'INSERT' ] )
( sql_query, fetch_nb ) = self.extract_sql_fetch( sql_query, 'nb', [ 'UPDATE', 'DELETE' ] )
if self.multi:
fetch_one = False
fetch_all = False
fetch_oid = False
fetch_nb = False
fetch_all = fetch_all and not fetch_one
# build query
self.queries.append( Query( sql=sql_query, parameters=sql_parameters, fetch_one=fetch_one, fetch_all=fetch_all, fetch_oid=fetch_oid, fetch_nb=fetch_nb ) )
# ##################################################
# extract_sql_fetch
def extract_sql_fetch( self, sql_query, fetch_id, sql_query_types ):
# extract sql_fetch from fetch_id
regexp = re.compile( '\s*\|\s*%s\s*' % ( fetch_id ), re.IGNORECASE )
if regexp.search( sql_query ):
sql_query = regexp.sub( '', sql_query )
return ( sql_query, True )
# extract sql_fetch from sql_query_types
if len( sql_query_types ) > 0 :
regexp = re.compile( '^\s*(%s)\s*' % ( '|'.join( sql_query_types ) ), re.IGNORECASE )
if regexp.search( sql_query ):
return ( sql_query, True )
return ( sql_query, False )
# ##################################################
# class Response
class Response:
# ##################################################
# constructor
def __init__( self ):
pass
# ##################################################
# set
def __setitem__( self, key, value ):
self.__dict__[ key ] = value
# ##################################################
# dump_header
def dump_header( self ):
pass
# ##################################################
# dump
def dump( self ):
pass
# ##################################################
# class JsonResponse
class JsonResponse( Response ):
# ##################################################
# header
def dump_header( self ):
print 'Content-Type: text/json'
print
# ##################################################
# dump_body
def dump( self ):
print json.dumps( self.__dict__, sort_keys=True, indent=4, separators=( ',', ': ' ) )
# ##################################################
# class Usecase
class Usecase:
# ##################################################
# constructor
def __init__( self, request=None, response=None ):
self.request = request or Request()
self.response = response or Response()
# ##################################################
# set up
def __enter__( self ):
self.response.dump_header()
return self
# ##################################################
# tear down
def __exit__( self, type, value, stack ):
if value is not None:
# print '[error] %s %s ' % ( type, value )
# traceback.print_tb( stack, file=sys.stdout )
self.response.success = False
self.response.error = '%s' % value
else:
self.response.success = True
self.response.dump()
return False
# ##################################################
# execute
def execute( self ):
# prepare sql query
self.request.build_query()
with Database( self.request.database ) as database:
# execute sql queries
for query in self.request.queries:
query.execute( database, self.response )
# ##################################################
# main
if __name__ == '__main__':
with Usecase( response=JsonResponse() ) as uc:
uc.execute()
<file_sep>/test.ini
[DEFAULT]
select.one=SELECT * FROM %tb% WHERE oid = %oid% | one
select.all=SELECT * FROM %tb%
delete=DELETE FROM %tb% WHERE oid = %oid%
delete.all=DELETE FROM %tb% WHERE 1=1
select.all=SELECT * FROM %tb%
drop=DROP TABLE test;
DROP TABLE tmp;
create=CREATE TABLE test ( oid INTEGER PRIMARY KEY, key TEXT NOT NULL, value TEXT );
CREATE TABLE tmp ( oid INTEGER PRIMARY KEY, key TEXT NOT NULL, value TEXT );
upsert=DELETE FROM test WHERE key = %key%;
INSERT INTO test ( key, value ) VALUES ( %key%, %value% );
[test]
select.one.ignorecase=SELECT * FROM %tb% WHERE oid = %oid%|OnE
insert=INSERT INTO %tb% ( key, value ) VALUES ( %key%, %value% )
update=UPDATE %tb% SET value = %value% WHERE key = %key%
count=SELECT COUNT(*) AS nb FROM test WHERE key = %key% | one | all | oid | nb ; ;
;
;
|
f0928b81b5beeaead224e317a80248e33616d2f8
|
[
"Python",
"INI"
] | 3
|
Python
|
gre-ory/lite
|
44902ed9d19d789b96ce40c0c90508829a77395e
|
898034a61ffcdae7567ba8bc3a9832b189cd8488
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class Gun : NetworkBehaviour {
public Transform muzzle;
public GameObject projectile;
public float timeBetweenShots = 0.1f;
public float muzzleVelocity = 35;
float nextShotTime;
void Update() {
if (hasAuthority && Input.GetButton("Fire1")) {
CmdShoot();
}
}
[Command]
public void CmdShoot() {
if (Time.time > nextShotTime) {
GameObject newProjectile = Instantiate(projectile, muzzle.position, muzzle.rotation);
var projectileComponent = newProjectile.GetComponent<Projectile>();
projectileComponent.SetSpeed(muzzleVelocity);
NetworkServer.Spawn(newProjectile);
nextShotTime = Time.time + timeBetweenShots;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.AI;
[RequireComponent(typeof(NavMeshAgent))]
public class Enemy : LivingEntity {
const float refreshRate = 0.25f;
NavMeshAgent pathfinder;
Transform target;
protected override void Start () {
base.Start();
pathfinder = GetComponent<NavMeshAgent>();
StartCoroutine(UpdatePath());
}
IEnumerator UpdatePath() {
while (true) {
if (target == null)
FindTarget();
if (target != null) {
Vector3 targetPosition = new Vector3(target.position.x, 0, target.position.z);
if (dead)
yield break;
pathfinder.SetDestination(targetPosition);
}
yield return new WaitForSeconds(refreshRate);
}
}
void FindTarget() {
GameObject[] players = GameObject.FindGameObjectsWithTag("Player");
float minDistance = float.PositiveInfinity;
foreach (GameObject p in players) {
float dist = Vector3.Distance(p.transform.position, transform.position);
if (target == null || dist < minDistance) {
target = p.transform;
minDistance = dist;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunManager : MonoBehaviour {
public Gun[] Guns;
public static GunManager Instance { get; private set; }
void Start() {
Instance = this;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
public class PlayerConnection : NetworkBehaviour {
public GameObject playerPrefab;
public override void OnStartLocalPlayer() {
CmdSpawnPlayer();
}
[Command]
void CmdSpawnPlayer() {
GameObject player = Instantiate(playerPrefab);
NetworkServer.SpawnWithClientAuthority(player, connectionToClient);
player.GetComponent<Player>().playerConnection = gameObject;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent (typeof(Rigidbody))]
public class Player : LivingEntity {
public float moveSpeed = 5;
public Transform weaponHold;
public GameObject playerConnection;
Vector3 velocity;
Rigidbody myRigidbody;
GameObject equippedGun;
protected override void Start () {
base.Start();
myRigidbody = GetComponent<Rigidbody>();
}
public override void OnStartAuthority() {
CmdEquipGun(0);
}
void Update () {
if (hasAuthority) {
// Movement input
velocity = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")) * moveSpeed;
// Look input
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayDistance;
if (groundPlane.Raycast(ray, out rayDistance)) {
Vector3 point = ray.GetPoint(rayDistance);
Vector3 lookPoint = new Vector3(point.x, transform.position.y, point.z);
transform.LookAt(lookPoint);
}
}
}
void FixedUpdate() {
myRigidbody.MovePosition(myRigidbody.position + velocity * Time.deltaTime);
}
[Command]
void CmdEquipGun(int gunId) {
if (0 <= gunId && gunId < GunManager.Instance.Guns.Length) {
if (equippedGun != null)
Destroy(equippedGun);
GameObject gun = Instantiate(GunManager.Instance.Guns[gunId].gameObject, weaponHold.position, weaponHold.rotation);
gun.transform.parent = weaponHold;
equippedGun = gun;
NetworkServer.SpawnWithClientAuthority(gun, playerConnection);
RpcSyncGun(gun);
}
}
[ClientRpc]
void RpcSyncGun(GameObject gun) {
gun.transform.parent = weaponHold;
gun.transform.position = weaponHold.position;
gun.transform.rotation = weaponHold.rotation;
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour {
public LayerMask collisionMask;
float speed = 10;
float damage = 1;
public void SetSpeed(float newSpeed) {
speed = newSpeed;
}
void Update () {
float distToMove = speed * Time.deltaTime;
CheckCollisions(distToMove);
transform.Translate(Vector3.forward * distToMove);
}
void CheckCollisions(float distToMove) {
Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, distToMove, collisionMask, QueryTriggerInteraction.Collide)) {
OnHit(hit);
}
}
void OnHit(RaycastHit hit) {
IDamagable damagableObject = hit.collider.GetComponent<IDamagable>();
if (damagableObject != null)
damagableObject.TakeHit(damage, hit);
GameObject.Destroy(gameObject);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
[RequireComponent(typeof(NetworkIdentity))]
public class LivingEntity : NetworkBehaviour, IDamagable {
public float startingHealth = 5;
[SyncVar]
protected float health;
protected bool dead;
protected virtual void Start() {
health = startingHealth;
}
public void TakeHit(float damage, RaycastHit hit) {
health -= damage;
if (health <= 0 && !dead) {
Die();
}
}
void Die() {
dead = true;
GameObject.Destroy(gameObject);
}
}
|
e6e4702d90b17271e98022133dfe8657bb0fbb69
|
[
"C#"
] | 7
|
C#
|
benediktwerner/Boxhead
|
2588ba093a81efffb3050a2cabf5e95c4e258980
|
70ba56f1869249e05547eb57434e4f4b4b8f6827
|
refs/heads/master
|
<file_sep>android_listview
================
listivew tayyar manba
<file_sep>package mouse.simple;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
public class ListView2 extends Activity {
private SimpleAdapter adapter;
private ListView listView2;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview2);
// 先創出主要layout(包含一個ListView),裡面的清單項目由
// 另一個layout(view2content.xml)去部屬,來達到圖文的清單
listView2 = (ListView) findViewById(R.id.listView2);
//清單面版
adapter = new SimpleAdapter(this, getData(), R.layout.view2content,
new String[] { "title", "info", "img" }, new int[] {
R.id.title, R.id.info, R.id.img });
listView2.setAdapter(adapter);
listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ListView listView = (ListView) arg0;
Toast.makeText( ListView2.this,
"ID:" + arg3 +
" 選單文字:"+ listView.getItemAtPosition(arg2).toString(),
Toast.LENGTH_LONG).show();
}
});
}
/**
* 設定清單資料
* */
private List<? extends Map<String, ?>> getData() {
// TODO Auto-generated method stub
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("title", "G1");
map.put("info", "紅豆");
map.put("img", R.drawable.icon);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "G2");
map.put("info", "綠豆");
map.put("img", R.drawable.icon);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "G3");
map.put("info", "土豆");
map.put("img", R.drawable.icon);
list.add(map);
map = new HashMap<String, Object>();
map.put("title", "G4");
map.put("info", "毛豆");
map.put("img", R.drawable.icon);
list.add(map);
return list;
}
}
<file_sep>package mouse.simple;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.widget.MediaController;
import android.widget.TextView;
import android.widget.VideoView;
public class kubul extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.kubul);
Intent in = getIntent();
String name = in.getStringExtra("name");
TextView vt=(TextView)findViewById(R.id.textView1);
vt.setText(name);
VideoView videoView = (VideoView) findViewById(R.id.videoView1);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
// Set video link (mp4 format )
// http://www.androidbegin.com/tutorial/AndroidCommercial.3gp
//http://tormahiri-js.weebly.com/uploads/1/0/6/7/1067082/java_hashset.mp4
Uri video = Uri.parse("http://tormahiri-js.weebly.com/uploads/1/0/6/7/1067082/java_hashset.mp4");
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.start();
}
}
|
38e17303035d3e84454d3afac195e11f983f76f9
|
[
"Markdown",
"Java"
] | 3
|
Markdown
|
birogul2014/android_listview
|
2d5deee076f7f0b5ce907a0b11c915fa67304a50
|
54fbe5af34cabb7bc34942bd089cb058602f5576
|
refs/heads/main
|
<repo_name>ScottStanton/Python-Ticker<file_sep>/README.md
# Python-Ticker
This is a small program to get stock values from Yahoo and display them on the command line.
This program is a way for me to learn two new items.
1. Python
1. Git
I guess I'm also learning markdown by writing this readme file.
If you like this idea and you want to take it and make it better, feel free to fork the project.
Thanks for looking, I hope you enjoying learning through this as much as I have.
## Usage:
```
usage: ticker.py [-h]|[--help]
-s|--stock stock_symbol [stock_symbol ...]
[-l|--list]
[-a|--attributes known_attributes [known_attributes ...]]
[-b|--boundary BOUNDARY BOUNDARY]
[-p|--pushbullet [l] [w] [h] [-q|--quiet]]
-s --stock --stocks: Takes one or more stock symbols to lookup.
-l --list: Prints a list of attributes that can be used with -a.
-a --attributes: Takes a list of attributes and returns the values for those attributes.
-b --boundary: Takes two values and returns "lower than XX" if the current value of the stock is lower than the lowest range.
or it returns "within XX and YY" if the current value of the stock is within the two values.
or it retuns "higher than YY" if the current value of the stock is higher than the higest value.
-p --pushbullet Sends output to Pushbullet. Requires a pushbullet token in the file ~/.pushbullettoken.
The l, w, or h options only work with boundaries. They are ignored for other options
If 'l' is chosen then it only sends if the value is lower. 'w' for within and 'h' for higher.
You can combine them (i.e. -p w h) to get data sent if it is within or higher.
-q --quiet Stops the "Message sent" message from being diplayed when pushbullet message is sent
This is useful when the command is used in a cron job
```
<file_sep>/ticker.py
#!/usr/bin/python3
#
#
import argparse
import json
import os
import requests
import sys
import time
parser = argparse.ArgumentParser()
parser.add_argument('-s','--stock','--stocks', required=True, nargs='*',
metavar='stock_symbol', help="List of stocks to get information for.")
parser.add_argument('-a','--attributes', nargs='*', metavar='known_attributes',
help="Optional list of attributes instead of the usual output.")
parser.add_argument('-l','--list', action='store_true', help="List the parameters available")
parser.add_argument('-p','--pushbullet', nargs='*', help="Send results via Pushbullet. Requires your token to be in ~/.pushbullettoken")
parser.add_argument('-b','--boundary', nargs=2, type=int,
help="Use to find out if the stock has reached the lower or upper boundary.")
parser.add_argument('-q','--quiet', nargs='*', help="Give no response when using boundary and pushbullet. Good for when running from cron.")
parser.add_argument('-v','--verbose', action='store_true', help="Write verbose output")
args = parser.parse_args()
if args.attributes and args.boundary:
parser.error("--attributes and --boundary cannot be used together.")
if args.attributes and args.list:
parser.error("--attributes and --list cannot be used together.")
if args.boundary and args.list:
parser.error("--boundary and --list cannot be used together.")
if args.list and args.pushbullet:
parser.error("--list and --pushbullet cannot be used together.")
if args.quiet and not args.pushbullet:
parser.error("--quiet requires --pushbullet")
# Let's setup some functions for later use
def debug_print(string):
# Add print statement here is -v is set. Still have to figure out how to set it.
if args.verbose:
now = time.localtime()
debug_time = str(time.strftime("%H:%M:%S ", now))
print(f'DEBUG: {debug_time} - {string}')
## End of function
#Pushbullet function
def pushbullet_note(title, body):
data_send = {"type": "note", "title": title, "body": body}
tokenpath=os.path.expanduser("~") + "/.pushbullettoken"
try:
f = open(tokenpath, "r")
except:
print("Your pushbullet token needs to be saved in " + tokenpath)
sys.exit(1)
atoken=f.read().rstrip()
f.close()
resp = requests.post('https://api.pushbullet.com/v2/pushes', data=json.dumps(data_send),
headers={'Authorization': 'Bearer ' + atoken, 'Content-Type': 'application/json'})
if resp.status_code != 200:
raise Exception('Something wrong')
else:
if args.quiet is None:
print('Message sent.')
# This function will take the stock symbol and turn the data from it into a dictionary variable that
# is able to be used in the rest of the program.
def getStockData(symbol):
global stockData
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.76 Safari/537.36'}
URL='https://query1.finance.yahoo.com/v7/finance/quote?lang=en-US®ion=US&corsDomain=finance.yahoo.com&symbols=' + symbol
debug_print(URL)
stockInfo=requests.get(URL, headers=headers)
debug_print('stockInfo is ' + str(stockInfo))
# Change the output to be a dictionary value from the psudeo json that we get.
stockData=json.loads(stockInfo.text) # Load up the json
stockData = stockData["quoteResponse"] # Strip off the first two sections
stockData = stockData["result"]
stockData = str(stockData).lstrip("[").rstrip("]") # Make valid dictionary format
stockData = stockData.replace("'",'"').replace("True",'"True"').replace("False",'"False"')
stockData = json.loads(stockData) # Now we have a dictionary set
# End of getStockData function
def printStockData():
if stockData.get('regularMarketChangePercent',0) < 0:
upDown = 'down by'
elif stockData.get('regularMarketChangePercent',0) > 0:
upDown = 'up by'
else:
upDown = 'unchanged at'
# marketState can be PRE, REGULAR, POST or POSTPOST or CLOSED
if stockData.get('marketState','err') == 'PRE':
txt = "{} closed yesterday at {:.2f} {} {:.2f}%. Yesterday's range was {}."
elif stockData.get('marketState','err') == 'REGULAR':
txt = "{} is currently at {:.2f} {} {:.2f}%. The day's range so far is {}."
else:
txt = "{} closed at {:.2f} {} {:.2f}%. The day's range is {}."
if args.pushbullet is not None:
stitle=stockData.get('symbol','err')
sbody=txt.format(stockData.get('symbol','err'),stockData.get('regularMarketPrice',0),upDown,stockData.get('regularMarketChangePercent',0),stockData.get('regularMarketDayRange','err'))
pushbullet_note(stitle,sbody)
else:
print(txt.format(stockData.get('symbol','err'),stockData.get('regularMarketPrice',0),upDown,stockData.get('regularMarketChangePercent',0),stockData.get('regularMarketDayRange','err')))
# End of printStockData
# Main program
# Deal with the command line options
# Run through each stock symbol listed on the command line
if args.list:
getStockData(args.stock[0])
for k in stockData.keys():
print(k)
sys.exit(0)
elif args.attributes:
attrbody=""
attrtitle=""
for stocks in args.stock:
attrbody += stocks + "\n"
attrtitle += "," + stocks
getStockData(stocks)
for p in args.attributes:
attrbody += p + ": " + str(stockData.get(p,'err')) + "\n"
if args.pushbullet is not None:
attrtitle = attrtitle.lstrip(",")
pushbullet_note(attrtitle,attrbody)
else:
print(attrbody)
sys.exit(0)
elif args.boundary:
low = args.boundary[0]
high = args.boundary[1]
if low > high:
low = args.boundary[1]
high = args.boundary[0]
btitle = ""
bbody = ""
barg=""
for stocks in args.stock:
btitle += "," + stocks
bbody += stocks + ": "
getStockData(stocks)
if stockData.get('regularMarketPrice',0) < low:
bbody += 'lower than ' + str(low) + '\n'
barg += 'l'
elif stockData.get('regularMarketPrice',0) > high:
bbody += 'higher than ' + str(high) + '\n'
barg += 'h'
else:
bbody += 'within ' + str(low) + ' and ' + str(high) + '\n'
barg += 'w'
if args.pushbullet is not None:
btitle = btitle.lstrip(",")
if 'l' in args.pushbullet and 'l' in barg:
pushbullet_note(btitle,bbody)
elif 'h' in args.pushbullet and 'h' in barg:
pushbullet_note(btitle,bbody)
elif 'w' in args.pushbullet and 'w' in barg:
pushbullet_note(btitle,bbody)
elif len(args.pushbullet) == 0:
pushbullet_note(btitle,bbody)
else:
print(bbody)
sys.exit(0)
else:
for stocks in args.stock:
getStockData(stocks)
printStockData()
sys.exit(0)
#End of program
|
02c35d0c2fbd6dd11e07c3768fb96ddf78cd6c75
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
ScottStanton/Python-Ticker
|
9f55ce79fa20cf93531a461d833e42f79e848599
|
46bfb06f9357d5434b870ad20c38bc767d6c1895
|
refs/heads/master
|
<file_sep># coding: utf-8
import os
import sys
import webbrowser
import pyqrcode
import time
import re
import random
import xml.dom.minidom
from safesession import SafeSession
import json
from collections import defaultdict
import multiprocessing
import mimetypes
class WeChat:
def __init__(self):
self.mode = 1 # debug mode
self.session = SafeSession()
self.encoding = 'utf-8'
self.resource_dir = os.path.join(os.getcwd(), 'resource')
self.img_resource_dir = os.path.join(os.getcwd(), 'resource', 'image')
self.voice_resource_dir = os.path.join(os.getcwd(), 'resource', 'voice')
self.video_resource_dir = os.path.join(os.getcwd(), 'resource', 'video')
self._check_and_create_dir()
self.login_retry_times = 10
self.login_retry_interval = 1 # seconds
self.timeout = 60 # seconds
self.sync_time_interval = 1 # seconds
self.default_sync_host = ['webpush.wx.qq.com', 'wx2.qq.com'] # sync check hosts
self.default_special_accounts = ['newsapp', 'filehelper', 'weibo', 'qqmail',
'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp',
'blogapp', 'facebookapp', 'masssendapp', 'meishiapp',
'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
'weixinreminder', 'wxid_novlwrv3lqwv11',
'officialaccounts',
'gh_22b87fa7cb3c', 'wxitil', 'userexperience_alarm',
'notification_messages', 'notifymessage'] # all known special accounts, always default accounts
self.uuid = ''
self.redirect_uri = ''
self.base_uri = ''
self.base_host = ''
self.uin = ''
self.sid = ''
self.skey = ''
self.pass_ticket = ''
self.device_id = 'e' + repr(random.random())[2:17]
self.base_request = {}
self.sync_key = []
self.sync_check_key = '' # formatted sync key for sync check
self.sync_check_host = ''
self.media_index = 0
self.user_info = {} # UserName->id, NickName->nickname, HeadImgUrl
self.account_info = {'group_member': {}, 'normal_member': {}} # all the accounts
# format {'group_member':{'id':{'type':'group_member', 'info':{}}, ...}, 'normal_member':{'id':{}, ...}}
self.contact_list = [] # contacts
self.public_list = [] # public accounts
self.special_list = [] # special accounts
self.group_list = [] # group chats
self.group_members_list = {} # members of all the group chats
# format {'group_id':[member, member, ...]}
self.encry_chat_room_id_list = [] # for group members' head img
def __unicode__(self, string, encoding='utf-8'):
if isinstance(string, str):
return string.decode(encoding)
elif isinstance(string, unicode):
return string
def _refresh_contact(self):
self.contact_list = []
self.public_list = []
self.group_list = []
def _check_and_create_dir(self):
if not os.path.exists(self.resource_dir):
os.makedirs(self.resource_dir)
if not os.path.exists(self.img_resource_dir):
os.makedirs(self.img_resource_dir)
if not os.path.exists(self.video_resource_dir):
os.makedirs(self.video_resource_dir)
if not os.path.exists(self.voice_resource_dir):
os.makedirs(self.voice_resource_dir)
def get_display_name(self, id):
# [TODO]
name = 'Unknown'
if id == self.user_info['UserName']:
return self.user_info['NickName'] # self
if id[:2] == '@@':
# group chat
name = 'Group Chat'
else:
# special
for member in self.special_list:
if member['UserName'] == id:
name = member['RemarkName'] if member[
'RemarkName'] else member['NickName']
# public
for member in self.public_list:
if member['UserName'] == id:
name = member['RemarkName'] if member[
'RemarkName'] else member['NickName']
# contact
for member in self.contact_list:
if member['UserName'] == id:
name = member['RemarkName'] if member[
'RemarkName'] else member['NickName']
# group chat members
return name
def get_msg_image(self, msg_id):
url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msg_id, self.skey)
r = self.session.get(url)
data = r.content
fn = 'img_' + msg_id + '.jpg'
with open(os.path.join(self.img_resource_dir, fn), 'wb') as f:
f.write(data)
return fn
def get_msg_voice(self, msg_id):
url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msg_id, self.skey)
r = self.session.get(url)
data = r.content
fn = 'voice_' + msg_id + '.mp3'
with open(os.path.join(self.voice_resource_dir, fn), 'wb') as f:
f.write(data)
return fn
def get_msg_video(self, msg_id):
url = self.base_uri + '/webwxgetvideo?msgid=%s&skey=%s' % (msg_id, self.skey)
headers = {
'Range': 'bytes=0-'
}
r = self.session.get(url, headers=headers)
data = r.content
fn = 'video_' + msg_id + '.mp4'
with open(os.path.join(self.video_resource_dir, fn), 'wb') as f:
f.write(data)
return fn
def run(self):
try:
self.get_uuid()
self.get_qrcode(os.path.join(self.resource_dir, 'qr.png'))
result = self.wait_for_login()
print 'wait_for_login : {r}'.format(r=result)
result = self.sync_login()
print 'sync_login : {r}'.format(r=result)
result = self.wechat_init()
print 'wechat_init : {r}'.format(r=result)
result = self.status_notify()
print 'status_notify : {r}'.format(r=result)
if self.get_contact():
print 'get_contacts: %d contacts' % len(self.contact_list)
# print self.contact_list
# print self.group_members_list
with open(os.path.join(self.resource_dir, 'contact_list.json'), 'w') as f:
f.write(json.dumps(self.contact_list))
with open(os.path.join(self.resource_dir, 'special_list.json'), 'w') as f:
f.write(json.dumps(self.special_list))
with open(os.path.join(self.resource_dir, 'group_list.json'), 'w') as f:
f.write(json.dumps(self.group_list))
with open(os.path.join(self.resource_dir, 'public_list.json'), 'w') as f:
f.write(json.dumps(self.public_list))
with open(os.path.join(self.resource_dir, 'group_list.json'), 'w') as f:
f.write(json.dumps(self.group_list))
with open(os.path.join(self.resource_dir, 'group_members_list.json'), 'w') as f:
f.write(json.dumps(self.group_members_list))
with open(os.path.join(self.resource_dir, 'account_info.json'), 'w') as f:
f.write(json.dumps(self.account_info))
# result = self.send_text_message('123', 'ljy')
# print 'send_text_message to user : {r}'.format(r=result)
# self.upload_media('siri.jpeg')
# self.upload_media('safesession.py')
# result = self.send_image_and_emotion_message('siri.jpeg', 'ljy')
# print 'send_image_and_emotion_message to user : {r}'.format(r=result)
# self.message_listener()
listener = multiprocessing.Process(target=self.message_listener())
listener.run()
except KeyboardInterrupt:
print ' command : QUIT'
def get_uuid(self):
url = 'https://login.weixin.qq.com/jslogin'
params = {
'appid' : 'wx782c26e4c19acffb', # web微信
# wxeb7ec651dd0aefa9 微信网页版
'fun' : 'new',
'lang' : 'zh_CN',
'_' : int(time.time()) * 1000 + random.randint(1, 999),
}
r = self.session.get(url, params=params)
r.encoding = self.encoding
pattern = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
result = re.search(pattern, r.text)
if result:
self.uuid = result.group(2)
return result.group(1) == '200'
return False
def get_qrcode(self, qrcode_path):
qr = pyqrcode.create('https://login.weixin.qq.com/l/' + self.uuid)
qr.png(qrcode_path, scale=8)
if sys.version_info >= (3, 3):
from shlex import quote
else:
from pipes import quote
if sys.platform.find('darwin') >= 0:
command = "open -a /Applications/Preview.app %s&" % quote(qrcode_path)
os.system(command)
else:
webbrowser.open(qrcode_path)
def wait_for_login(self):
# tip = 1, 未扫描,
# 201: scaned
# 408: timeout
# tip = 0, 已扫描,
# 200: confirmed
url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login'
params = {
'tip' : 1,
'uuid': self.uuid,
'_' : int(time.time())
}
retry_time = 0
code = 'unknown'
data = ''
while retry_time < self.login_retry_times:
r = self.session.get(url, params=params)
r.encoding = self.encoding
data = r.text
pattern = r'window.code=(\d+);'
result = re.search(pattern, data)
code = result.group(1)
if code == '200':
pattern = r'window.redirect_uri="(\S+?)";'
result = re.search(pattern, data)
redirect_uri = result.group(1) + '&fun=new'
self.redirect_uri = redirect_uri
self.base_uri = redirect_uri[:redirect_uri.rfind('/')] # https://wx.qq.com/cgi-bin/mmwebwx-bin
temp_host = self.base_uri[8:]
self.base_host = temp_host[:temp_host.find("/")] # wx.qq.com
return code
elif code == '201':
print '[DEBUG]scanned'
params['tip'] = 0
elif code == '408':
print '[DEBUG]timeout-retry time: %s' % (retry_time + 1)
params['tip'] = 1
retry_time += 1
time.sleep(self.login_retry_interval)
else:
print '[DEBUG]unknown errors'
params['tip'] = 1
retry_time += 1
time.sleep(self.login_retry_interval)
return code
def sync_login(self):
r = self.session.get(self.redirect_uri)
# https://wx.qq.com/cgi-bin/mmwebwx-bin/webwxnewloginpage?ticket=xxx&uuid=xxx&lang=xxx&scan=xxx&fun=new
r.encoding = 'utf-8'
data = r.text
root = xml.dom.minidom.parseString(data).documentElement
for node in root.childNodes:
if node.nodeName == 'wxuin':
self.uin = node.childNodes[0].data
elif node.nodeName == 'wxsid':
self.sid = node.childNodes[0].data
elif node.nodeName == 'skey':
self.skey = node.childNodes[0].data
elif node.nodeName == 'pass_ticket':
self.pass_ticket = node.childNodes[0].data
if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
return False
self.base_request = {
'Uin': self.uin,
'Sid': self.sid,
'Skey': self.skey,
'DeviceID': self.device_id,
}
return True
def wechat_init(self):
url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s&skey=%s' \
% (int(time.time()), self.pass_ticket, self.skey)
params = {
'BaseRequest': self.base_request
}
r = self.session.post(url, data=json.dumps(params))
r.encoding = self.encoding
result = json.loads(r.text)
self.sync_key = result['SyncKey']
self.sync_check_key = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
for keyVal in self.sync_key['List']])
self.user_info = result['User']
#print self.user_info
return result['BaseResponse']['Ret'] == 0
def status_notify(self):
url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
params = {
'BaseRequest' : self.base_request,
"Code" : 3,
"FromUserName" : self.user_info['UserName'],
"ToUserName" : self.user_info['UserName'],
"ClientMsgId" : int(time.time())
}
r = self.session.post(url, data=json.dumps(params))
r.encoding = self.encoding
result = json.loads(r.text)
return result['BaseResponse']['Ret'] == 0
def get_contact(self):
url = self.base_uri + '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' \
% (self.pass_ticket, self.skey, int(time.time()))
params = {}
r = self.session.post(url, data=json.dumps(params))
if r == '':
return False
r.encoding = self.encoding
result = json.loads(r.text)
self.group_members_list = result['MemberList']
self._refresh_contact()
for contact in self.group_members_list:
if contact['VerifyFlag'] & 8 != 0:
self.public_list.append(contact)
self.account_info['normal_member'][contact['UserName']] = {'type': 'public', 'info': contact}
elif contact['UserName'] in self.default_special_accounts:
self.special_list.append(contact)
self.account_info['normal_member'][contact['UserName']] = {'type': 'special', 'info': contact}
elif contact['UserName'].find('@@') != -1:
self.group_list.append(contact)
self.account_info['normal_member'][contact['UserName']] = {'type': 'group', 'info': contact}
elif contact['UserName'] == self.user_info['UserName']:
self.account_info['normal_member'][contact['UserName']] = {'type': 'self', 'info': contact}
else:
self.contact_list.append(contact)
self.account_info['normal_member'][contact['UserName']] = {'type': 'unknown', 'info': contact}
url = self.base_uri + '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
params = {
'BaseRequest' : self.base_request,
"Count" : len(self.group_list),
"List" : [{"UserName": group['UserName'], "EncryChatRoomId": ""} for group in self.group_list]
}
r = self.session.post(url, data=json.dumps(params))
r.encoding = self.encoding
dic = json.loads(r.text)
group_members = {}
encry_chat_room_id = {}
for group in dic['ContactList']:
gid = group['UserName']
members = group['MemberList']
group_members[gid] = members
encry_chat_room_id[gid] = group['EncryChatRoomId']
self.group_members_list = group_members
self.encry_chat_room_id_list = encry_chat_room_id
for group in self.group_members_list:
for member in self.group_members_list[group]:
if member['UserName'] not in self.account_info:
self.account_info['group_member'][member['UserName']] = \
{'type': 'group_member', 'info': member, 'group': group}
return True
def sync_check(self): # return [retcode, selector]
url = 'https://' + self.sync_check_host + '/cgi-bin/mmwebwx-bin/synccheck?'
params = {
'r': int(time.time()),
'sid': self.sid,
'uin': self.uin,
'skey': self.skey,
'deviceid': self.device_id,
'synckey': self.sync_check_key,
'_': int(time.time()),
}
r = self.session.get(url, params=params, timeout=60)
if r == '':
return [-1, -1]
r.encoding = self.encoding
data = r.text
result = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
retcode = result.group(1)
selector = result.group(2)
return [retcode, selector]
def choose_sync_host(self):
for host in self.default_sync_host:
self.sync_check_host = host
retcode = self.sync_check()[0]
if retcode == '0':
return True
return False
def sync(self):
url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
% (self.sid, self.skey, self.pass_ticket)
params = {
'BaseRequest' : self.base_request,
'SyncKey' : self.sync_key,
'rr' : ~int(time.time())
}
r = self.session.post(url, data=json.dumps(params), timeout=60)
if r == '':
return None
r.encoding = self.encoding
result = json.loads(r.text)
if result['BaseResponse']['Ret'] == 0:
self.sync_key = result['SyncKey']
self.sync_check_key = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
for keyVal in self.sync_key['List']])
return result
def search_content(self, key, content, ft):
if ft == 'attr': # key is an attribution of a xml label
result = re.search(key + '\s?=\s?"([^"<]+)"', content)
if result:
return result.group(1)
elif ft == 'xml': # key is a xml label
result = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
if not result:
result = re.search(
'<{0}><!\[CDATA\[(.*?)\]\]></{0}>'.format(key), content)
if result:
return result.group(1)
return None
def custom_message_receiver(self, msg):
# add custom message receiver in or by inheriting this func
print msg["msg_id"]
print msg["hint"]
pass
def message_handler(self, r):
for msg in r['AddMsgList']:
msg_type = msg['MsgType']
name = self.get_display_name(msg['FromUserName'])
content = msg['Content'].replace('<', '<').replace('>', '>')
msg_id = msg['MsgId']
hint_msg = ''
if msg_type == 1: # text
hint_msg = content
elif msg_type == 3: # image
image = self.get_msg_image(msg_id)
hint_msg = '%s send image: %s' % (name, image)
elif msg_type == 34: # voice
voice = self.get_msg_voice(msg_id)
hint_msg = '%s send voice: %s' % (name, voice)
elif msg_type == 42: # recommend card
info = msg['RecommendInfo']
# print('%s send you recommend:' % name)
# print(' nickname : %s' % info['NickName'])
# print(' alias : %s' % info['Alias'])
# print(' district : %s %s' % (info['Province'], info['City']))
# print(' gender : %s' % ['unknown', 'male', 'female'][info['Sex']])
elif msg_type == 47: # emotion
url = self.search_content('cdnurl', content, 'attr')
hint_msg = '%s send emotion: %s' % (name, url)
elif msg_type == 49: # link
app_msg_type = defaultdict(lambda: "")
app_msg_type.update({5: 'link', 3: 'music', 7: 'weibo'}) # red package 2001
# print('%s share %s:' % (name, app_msg_type[msg['AppMsgType']]))
# print(' title : %s' % msg['FileName'])
# print(' description : %s' % self.search_content('des', content, 'xml'))
# print(' link : %s' % msg['Url'])
# print(' from : %s' % self.search_content('appname', content, 'xml'))
card = {
'title': msg['FileName'],
'description': self.search_content('des', content, 'xml'),
'url': msg['Url'],
'appname': self.search_content('appname', content, 'xml')
}
hint_msg = '%s shared %s: %s' % (name, app_msg_type[msg['AppMsgType']], json.dumps(card))
elif msg_type == 51: # init message
#hint_msg = ' contact init'
return
elif msg_type == 62: # video
video = self.get_msg_video(msg_id)
hint_msg = '%s send video : %s' % (name, video)
elif msg_type == 10002: # recall
recall_msg_content = json.dumps(msg)
result = re.search('<msgid>([^<]+)</msgid>', recall_msg_content)
hint_msg = 'recalled message id: %s' % result.group(1)
else: # unknown
hint_msg = 'message type: %d, unknown message(maybe view it on phone)' % msg['MsgType']
# add custom message receiver
msg = {
"msg_type_id" : msg_type,
"msg_id" : msg_id,
"user_id" : msg['FromUserName'],
"to_user_id" : msg['ToUserName'],
"hint" : hint_msg
}
self.custom_message_receiver(msg)
def message_listener(self):
self.choose_sync_host()
while True:
current_check_time = time.time()
[retcode, selector] = self.sync_check()
if retcode == '1100': # logout / fail to login
break
elif retcode == '1101': # login at another device
break
elif retcode == '0':
if selector == '2': # new message
r = self.sync()
if r is not None:
self.message_handler(r)
elif selector == '3': #
r = self.sync()
if r is not None:
self.message_handler(r)
elif selector == '4': # contact update
r = self.sync()
if r is not None:
self.get_contact()
elif selector == '6': #
r = self.sync()
if r is not None:
self.message_handler(r)
elif selector == '7': # operate on phone
r = self.sync()
if r is not None:
self.message_handler(r)
elif selector == '0': # none
pass
else:
print 'Unknown error'
current_check_time = time.time() - current_check_time
if current_check_time < self.sync_time_interval:
time.sleep(self.sync_time_interval - current_check_time)
def send_text_message(self, content, dst):
content = self.__unicode__(content)
msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
# print msg_id
if dst == '':
return False
dst = self.__unicode__(dst)
dst_id = ''
for contact in self.contact_list:
if 'RemarkName' in contact and contact['RemarkName'] == dst:
dst_id = contact['UserName']
if 'NickName' in contact and contact['NickName'] == dst:
dst_id = contact['UserName']
if 'DisplayName' in contact and contact['DisplayName'] == dst:
dst_id = contact['UserName']
for group in self.group_list:
if 'RemarkName' in group and group['RemarkName'] == dst:
dst_id = group['UserName']
if 'NickName' in group and group['NickName'] == dst:
dst_id = group['UserName']
if 'DisplayName' in group and group['DisplayName'] == dst:
dst_id = group['UserName']
if dst_id == '':
return False
url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
params = {
'BaseRequest' : self.base_request,
'Msg': {
'Type' : 1, # text
'Content' : content,
'FromUserName' : self.user_info['UserName'],
'ToUserName' : dst_id,
'LocalID' : msg_id,
'ClientMsgId' : msg_id
}
}
result = self.session.post(url, data=json.dumps(params).encode(self.encoding))
# print result.json()
if result == '':
return False
return result.json()['BaseResponse']['Ret'] == 0
def upload_media(self, path):
if not os.path.exists(path=path):
return None
file_len = str(os.path.getsize(path))
file_type = mimetypes.guess_type(path, strict=False)[0]
media_type = ''
if file_type.split('/')[0] == 'image':
media_type = 'pic'
else:
media_type = 'doc'
# print media_type
last_modified_date = time.strftime('%m/%d/%Y, %H:%M:%S GMT+0800 (CST)')
client_media_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
url = 'https://file.'+self.base_host+'/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json'
upload_media_request = {
'BaseRequest' : self.base_request,
'ClientMediaId' : client_media_id,
'TotalLen' : file_len,
'StartPos' : 0,
'DataLen' : file_len,
'MediaType' : 4,
}
params = {
'id' : (None, 'WU_FILE_%s' % str(self.media_index)),
'name' : (None, os.path.basename(path)),
'type' : (None, file_type),
'lastModifiedDate' : (None, last_modified_date),
'size' : (None, file_len),
'mediatype' : (None, media_type),
'uploadmediarequest': (None, json.dumps(upload_media_request)),
'webwx_data_ticket' : (None, self.session.cookies['webwx_data_ticket']),
'pass_ticket' : (None, self.pass_ticket),
'filename' : (os.path.basename(path), open(path, 'rb'), file_type.split('/')[1]),
}
r = self.session.post(url, files=params)
self.media_index += 1
# print r.json()
if r == '':
return None
media_id = json.loads(r.text)['MediaId']
return media_id
def send_image_and_emotion_message(self, path, dst):
media_id = self.upload_media(path)
if media_id is None:
return False
if dst == '':
return False
dst = self.__unicode__(dst)
dst_id = ''
for contact in self.contact_list:
if 'RemarkName' in contact and contact['RemarkName'] == dst:
dst_id = contact['UserName']
if 'NickName' in contact and contact['NickName'] == dst:
dst_id = contact['UserName']
if 'DisplayName' in contact and contact['DisplayName'] == dst:
dst_id = contact['UserName']
for group in self.group_list:
if 'RemarkName' in group and group['RemarkName'] == dst:
dst_id = group['UserName']
if 'NickName' in group and group['NickName'] == dst:
dst_id = group['UserName']
if 'DisplayName' in group and group['DisplayName'] == dst:
dst_id = group['UserName']
if dst_id == '':
return False
url = self.base_uri + '/webwxsendmsgimg?fun=async&f=json'
params = {
'BaseRequest': self.base_request,
'Msg': {
'Type' : 3,
'MediaId' : media_id,
'FromUserName' : self.user_info['UserName'],
'ToUserName' : dst_id,
'LocalID' : str(time.time() * 1e7),
'ClientMsgId' : str(time.time() * 1e7),
},
}
if path[-4:] == '.gif':
url = self.base_uri + '/webwxsendemoticon?fun=sys'
params['Msg']['Type'] = 47
params['Msg']['EmojiFlag'] = 2
r = self.session.post(url, data=json.dumps(params))
if r == '':
return False
if json.loads(r.text)['BaseResponse']['Ret'] == 0:
return True
else:
return False
<file_sep>from enum import Enum
from wechat import WeChat
class Mode(Enum):
NORMAL = 0,
DEBUG = 1,
BOT = 2
def main():
client = WeChat()
client.run()
if __name__ == '__main__':
main()
<file_sep>import requests
import traceback
class SafeSession(requests.Session):
def request(self, method, url, retry_time=4, params=None, data=None, headers=None, cookies=None, files=None, auth=None,
timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None,
json=None):
for i in range(retry_time):
try:
return super(SafeSession, self).request(method, url, params, data, headers, cookies, files, auth,
timeout,
allow_redirects, proxies, hooks, stream, verify, cert, json)
except Exception as e:
print e.message, traceback.format_exc()
continue
try:
return super(SafeSession, self).request(method, url, params, data, headers, cookies, files, auth,
timeout,
allow_redirects, proxies, hooks, stream, verify, cert, json)
except Exception as e:
raise e
|
a1ad71108dd9cd2229dbfc7e49409667abe84144
|
[
"Python"
] | 3
|
Python
|
stoneSJH/WechatClient
|
549ef3c0858247aad48d0d8fdc561d0acb994464
|
19055029b2d944a368169b94e065f8059de3c65a
|
refs/heads/master
|
<repo_name>KillerDeveloper/VPN_Android<file_sep>/app/src/main/java/com/example/vpnandroid/MainActivity.java
package com.example.vpnandroid;
import androidx.appcompat.app.AppCompatActivity;
import android.net.VpnService;
import android.net.VpnService.Builder;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
public class MainActivity extends AppCompatActivity {
VpnService.Builder builder = new VpnService.Builder();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VpnService.Builder builder = new VpnService.Builder();
ParcelFileDescriptor localTunnel = builder
.addAddress("192.168.2.2", 24)
.addRoute("0.0.0.0", 0)
.addDnsServer("192.168.1.1")
.establish();
}
}
|
91b813b2adff39485b2088b5ee56cb4731987c06
|
[
"Java"
] | 1
|
Java
|
KillerDeveloper/VPN_Android
|
eb0864c5089d165e3dd39e2eda76ccae9384e62c
|
43c1c5365f0bfacdd59ee0ebac36fb0fee80e803
|
refs/heads/master
|
<file_sep>class Calculadora
def soma(n1, n2)
n1 + n2
end
def subtracao(n1, n2)
n1 - n2
end
def multiplicacao(n1, n2)
n1 * n2
end
def divisao(n1, n2)
case n2
when 0
0
else
n1 / n2
end
end
def calcular(n1, n2, op)
case op
when '/'
n1 / n2
when '*'
n1 * n2
when '+'
n1 + n2
when '-'
n1 - n2
end
end
end
|
87352d802fdac306378b0904cfebaecfba017c19
|
[
"Ruby"
] | 1
|
Ruby
|
tuannyruiz/codesaga-ruby
|
06bffbb61f9d5718668ec6bf01925f95da118e24
|
0adc73e28eb5b4c9bb1177f69497a770ff5fa2d9
|
refs/heads/master
|
<file_sep>package warrior2;
import java.util.ArrayList;
public class Board {
private int position;
private ArrayList<Cell> cases;
private Gobelin mob;
private Menu menu;
public Character mag;
private final int BOARD_SIZE = 64;
public Board() {
this.cases = new ArrayList<Cell>();
this.menu = new Menu();
fillCasesRandomly();
}
public void fillCasesRandomly() {
this.cases.add(0, new EmptyCell());
for (int i = 1; i <= BOARD_SIZE; i++) {
int random = 1 + (int) (Math.random() * 7);
switch (random) {
case 1:
case 2:
this.cases.add(new EmptyCell());
break;
case 3: case 5:
this.cases.add(new Gobelin());
break;
case 4:
this.cases.add(new Mjolnir());
break;
case 7 :
this.cases.add(new Excalibur());
case 6:
this.cases.add(new SmallPotion());
}
}
for (int i = 0; i <= BOARD_SIZE; i ++ ) {
Cell cellule = this.cases.get(i);
System.out.println(cellule.toString());
}
}
public void positionJoueur(int dice ) {
if( this.position > BOARD_SIZE) {
this.position = BOARD_SIZE;
}
}
public int rollDice() {
int dice = 1+ (int)(Math.random()*6);
this.position +=dice ;
positionJoueur(dice);
return this.position;
}
public int getPosition() {
return position;
}
public void setPosition(int position) {
this.position = position;
}
public Cell currentCellAtPosition() {
return this.cases.get(this.position);
}
}
<file_sep>package warrior2;
public class SmallPotion extends Cell {
private final int ADD_HEALTH = 8;
public SmallPotion() {}
public void interactWithPlayer(Character Player) {
int newHealth;
System.out.println("Je suis une petite potion");
System.out.println(Player);
System.out.println( "PV avant : " + Player.getHealth());
newHealth = Player.getHealth() + ADD_HEALTH;
System.out.println("PV après : " + newHealth);
Player.setHealth(newHealth);
System.out.println(Player.getHealth());
}
public String toString() {
return "je suis une potion";
}
}
<file_sep>package warrior2;
public class Fireball extends Weapons {
public Fireball(int strength, String nom) {
super(strength, nom);
}
@Override
void interactWithPlayer(Character player) {
// TODO Auto-generated method stub
}
}
<file_sep>package warrior2;
public class Magician extends Character {
private final static int HEALTH = 3;
private final static int HEALTH_MAX = 6;
private final static int STRENGTH = 8;
private final static int STRENGTH_MAX= 15;
public Magician() {
this("toto",HEALTH,STRENGTH);
}
public Magician(String name) {
super(name,HEALTH,STRENGTH);
}
public Magician(String name,int health,int strength) {
super(name,health,strength);
}
@Override
public String toString() {
return "Magician : " +getName()+"\nPV : "+HEALTH+"\nATK :"+STRENGTH+ "\n";
}
@Override
public void interactWithPlayer(Character player) {
// TODO Auto-generated method stub
}
}
<file_sep>package warrior2;
import java.util.Scanner;
public class Menu {
private Scanner sc;
public Menu() {
sc = new Scanner(System.in);
}
public int displayMenuNoPlayer() {
int option = 0;
do {
System.out.println(" ==== Bienvenue dans le jeu Warriors !! ====");// Affichage menu
System.out.println("1 - Créer Personnage ");
System.out.println("2 - Voir les personnages");
System.out.println("3 - Modifier les personnage");
System.out.println("4 - Quittez le jeu");
option = sc.nextInt();// Récupération choix
sc.nextLine();
} while (option < 1 || option > 4);
return option;
}
public char displayMenuPlayer() {
char option = ' ';
System.out.println("\n 1 - Lancer une partie");
System.out.println(" 2 - Créer un autre personnage ");
System.out.println(" Q - Revenir au menu principal");
option = sc.nextLine().charAt(0);
return option;
}
public String displayDice(int dice,int position) {
String option = "";
System.out.println("Entrée - Lancez le dè");
option = sc.nextLine();
System.out.println("Résultat du lancé de dé : " + dice + "\n");
System.out.println("Vous avancez a la case " + position);
return option;
}
}
<file_sep>package warrior2;
abstract class Item {
}
<file_sep>package warrior2;
public abstract class Cell {
public Cell() {}
abstract void interactWithPlayer(Character player);
public String toString() {
return "je suis une case ";
}
}
<file_sep>package warrior2;
import java.util.Scanner;
import java.util.ArrayList;
public class Game {
// Attributs
private Board board;
private Character player;
private Character mob;
private Menu menu;
private Scanner sc;
private int etatDuJeu;
private final int NEW_GAME = 1;
private final int CREATE_CHAR = 2;
private final int NEW_CHAR = 3;
private final int IN_GAME = 4;
private final int CREATE_NEW_CHAR = 5;
public final int END_GAME = 6;
private final static int CASE_MAX = 30;
public int getEtatDuJeu() {
return etatDuJeu;
}
public void setEtatDuJeu(int etatDuJeu) {
this.etatDuJeu = etatDuJeu;
}
// Constructeur
public Game() {
this.sc = new Scanner(System.in);
this.menu = new Menu();
this.board = new Board();
this.etatDuJeu = NEW_GAME;
}
// Méthode instancier pour lancer le jeu
public void playGame() {
switch (etatDuJeu) {
case NEW_GAME:
this.getChoiceNoPlayer();
break;
case CREATE_CHAR:
this.getChoicePlayer();
break;
case CREATE_NEW_CHAR:
this.getChoicePlayer();
this.play();
break;
case IN_GAME:
this.play();
break;
case END_GAME:
System.out.println("Fin du jeu ");
break;
}
}
//Permet de jouer un tour
private void play() {
int positionPlayer = board.rollDice();
menu.displayDice(positionPlayer, board.getPosition());
board.currentCellAtPosition().interactWithPlayer(this.player);
etatDuJeu = IN_GAME;
//le joueur a une arme
//statut = armeEquipé
}
// Récpére le choix du joueur depuis la classe menu
public void getChoiceNoPlayer() {
int choiceNoPlayer = menu.displayMenuNoPlayer();
switch (choiceNoPlayer) {
case 1:
this.createCharacter();// Appelle de la fontion pour crée un personnage
etatDuJeu = CREATE_CHAR;// L'état du jeu passera au stade de création de personnage
break;
case 2:
Magician mag = new Magician("Wizard", 10, 6); // Affichage de classe par défaut
System.out.println("1 - " + mag.toString() + "\n");
Warrior war = new Warrior("Arthur", 12, 8);
System.out.println("2 - " + war.toString() + "\n");
etatDuJeu = NEW_GAME;
break;
case 3:
System.out.println("Fonctionnalité a venir");
break;
case 4:
System.out.println("See you space cowboys");
break;
default:
System.out.println("Veuillez faire un choix valide");
break;
}
}
public void getChoicePlayer() {
char choicePLayer = menu.displayMenuPlayer();
switch (choicePLayer) {
case '1':
this.play();
break;
case '2':
etatDuJeu = CREATE_NEW_CHAR;
//this.createCharacter();
break;
case 'q':
menu.displayMenuNoPlayer();
etatDuJeu = NEW_GAME;
break;
default:
System.out.println("Veuillez faire un choix valide");
break;
}
}
//Permet de créer un personnage
public void createCharacter() {
char characterSelect = ' ';
String name;
do {
System.out.println(" Créer Personnage \n 1 - Guerrier \n 2 - Magicien ");
characterSelect = sc.nextLine().charAt(0);
if (characterSelect != '1' && characterSelect != '2') {
System.out.println("Veuillez faire un choix valide \n");
}
else if (characterSelect == '1') {
System.out.println("Vous avez choisis le guerrier");
System.out.print("Choisisez un pseudo : ");
name = sc.nextLine();
Warrior war = new Warrior(name);
this.player = war;
System.out.println(war.toString());
}
else {
System.out.println("Vous avez choisi le magicien ");
System.out.print("Choisisez un pseudo : ");
name = sc.nextLine();
Magician mag = new Magician(name);
this.player = mag;
System.out.println(mag.toString());
}
} while (characterSelect < '1' || characterSelect > '2');
}
// Génére un dé aléatoire
// public int rollDice() {
// int dice = 1 + (int) (Math.random() * 6);
// try {
// movePlayer(dice);
// } catch (MovePlayerException e) {
// // TODO Auto-generated catch block
// e.getMessage();
// }
// return dice;
// }
//
//// Met a jour la position du joueur par rapport au dé
// private void movePlayer(int dice) throws MovePlayerException {
// this.position += dice;
//
// if (this.position > CASE_MAX)
// throw new MovePlayerException();
// }
}
<file_sep>package warrior2;
public class MovePlayerException extends Exception {
public MovePlayerException() {
super("Vous avez depassť la taille du plateau, vous avez fiini la partie");
}
@Override
public String getMessage() {
String msg = "Error MovePlayerException : " + super.getMessage();
return msg;
}
}
<file_sep>package warrior2;
public class Main {
public static void main(String[] args) throws MovePlayerException {
Game game = new Game();
while(game.getEtatDuJeu() != game.END_GAME) {
game.playGame();
}
// Mjolnir weap = new Mjolnir();
// System.out.println(weap.toString());
//
// Excalibur weap1 = new Excalibur();
// System.out.println(weap1.toString());
// Gobelin mob = new Gobelin();
//
// System.out.println(mob.toString());
//gaw
//Board cases = new Board();
//
}}
<file_sep>package warrior2;
public class Warrior extends Character {
private final static int HEALTH = 5;
private final static int HEALTH_MAX = 12;
private final static int STRENGTH = 7;
private final static int STRENGTH_MAX= 15;
public Warrior() {
super("Dante",HEALTH,STRENGTH);
}
public Warrior(String name) {
super(name,HEALTH,STRENGTH);
}
public Warrior(String name,int health,int strength) {
super(name,health,strength);
}
@Override
public String toString() {
return "Warrior : " +getName()+"\nPV : "+HEALTH+"\nATK : "+STRENGTH;
}
@Override
void interactWithPlayer(Character player) {
}
}
|
a9626a29fb7e5ddddae0527051c901fd9e24dc07
|
[
"Java"
] | 11
|
Java
|
Git-Sebastien/Warrior2
|
bd38b9bee98f71bf2f225f15e93dd920e318f6e0
|
247b4f4b98fe2a496527f2c04e48e5fe5a2b65c2
|
refs/heads/master
|
<file_sep>package com.guan.panegame;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
/**
* 实现主角及主角相关元素的类
* @author Administrator
*
*/
public class Player
{
//主角的血量与血量图,血量默认为3
private int playerHp=3;
private Bitmap bmpPlayerHp;
//主角的坐标以及位图
public int x,y;
private Bitmap bmpPlayer;
//主角移动的速度
private int speed=5;
//移动标记
public static boolean isUp,isDown,isLeft,isRight,isUpLeft,isUpRight,isDownLeft,isDownRight;
//碰撞后处于物理状态
//计时器
private int noCollisionCount=0;
//无敌状态时间
private int noCollisionTime=60;
//是否相碰
private boolean isCollison;
//得分
private int score=0;
public Player(Bitmap bmpPlayer,Bitmap bmpPlayerHp)
{
this.bmpPlayer=bmpPlayer;
this.bmpPlayerHp=bmpPlayerHp;
//起初时,飞机在屏幕地下正中
x=MySurfaceView.screenW/2-bmpPlayer.getWidth()/2;
y=MySurfaceView.screenH-bmpPlayer.getHeight()/2;
}
/**
*绘制主角
*/
public void onDraw(Canvas canvas,Paint paint)
{
canvas.drawText("SCORE:"+score, 0,20, paint);
//绘制主角,当出于无敌状态则闪烁
if(isCollison)
{
//每两次游戏循环,绘制一次主角
if(noCollisionCount%2 ==0)
canvas.drawBitmap(bmpPlayer, x,y, paint);
}
else
{
canvas.drawBitmap(bmpPlayer, x,y, paint);
}
//绘制主角血量
for(int i=0;i<playerHp;i++)
{
canvas.drawBitmap(bmpPlayerHp,i*bmpPlayerHp.getWidth(),MySurfaceView.screenH-bmpPlayerHp.getHeight(), paint);
}
}
/**
* 主角移动逻辑
*/
public void logic()
{
if(isLeft)
{
x-=speed;
}
if(isRight)
{
x+=speed;
}
if(isUp)
{
y-=speed;
}
if(isDown)
{
y+=speed;
}
if(isUpRight)
{
y-=speed;
x+=speed;
}
if(isUpLeft)
{
y-=speed;
x-=speed;
}
if(isDownRight)
{
y+=speed;
x+=speed;
}
if(isDownLeft)
{
y+=speed;
x-=speed;
}
//判断是否出界
if(x+bmpPlayer.getWidth()>=MySurfaceView.screenW)
{
x=MySurfaceView.screenW-bmpPlayer.getWidth();
}
else if(x<=0)
{
x=0;
}
if(y+bmpPlayer.getHeight()>=MySurfaceView.screenH)
{
y=MySurfaceView.screenH-bmpPlayer.getHeight();
}
else if(y<0)
{
y=0;
}
//处理无敌状态
if(isCollison)
{
noCollisionCount++;
if(noCollisionCount>=noCollisionTime)
{
isCollison=false;
noCollisionCount=0;
}
}
}
/**
* 设置主角血量
*/
public void setPlayerHp(int Hp)
{
this.playerHp=Hp;
}
/**
* 获取主角血量
*/
public int getPlayerHp()
{
return playerHp;
}
/**
* 判断主角是不是与敌机相碰
*/
public boolean isCollsionWith(Enemy en)
{
if(isCollison==false)
{
int x2 = en.x;
int y2 = en.y;
int w2 = en.frameW;
int h2 = en.frameH;
if (x >= x2 && x >= x2 + w2) {
return false;
} else if (x <= x2 && x + bmpPlayer.getWidth() <= x2) {
return false;
} else if (y >= y2 && y >= y2 + h2) {
return false;
} else if (y <= y2 && y + bmpPlayer.getHeight() <= y2) {
return false;
}
//碰撞即进入无敌状态
isCollison = true;
return true;
}
else
return false;
}
/**
* 判断主角是不是与子弹相碰
*/
public boolean isCollsionWith(Bullet bullet)
{
if(isCollison==false)
{
int x2 = bullet.bulletX;
int y2 = bullet.bulletY;
int w2 = bullet.bmpBullet.getWidth();
int h2 = bullet.bmpBullet.getHeight();
if (x >= x2 && x >= x2 + w2) {
return false;
} else if (x <= x2 && x + bmpPlayer.getWidth() <= x2) {
return false;
} else if (y >= y2 && y >= y2 + h2) {
return false;
} else if (y <= y2 && y + bmpPlayer.getHeight() <= y2) {
return false;
}
//碰撞即进入无敌状态
isCollison = true;
return true;
}
else
return false;
}
/**
* 判断主角是不是与boss相碰
*/
public boolean isCollsionWith(Boss en)
{
if(isCollison==false)
{
int x2 = en.x;
int y2 = en.y;
int w2 = en.frameW;
int h2 = en.frameH;
if (x >= x2 && x >= x2 + w2) {
return false;
} else if (x <= x2 && x + bmpPlayer.getWidth() <= x2) {
return false;
} else if (y >= y2 && y >= y2 + h2) {
return false;
} else if (y <= y2 && y + bmpPlayer.getHeight() <= y2) {
return false;
}
//碰撞即进入无敌状态
isCollison = true;
return true;
}
else
return false;
}
/**
* 获取得分
*/
public int getScore()
{
return score;
}
/**
* 设置得分
*/
public void setScore(int score)
{
this.score=score;
}
public void onKeyDown(int keyCode,KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_DPAD_UP)
{
isUp=true;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN)
{
isDown=true;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
{
isLeft=true;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)
{
isRight=true;
}
}
public void onKeyUp(int keyCode,KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_DPAD_UP)
{
isUp=false;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN)
{
isDown=false;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_LEFT)
{
isLeft=false;
}
if(keyCode==KeyEvent.KEYCODE_DPAD_RIGHT)
{
isRight=false;
}
}
}
<file_sep>package com.guan.panegame;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* boss类
* @author Administrator
*
*/
public class Boss
{
//boss的血量
public int hp=50;
//boss图片
private Bitmap bmpBoss;
//boss坐标
public int x,y;
//boss每帧的宽高
public int frameW,frameH;
//boss当前帧下标
private int frameIndex;
//Boss运动速度
private int speed=5;
//是否疯狂状态
private boolean isCrazy;
//疯狂状态时间间隔
private int crazyTime=100;
//计时器
private int count;
public Boss(Bitmap bmpBoss)
{
this.bmpBoss=bmpBoss;
this.frameW=bmpBoss.getWidth()/10;
this.frameH=bmpBoss.getHeight();
//Bossx坐标居中
this.x=MySurfaceView.screenW/2-frameW/2;
this.y=0;
}
/**
* Boss的绘制
*/
public void onDraw(Canvas canvas,Paint paint)
{
canvas.save();
canvas.clipRect(x,y,x+frameW,y+frameH);
canvas.drawBitmap(bmpBoss, x-frameIndex*frameW,y, paint);
canvas.restore();
}
/**
* Boss的逻辑
*/
public void logic()
{
//不断循环播放帧形成动画
frameIndex++;
if(frameIndex>=10)
frameIndex=0;
//没有疯狂状态
if(isCrazy==false)
{
x+=speed;
if(x+frameW>=MySurfaceView.screenW)
speed=-5;
if(x<=0)
{
speed=5;
}
count++;
if(count % crazyTime ==0)
{
isCrazy=true;
speed=24;
}
}
else
{
speed-=1;
if(speed ==0)
{
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+30,y,Bullet.BULLET_BOSS,Bullet.DIR_UP));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_DOWN));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_RIGHT));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_LEFT));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_UP_RIGTH));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_UP_LEFT));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_DOWN_LEFT));
MySurfaceView.vcBulletBoss.add(new Bullet(MySurfaceView.bmpBossBullet,x+0,y,Bullet.BULLET_BOSS,Bullet.DIR_DOWN_RIGHT));
}
y+=speed;
if(y<=0)
{
isCrazy=false;
speed=5;
}
}
}
/**
* 判断Boss与主角子弹相碰
*/
public boolean isCollsionWith(Bullet bullet)
{
int x2=bullet.bulletX;
int y2=bullet.bulletY;
int w2=bullet.bmpBullet.getWidth();
int h2=bullet.bmpBullet.getHeight();
if(x >= x2 && x>=x2+w2)
return false;
else if(x <=x2 && x+frameW <=x2)
return false;
else if(y >=y2 && y>= y2+h2)
return false;
else if(y<= y2 && y+frameH <=y2)
return false;
return true;
}
/**
* 设置Boss血量
*/
public void setHp(int hp)
{
this.hp=hp;
}
}
<file_sep>package com.guan.panegame;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
/**
* 绘制子弹
* @author Administrator
*
*/
public class Bullet
{
//子弹类型
public int bulletType;
//类型常量
public static final int BULLET_PLAYER= -1;
public static final int BULLET_DUCK=1;
public static final int BULLET_FLY=2;
public static final int BULLET_BOSS=3;
//子弹是否超屏
public boolean isDead;
//子弹图片
public Bitmap bmpBullet;
//子弹坐标
public int bulletX,bulletY;
//子弹速度
public int speed;
//boss疯狂状态下的子弹相关变量
//子弹方向
private int dir;
public static final int DIR_UP=-1;
public static final int DIR_DOWN=2;
public static final int DIR_LEFT=3;
public static final int DIR_RIGHT=4;
public static final int DIR_UP_LEFT=5;
public static final int DIR_UP_RIGTH=6;
public static final int DIR_DOWN_LEFT=7;
public static final int DIR_DOWN_RIGHT=8;
public Bullet(Bitmap bmpBullet,int bulletX,int bulletY,int bulletType)
{
this.bmpBullet=bmpBullet;
this.bulletType=bulletType;
this.bulletX=bulletX;
this.bulletY=bulletY;
//不同类型的子弹有不同的速度
switch(bulletType)
{
case BULLET_PLAYER:
speed=4;
break;
case BULLET_DUCK:
speed=3;
break;
case BULLET_FLY:
speed=4;
break;
case BULLET_BOSS:
speed=5;
break;
}
}
/**
* 专门用于处理boss疯狂状态下的子弹
*/
public Bullet(Bitmap bmpBullet,int bulletX,int bulletY,int bulletType, int dir)
{
this.bmpBullet=bmpBullet;
this.bulletX=bulletX;
this.bulletY=bulletY;
this.bulletType=bulletType;
this.dir=dir;
speed=5;
}
/**
* 子弹绘制
*/
public void onDraw(Canvas canvas,Paint paint)
{
canvas.drawBitmap(bmpBullet, bulletX,bulletY, paint);
}
/**
* 子弹逻辑
*/
public void logic()
{
switch(bulletType)
{
case BULLET_PLAYER:
//主角的子弹是向上的
bulletY-=speed;
if(bulletY<-bmpBullet.getHeight())
isDead=true;
break;
case BULLET_DUCK:
case BULLET_FLY:
//鸭子和苍蝇的子弹都是向下的
bulletY+=speed;
if(bulletY>=MySurfaceView.screenH)
isDead=true;
case BULLET_BOSS:
switch(dir)
{
case DIR_UP:
bulletY-=speed;
break;
case DIR_DOWN:
bulletY+=speed;
break;
case DIR_RIGHT:
bulletX+=speed;
break;
case DIR_LEFT:
bulletX-=speed;
break;
case DIR_UP_LEFT:
bulletY-=speed;
bulletX+=speed;
break;
case DIR_UP_RIGTH:
bulletY-=speed;
bulletX-=speed;
break;
case DIR_DOWN_RIGHT:
bulletY+=speed;
bulletX+=speed;
break;
case DIR_DOWN_LEFT:
bulletY+=speed;
bulletX-=speed;
break;
}
if(bulletY>MySurfaceView.screenH ||bulletY<=-40 ||bulletX>MySurfaceView.screenW ||bulletX<= -40)
isDead=true;
break;
}
}
}
|
a7d5b571da23176dca8ad4c9a3e5cb87cfa377eb
|
[
"Java"
] | 3
|
Java
|
guanMac/android_paneGame
|
9f1ded4b9b08f6826ac074d98e3b5a6f202eb06f
|
4d134248d3fb5d8b3314d5ec4bd43a7d046b20f6
|
refs/heads/master
|
<file_sep>package myfirst;
public class Remote {
public static void main(String[] args) {
System.out.println("Hello this is remote page");
}
}
<file_sep>module myfirst {
}
|
1abfc55532ccba4a6782457358a6f79e33d74eea
|
[
"Java"
] | 2
|
Java
|
ypavankrishna/iderepo
|
752fdf2aaf6799d2181a5b746c9053132735953e
|
7daf1296b625dd07cc680402d7a375bcc9a59a64
|
refs/heads/master
|
<file_sep>/* File: inlineEdit.v3.js
Title: Mootools inlineEdit Plugin
Author: <NAME>
Url: http://justinmaier.com
Date: 2008-06-06
Ver: 1*/
var inlineEdit = new Class({
Implements: [Options,Events],
options: {
onComplete:$empty,//passes element
onLoad:$empty,//passes element,input
onKeyup:$empty,//passes element, input, event
inputClass:'input',
stripHtml:true
},
initialize: function(element,options){
this.setOptions(options);
this.element = element;
this.originalText = element.get('html').replace(/<br>/gi,"\n");
this.input = new Element('textarea',{
'class':this.options.inputClass,
'styles':this.element.getStyles('width','height','padding-top','padding-right','padding-bottom','padding-left','margin-top','margin-right','margin-bottom','margin-left','font-family','font-size','font-weight','line-height','border-top','border-right','border-bottom','border-left','background-color','color'),
'events':{
'keyup':this.keyup.bind(this),
'blur':this.complete.bind(this)
},
'value':this.originalText
});
this.input.setStyle('margin-left',this.input.getStyle('margin-left').toInt()-0);
this.input.setStyle('margin-bottom',this.input.getStyle('margin-bottom').toInt()-8);
this.originalWidth = this.element.getStyle('width');
// this.element.setStyles({'visibility':'hidden','position':'absolute','width':this.element.offsetWidth});
this.element.setStyles({'visibility':'hidden','position':'absolute'});
this.input.inject(this.element,'after');
this.input.focus();
this.fireEvent('onLoad', [this.element,this.input])
},
keyup: function(e){
if(e)e=new Event(e);
else return;
this.fireEvent('onKeyup', [this.element,this.input,e])
//this.element.set('html',(e.key=='enter')?this.getContent()+" ":this.getContent());
//if(e.key=='enter')this.input.addEvent('keydown',this.newLine.bind(this));
this.input.setStyle('height',this.element.offsetHeight);
if(e.key=='esc'){
this.element.set('text',this.originalText);
this.end();
}
},
getContent: function(){
var content = this.input.value
if(this.options.stripHtml)content = content.replace(/(<([^>]+)>)/ig,"");
return(content.replace(/\n/gi,"<br>"));
},
newLine: function(){
this.element.innerHTML=this.element.innerHTML.replace(" ","");
this.input.removeEvents('keydown');
},
complete: function(){
this.element.set('html',this.getContent());
this.fireEvent('onComplete', this.element)
this.end();
},
end: function(){
this.input.destroy();
this.element.setStyles({'visibility':'visible','position':'relative'});
// this.element.setStyles({'visibility':'visible','position':'relative','width':this.originalWidth});
}
});
Element.implement({
inlineEdit: function(options) {
return new inlineEdit(this, options);
}
});<file_sep>/*globals App Class Element Options Events $merge MD5*/
App.ns('App.Message');
App.Message = new Class({
Extends: App.TextCircle,
Implements: [Options, Events],
options: {
cls: 'message',
text: '...',
author: ''
},
initialize: function(options) {
this.setOptions(options);
this.setOptions({fill: this.messageColor(options.author)});
this.parent(this.options);
this.initEvents();
},
/**
* initEvents
* initialize object events
*/
initEvents: function() {
this.getTextEl().addEvent('click', function() {
this.beginEdit();
this.fireEvent('click');
}.bind(this));
},
/**
* sets message text
* @param String
*/
setMessage: function(text) {
this.setOptions({text: text});
this.setText(this.options.text);
},
/**
* beginEdit
* starts user editing of message text
*/
beginEdit: function() {
this.getTextEl().inlineEdit({
onComplete: function(el) {
this.setMessage($(el).get('text'));
this.fireEvent('afterEdit', [this]);
}.bind(this),
onKeyup: function(el, input, event) {
if (event.key=="enter") {
input.blur();
}
},
onLoad: function(el, input) {
input.select();
}
});
},
/**
* setAge
* sets the message age as to cause fading of old messages
* @param Float 0-1 relative representation of age
*/
setAge: function(ageScale) {
this.fade(ageScale);
},
/**
* remove
* removes message from teh stage
*/
remove: function() {
this.parent();
this.setOptions({r: 0, 'stroke-width': 0});
this.animate('<');
return this;
},
/**
* messageColor
* @param String text value to hash
* @return String color value from hashed inpue
*/
messageColor: function(string) {
return MD5(string).slice(0,6).hexToRgb(true).rgbToHex();
}
});<file_sep>/*globals App Class Events $merge*/
App.ns('App.Messanger');
App.Messanger = new (new Class((function(){
// private
var _message_dict = {};
var _message_stack = [];
var _fire_update_onmove = true;
var _message_stack_limit = 6;
// public
return {
Implements: Events,
/**
* setAuthor
* @param String
*/
setAuthor: function(author) {
this.client_author = author;
},
/**
* setMessage
* updates an existing message or builds a new message
* @param Object message configuration
*/
setMessage: function(config) {
var id = config['id'];
if (id && id in _message_dict) {
this.updateMessage(id, config);
}
else {
id = this.createMessage(config);
}
return id;
},
/**
* createNewMessage
* creates a new message obj
* @param Object message configuration
*/
createMessage: function(config) {
var message;
config['id'] = config['id'] || String(config['author']) + String(Date.now());
message = new App.Message(config);
message.addEvent('afterEdit', function(msg) {
this.fireEvent('update', [msg.options]);
}.bind(this));
message.addEvent('afterMove', function(msg) {
this.fireEvent('update', [msg.options]);
}.bind(this));
message.addEvent('move', function(msg) {
if (_fire_update_onmove) {
this.fireEvent('update', [msg.options]);
_fire_update_onmove = false;
}
(function(){_fire_update_onmove = true;}).delay(100, this);
}.bind(this));
if (this.client_author === config.author) {
message.beginEdit();
}
_message_dict[config.id] = message;
// ageing
if (_message_stack.unshift(message) > _message_stack_limit) {
delete _message_dict[_message_stack.pop().remove().options.id];
}
this._updateAgeing();
return config.id;
},
/**
* updateMessage
* update an existing message with id
* @param String id of message
* @param Object message configuration properties
*/
updateMessage: function(id, config) {
var m = _message_dict[id];
if (m.options.text != config.text) m.setMessage(config.text);
m.moveTo(config.x, config.y);
},
// private methods
// ...............
_updateAgeing: function() {
_message_stack.each(function(m, idx) {
if (idx > 0) {
m.setAge(1 - idx/_message_stack_limit);
}
}, this);
},
dump: function() {
return _message_stack;
}
};
})()))();<file_sep>task :start do
sh "node server.js &"
end
task :show do
sh 'ps aux | grep -E "(server.js)$"'
end<file_sep>/*globals App Class Element Options Events $merge*/
App.ns('App.TextNode');
App.TextNode = new Class({
Implements: [Options],
options: {
text: '',
x: 0,
y: 0,
w: 100,
text_container_styles: {
position: 'absolute',
'z-index': 1000
},
text_cell_styles: {
display: 'table-cell',
'text-align': 'center',
'vertical-align': 'middle'
}
},
initialize: function(options) {
this.setOptions(options);
// expose methods to text_container object
['setStyles'].each(function(method_name) {
this[method_name] = function(method_name){
var method = method_name;
return function() {
this.text_container[method].apply(this.text_container, arguments);
};
}(method_name);
}.bind(this));
this._initializeElements();
},
/**
* setText
* @param String
* set's the text property of the text node
*/
setText: function(text) {
this.text_node.set('html', text);
},
/**
* resize
* @param Integer x
* @param Integer y
* @param Float width
* sets width of text node
* needed because updates to both parent and child nodes required
* also repositions item assuming text to remain centered
*/
resize: function(x,y,w) {
this.setOptions({x: x, y: y, w: w});
this.text_container.setStyles(this._getDefaultContainerSizing());
this.text_cell.setStyles(this._getDefaultNodeSizing());
},
/**
* getTextSize
* @return Object the actual size of the text node so that parent
* nodes can accomadate container size
*/
getTextSize: function() {
this.test_sizing_span.set('text', this.options.text);
return {
w: this.test_sizing_span.clientWidth,
h: this.test_sizing_span.clientHeight
};
},
/**
* getTextEl
* @return Element the base text element so that other objects can add events
*/
getTextEl: function() {
return this.text_node;
},
/**
* remove
* clean up dom and remove
*/
remove: function() {
this.text_container.dispose();
},
// private methods
// ...............
/**
* renders the text node
*/
_initializeElements: function() {
var o = this.options;
this.text_container = new Element('div', {
'class': o.cls,
styles: $merge(o.text_container_styles, this._getDefaultContainerSizing())
});
this.text_cell = new Element('div', {
styles: $merge(o.text_cell_styles, this._getDefaultNodeSizing())
});
this.text_node = new Element('div', {
'class': 'text_node',
text: o.text
});
this.text_node.inject(this.text_cell);
this.text_cell.inject(this.text_container);
this.text_container.inject($(document.body), 'top');
this.test_sizing_span = new Element('span', {
styles: {
position: 'absolute',
visibility:'hidden'
}
});
this.test_sizing_span.inject(this.text_cell, 'top');
},
/**
* returns default sizing for container
*/
_getDefaultContainerSizing: function() {
var o = this.options;
return {
top: o.y - o.w/2,
left: o.x - o.w/2,
width: o.w,
height: o.w
};
},
/**
* returns default sizing for node
*/
_getDefaultNodeSizing: function() {
var o = this.options;
return {
width: o.w,
height: o.w
};
}
});<file_sep>/*globals App Class Raphael Element Options $lambda */
App.ns('App.TextCircle');
App.TextCircle = new Class({
Extends: App.TextNode,
Implements: Options,
options: {
cls: 'text-circle',
fill: '#f00',
stroke: '#fff',
'stroke-width': 10,
opacity: 0.75,
x: 0,
y: 0,
r: 300,
min_r: 75,
text: 'Lorem Ipsum',
textSizeBuffer: 20
},
initialize: function(options) {
var o = this.options,
c_atr;
// set options
this.setOptions(options);
// draw canvas and circle
this._initialize_svg();
this._drawShape();
// draw text object
c_atr = this.circle.attrs;
this.parent({
cls: o.cls,
text: o.text,
x: c_atr.cx,
y: c_atr.cy,
w: 30
});
// does proper positioning
this.setText(o.text);
this._initialize_drag_drop();
this.fireEvent('create');
},
/**
* setText
* sets message text and readjusts underlying text and circle sizes to accomdate
* @param String
*/
setText: function(text) {
var o = this.options,
longest_word = 0,
size;
this.parent(text);
this.setOptions({text: text});
size = this.getTextSize();
text.split(' ').each(function(w) {
if (w.length > longest_word) {
longest_word = w.length;
}
}, this);
// if line breaks are such that calculating width won't accomodate line width
if (longest_word > 3 && longest_word > text.length/2) {
this.grow(((longest_word/text.length)*size.w)/2*Math.sqrt(2) - o.r + o.textSizeBuffer);
}
// else extrapolate the estimated square size of the text
else {
this.grow(Math.sqrt(size.w*size.h)/2*Math.sqrt(2) - o.r + o.textSizeBuffer);
}
},
/**
* grow
* change the size of the shape and text node
* @param Integer change in circle radius
*/
grow: function(dr) {
var o = this.options,
new_r = o.r + dr;
if (!this.first) {
new_r = o.r/2;
this.first = true;
}
new_r = (new_r < this.options.min_r) ? this.options.min_r : new_r;
this.setOptions({r: new_r});
this.animate();
// resize text node
this.resize(this.circle.attrs.cx, this.circle.attrs.cy, this._width());
},
/**
* moveTo
* provides non animated translation
* @param Integer x
* @param Integer y
*/
moveTo: function(x, y) {
var w = this._width();
this.circle.attr({cx: x, cy: y});
this.outline.attr({cx: x, cy: y});
this.setStyles({left: x - w/2, top: y - w/2});
},
/**
* fade
* fades elements
* @param Float opacity value
*/
fade: function(opacity) {
var o = this.options;
this.getTextEl().setStyles({opacity: opacity});
this.setOptions({opacity: opacity});
this.animate('<');
},
/**
* animate
* animates in the currently specified configuration options
* @param String name of Raphael.js easing function
*/
animate: function(easing) {
easing = easing || "bounce";
if (!this.circle.in_animation) {
this.circle.animate({
r: this.options.r,
opacity: this.options.opacity
}, 500, easing);
}
if (!this.outline.in_animation) {
this.outline.animate({
r: this.options.r + this.options['stroke-width']/2,
opacity: this.options.opacity
}, 500, easing);
}
},
/**
* remove
* removes this element giving enough time for removal animation
*/
remove: function() {
this.parent();
(function() {
console.log('removing svg els');
this.circle.remove();
this.outline.remove();
}).delay(1000, this);
},
// private methods
// ...............
/**
* _initialize_svg
* create svg drawing area, requires raphael.js
*/
_initialize_svg: function(){
App.TextCircle.paper = App.TextCircle.paper || Raphael(0, 0, '100%', '100%');
},
/**
* _drawShape
* draws the underlying svg shapes
*/
_drawShape: function() {
var o = this.options;
this.circle = App.TextCircle.paper.circle(o.x, o.y, o.r).attr({
fill: o.fill,
opacity: o.opacity,
stroke: 0
});
this.outline = App.TextCircle.paper.circle(o.x, o.y, o.r + o['stroke-width']/2).attr({
stroke: o.stroke,
'stroke-width': o['stroke-width'],
opacity: o.opacity
});
$(this.outline.node).setStyle('cursor', 'move');
},
/**
* _initialize_drag_drop
* initializes drag and drop
* passes mousedown events from text to the svg node
* builds drag and drop for the svg node
*/
_initialize_drag_drop: function() {
this.addEvent('mousedown', function(e){
var fireOnThis = this.circle.node;
var evObj = document.createEvent('MouseEvents');
evObj.initMouseEvent('mousedown', true, true, window, 1, e.client.x, e.client.y, e.client.x, e.client.y);
fireOnThis.dispatchEvent(evObj);
}.bind(this));
this.outline.drag(this._dd_functions()._moving, this._dd_functions()._startMove, this._dd_functions()._endMove);
},
/**
* _dd_functions
* supporting drag and drop handlers
* this becomes circle and self becomes instance
*/
_dd_functions: function(){
var self = this;
return {
_startMove: function () {
this.ox = this.attr("cx");
this.oy = this.attr("cy");
this.attr({opacity: self.options.opacity/3});
self.circle.attr({opacity: self.options.opacity/3});
},
_moving: function (dx, dy) {
var w = self._width();
this.attr({cx: this.ox + dx, cy: this.oy + dy});
self.circle.attr({cx: this.ox + dx, cy: this.oy + dy});
self.setStyles({left: this.ox + dx - w/2, top: this.oy + dy - w/2});
self.setOptions({x: this.attr("cx"), y: this.attr("cy")});
self.fireEvent('move', [self]);
},
_endMove: function () {
this.attr({opacity: self.options.opacity});
self.circle.attr({opacity: self.options.opacity});
self.setOptions({x: this.attr("cx"), y: this.attr("cy")});
self.fireEvent('afterMove', [self]);
}
};
},
/**
* utility function to calculate an inscribed squares width within the circle
*/
_width: function() {
return this.options.r*Math.sqrt(2);
}
});<file_sep>var port = 8123,
http = require('http'),
url = require('url'),
fs = require('fs'),
io = require('socket.io').listen(port),
sys = require('sys'),
numClients = 0;
io.set('log level', 1);
io.sockets.on('connection', function(client){
client.on('messageupdate', function(message){
client.broadcast.emit('messageupdate', {message: JSON.parse(message)});
});
numClients++;
io.sockets.emit('announcement', {numberOfClients: numClients});
client.on('disconnect', function() {
numClients--;
io.sockets.emit('announcement', {numberOfClients: numClients});
});
});<file_sep># wordsworth
Experimental chat like application to show how users might use window space to communicate on top of an html document. Tested only in webkit based browsers – Safari, Chrome, and Mobile Safari.
Create a message by clicking anywhere in the document and typing a message. Move messages by grabbing the outer white border and dragging. Edit existing messages by clicking their text.
## built with
- [Node.js](http://github.com/ry/node)
- [Socket.IO](http://github.com/LearnBoost/Socket.IO)
- [MooTools](http://github.com/mootools/mootools-core)
- [Raphaël](http://github.com/DmitryBaranovskiy/raphael)
|
ad946e0726998173b23556b82c331ff9c964e0a9
|
[
"JavaScript",
"Ruby",
"Markdown"
] | 8
|
JavaScript
|
alexgb/wordsworth
|
0b861a7c9f2e731fc9d82b6e1527912a33bb6ac8
|
66963e623a9d0fcce332c91192cfa4eb37a42248
|
refs/heads/master
|
<repo_name>iamdavidmichaelmoore/triangle-classification-v-000<file_sep>/lib/triangle.rb
require 'pry'
class Triangle
attr_reader :length1, :length2, :length3
def initialize(length1,length2,length3)
@length1 = length1
@length2 = length2
@length3 = length3
@lengths = [length1, length2, length3]
end
def kind
triangles = {:equilateral => 1, :isosceles => 2, :scalene => 3}
lengths = @lengths.sort
triangle_inequality_test = lengths[0] + lengths[1] > lengths[2]
if @lengths.include?("/0|-\d+/") || !triangle_inequality_test
raise TriangleError
else
type = triangles.detect do |triangle, sides|
@lengths.uniq.size == sides
end
type[0]
end
end
class TriangleError < StandardError
end
end
|
2191c1dc3663f8e6bbc6475232eeb2e468cbae90
|
[
"Ruby"
] | 1
|
Ruby
|
iamdavidmichaelmoore/triangle-classification-v-000
|
f7a25b7333cc05a7c7e3440ffc419e9f716a06a9
|
0f6268aa411ee5dccf1eaa12a8f80112865feb8a
|
refs/heads/master
|
<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.0.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Nov 21, 2019 at 12:04 AM
-- Server version: 10.4.6-MariaDB
-- PHP Version: 7.1.32
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `dkut_clearance_system`
--
-- --------------------------------------------------------
--
-- Table structure for table `admins`
--
CREATE TABLE `admins` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `admins`
--
INSERT INTO `admins` (`id`, `username`, `email`, `password`) VALUES
(1, 'ADMIN1', '<EMAIL>', '<PASSWORD>');
-- --------------------------------------------------------
--
-- Table structure for table `clearance`
--
CREATE TABLE `clearance` (
`id` int(11) NOT NULL,
`student_reg` varchar(100) NOT NULL,
`cod` varchar(255) NOT NULL,
`librarian` varchar(255) NOT NULL,
`housekeeper` varchar(255) NOT NULL,
`dean_of_students` varchar(255) NOT NULL,
`sports_officer` varchar(255) NOT NULL,
`registrar` varchar(255) NOT NULL,
`finance` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `clearance`
--
INSERT INTO `clearance` (`id`, `student_reg`, `cod`, `librarian`, `housekeeper`, `dean_of_students`, `sports_officer`, `registrar`, `finance`) VALUES
(1, 'C025-02-0032/2016', 'PENDING', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'PENDING'),
(2, 'C025-02-0033/2016', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING'),
(3, 'C026-02-0040/2016', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING'),
(4, 'C026-02-0041/2016', 'CLEARED', 'CLEARED', 'PENDING', 'PENDING', 'PENDING', 'PENDING', 'PENDING'),
(5, 'C025-02-0029/2015', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED'),
(6, 'C025-02-0030/2015', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED', 'CLEARED');
-- --------------------------------------------------------
--
-- Table structure for table `departments`
--
CREATE TABLE `departments` (
`id` int(11) NOT NULL,
`dept_name` varchar(255) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `departments`
--
INSERT INTO `departments` (`id`, `dept_name`) VALUES
(1, 'cod'),
(2, 'librarian '),
(3, 'housekeeper'),
(4, 'deanOfStudents'),
(5, 'sportsOfficer'),
(6, 'registrar'),
(7, 'finance');
-- --------------------------------------------------------
--
-- Table structure for table `depertment_officers`
--
CREATE TABLE `depertment_officers` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`departmment` varchar(255) NOT NULL,
`dateadded` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `depertment_officers`
--
INSERT INTO `depertment_officers` (`id`, `username`, `password`, `departmment`, `dateadded`) VALUES
(1, 'COD1', 'cd5cedd385ce4e84e8405997c37a8e3d', 'cod', '2019-08-04'),
(2, 'LIBRARY1', 'aa796f0f1579803a07c3eb91de612a27', 'librarian ', '2019-08-05'),
(3, 'HOUSE1', '14c36ef64fbce323b720886a0d7793ea', 'housekeeper', '2019-08-06'),
(4, 'DEAN1', 'f948390969e805b3819c831fe3840d70', 'deanOfStudents', '2019-08-07'),
(5, 'SPORTS1', '6d7402ff98e<PASSWORD>', 'sportsOfficer', '2019-08-07'),
(6, 'REGISTRAR1', '<PASSWORD>', 'registrar', '2019-08-07'),
(7, 'FINANCE1', 'b11d49f3630e78c3ab484e3c311963e7', 'finance', '2019-08-20');
-- --------------------------------------------------------
--
-- Table structure for table `gawnofficer`
--
CREATE TABLE `gawnofficer` (
`id` int(11) NOT NULL,
`username` varchar(255) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`dateadded` date NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `gawnofficer`
--
INSERT INTO `gawnofficer` (`id`, `username`, `email`, `password`, `dateadded`) VALUES
(1, 'gawn1', '<EMAIL>', '<PASSWORD>', '2019-11-16'),
(2, 'derrik', '<EMAIL>', '<PASSWORD>', '2019-11-16');
-- --------------------------------------------------------
--
-- Table structure for table `issues`
--
CREATE TABLE `issues` (
`id` int(11) NOT NULL,
`std_reg` varchar(20) NOT NULL,
`department` varchar(50) NOT NULL,
`description` varchar(255) NOT NULL,
`category` varchar(255) NOT NULL,
`monetary_value` double NOT NULL,
`datecreated` date NOT NULL,
`timecereated` time NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issues`
--
INSERT INTO `issues` (`id`, `std_reg`, `department`, `description`, `category`, `monetary_value`, `datecreated`, `timecereated`) VALUES
(1, 'C026-02-0040/2016', 'cod', 'has remaining payments to make on project processing ', 'ARREARS', 2000, '2019-08-24', '00:00:05'),
(2, 'C025-02-0033/2016', 'librarian', 'aliharibu vitabu', 'DAMAGES', 2000, '2019-09-02', '10:36:34');
-- --------------------------------------------------------
--
-- Table structure for table `issue_cod`
--
CREATE TABLE `issue_cod` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(12) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_cod`
--
INSERT INTO `issue_cod` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C025-02-0032/2016', 'Exams', 'The student is yet to complete the IOT exam as required by the Department. student should visit my office soonest possible\r\n', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `issue_deanofstudents`
--
CREATE TABLE `issue_deanofstudents` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_deanofstudents`
--
INSERT INTO `issue_deanofstudents` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C026-02-0041/2016', 'Co Carricular', 'some papers need to be signed by student.kindly meet dean in the office for clearance', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `issue_finance`
--
CREATE TABLE `issue_finance` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_finance`
--
INSERT INTO `issue_finance` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C026-02-0041/2016', 'Ariase', 'not completed fees ', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `issue_housekeeper`
--
CREATE TABLE `issue_housekeeper` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_housekeeper`
--
INSERT INTO `issue_housekeeper` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C025-02-0033/2016', 'Vundalism', 'Broke Pane at Batian Hostels', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `issue_librarian`
--
CREATE TABLE `issue_librarian` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_librarian`
--
INSERT INTO `issue_librarian` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C026-02-0040/2016', 'Lost Book', 'Book Tile: The infinity war', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `issue_registrar`
--
CREATE TABLE `issue_registrar` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `issue_sportsofficer`
--
CREATE TABLE `issue_sportsofficer` (
`id` int(11) NOT NULL,
`std_reg` varchar(30) NOT NULL,
`category` varchar(30) NOT NULL,
`description` varchar(255) NOT NULL,
`status` varchar(14) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `issue_sportsofficer`
--
INSERT INTO `issue_sportsofficer` (`id`, `std_reg`, `category`, `description`, `status`) VALUES
(1, 'C025-02-0033/2016', 'Lost Item', 'Misplaced the hocky stick size 32xwd, need to avail with a replacement to sports office to be cleared', 'PENDING'),
(2, 'C026-02-0041/2016', 'Damages', 'need to repair the DKUT football tem banner after it was damaeged under your possesioin. see sports officer for clearance ', 'PENDING');
-- --------------------------------------------------------
--
-- Table structure for table `mpesa`
--
CREATE TABLE `mpesa` (
`id` int(100) NOT NULL,
`resultCode` varchar(1000) NOT NULL,
`resultDesc` varchar(1000) NOT NULL,
`merchantRequestID` varchar(1000) NOT NULL,
`checkoutRequestID` varchar(1000) NOT NULL,
`amount` varchar(1000) NOT NULL,
`mpesaReceiptNumber` varchar(1000) NOT NULL,
`transactionDate` varchar(1000) NOT NULL,
`phoneNumber` varchar(1000) NOT NULL,
`state` int(10) NOT NULL DEFAULT 0,
`datetime` timestamp(6) NOT NULL DEFAULT current_timestamp(6)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `mpesa`
--
INSERT INTO `mpesa` (`id`, `resultCode`, `resultDesc`, `merchantRequestID`, `checkoutRequestID`, `amount`, `mpesaReceiptNumber`, `transactionDate`, `phoneNumber`, `state`, `datetime`) VALUES
(33, '0', 'The service request is processed successfully.', '21098-12894606-1', 'ws_CO_DMZ_400337515_14092019184131462', '4', 'NIE6L5OVQO', '20190914184140', '254704003701', 0, '2019-09-14 15:41:41.900599'),
(36, '0', 'The service request is processed successfully.', '21097-12914299-1', 'ws_CO_DMZ_400339828_14092019185424523', '4', 'NIE4L67WVW', '20190914185435', '704003701', 0, '2019-09-14 15:54:37.010361'),
(40, '0', 'The service request is processed successfully.', '21087-13163562-1', 'ws_CO_DMZ_400365300_14092019212214802', '1', 'NIE2LC2AX4', '20190914212223', '704003701', 1, '2019-09-14 18:22:24.202099'),
(51, '0', 'The service request is processed successfully.', '21093-13257556-1', 'ws_CO_DMZ_982437677_14092019222554942', '4', 'NIE8LDG2UQ', '20190914222615', '704003701', 1, '2019-09-14 19:26:16.008046'),
(52, '0', 'The service request is processed successfully.', '31322-6543329-1', 'ws_CO_DMZ_982905760_14092019225146769', '1', 'NIE5LDTEHB', '20190914225158', '704003701', 1, '2019-09-14 19:51:59.917162'),
(53, '1032', '[STK_CB - ]Request cancelled by user', '31323-6613838-1', 'ws_CO_DMZ_984787433_15092019003545223', '', '', '', '', 3, '2019-09-14 21:36:24.845647'),
(54, '1032', '[STK_CB - ]Request cancelled by user', '6644-8904475-1', 'ws_CO_DMZ_400469550_15092019144515804', '', '', '', '', 3, '2019-09-15 11:45:24.168565');
-- --------------------------------------------------------
--
-- Table structure for table `users`
--
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(100) NOT NULL,
`email` varchar(255) NOT NULL,
`password` varchar(255) NOT NULL,
`tel` varchar(15) NOT NULL,
`gpayment` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `email`, `password`, `tel`, `gpayment`) VALUES
(4, 'C025-02-0032/2016', '<EMAIL>', '<PASSWORD>', '0744845902', 0),
(5, 'C025-02-0033/2016', '<EMAIL>', '0a791842f52a0acfbb3a783378c066b8', '0724789456', 0),
(6, 'C026-02-0040/2016', '<EMAIL>', 'b200d9b6e538b8c6f50c1cae6c7c7094', '0718610555', 0),
(7, 'C026-02-0041/2016', '<EMAIL>', '9cdca52def14f774d6ed3b385b516f45', '0712610463', 0),
(8, 'C025-02-0029/2015', '<EMAIL>', 'affec3b64cf90492377a8114c86fc093', '0718610463', 0),
(9, 'C025-02-0030/2015', '<EMAIL>', '3e0469fb134991f8f75a2760e409c6ed', '0718610463', 0);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `admins`
--
ALTER TABLE `admins`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `clearance`
--
ALTER TABLE `clearance`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `departments`
--
ALTER TABLE `departments`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `depertment_officers`
--
ALTER TABLE `depertment_officers`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `gawnofficer`
--
ALTER TABLE `gawnofficer`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issues`
--
ALTER TABLE `issues`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_cod`
--
ALTER TABLE `issue_cod`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_deanofstudents`
--
ALTER TABLE `issue_deanofstudents`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_finance`
--
ALTER TABLE `issue_finance`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_housekeeper`
--
ALTER TABLE `issue_housekeeper`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_librarian`
--
ALTER TABLE `issue_librarian`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_registrar`
--
ALTER TABLE `issue_registrar`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `issue_sportsofficer`
--
ALTER TABLE `issue_sportsofficer`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `mpesa`
--
ALTER TABLE `mpesa`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `admins`
--
ALTER TABLE `admins`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `clearance`
--
ALTER TABLE `clearance`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `departments`
--
ALTER TABLE `departments`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `depertment_officers`
--
ALTER TABLE `depertment_officers`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8;
--
-- AUTO_INCREMENT for table `gawnofficer`
--
ALTER TABLE `gawnofficer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `issues`
--
ALTER TABLE `issues`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `issue_cod`
--
ALTER TABLE `issue_cod`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `issue_deanofstudents`
--
ALTER TABLE `issue_deanofstudents`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `issue_finance`
--
ALTER TABLE `issue_finance`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `issue_housekeeper`
--
ALTER TABLE `issue_housekeeper`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `issue_librarian`
--
ALTER TABLE `issue_librarian`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2;
--
-- AUTO_INCREMENT for table `issue_registrar`
--
ALTER TABLE `issue_registrar`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `issue_sportsofficer`
--
ALTER TABLE `issue_sportsofficer`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
--
-- AUTO_INCREMENT for table `mpesa`
--
ALTER TABLE `mpesa`
MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=74;
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
92460592e95fd22dec44b77c292a34eafbe9d387
|
[
"SQL"
] | 1
|
SQL
|
washie254/cleaaranceSystem
|
77ba9bdc97f4f2e3c43000628fac94a53a82fda1
|
65436902d5bcd5d976537fb19942c5115be8e2aa
|
refs/heads/master
|
<repo_name>varunchanddra/SLAM_with_YOLO<file_sep>/bbox.h
#include <stdio.h>
#include "darknet.h"
// #include "stdio.h"
// #include "stdlib.h"
// #include "opencv2/opencv.hpp"
// #include "image.h"
// image ipl_to_image(IplImage* src)
// {
// int h = src->height;
// int w = src->width;
// int c = src->nChannels;
// image im = make_image(w, h, c);
// unsigned char *data = (unsigned char *)src->imageData;
// int step = src->widthStep;
// int i, j, k;
// for(i = 0; i < h; ++i){
// for(k= 0; k < c; ++k){
// for(j = 0; j < w; ++j){
// im.data[k*w*h + i*w + j] = data[i*step + j*c + k]/255.;
// }
// }
// }
// return im;
// }
// image mat_to_image(cv::Mat m)
// {
// IplImage ipl = m;
// image im = ipl_to_image(&ipl);
// rgbgr_image(im);
// return im;
// }
// image mat_to_image(cv::Mat m);
<file_sep>/Main.cpp
/*
* This file is part of ElasticFusion.
*
* Copyright (C) 2015 Imperial College London
*
* The use of the code within this file and all code within files that
* make up the software that is ElasticFusion is permitted for
* non-commercial purposes only. The full terms and conditions that
* apply to the code within this file are detailed within the LICENSE.txt
* file and at <http://www.imperial.ac.uk/dyson-robotics-lab/downloads/elastic-fusion/elastic-fusion-license/>
* unless explicitly stated. By downloading this file you agree to
* comply with these terms.
*
* If you wish to use any of this code for commercial purposes then
* please email <EMAIL>.
*
*/
#include "MainController.h"
MainController * mainc;
extern "C" void addFrames(char * rgb, char * dep)
{
mainc->addFrames(rgb, dep);
}
extern "C" void fun_start()
{
char* args [3] = {"./a.out", "-l", "~/Downloads/dyson_lab.klg"};
// arg?v[1] = "-l";
// argv?[2] = "~/Downloads/dyson_lab.klg";
mainc = new MainController(3, (char **)args);
mainc->launch();
// return 0;
}
<file_sep>/new_motion_demo.py
import rospy
import actionlib
import os
import time
from geometry_msgs.msg import Twist
from math import pi, sin, cos
from control_msgs.msg import (FollowJointTrajectoryAction,
FollowJointTrajectoryGoal,
GripperCommandAction,
GripperCommandGoal)
from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint
from control_msgs.msg import PointHeadAction, PointHeadGoal
from sensor_msgs.msg import Image, JointState, PointCloud2
from cv_bridge import CvBridge, CvBridgeError
import cv2
import threading
import message_filters
import ctypes
from numpy.ctypeslib import ndpointer
import numpy as np
from std_msgs.msg import String
global fusion
class EF():
def __init__(self):
self.controller = ctypes.CDLL("/home/varun/Humanoid/Project/semanticfusion/elasticfusionpublic/GUI/build/libElasticFusion.so")
self.sendFrames = self.controller.addFrames
self.thread = threading.Thread(target = self.controller.fun_start)
self.thread.start()
time.sleep(5)
def process( self, color, depth):
self.sendFrames(ctypes.c_void_p(carr.ctypes.data), ctypes.c_void_p(darr.ctypes.data))
class BaseMovements:
def __init__(self):
self.cmd_vel = rospy.Publisher('/cmd_vel', Twist)
self.rate = 50
self.r = rospy.Rate(self.rate)
def move(self, dist, speed):
move_cmd = Twist()
move_cmd.linear.x = speed
duration = abs(dist / speed)
ticks = int(duration * self.rate)
for t in range(ticks):
self.cmd_vel.publish(move_cmd)
self.r.sleep()
self.cmd_vel.publish( Twist() )
def turn(self, angle, angular_speed):
move_cmd = Twist()
goal_angle = angle * (2*pi/360)
# angular_speed = 1.0
if angle < 0:
angular_speed *= -1
angular_duration = goal_angle / angular_speed
move_cmd = Twist()
move_cmd.angular.z = angular_speed
ticks = int(angular_duration * self.rate)
for t in range(ticks):
self.cmd_vel.publish(move_cmd)
self.r.sleep()
self.cmd_vel.publish( Twist() )
class HeadMovements():
def __init__(self):
self.joint_names = ["head_pan_joint", "head_tilt_joint"]
self.joint_positions = [ 0.0, 0.0]
self.client = actionlib.SimpleActionClient("head_controller/follow_joint_trajectory", FollowJointTrajectoryAction)
rospy.loginfo("Waiting for head_controller...")
self.client.wait_for_server()
rospy.loginfo("Connected to head_controller")
def move(self, inp, duration = 5.0):
self.joint_positions = inp
traj = JointTrajectory()
traj.joint_names = self.joint_names
traj.points.append(JointTrajectoryPoint())
traj.points[0].positions = self.joint_positions
traj.points[0].velocities = [0.0] * len(self.joint_positions)
traj.points[0].accelerations = [0.0] * len(self.joint_positions)
traj.points[0].time_from_start = rospy.Duration(5.0)
head_goal = FollowJointTrajectoryGoal()
head_goal.trajectory = traj
head_goal.goal_time_tolerance = rospy.Duration(0.0)
self.client.send_goal(head_goal)
self.client.wait_for_result(rospy.Duration(6.0))
class TorsoMovements():
def __init__(self):
self.joint_names = ["torso_lift_joint"]
self.joint_positions = [ 4.0]
self.client = actionlib.SimpleActionClient("torso_controller/follow_joint_trajectory", FollowJointTrajectoryAction)
rospy.loginfo("Waiting for torso_controller...")
self.client.wait_for_server()
rospy.loginfo("Connected to torso_controller")
def move(self, dist, duration = 5.0):
self.joint_positions = [ dist ]
traj = JointTrajectory()
traj.joint_names = self.joint_names
traj.points.append(JointTrajectoryPoint())
traj.points[0].positions = self.joint_positions
traj.points[0].velocities = [0.0] * len(self.joint_positions)
traj.points[0].accelerations = [0.0] * len(self.joint_positions)
traj.points[0].time_from_start = rospy.Duration(5.0)
head_goal = FollowJointTrajectoryGoal()
head_goal.trajectory = traj
head_goal.goal_time_tolerance = rospy.Duration(0.0)
self.client.send_goal(head_goal)
self.client.wait_for_result(rospy.Duration(6.0))
class ArmMovements():
def __init__(self):
self.joint_names = ["shoulder_pan_joint", "shoulder_lift_joint", "upperarm_roll_joint",
"elbow_flex_joint", "forearm_roll_joint", "wrist_flex_joint", "wrist_roll_joint"]
self.joint_positions = [0, 0, 0, 0, 0, 0, 0]
self.client = actionlib.SimpleActionClient("arm_controller/follow_joint_trajectory", FollowJointTrajectoryAction)
rospy.loginfo("Waiting for arm_controller...")
self.client.wait_for_server()
rospy.loginfo("Connected to arm_controller")
def move(self, inp, duration = 5.0):
self.joint_positions = inp
traj = JointTrajectory()
traj.joint_names = self.joint_names
traj.points.append(JointTrajectoryPoint())
traj.points[0].positions = self.joint_positions
traj.points[0].velocities = [0.0] * len(self.joint_positions)
traj.points[0].accelerations = [0.0] * len(self.joint_positions)
traj.points[0].time_from_start = rospy.Duration(9.0)
head_goal = FollowJointTrajectoryGoal()
head_goal.trajectory = traj
head_goal.goal_time_tolerance = rospy.Duration(0.0)
self.client.send_goal(head_goal)
self.client.wait_for_result(rospy.Duration(9.0))
class GripMovements():
def __init__(self):
self.client = actionlib.SimpleActionClient("gripper_controller/gripper_action", GripperCommandAction)
self.client.wait_for_server()
def move(self, position, effort, duration = 5.0):
gripper_goal = GripperCommandGoal()
gripper_goal.command.max_effort = effort
gripper_goal.command.position = position
self.client.send_goal(gripper_goal)
self.client.wait_for_result(rospy.Duration(5.0))
def image_callback(rgb, depth):
global fusion
bridge = CvBridge()
img = bridge.imgmsg_to_cv2(rgb, desired_encoding="passthrough")
rate = rospy.Rate(10)
rate.sleep()
img_depth = bridge.imgmsg_to_cv2(depth, desired_encoding="passthrough")
rate = rospy.Rate(10)
rate.sleep()
# timestamp = rgb.header.stamp
# print(timestamp)
fusion.process(img, img_depth)
def move_thread(task, head):
#head.move( [0, pi/4.0])
task.move( 1, 0.2 )
head.move( [0, pi/6.0])
task.turn(100, 1.0)
task.turn(-120, 0.5)
'''
def sub1():
rospy.Subscriber('head_camera/rgb/image_raw', Image, image_callback, ("1,"))
rospy.spin()
def sub2():
rospy.Subscriber('head_camera/depth_registered/image_raw', Image, image_callback_d, ("2",))
rospy.spin()
'''
if __name__ == "__main__":
global fusion
fusion = EF()
rospy.init_node("motion_demo")
task = BaseMovements()
head = HeadMovements()
x = threading.Thread(target=move_thread, args=(task,head))
x.start()
depth_sub = message_filters.Subscriber('head_camera/depth_registered/image_raw', Image)
rgb_sub = message_filters.Subscriber('head_camera/rgb/image_raw', Image)
ts = message_filters.TimeSynchronizer([rgb_sub, depth_sub], 10)
ts.registerCallback(image_callback)
'''
torso = TorsoMovements()
torso.move(3.0)
arm = ArmMovements()
arm.move([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0])
grip = GripMovements()
grip.move(0.0, 10.0)
grip.move(1.0, 10.0)
'''
|
3a17e2806d709db1754f0225d82d130a686d5ca8
|
[
"C",
"Python",
"C++"
] | 3
|
C
|
varunchanddra/SLAM_with_YOLO
|
fa5d1f18a8bad3594903ec6c5c3932af813e5598
|
2bad2a7a51ba9d8b217485d300cd3b6a1d84b8f9
|
refs/heads/master
|
<repo_name>buddalasunil999/RserveCLI2<file_sep>/RServeCLI2.Example/RserveExamples.cs
//-----------------------------------------------------------------------
// Copyright (c) 2011, <NAME>
// All rights reserved.
//-----------------------------------------------------------------------
namespace RserveCLI2.Example
{
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
public class RProcess
{
private const int Port = 6311;
private readonly Process _rtermProcess;
public RConnection RConnection { get; private set; }
public int ProcessId
{
get
{
return _rtermProcess.Id;
}
}
public bool IsRunning
{
get
{
try { Process.GetProcessById(_rtermProcess.Id); }
catch (InvalidOperationException) { return false; }
catch (ArgumentException) { return false; }
return true;
}
}
/// <summary>
/// Creates a self-hosted Rserve.
/// </summary>
/// <param name="showWindow">If true then the Rserve window will be visible. Useful for debugging. Default is false.</param>
/// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes. That is, the maximal size of data transported from the client to the server.</param>
public RProcess(bool showWindow = false, int maxInputBufferSizeInKb = 0, int portNum = 6311)
{
// ReSharper restore AssignNullToNotNullAttribute
string rExeFilePath = Path.Combine(@"C:\Program Files\R\R-3.2.2\bin", Environment.Is64BitOperatingSystem ? "x64" : "i386", "Rterm.exe");
// the only way to set maxinbuf is via configuration file
// generate a config file and reference it as part of the args parameter to Rserve() below
string args = "";
if (maxInputBufferSizeInKb > 0)
{
string configFile = Path.GetTempFileName();
// plaintext warning only shows when using a config file. setting plaintext enable to eliminate the warning
File.WriteAllText(configFile, "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable");
args = string.Format(", args = '--RS-conf {0}' ", configFile.Replace(@"\", "/"));
}
// launch RTerm and tell it load Rserve.
// Keep RTerm open, otherwise the child process will be killed.
// We will use CmdShutdown to stop the server
// ReSharper disable UseObjectOrCollectionInitializer
_rtermProcess = new Process();
_rtermProcess.StartInfo.FileName = rExeFilePath;
_rtermProcess.StartInfo.Arguments = string.Format("--no-site-file --no-init-file --no-save -e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"", portNum, args);
_rtermProcess.StartInfo.UseShellExecute = false;
_rtermProcess.StartInfo.CreateNoWindow = !showWindow;
_rtermProcess.Start();
Thread.Sleep(3000);
// ReSharper restore UseObjectOrCollectionInitializer
// create a connection to the server
// ReSharper disable RedundantArgumentDefaultValue
RConnection = RConnection.Connect(port: portNum);
// ReSharper restore RedundantArgumentDefaultValue
}
}
public class REngine
{
private static ConcurrentDictionary<string, RProcess> _userProcesses = new ConcurrentDictionary<string, RProcess>();
private static int _lastPort = 6311;
private static object portLock = new object();
public static RConnection GetConnection(string userId)
{
if (!_userProcesses.ContainsKey(userId))
{
RProcess process;
lock (portLock)
{
process = new RProcess(portNum: _lastPort++);
}
RunScript(process.RConnection, @"C:\OnlineDataLab\Scripts\global.R");
_userProcesses.TryAdd(userId, process);
}
return _userProcesses[userId].RConnection;
}
public static void RunScript(RConnection c, string scriptPath)
{
try
{
string script = File.ReadAllText(scriptPath);
script = script.Replace("\r\n", "\r");
c.TryVoidEval(script);
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
/// <summary>
/// A set of simple examples for RserveCLI.
/// </summary>
public class MainClass
{
/// <summary>
/// Executes the program
/// </summary>
/// <param name="args">The arguments.</param>
public static void Main(string[] args)
{
Task.Factory.StartNew(() =>
{
Run(REngine.GetConnection("<EMAIL>"));
Console.WriteLine("buddalasunil999 Done");
});
Task.Factory.StartNew(() =>
{
Run(REngine.GetConnection("<EMAIL>"));
Console.WriteLine("test1 first Done");
}).ContinueWith((t) =>
{
Run(REngine.GetConnection("<EMAIL>"));
Console.WriteLine("test1 second Done");
});
Console.ReadKey();
}
private static void Run(RConnection c)
{
string filePath = "C:/Users/DarkBlue/Google Drive/onlinedatalab/source/dummy data.csv";
string scriptPath = @"C:\OnlineDataLab\Scripts\input.R";
REngine.RunScript(c, scriptPath);
Sexp r = c.TryEval(string.Format("processInput(\"{0}\")", filePath));
Console.WriteLine(r.AsDictionary);
//var x = c.Eval("R.version.string");
//Console.WriteLine(x.AsString);
//Task.Factory.StartNew(() =>
//{
// //using (var s1 = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
// //{
// string filePath = "C:/Users/DarkBlue/Google Drive/onlinedatalab/source/dummy data.csv";
// string scriptPath = @"C:\OnlineDataLab\Scripts\input.R";
// c.TryVoidEval(File.ReadAllText(scriptPath));
// c.TryVoidEval("processInput <- function(inputFilePath){ uploaddata < -read.csv(inputFilePath);outputdata < -toJSON(uploaddata[1:20,]);allchoices < -names(uploaddata);return (list(\"uploaddata\" = uploaddata, \"outputdata\" = outputdata, \"allchoices\" = allchoices));}");
// //c.VoidEval(string.Format("uploaddata <- read.csv(\"{0}\")", filePath));
// var data = c.Eval("test()");
// Console.WriteLine(data.AsList);
// //s1.Shutdown();
// //}
//}).Wait();
//using (var s = RConnection.Connect(new System.Net.IPAddress(new byte[] { 127, 0, 0, 1 })))
//{
// // Generate some example data
// var x = Enumerable.Range(1, 20).ToArray();
// var y = (from a in x select (0.5 * a * a) + 2).ToArray();
// // Build an R data frame
// var d = Sexp.MakeDataFrame();
// d["x"] = Sexp.Make(x);
// d["y"] = Sexp.Make(y);
// s["d"] = d;
// // Run a linear regression, obtain the summary, and print the result
// s.VoidEval("linearModelSummary = summary(lm(y ~ x, d))");
// var coefs = s["linearModelSummary$coefficients"];
// var rSquared = s["linearModelSummary$r.squared"].AsDouble;
// Console.WriteLine("y = {0} x + {1}. R^2 = {2,4:F}%", coefs[1, 0], coefs[0, 0], rSquared * 100);
// // Now let's do some linear algebra
// var matA = new double[,] { { 14, 9, 3 }, { 2, 11, 15 }, { 0, 12, 17 }, { 5, 2, 3 } };
// var matB = new double[,] { { 12, 25 }, { 9, 10 }, { 8, 5 } };
// s["a"] = Sexp.Make(matA);
// s["b"] = Sexp.Make(matB);
// Console.WriteLine(s["a %*% b"].ToString());
//}
}
// need to work this into a unit test - create file on server, read from server, then delete from server
//// Make a chart and transfer it to the local machine
// s.VoidEval( "library(ggplot2)" );
// s.VoidEval( "pdf(\"outfile.pdf\")" );
// s.VoidEval( "print(qplot(x,y, data=d))" );
// s.VoidEval( "dev.off()" );
// using ( var f = File.Create( "Data Plot.pdf" ) )
// {
// s.ReadFile( "outfile.pdf" ).CopyTo( f );
// }
// s.RemoveFile( "outfile.pdf" );
}
/// Extension methods for Rserve components
public static class RserveExtensions
{
/// Eval method that catches errors and returns the actual R error.
/// See http://www.rforge.net/Rserve/faq.html#errors
/// According to the Rserve
/// docs the try() method is more reliable; however this method
/// sometimes gives us a stack trace which is very helpful.
public static Sexp TryEval(this RConnection conn, String expr)
{
try
{
return conn.Eval(expr);
}
catch (RserveException ex)
{
GetAndThrowRealError(conn, ex);
return null; // We won't get here but the compiler doesn't know that.
}
}
/// VoidEval method with error reporting.
public static void TryVoidEval(this RConnection conn, String expr)
{
try
{
conn.VoidEval(expr);
}
catch (RserveException ex)
{
GetAndThrowRealError(conn, ex);
}
}
/// Try to get a real error message and stack trace; if that fails rethrow the original exception.
private static void GetAndThrowRealError(RConnection conn, RserveException ex)
{
// Try to get the error message
String msg;
try
{
msg = conn.Eval("geterrmessage()").AsString;
}
catch
{
throw ex;
}
if (String.IsNullOrWhiteSpace(msg))
throw ex;
// Try to get the stack trace
// It's possible that geterrmessage() succeeds and traceback() fails.
// If so just use the error message
try
{
var tracebacks = conn.Eval("traceback()").AsStrings;
var traceback = String.Join("\r\n", tracebacks);
#if DEBUG
msg = msg + traceback;
#endif
}
catch
{
}
// Throw with a helpful message
throw new RserveException(msg);
}
}
/// <summary>
/// Starts RServe and opens a connections to the server.
/// </summary>
/// <remarks>
/// We are launching RServ using Rterm because its a reliable way to do that.
/// R CMD Rserve requires RHOME to be in the registry.
/// </remarks>
public class Rservice : IDisposable
{
#region Constants and Fields
/// <summary>
/// The Sexp attributes, if any
/// </summary>
private const int Port = 6311;
#endregion
#region Constructors
/// <summary>
/// Creates a self-hosted Rserve.
/// </summary>
/// <param name="showWindow">If true then the Rserve window will be visible. Useful for debugging. Default is false.</param>
/// <param name="maxInputBufferSizeInKb">The maximal allowable size of the input buffer in kilobytes. That is, the maximal size of data transported from the client to the server.</param>
public Rservice(bool showWindow = false, int maxInputBufferSizeInKb = 0, int portNum = 6311)
{
// ReSharper restore AssignNullToNotNullAttribute
string rExeFilePath = Path.Combine(@"C:\Program Files\R\R-3.2.2\bin", Environment.Is64BitOperatingSystem ? "x64" : "i386", "Rterm.exe");
// the only way to set maxinbuf is via configuration file
// generate a config file and reference it as part of the args parameter to Rserve() below
string args = "";
if (maxInputBufferSizeInKb > 0)
{
string configFile = Path.GetTempFileName();
// plaintext warning only shows when using a config file. setting plaintext enable to eliminate the warning
File.WriteAllText(configFile, "maxinbuf " + maxInputBufferSizeInKb + "\r\n" + "plaintext enable");
args = string.Format(", args = '--RS-conf {0}' ", configFile.Replace(@"\", "/"));
}
// launch RTerm and tell it load Rserve.
// Keep RTerm open, otherwise the child process will be killed.
// We will use CmdShutdown to stop the server
// ReSharper disable UseObjectOrCollectionInitializer
_rtermProcess = new Process();
_rtermProcess.StartInfo.FileName = rExeFilePath;
_rtermProcess.StartInfo.Arguments = string.Format("--no-site-file --no-init-file --no-save -e \"library( Rserve ); Rserve( port = {0} , wait = TRUE {1});\"", portNum, args);
_rtermProcess.StartInfo.UseShellExecute = false;
_rtermProcess.StartInfo.CreateNoWindow = !showWindow;
_rtermProcess.Start();
Thread.Sleep(3000);
// ReSharper restore UseObjectOrCollectionInitializer
// create a connection to the server
// ReSharper disable RedundantArgumentDefaultValue
RConnection = RConnection.Connect(port: portNum);
// ReSharper restore RedundantArgumentDefaultValue
}
#endregion
#region Properties
/// <summary>
/// Get the wrapped RConnection
/// </summary>
public RConnection RConnection { get; private set; }
#endregion
#region Public Members
public void Dispose()
{
Dispose(true);
}
#endregion
#region Interface Implimentations
protected virtual void Dispose(bool disposing)
{
if (!_disposed)
{
//if (disposing)
//{
// // dispose the connection to server
// if (RConnection != null)
// {
// // Kill the server
// RConnection.Shutdown();
// RConnection.Dispose();
// }
//}
_disposed = true;
}
}
#endregion
#region Private Members
private bool _disposed; // to detect redundant calls
private readonly Process _rtermProcess;
#endregion
}
}
|
042cebf14d67373474e7913c3f94660d4f923b9e
|
[
"C#"
] | 1
|
C#
|
buddalasunil999/RserveCLI2
|
5299e8316068070983c258411b6af4c171718e0b
|
6ddd1a2df298fdf4e48abddf04ae777a7644c8e9
|
refs/heads/master
|
<repo_name>englishphilosophy/hume-texts-online<file_sep>/texts/n/12.md
---
layout: 'texts'
text: 'N.12'
tab: 'text'
---
<file_sep>/texts/h/vol5/full.md
---
layout: texts
text: 'H.Vol5'
tab: 'text'
---
<file_sep>/texts/m/app1.md
---
layout: 'texts'
text: 'M.App1'
tab: 'text'
---
<file_sep>/texts/mol/index.md
---
layout: 'texts'
text: 'MOL'
tab: 'text'
notes: true
---
<file_sep>/texts/empl2/pc.md
---
layout: texts
text: 'PC'
parent: 'EMPL2'
essay: 9
tab: 'text'
---
<file_sep>/texts/h/25.md
---
layout: texts
text: 'H.25'
tab: 'text'
---
<file_sep>/texts/h/59.md
---
layout: texts
text: 'H.59'
tab: 'text'
---
<file_sep>/texts/p/notes.md
---
layout: 'texts'
text: 'P'
tab: 'notes'
notes: true
---
{% include notes/p.md %}
<file_sep>/_includes/notes/n.md
## The Natural History of Religion
_prepared by <NAME>_
Notes on this text will be added soon.
<file_sep>/texts/empw/mp.md
---
layout: 'texts'
text: 'MP'
parent: 'EMPW'
tab: 'text'
---
<file_sep>/_includes/notes/d.md
## Dialogues Concerning Natural Religion (1779)
_prepared by <NAME>_
Hume's final masterpiece was mostly written in 1751-2, apparently revised around 1757 and again in 1761, with the last revision taking place only in 1776 when he was very close to death (the timing of these revisions is carefully discussed by <NAME>, "The Dating of Hume's Manuscripts", in <NAME>, *The Scottish Enlightenment: Essays in Reinterpretation*, University of Rochester Press, 2000, chapter 9). Dissuaded by friends from publishing such a controversial work in his lifetime, Hume planned to leave the manuscript to one of his closest, <NAME>. But Smith was clearly reluctant to publish, so the dying Hume decided instead to entrust it to <NAME>, his printer, through a codicil to his will dated 7th August 1776 (he died on 25th August): "I ... leave my Manuscripts to the Care of Mr <NAME> ... I desire, that my Dialogues concerning Natural Religion may be printed and published any time within two Years after my Death; ... I also ordain, that if my Dialogues from whatever Cause, be not published within two Years and a half after my Death ... the Property shall return to my Nephew, David, whose Duty, in publishing them as the last Request of his Uncle, must be approved of by all the World." Meanwhile he ordered two copies to be made, one of them to remain with his nephew, who in the event kept the original manuscript from which he ultimately brought the work to publication in 1779. The text here follows that first 1779 edition, with a minimal number of editorial changes where clear mistakes can be identified (consulting the manuscript in appropriate cases).
Uniquely amongst Hume's major philosophical works, we still possess the entire original manuscript, preserved by the Royal Society of Edinburgh and housed in the National Library of Scotland (to both of which we are very grateful for providing such excellent images). It is made public for the first time on this website, and provides intriguing clues to both the composition and interpretation of a work whose very dialogue form serves to camouflage Hume's intentions. It is divided into 12 parts (after a short introduction), involving three main characters, and mostly consists of an analysis and critical discussion of the popular Design Argument for God's existence, at the time widely considered the decisive proof of theism. Just as in Section 11 of the first *Enquiry*, this dialogue form allows Hume to canvass "dangerous" opinions without committing himself to them, resulting in much debate as to which of the characters---or what combination of their views---best reflects his own position.
After a few preliminaries, Part 1 provides a discussion of scepticism that gives valuable insights into the "mitigated scepticism" which Hume had reached as the concluding position of his first *Enquiry* (E 12.24-34). The Design Argument is presented in Part 2 by Cleanthes, the advocate for "experimental Theism" (D 5.2), who appeals to the analogy between the intricately ordered universe and a complex machine. Philo---the "careless sceptic" (D Intro.6) who is generally thought to be Hume's main spokesman---goes on to attack this argument, objecting that the supposed analogy is too distant to sustain any reliable inference (D 2.17-24). The third main character Demea---introduced as a believer of "rigid orthodoxy" (D Intro.6)---joins with Philo in attacking Cleanthes' "anthropomorphism", but is himself taken to task by Cleanthes for the opposite vice of "mysticism", which by insisting that God is entirely incomprehensible in human terms, becomes indistinguishable from atheism (D 4.1-3).
Parts 5 to 8 are mostly taken up with Philo's inventive proferring of numerous alternative analogies, by which he effectively ridicules Cleathes' Design Argument. Rather than a machine, the universe might more properly be compared to a ship or city, produced not by a single perfect designer, but by a succession of many fallible workers who slowly learn their craft by trial and error (D 5.7-12). Its intricate order, so far from being like that of "a watch or a knitting-loom" (D 7.3), is more like that of an animal or plant, which derive from generation or vegetation rather than design (D 6-7). Philo even suggests reviving "the old <span style="font-variant:small-caps;">Epicurean</span> hypothesis" (D 8.2), accounting for the universe's apparent order in terms of stable patterns that arise purely by chance — many of Hume's readers have seen here a possible foreshadowing of Darwin's theory of evolution.
In Part 9, Demea recommends abandoning Cleathes' "argument *a posteriori*" in favour of "the simple and sublime argument *a priori*" which is strongly reminiscent of <NAME>. Now it is Cleanthes' turn to attack, efficiently dismissing Demea's argument in an entirely Humean spirit (compare D 9.5 with E 12.28). Demea's reaction is to admit that his belief in God is based not on reasoning but on "a consciousness of his imbecility and misery ... Wretched creatures that we are! what resource for us amidst the innumerable ills of life, did not Religion ... appease those terrors ..." (D 10.1). Philo now joins with Demea in emphasising the horrors of the world (Parts 11 and 12 together constituting one of the classic discussions of the Problem of Evil), but he ultimately presses the argument well beyond the boundaries that Demea has in mind, towards the conclusion that any creator is likely to be morally indifferent (D 11.15) or even immoral (D 11.16-17). Demea, clearly upset by this turn of events, "took occasion soon after, on some pretence or other, to leave the company" (D 11.21), leaving Cleanthes and Philo to finish the discussion in the famously perplexing Part 12.
The notorious puzzle of the *Dialogues* is how to make sense of Philo's apparent *volte-face* in which, having criticised the Design Argument so heavily in the earlier parts, he ends up advocating the argument himself (e.g. D 12.2-4), and ultimately accepting on this basis "_That the cause or causes of order in the universe probably bear some remote analogy to human intelligence_" (D 12.33), a passage commonly known as "Philo's confession". There are several themes running through Part 12 that might help to explain (or explain away) this apparent inconsistency, for example Philo's suggestion at D 12.6-7 that the level of analogy between the human mind and the supposed divine mind is a matter of degree, making the debate between theists and atheists largely verbal. If this is really the ultimate upshot of the debate — as might seem to be confirmed by the authorial footnote 11 (although that concerns "the dispute between the Sceptics and Dogmatists", and makes no mention of religion) — then Philo's apparent confession of faith amounts to virtually nothing at all. Nevertheless his overt expression of "veneration for true religion" (D 12.9) has a point within the dialogue, by giving him licence to launch a fierce attack on the contrasting moral corruptions of "vulgar superstition" (D 12.11-21). "True religion, I allow, has no such pernicious consequences" (D 12.23), he says, but one has to wonder whether his appeal to "true religion" here is mere window-dressing, a way of avoiding universal censure and rejection of the views that he is expressing, by purporting to stand up for a virtuous form of religion which supposedly encapsulates "genuine Theism" (D 12.24), but which is in fact conspicuous by its absence in the real world of religious practice. Philo's unflattering picture of popular religion portrays it as corrupting morality by "raising up a new and frivolous species of merit", tending to "weaken ... men's attachment to the natural motives of justice and humanity", and promoting hypocrisy (D 12.16-17). So far from being founded on reason, its psychological basis lies in fear and misery (D 12.25-30), and Philo again emphasises the contrast between such vulgar superstition and the minimal abstract true religion of "philosophical Theists" (D 12.32) before delivering his somewhat surprising confession. He ends on an even more surprising note, remarking that because reason is unable to establish more than a minimal theism, "A person, seasoned with a just sense of the imperfections of natural reason, will fly to revealed truth with the greatest avidity ... To be a philosophical Sceptic is, in a man of letters, the first and most essential step towards being a sound, believing Christian" (D 12.33).
Those familiar with Hume's rejection of "revealed truth" (e.g. E 10.40) and his penchant for "theological lying" (as perhaps exemplified most clearly in the first and last paragraphs of his essay *Of the Immortality of the Soul*) might well consider that Philo is being patently insincere in his final flourish of devout fideism. But Philo is not Hume, and it is therefore possible that his intended role is to portray a genuine sceptical fideist on the model of Pierre Bayle. _Hume's_ message must then be read not directly from what Philo says, but from the artfully constructed *Dialogues* as a whole. And this is where the value of his physical manuscript becomes most apparent, enabling us to see some of the stages by which that artful construction took place. Those wanting to follow this up in detail are advised to consult Stewart's article mentioned above, and one illustration must suffice here.
If you go to <a href="/texts/dms.html#MS79">Page 79</a> of the manuscript, on the right-hand side of the sreen you will see the printed text of the Dialogues (as in the first 1779 edition), and on the left-hand side, Hume's handwritten page. Many traces of revision and deletion are evident, and about halfway down a sign "BB" indicating a place for insertion (just after the line "he is justly suppos'd to bear a considerable Resemblance?"). Looking back now to the text at the left of the screen, scroll down until you come to the corresponding point in the printed version, where "BB" is highlighted in blue to show that it is an active link. Clicking on this blue text will now bring up manuscript page 87 on the left of the screen, showing the "BB" insertion as written by Hume. The "AA" insertion (containing footnote 11 mentioned above) is also on this page, but notice how different the two passages look. This is because the "BB" insertion, which extends over to the last page of the manuscript (click on the "next page" button at the top right) was added as Hume was dying, and the deterioration in his handwriting is very evident. The text around the page break here is highly significant: "... I ask [the Atheist], whether, from the coherence and apparent Sympathy in all the parts of this world, there be not a certain degree of analogy among all the operations of Nature, in every situation and in every age; whether the rotting of a Turnip, the generation of an animal, and the structure of human thought be not energies that probably bear some remote analogy to each other: It is impossible he can deny it ... Having obtain'd this Concession, I push him still farther in his retreat; and I ask him, if it be not probable, that the Principle which first arrang'd, and still maintains order in this universe, bears not also some remote inconceivable analogy to the other operations of Nature, and among the rest to the Oeconomy of human Mind and Thought. However reluctant, he must give his Assent. ..." Note how this passage (which Stewart calls Hume's "dying testament to posterity"), while purporting to put pressure on the atheist, in fact serves to undermine completely the force of Philo's celebrated "confession": the cause or causes of order in the universe might indeed bear some remote analogy to human intelligence, but no more than to the rotting of a turnip, and this clearly does not amount to any theism worthy of the name! Moreover these are the only two passages in all of Hume's writings to use the phrase "remote analogy" — and they share the entire phrase "probably bear some remote analogy" — so it seems overwhelmingly likely that they are intended to be read together. Here we have a wonderful example of Hume's clever composition, hiding a message within the very last paragraph that he ever wrote for publication, so that it might later be discovered and appropriately understood by his discerning readers. That message is Hume's, but not apparently Philo's, for Philo remains a Baylean fideist, but this evidence strongly suggests that Hume was far closer to what we would call atheism.
<file_sep>/texts/h/38.md
---
layout: texts
text: 'H.38'
tab: 'text'
---
<file_sep>/texts/emp/mp.md
---
layout: texts
text: 'MP'
parent: 'EMP'
essay: 18
tab: 'text'
---
<file_sep>/texts/n/notes.md
---
layout: 'texts'
text: 'N'
tab: 'notes'
notes: true
---
{% include notes/n.md %}
<file_sep>/texts/t/ad1740.md
---
layout: 'texts'
text: 'Ad1740'
tab: 'text'
---
<file_sep>/texts/emp/pr.md
---
layout: texts
text: 'PR'
parent: 'EMP'
essay: 4
tab: 'text'
---
<file_sep>/texts/pld/index.md
---
layout: texts
text: 'PLD'
tab: 'text'
contents: true
fulltext: true
context: 'PLD'
notes: true
---
<file_sep>/texts/emp/dm.md
---
layout: texts
text: 'DM'
parent: 'EMP'
essay: 14
tab: 'text'
---
<file_sep>/notes/abbreviations.md
---
layout: notes
subsection: abbreviations
---
## Abbreviations for the Texts
It is standard practice to refer to Hume's texts using abbreviations, though not everyone uses the same abbreviations. Commonly the *Treatise of Human Nature*, *Enquiry Concerning Human Understanding*, and *Dialogues Concerning Natural Religion*, for example, are referred to using just the letters "T", "E", and "D" respectively, while other authors prefer "THN", "EHU", and "DNR". But on a website such as this, long abbreviations can be cumbersome and awkward to place neatly, especially when they need to include section and paragraph details (e.g "THN 1.3.14.24"). For this reason, we have adopted the convention of using single letter abbreviations for all of Hume's major works (including the *Abstract* and the *Letter from a Gentleman*), and longer abbreviations for his essays (including *My Own Life*). These are as follows:
### 1. Major works (in chronological order)
| T | _[Treatise of Human Nature]({{ site.baseurl }}/texts/t)_ |
| A | _[Abstract of the Treatise]({{ site.baseurl }}/texts/a)_ |
| L | _[Letter from a Gentleman]({{ site.baseurl }}/texts/l)_ |
| E | _[Enquiry Concerning Human Understanding]({{ site.baseurl }}/texts/e)_ |
| M | _[Enquiry Concerning the Principles of Morals]({{ site.baseurl }}/texts/m)_ |
| P | _[Dissertation on the Passions]({{ site.baseurl }}/texts/p)_ |
| N | _[Natural History of Religion]({{ site.baseurl }}/texts/n)_ |
| D | _[Dialogues Concerning Natural Religion]({{ site.baseurl }}/texts/d)_ |
| H | _[History of England]({{ site.baseurl }}/texts/h)_ |
### 2. Essays (as ordered in Miller's standard edition)
{% assign suis = 'su,is' | split: ',' %}
{% assign ids = site.data.empl1.index.texts | concat: site.data.empl2.index.texts | concat: site.data.empw.index.texts | concat: suis %}
{% for id in ids %}
{%- include assign/text.html id=id -%}
{{ text.id }} | _[{{ text.title }}]({{ url }})_ |
{% endfor %}
<file_sep>/texts/h/67.md
---
layout: texts
text: 'H.67'
tab: 'text'
---
<file_sep>/texts/h/17.md
---
layout: texts
text: 'H.17'
tab: 'text'
---
<file_sep>/texts/emp/sc.md
---
layout: texts
text: 'Sc'
parent: 'EMP'
essay: 24
tab: 'text'
---
<file_sep>/texts/empl2/full.md
---
layout: texts
text: 'EMPL2'
tab: 'text'
notes: true
---
<file_sep>/texts/empl1/pl.md
---
layout: texts
text: 'Pl'
parent: 'EMPL1'
essay: 17
tab: 'text'
---
<file_sep>/texts/empl2/mo.md
---
layout: texts
text: 'Mo'
parent: 'EMPL2'
essay: 3
tab: 'text'
---
<file_sep>/texts/e/3v.md
---
layout: 'texts'
text: 'E.3'
tab: 'variants'
---
<file_sep>/texts/e/9.md
---
layout: 'texts'
text: 'E.9'
tab: 'text'
---
<file_sep>/texts/emp/pd.md
---
layout: texts
text: 'PD'
parent: 'EMP'
essay: 25
tab: 'text'
---
<file_sep>/texts/h/index.md
---
layout: texts
text: 'H'
tab: 'text'
contents: true
notes: true
---
<file_sep>/texts/emp/ip.md
---
layout: texts
text: 'IP'
parent: 'EMP'
essay: 8
tab: 'text'
---
<file_sep>/texts/emp/lp.md
---
layout: texts
text: 'LP'
parent: 'EMP'
essay: 2
tab: 'text'
---
<file_sep>/texts/h/27.md
---
layout: texts
text: 'H.27'
tab: 'text'
---
<file_sep>/texts/emp/el.md
---
layout: texts
text: 'El'
parent: 'EMP'
essay: 17
tab: 'text'
---
<file_sep>/texts/h/7.md
---
layout: texts
text: 'H.7'
tab: 'text'
---
<file_sep>/assets/js/jump.js
---
---
export default (id) => {
const href = lookup[id.toLowerCase().replace(/\s/g, '.')]
if (href) {
window.location.href = href
} else {
window.alert('This does not appear to be a valid reference.')
}
}
const lookup = {
{%- for id in site.data.all -%}
{% include assign/text.html id=id %}
{% include json/urls.html text=text url=url %}
{%- endfor -%}
}
<file_sep>/texts/empl1/nc.md
---
layout: texts
text: 'NC'
parent: 'EMPL1'
essay: 21
tab: 'text'
---
<file_sep>/texts/l/notes.md
---
layout: 'texts'
text: 'L'
tab: 'notes'
notes: true
---
{% include notes/l.md %}
<file_sep>/texts/h/5.md
---
layout: texts
text: 'H.5'
tab: 'text'
---
<file_sep>/texts/empl1/index.md
---
layout: texts
text: 'EMPL1'
tab: 'text'
contents: true
fulltext: true
context: 'EMPL1'
notes: true
---
<file_sep>/texts/h/vol2/full.md
---
layout: texts
text: 'H.Vol2'
tab: 'text'
---
<file_sep>/texts/t/1/3/2.md
---
layout: 'texts'
text: 'T.1.3.2'
tab: 'text'
---
<file_sep>/texts/empl2/oc.md
---
layout: texts
text: 'OC'
parent: 'EMPL2'
essay: 12
tab: 'text'
---
<file_sep>/texts/h/18.md
---
layout: texts
text: 'H.18'
tab: 'text'
---
<file_sep>/texts/n/14.md
---
layout: 'texts'
text: 'N.14'
tab: 'text'
---
<file_sep>/_includes/notes/l.md
## A Letter from a Gentleman (1745)
_prepared by <NAME>_
Notes on this text will be added soon.
<file_sep>/texts/e/full.md
---
layout: 'texts'
text: 'E'
tab: 'text'
notes: true
---
<file_sep>/texts/t/2/3/9.md
---
layout: 'texts'
text: 'T.2.3.9'
tab: 'text'
---
<file_sep>/texts/empl1/dm.md
---
layout: texts
text: 'DM'
parent: 'EMPL1'
essay: 11
tab: 'text'
---
<file_sep>/texts/e/1v.md
---
layout: 'texts'
text: 'E.1'
tab: 'variants'
---
<file_sep>/texts/emp/ad1741.md
---
layout: texts
text: 'Ad1741'
parent: 'EMP'
tab: 'text'
---
<file_sep>/texts/h/vol4/index.md
---
layout: texts
text: 'H.Vol4'
tab: 'text'
contents: true
fulltext: true
---
<file_sep>/texts/emp/sto.md
---
layout: texts
text: 'Sto'
parent: 'EMP'
essay: 22
tab: 'text'
---
<file_sep>/texts/etss/ad1758.md
---
layout: texts
text: 'Ad1758'
tab: 'text'
---
<file_sep>/_includes/notes/p.md
## A Dissertation on the Passions (1757, 1777)
_prepared by <NAME>_
More notes on this text will be added soon. In the meantime, note that there is one substantial alteration to the text: it seems clear to me from the context that the word "compassion" in section 3, paragraph 12 should be "dislike". Obviously this changes the sense considerably, and unfortunately, since this is a new paragraph first added in the 1777 edition, there are no other editions to compare. Thus forewarned, readers may judge for themselves.
<file_sep>/texts/empl1/pr.md
---
layout: texts
text: 'PR'
parent: 'EMPL1'
essay: 3
tab: 'text'
---
<file_sep>/texts/emp/pl.md
---
layout: texts
text: 'Pl'
parent: 'EMP'
essay: 23
tab: 'text'
---
<file_sep>/texts/e/11.md
---
layout: 'texts'
text: 'E.11'
tab: 'text'
---
<file_sep>/texts/n/10.md
---
layout: 'texts'
text: 'N.10'
tab: 'text'
---
<file_sep>/texts/h/50.md
---
layout: texts
text: 'H.50'
tab: 'text'
---
<file_sep>/_includes/notes/h.md
## The History of England (1754-62, 1778)
_prepared by <NAME>_
Hume's *History of England* was written in three stages, and in reverse chronological order. He began with two volumes on the *History of Great Britain* (from the Union of the Crowns to the death of James II), published in 1754 and 1757. In 1759 he then published two more volumes, on the House of Tudor. This necessitated changing the title from the *History of Great Britain* to the *History of England*, since he now began the story a century and a half before the union. Finally, in 1762, he published two more volumes tracing the country's history back even further, all the way to the Celtic Britons and the Roman invasion. In 1763, the first complete set was published, but owing to the size of the work---including the now very large index included in the final volume---it had to be chopped up rather awkwardly into 8 volumes rather than 6.
The text here follows the posthumous 1778 edition, which Hume was working on before he died. That edition was also (of necessity) printed in 8 volumes, but it is shown here divided into 6 volumes instead (matching the breaks that appeared in the volumes as they were originally published). The other texts on this site are not divided up into separate volumes at all (even where the originals were), since such divisions are unnecessary and presumed to be of little interest. In the case of the *History of England*, however, we have made an exception; with its 71 chapters and four appendices, and no other internal structure, it would be rather unwieldy without these divisions.
The text here is derived from the HTML version of the *Liberty Classics* edition, available at [http://oll.libertyfund.org/titles/hume-the-history-of-england-6-vols](http://oll.libertyfund.org/titles/hume-the-history-of-england-6-vols). I am hugely grateful to the [Liberty Fund](https://www.libertyfund.org/) for making this text available. The text was imported automatically, and is being checked and edited by hand. I have not yet checked it all (far from it), but from what I can tell so far it is very accurate. There are some systematic stylistic changes that have been undone here, and a handful of small errors that I am correcting as I see them. Don't expect me to get through the text quickly; it is about twice as long as everything else Hume ever published put together.
<file_sep>/texts/t/2/2/9.md
---
layout: 'texts'
text: 'T.2.2.9'
tab: 'text'
---
<file_sep>/texts/empl2/cp.md
---
layout: texts
text: 'CP'
parent: 'EMPL2'
essay: 14
tab: 'text'
---
<file_sep>/scholarship/merivale.md
---
layout: scholarship
subsection: scholarship
---
## <NAME>'s Papers and Talks on Hume
[<NAME>](http://www.merivale.co.uk/) (known as Henry in person, but also answers to Amyas if you know how to pronounce it) works on the philosophy of language and early modern philosophy. I also have a keen interest in digital humanities, and created this site.
### Books
- [*Hume on Art, Superstition, and Emotion: A Critical Study of the Four Dissertations*](https://www.routledge.com/Hume-on-Art-Emotion-and-Superstition-A-Critical-Study-of-the-Four-Dissertations/Merivale/p/book/9781138351462) (Routledge, 2018)
### Papers
- ["Hume's Mature Account of the Indirect Passions"]({{ site.baseurl }}{% link scholarship/papers/merivale/2009_Hume_Indirect_Passions.pdf %}), *Hume Studies* 35.1&2 (2009): 185-210
- ["Mixed Feelings, Mixed Metaphors: Hume on Tragic Pleasure"](http://bjaesthetics.oxfordjournals.org/content/51/3/259.full?keytype=ref&ijkey=8IcmbuAtY0lNZbY), *British Journal of Aesthetics* 51.3 (2011): 259-269
### Talks
Slides from my talks are available here: [https://merivale.uk/talks/](https://merivale.uk/talks/).
<file_sep>/texts/empl2/pa.md
---
layout: texts
text: 'PA'
parent: 'EMPL2'
essay: 11
tab: 'text'
---
<file_sep>/texts/d/5.md
---
layout: 'texts'
text: 'D.5'
manuscript: true
tab: 'text'
---
<file_sep>/texts/d/8m.md
---
layout: 'texts'
text: 'D.8'
tab: 'images'
---
<file_sep>/notes/update-2012.md
---
layout: notes
subsection: update-2012
---
## Update, May 2012
A year after the previous version of this site was launched, we are proud to unveil the latest version of davidhume.org. We have been hard at work over the last twelve months, making the following major improvements:
- We have added the texts of *A Letter from a Gentleman* and the remaining *Essays*, thus completing our collection. We now have texts of everything that Hume published apart from the historical writings. This is the first electronic edition of Hume's collected philosophical works to be made publicly available completely free of charge.
- All of our texts are now fully searchable. Using our substantial database of around 5,000 paragraphs of text, you can perform conjunctive and disjunctive searches, search for phrases, restrict your search to particular texts, lookup pages by paragraph number, or paragraphs by page number. Again, this is the first searchable edition of Hume's philosophical texts to be made available completely free of charge. We very much hope that you find this feature useful. And feel free to tell us if you do, as it was a huge job getting it set up!
- A number of formatting details have been improved; it would be tedious to list them all, but suffice it to say that the look of our editions here is now about as close to the 18th century originals as it is possible to get, without neglecting the advantages of modern editions.
<file_sep>/texts/emp/pgb.md
---
layout: texts
text: 'PGB'
parent: 'EMP'
essay: 11
tab: 'text'
---
<file_sep>/texts/pld/rc.md
---
layout: texts
text: 'RC'
parent: 'PLD'
essay: 9
tab: 'text'
---
<file_sep>/texts/empl2/ta.md
---
layout: texts
text: 'Ta'
parent: 'EMPL2'
essay: 8
tab: 'text'
---
<file_sep>/texts/m/d.md
---
layout: 'texts'
text: 'M.D'
tab: 'text'
---
<file_sep>/_includes/notes/suis.md
## Of Suicide and Of the Immortality of the Soul
_Of Suicide prepared by <NAME>_
_Of the Immortality of the Soul prepared by <NAME>_
The two essays *Of Suicide* and *Of the Immortality of the Soul* were briefly planned for publication in a projected 1755 collection called *Five Dissertations*, but Hume decided to withdraw them prior to publication. They were replaced with *Of the Standard of Taste*, and the collection appeared in 1757 under the name *Four Dissertations*. The suppressed essays were eventually published posthumously and anonymously in 1777, but the text here---like the standard edition of Miller (1987)---follows instead the 1755 version, of which a proof-copy exists in the National Library of Scotland with some corrections in Hume's handwriting.
The main departures from that copy are precisely these handwritten alterations. Hume seems to have been systematically changing the printed abbreviation "’tis" to "it is", but he did not change every instance. We presume this was simply because he didn't catch them all, and accordingly we have favoured the latter throughout (this was his preference generally in his later publications).
<file_sep>/texts/emp/fp.md
---
layout: texts
text: 'FP'
parent: 'EMP'
essay: 5
tab: 'text'
---
<file_sep>/texts/su/notes.md
---
layout: 'texts'
text: 'Su'
tab: 'notes'
notes: true
---
{% include notes/suis.md %}
<file_sep>/texts/e/notes.md
---
layout: 'texts'
text: 'E'
tab: 'notes'
notes: true
---
{% include notes/e.md %}
<file_sep>/texts/d/5m.md
---
layout: 'texts'
text: 'D.5'
tab: 'images'
---
<file_sep>/texts/empl1/el.md
---
layout: texts
text: 'El'
parent: 'EMPL1'
essay: 13
tab: 'text'
---
<file_sep>/assets/js/session.js
// set a session variable
export const set = (item, value) => {
window.localStorage.setItem(item, JSON.stringify(value))
if (item === 'search-all') groups.forEach((id) => { set(`search-${id}`, value) })
update()
}
// get a session variable
export const get = item =>
JSON.parse(window.localStorage.getItem(item))
// get an array of texts in the current search range
export const getRange = () =>
groups.filter(x => get(`search-${x}`))
// toggle a (boolean) session variable
export const toggle = item => {
set(item, !get(item))
}
// text groups for searching
const groups = ['t0', 't1', 't2', 't3', 'tapp', 'a', 'l', 'e', 'p', 'm', 'n', 'h', 'd', 'essays', 'ads']
// function to update the page to reflect current state
const update = () => {
const inputs = Array.from(document.querySelectorAll('[data-session]'))
const textPane = document.getElementById('text-pane')
const showChanges = document.getElementById('show-changes')
inputs.forEach((input) => {
input.checked = input.dataset.invert ? !get(input.dataset.session) : get(input.dataset.session)
})
if (textPane) {
if (get('show-edited')) {
textPane.classList.remove('original')
showChanges.disabled = false
showChanges.parentElement.classList.remove('disabled')
} else {
textPane.classList.add('original')
showChanges.disabled = true
showChanges.parentElement.classList.add('disabled')
}
if (get('show-breaks')) {
textPane.classList.add('breaks')
} else {
textPane.classList.remove('breaks')
}
if (get('show-changes')) {
textPane.classList.add('changes')
} else {
textPane.classList.remove('changes')
}
}
}
// set session variable defaults if they are not yet set
if (get('show-edited') === null) set('show-edited', true)
if (get('show-changes') === null) set('show-changes', false)
if (get('show-breaks') === null) set('show-breaks', false)
if (get('search-advanced') === null) set('search-advanced', false)
if (get('search-variants') === null) set('search-variants', true)
if (get('search-all') === null) set('search-all', true)
// update the page to reflect current state
update()
<file_sep>/assets/js/search.js
import * as session from './session.js'
// text data object
const blocks = {}
// load the text data for searching and paragraph lookup
const init = async () => {
const get = async (id) => {
const text = await window.fetch(`/assets/js/data/${id}.json`)
const data = await text.json()
return data.map(prepare).reduce((x, y) => x.concat(y), [])
}
blocks['t0'] = await get('t0')
blocks['t1'] = await get('t1')
blocks['t2'] = await get('t2')
blocks['t3'] = await get('t3')
blocks['tapp'] = await get('tapp')
blocks['a'] = await get('a')
blocks['l'] = await get('l')
blocks['e'] = await get('e')
blocks['p'] = await get('p')
blocks['m'] = await get('m')
blocks['n'] = await get('n')
blocks['h'] = await get('h')
blocks['d'] = await get('d')
blocks['essays'] = await get('essays')
blocks['ads'] = await get('ads')
}
// new search query
export const newSearch = async (query) => {
if (Object.keys(blocks).length !== 15) await init()
const outer = session.getRange().map(id => blocks[id]).reduce((x, y) => x.concat(y), [])
const inner = session.get('search-variants') ? outer : outer.filter(x => !x.variant)
return subSearch(query, inner)
}
// search within given results
export const subSearch = (query, range) =>
session.get('show-edited')
? range.filter(x => x.edited.plain.match(regex(query)))
: range.filter(x => x.original.plain.match(regex(query)))
// display search result
export const display = (query, block) =>
`<div class="${classes(block)}">
<div class="meta">${ref(block)}</div>
<div class="content">
${content(block).replace(regex(query), '<mark>$&</mark>')}
</div>
</div>`
// get an array of all the searchable blocks from a text
export const prepare = (text) => {
let result = text.paragraphs.map(block.bind(null, text, false, false))
if (text.notes) {
result = result.concat(text.notes.map(block.bind(null, text, true, false)))
}
if (text.variants) {
text.variants.forEach((variant) => {
if (variant.paragraphs) {
result = result.concat(variant.paragraphs.map(block.bind(null, text, false, true)))
}
if (variant.notes) {
result = result.concat(variant.notes.map(block.bind(null, text, true, true)))
}
})
}
return result
}
// augment a block (i.e. paragraph or note) so it's ready for searching
const block = (text, note, variant, block) =>
({
text: text.id,
id: note ? `${block.paragraph}n${block.id}` : block.id,
url: variant ? `${textUrl(text)}v` : textUrl(text),
pages: block.pages ? `${text.pages} ${block.pages}` : '',
type: block.type,
note,
variant,
original: fullContent(block.content, false),
edited: fullContent(block.content, true)
})
// functions needed to augment a block
const textUrl = text =>
text.parent
? `/texts/${idlUrl(text.parent)}/${idlUrl(text.id)}`
: `/texts/${idlUrl(text.id)}`
const idlUrl = id =>
id.toLowerCase().replace(/(\.|-)/g, '/')
const fullContent = (content, edited) =>
({
plain: plainContent(content, edited),
rich: richContent(content, edited)
})
const plainContent = (content, edited) =>
richContent(content, edited)
.replace(/<i>(.*?)<\/i>/g, '') // remove greek text
.replace(/(<(.*?)>)/g, '') // remove all HTML markup
.replace(/( )+/g, ' ') // replace tabs with single spaces
.replace(/\s\s/g, ' ').trim() // trim whitespace
const richContent = (content, edited) =>
baseContent(content, edited)
.replace(/<a href="(.*?)"><sup>(.*?)<\/sup><\/a>/g, '') // remove footnote anchors
.replace(/<small>(.*?)<\/small>/g, '') // remove small things
.replace(/\|/g, '') // remove page breaks
const baseContent = (content, edited) =>
edited
? content.replace(/<del( title="(.*?)")?>(.*?)<\/del>/g, '').replace(/<ins( title="(.*?)")?>(.*?)<\/ins>/g, '$3')
: content.replace(/<ins( title="(.*?)")?>(.*?)<\/ins>/g, '').replace(/<del( title="(.*?)")?>(.*?)<\/del>/g, '$3')
// turn a query string into a regular expression
const regex = (query) =>
session.get('search-advanced')
? new RegExp(`(${query})`, 'gi')
: new RegExp(`\\b(${simplify(query)})\\b`, 'gi')
const simplify = query =>
query.replace(/[.,;:?!]/g, '')
.replace(/(ct|x)ion\b/g, '(ct|x)ion')
.replace(/ould\b/g, 'ou(l|\')d')
.replace(/ied\b/g, '(ied|y\'d)')
.replace(/ed\b/g, '(ed|\'d)')
.replace(/though\b/g, 'tho(ugh|\')')
.replace(/\bbetw(ixt|een)\b/g, 'betw(ixt|een)')
.replace(/\bdispatch(t|ed)\b/g, 'dispatch(t|ed)')
.replace(/\bstop(t|ed)\b/g, 'stop(t|ed)')
.replace(/phenomen/g, 'ph(e|ae)nomen')
.replace(/ae/g, '(ae|æ)')
.replace(/economy/g, '(e|oe)conomy')
.replace(/oe/g, '(oe|œ)')
.replace(/\ba\b/g, '(a|à)')
.replace(/\bit (is|was|were)\b/g, '(it $1|\'t$1)')
.replace(/\s/g, '[.,;:?!]? ')
// functions needed to display a block
const classes = block =>
block.type ? `block ${block.type}` : 'block'
const ref = block =>
block.pages
? `<a href="${block.url}#${block.id}">${label(block)}, ${block.pages}</a>`
: `<a href="${block.url}#${block.id}">${label(block)}</a>`
const label = block =>
`${block.text}.${block.id}`.replace('.', ' ')
const content = (block) =>
session.get('show-edited')
? block.edited.rich
: block.original.rich
<file_sep>/texts/empw/index.md
---
layout: 'texts'
text: 'EMPW'
tab: 'text'
contents: true
fulltext: true
context: 'EMPW'
notes: true
---
<file_sep>/texts/m/notes.md
---
layout: 'texts'
text: 'M'
tab: 'notes'
notes: true
---
{% include notes/m.md %}
<file_sep>/texts/t/3/3/2.md
---
layout: 'texts'
text: 'T.3.3.2'
tab: 'text'
---
<file_sep>/texts/empl2/co.md
---
layout: texts
text: 'Co'
parent: 'EMPL2'
essay: 1
tab: 'text'
---
<file_sep>/texts/h/22.md
---
layout: texts
text: 'H.22'
tab: 'text'
---
<file_sep>/texts/empl2/ra.md
---
layout: texts
text: 'RA'
parent: 'EMPL2'
essay: 2
tab: 'text'
---
<file_sep>/texts/h/37.md
---
layout: texts
text: 'H.37'
tab: 'text'
---
<file_sep>/texts/empl1/sto.md
---
layout: texts
text: 'Sto'
parent: 'EMPL1'
essay: 16
tab: 'text'
---
<file_sep>/texts/fd/full.md
---
layout: texts
text: 'FD'
tab: 'text'
notes: true
---
<file_sep>/texts/h/53.md
---
layout: texts
text: 'H.53'
tab: 'text'
---
<file_sep>/texts/h/4.md
---
layout: texts
text: 'H.4'
tab: 'text'
---
<file_sep>/texts/pld/full.md
---
layout: texts
text: 'PLD'
tab: 'text'
notes: true
---
<file_sep>/texts/h/34.md
---
layout: texts
text: 'H.34'
tab: 'text'
---
<file_sep>/texts/empw/full.md
---
layout: 'texts'
text: 'EMPW'
tab: 'text'
context: 'EMPW'
notes: true
---
<file_sep>/texts/e/5.md
---
layout: 'texts'
text: 'E.5'
tab: 'text'
---
<file_sep>/texts/h/30.md
---
layout: texts
text: 'H.30'
tab: 'text'
---
<file_sep>/texts/h/19.md
---
layout: texts
text: 'H.19'
tab: 'text'
---
<file_sep>/notes/edited.md
---
layout: notes
subsection: edited
---
## Edited Versions
The edited versions available on this site differ from the copytexts in various ways particular to each text; for details of these particular departures, see the notes for each individual text. On the whole, our policy has been to keep editorial interventions to a minimum, and almost all our changes are those sanctioned by Hume himself (e.g. from ERRATA sheets, appendices, or written corrections in his own hand), or obvious typographical errors not present in editions other than the copytext.
In any event, differences between the edited version and the original version can be inspected *in situ* by checking the "Show Changes" option at the top of each text. Hovering over any such change with the mouse will then bring up a brief comment explaining the intervention.
There are two respects in which our edited versions do _not_ differ from the copytexts, where other modern editions typically do. These concern, respectively, the use of apostrophes and Hume's distinction between footnotes and endnotes. These decisions call for further comment.
### 1. Apostrophes
Conventions regarding the use of the apostrophe changed around the middle of the eighteenth century. At the start of this century, it was common to use apostrophes in place of letters that are not pronounced (as in "cou'd", "deriv'd", or "thro'"), and to abbreviate "it is" as "’tis". It was also common to use an apostrophe for possessive pronouns, but not for possessive nouns (the exact reverse of the present practice), though there seems to have been no very precise convention in this regard. By the end of the century, however, the apostrophe was used as it is today.
Most of Hume's publications conform to the old-fashioned conventions (including a somewhat inconsistent use of the apostrophe for possessive nouns and pronouns). From the 1770 edition of his *Essays and Treatises on Several Subjects* onwards, however, the modern conventions are used. Consequently all the texts on this site that appeared in that collection conform to these modern conventions, while those that did not (the *Treatise*, the *Abstract*, the *Letter from a Gentleman*, and some previously withdrawn essays) exhibit the old-fashioned conventions.
We have elected _not_ to edit these earlier works so as to conform to the modern conventions, since this is the least intrusive option. In leaving the apostrophes in place of letters that are not pronounced, we are agreeing with both Selby-Bigge's and the Nortons' editions of the *Treatise* and *Abstract*. In leaving the possessive apostrophes as they were, however, we are diverging from those editions. Selby-Bigge seems inconsistently to have changed some possessive apostrophes and not others. The Nortons seem to have intended to change them all, though they missed at least one: "three or four hour's amusement" at T 1.4.7.9 should by modern lights be "three or four hours' amusement".
### 2. Footnotes and endnotes
In respect of those texts that were included within the 1777 *Essays and Treatises on Several Subjects*, we continue to draw a distinction between notes that appeared as footnotes in the copytext and those that appeared as endnotes. Since no other modern edition draws any such distinction, and even Beauchamp's (otherwise excellent) critical editions fail to indicate which notes took each form, our policy is perhaps worth discussing in a bit more detail.
In editions of the *Essays and Treatises on Several Subjects* prior to 1770, all Hume's notes appeared as footnotes, but in his three last editions (1770, 1772 and 1777), he moved most of the larger notes to a separate section at the end of each volume. That he took an interest in such matters is clear from his letters, in particular to his printer <NAME> on 8th April 1776:
> I am very much taken with Mr Gibbon's Roman History which came from your press ... I intended to have given him my Advice with regard to the manner of printing it ... One is ... plagued with his Notes, according to the present Method of printing the Book: When a note is announced, you turn to the End of the Volume; and there you often find nothing but the Reference to an Authority. All these Authorities ought only to be printed at the Margin on the Bottom of the Page. I desire, that a Copy of my new Edition [i.e. the posthumous edition then in preparation] should be sent to Mr Gibbon, as wishing that a Gentleman, whom I so highly value, shoud peruse me in the form the least imperfect, to which I can bring my work. (HL ii 313)
In another letter to Strahan of 8th June, Hume reports the seriousness of his illness, and makes some last requests concerning the printing of *My Own Life* in his forthcoming edition, and the future publication of the *Dialogues Concerning Natural Religion*. Here again he expresses enthusiasm for the quality of what would become the 1777 edition of the *Essays and Treatises*, and the 1778 edition of the *History of England*:
> I am glad to find, that you have been able to set about this New Edition in earnest. I have made it extremely correct; at least I believe that, if I were to live twenty Years longer, I shoud never be able to give it any further Improvements.
Hence the policy followed here, of carefully following that 1777 edition for all the relevant texts, including its distinction between footnotes and endnotes, with footnotes being used for references to "Authorities" and other relatively short comments, and endnotes generally containing the longer material. Whether the distinction has any deeper significance is now open for the reader to judge, but since some footnotes are longer than many of the endnotes, this at least suggests that length was not Hume's only criterion.
<file_sep>/texts/h/41.md
---
layout: texts
text: 'H.41'
tab: 'text'
---
<file_sep>/texts/emp/index.md
---
layout: 'texts'
text: 'EMP'
tab: 'text'
contents: true
context: 'EMP'
fulltext: true
notes: true
---
<file_sep>/texts/d/9m.md
---
layout: 'texts'
text: 'D.9'
tab: 'images'
---
<file_sep>/texts/empl1/sr.md
---
layout: texts
text: 'SR'
parent: 'EMPL1'
essay: 20
tab: 'text'
---
<file_sep>/texts/empl2/po.md
---
layout: texts
text: 'PO'
parent: 'EMPL2'
essay: 13
tab: 'text'
---
<file_sep>/texts/h/52.md
---
layout: texts
text: 'H.52'
tab: 'text'
---
<file_sep>/notes/update-2018.md
---
layout: notes
subsection: update-2018
---
## Update, March 2018
_by <NAME>_
When the Leeds Electronic Text Centre closed in 2011, I continued working on my doctorate full time, and then returned to Oxford to work as a lecturer and outreach officer. Work and family commitments inevitably took over, and for almost six years this site remained unchanged. During that time I learned a lot more about building web sites, however, and I am delighted to have finally found the time to give this site a much-needed overhaul.
- With an entirely new look, the site now works better on small screens and mobile devices.
- The site structure has been simplified, dividing everything into four main areas: [Texts]({{ site.baseurl }}{% link index.md %}) (for Hume's texts and associated editorial commentary), [Notes]({{ site.baseurl }}{% link notes/index.md %}) (for help on how to use the site and information on our general editorial policies) and [Scholarship]({{ site.baseurl }}{% link scholarship/index.md %}) (for bibliographies, papers, and links to other resources), and [Search]({{ site.baseurl }}{% link search.md %}) (for interrogating our database of Hume's publications).
- Editorial notes can now be found immediately alongside each text, by clicking on the "Editorial Notes" tab.
- Search functionality has been completely redesigned. The default _simple search_ is for finding specific passages, and it will endeavour to match variant spellings, so as to maximise your chances of finding the passage you want. By switching to _advanced search_, meanwhile, you can interrogate our database of texts for scholarly purposes, using _regular expressions_. See the [Search]({{ site.baseurl }}{% link search.md %}) page for more information.
- The site is now open source. You can view the code that generates these pages, including the database of texts, at [https://github.com/merivale/davidhume.org](https://github.com/merivale/davidhume.org).
<file_sep>/scholarship/workshops.md
---
layout: scholarship
subsection: workshops
---
## Recasting the *Treatise*
The MTA BTK Lendület Morals and Science Research Group and Hertford College, Oxford are hosting a workshop entitled
### RECASTING THE TREATISE VOL. II.
This is the second workshop of a series focusing on the contrasts and differences between David Hume’s *A Treatise of Human Nature* and his later philosophical works that descended from it. The first workshop was held in Budapest in March 2018, and focused on topics from *Treatise* Book 1, the *Enquiry concerning Human Understanding*, and relevant essays. The second workshop will be held at Hertford College, Oxford, on the 23rd-24th of March 2019.
[Workshop Programme](/assets/img/Recasting_2_Programme.jpg)
Everyone is welcome, but please note that space is limited. Anyone wishing to attend should please contact <NAME> (<EMAIL>) beforehand.
<file_sep>/texts/emp/pg.md
---
layout: texts
text: 'PG'
parent: 'EMP'
essay: 10
tab: 'text'
---
<file_sep>/texts/emp/ad1742.md
---
layout: texts
text: 'Ad1742'
parent: 'EMP'
tab: 'text'
---
<file_sep>/texts/emp/ms.md
---
layout: texts
text: 'MS'
parent: 'EMP'
essay: 19
tab: 'text'
---
<file_sep>/_includes/notes/etss.md
## Essays and Treatises on Several Subjects (1758, 1777)
_prepared by <NAME> and <NAME>_
Hume first published a set of *Essays and Treatises on Several Subjects* in 1753. It was a four-volume set containing (in this order) the *Essays, Moral and Political*, the first *Enquiry*, the second *Enquiry*, and the *Political Discourses*. In 1754 he published another edition of volume 4 (the *Political Discourses*), and in 1756 another edition of volume 2 (the first *Enquiry*). It is the next edition, in 1758, that is particularly interesting, however, since it is here that Hume renames and reorders his philosophical writings for the last time. A large single-volume set, this collection contained the *Essays, Moral and Political* and the *Political Discourses*, now renamed *Essays, Moral, Political, and Literary* parts 1 and 2, the first *Enquiry* (now called an enquiry, rather than philosophical essays), the *Dissertation on the Passions*, the second *Enquiry*, and the *Natural History of Religion*. Though subsequent editions of these *Essays and Treatises* were sometimes in two volumes, sometimes in four, the structure from this point onwards remained the same, right up to the posthumous 1777 edition, which Hume was working on until his death in 1776.
<file_sep>/notes/leedshume.md
---
layout: notes
subsection: history
---
## The Leeds Hume Project (archived page, July 2001)
This is a new web project co-ordinated by <NAME>, Director of the Leeds Electronic Text Centre and a keen Hume scholar. Starting in May 2000, the aim of the project is to provide a _permanent_ resource for scholars and students wishing to have access, _free of charge_, to _high quality texts_ of works by, and associated with, the great philosopher and historian David Hume, together with _relevant bibliographic materials_.
- **A Permanent Resource**
The texts published here are intended to be in a finished state (with any future revisions being fully documented), and to remain available from the site on a permanent basis. Hence---in contrast to most other web resources---they may safely be referenced in academic works with confidence that future readers will remain able to consult them.
- **Free of Charge**
Access to the texts and bibliographic materials published here is free of charge, but provided on the strict condition that they are neither altered nor sold unless written permission is given by the copyright holder. Anyone making copies from this site should respect carefully the copyright restrictions applying to the relevant materials. Typically they will be freely copiable for personal scholarly and class use only, and any copy (whether electronic or in printed form) must incorporate a notice recording the restrictions that apply.
- **Reliable Texts**
Historical texts will be placed on this site only if they have been thoroughly checked against original sources, the aim being to provide 100% accuracy in the text, including spelling, punctuation, capitalisation etc. The 1777 text of the *Enquiry Concerning Human Understanding* presented here is, as far as can be ascertained, the only major Hume text available on the web which even approaches this standard of accuracy.
- **Bibliographic Materials**
It is intended that each Hume text published here be accompanied (either immediately, or in due course) by a _survey of the relevant secondary literature_, to enable those researching, teaching, or studying the text to get to grips with current debates quickly and easily. This type of resource is particularly suitable for delivery via the Web, because the secondary literature on Hume is growing so quickly. The bibliographic surveys on the site will be updated regularly, and interested scholars or students are advised to 'bookmark' them for future reference.
- **Works by, and associated with, <NAME>**
This project will publish not only works by Hume himself, but also works associated with him, from contemporary sources to essays by modern scholars. Hume scholars are invited to offer their work for publication here, but such work will be accepted only with the written agreement of the copyright holder, and only if the author guarantees that the work is in a reliable and permanent form.
<file_sep>/texts/empl1/fp.md
---
layout: texts
text: 'FP'
parent: 'EMPL1'
essay: 4
tab: 'text'
---
<file_sep>/texts/empw/ms.md
---
layout: 'texts'
text: 'MS'
parent: 'EMPW'
tab: 'text'
---
<file_sep>/texts/h/49.md
---
layout: texts
text: 'H.49'
tab: 'text'
---
<file_sep>/texts/fd/index.md
---
layout: texts
text: 'FD'
tab: 'text'
contents: true
fulltext: true
notes: true
---
<file_sep>/texts/t/3/2/3.md
---
layout: 'texts'
text: 'T.3.2.3'
tab: 'text'
---
<file_sep>/texts/h/12.md
---
layout: texts
text: 'H.12'
tab: 'text'
---
<file_sep>/scholarship/ehusurvey.md
---
layout: scholarship
subsection: bibliographies
---
## Critical Survey of the Literature on Hume and the First *Enquiry*
### Edition 1.0, September 2000
#### <NAME>, University of Leeds
---
- [Introduction](#introduction)
- [1. Editions of the *Enquiry*](#1-editions-of-the-enquiry)
- [1(a) Printed Editions](#1a-printed-editions)
- [1(b) Electronic Editions](#1b-electronic-editions)
- [2. Hume's Other Works](#2-humes-other-works)
- [2(a) A Treatise of Human Nature](#2a-a-treatise-of-human-nature)
- [2(b) An Enquiry concerning the Principles of Morals](#2b-an-enquiry-concerning-the-principles-of-morals)
- [2(c) Dialogues concerning Natural Religion](#2c-dialogues-concerning-natural-religion)
- [2(d) Hume's Essays](#2d-humes-essays)
- [2(e) Other Writings by Hume](#2e-other-writings-by-hume)
- [3. General Secondary Literature on Hume and the *Enquiry*](#3-general-secondary-literature-on-hume-and-the-enquiry)
- [3(a) Recent General Collections of Scholarly Work on Hume](#3a-recent-general-collections-of-scholarly-work-on-hume)
- [3(b) General Introductory Books on Hume's Philosophy in the *Enquiry*](#3b-general-introductory-books-on-humes-philosophy-in-the-enquiry)
- [3(c) Hume's Life, his Aims in the *Enquiry*, and its Relation to the *Treatise*](#3c-humes-life-his-aims-in-the-enquiry-and-its-relation-to-the-treatise)
- [4. The Nature and Origin of Ideas](#4-the-nature-and-origin-of-ideas)
- [4(a) Impressions and Ideas, Force and Vivacity](#4a-impressions-and-ideas-force-and-vivacity)
- [4(b) The Copy Principle](#4b-the-copy-principle)
- [5. Reason and Induction](#5-reason-and-induction)
- [5(a) Hume's Philosophical Logic](#5a-humes-philosophical-logic)
- [5(b) The Structure of Hume's Argument concerning Induction](#5b-the-structure-of-humes-argument-concerning-induction)
- [5(c) Interpretations of Hume on Reason and Induction](#5c-interpretations-of-hume-on-reason-and-induction)
- [5(d) Inductive Scepticism](#5d-inductive-scepticism)
- [6. Belief, Probability, Rationality, and the Reason of Animals](#6-belief-probability-rationality-and-the-reason-of-animals)
- [6(a) Hume's Theory of Belief](#6a-humes-theory-of-belief)
- [6(b) Probability of Chances and Probability of Causes](#6b-probability-of-chances-and-probability-of-causes)
- [6(c) Probability and Rationality in the *Treatise* and the *Enquiry*](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry)
- [6(d) The Reason of Animals](#6d-the-reason-of-animals)
- [7. Causation](#7-causation)
- [7(a) Hume's Account of Causation](#7a-humes-account-of-causation)
- [7(b) Humean Theories of Causation](#7b-humean-theories-of-causation)
- [7(c) Causal Realism and the 'New Hume'](#7c-causal-realism-and-the-new-hume)
- [8. Liberty and Necessity](#8-liberty-and-necessity)
- [8(a) Hume's Treatment of Liberty and Necessity](#8a-humes-treatment-of-liberty-and-necessity)
- [8(b) Free Will and Determinism](#8b-free-will-and-determinism)
- [9. Hume's Philosophy of Religion](#9-humes-philosophy-of-religion)
- [9(a) Miracles](#9a-miracles)
- [9(b) Hume on the Design Argument](#9b-hume-on-the-design-argument)
- [9(c) The Contemporary Design Argument](#9c-the-contemporary-design-argument)
- [10. Scepticism](#10-scepticism)
- [10(a) Scepticism Regarding the External World](#10a-scepticism-regarding-the-external-world)
- [10(b) Scepticism Regarding Infinite Divisibility](#10b-scepticism-regarding-infinite-divisibility)
- [10(c) The Nature of Hume's Scepticism](#10c-the-nature-of-humes-scepticism)
---
### Introduction
This survey aims to provide both a research and a teaching resource, by giving useful suggestions for secondary reading directly related to Hume's *Enquiry Concerning Human Understanding*, together with discussion of the philosophical and scholarly issues raised by that literature and references to contemporary works on the same themes. It was conceived to accompany the book:
- <NAME> (ed.), *Reading Hume on Human Understanding: Essays on the First Enquiry* (Oxford: Clarendon Press, forthcoming 2001)
which is to be published by Oxford University Press next year, and will be referred to here as 'Millican (2001)'. This new book contains essays by many prominent Hume scholars, providing systematic coverage of the first *Enquiry* but at the same time giving a variety of contrasting views on the key scholarly issues. The main chapters within the book are as follows (and will be referred to in this survey by the capitalised word 'Chapter'):
| Introduction | *Peter Millican* | |
| Chapter 1 | *Peter Millican* | 'The Context, Aims, and Structure of Hume's First *Enquiry*' |
| Chapter 2 | *M. A. Stewart* | 'Two Species of Philosophy: The Historical Significance of the First *Enquiry*' |
| Chapter 3 | *Jonathan Bennett* | 'Empiricism about Meanings' |
| Chapter 4 | *Peter Millican* | 'Hume's Sceptical Doubts concerning Induction' |
| Chapter 5 | *Martin Bell* | 'Belief and Instinct in Hume's First *Enquiry*' |
| Chapter 6 | *Justin Broackes* | 'Hume, Belief, and Personal Identity' |
| Chapter 7 | *Edward Craig* | 'The Idea of Necessary Connexion' |
| Chapter 8 | *Galen Strawson* | 'David Hume: Objects and Powers' |
| Chapter 9 | *Simon Blackburn* | 'Hume and Thick Connexions' |
| Chapter 10 | *George Botterill* | 'Hume on Liberty and Necessity' |
| Chapter 11 | *Don Garrett* | 'Hume on Testimony concerning Miracles' |
| Chapter 12 | *David Owen* | 'Hume versus Price on Miracles and Prior Probabilities' |
| Chapter 13 | *J. C. A. Gaskin* | 'Religion: The Useless Hypothesis' |
| Chapter 14 | *David Fate Norton* | 'Of the Academical or Sceptical Philosophy' |
Although not all of the contributors to the book would entirely sympathise with this ambition, my own personal hope is that it will persuade at least some others to see the *Enquiry* as a major work of philosophy in its own right, and indeed as a more faithful presentation of the central themes of Hume's 'general philosophy' (i.e. his metaphysics, epistemology, philosophy of mind and language) than his earlier *Treatise*. Even if successful in scholarly terms, however, this by itself is unlikely to be sufficient in practice to displace Book I of the *Treatise* as the authoritative primary text for the study of Hume's general philosophy. For those who have worked mainly on the *Treatise* for many years, and perhaps guided generations of students through its intricacies, will naturally be reluctant to change their focus to the *Enquiry*, and in today's high-pressure academic environment they are unlikely to be able to spare the enormous amount of time that it can take to prepare appropriate new reading lists for their students. This literature survey will, I hope, solve this practical problem for any who face it, and make the transition to teaching Hume through the *Enquiry* straightforward.
But this survey is not aimed only at potential converts to the *Enquiry*, and it will, I hope, have nearly as much to offer those who continue to approach Hume primarily through Book I of the *Treatise*. For most of the secondary literature on the topics of the *Enquiry* makes reference equally to the *Treatise* and is highly relevant to its interpretation even when less focused upon it. Moreover a huge proportion (over 40%!) of the secondary works discussed here have appeared within the last decade, so only the most assiduous reader of the Hume literature will have come across most of them. Those outside this assiduous minority will, I hope, find their studies greatly facilitated by the sketches I have provided of the main lines of recent debate, and the summaries of many of the works contributing to them.
The survey starts with a short discussion of selected current editions of the *Enquiry* itself, then of Hume's other relevant works, before moving on to philosophical and interpretative topics, mostly organised according to the sections of the *Enquiry* where those topics are addressed. Wherever a topic is not only of scholarly interest, but also of continuing philosophical or scientific relevance, I have tried to suggest some useful points of access into the modern literature, so that those whose interest is stimulated by the reading of Hume can follow this through into some of the many fascinating areas of contemporary debate.
Since Beauchamp's student edition of the *Enquiry*, referenced in [§1a](#1a-printed-editions) below, already contains a useful and reasonably up-to-date annotated bibliography (in its 'Supplementary Reading' section), I have tried as far as possible to complement it rather than to overlap. Hence there is no special section here on historical sources or bibliographic materials, nor on introductory surveys of Hume's thought, nor on general anthologies and collections of essays -- in all of these areas, my own recommendations (except in the case of the recent general collections mentioned in [§3a](#3a-recent-general-collections-of-scholarly-work-on-hume) below) would correspond closely with those made by Beauchamp. Instead, I have tried to give more specific advice for students or scholars working on the philosophy or interpretation of the *Enquiry*, often under pressure of time, and needing to make decisions which more wide-ranging bibliographies typically leave open, such as which Hume edition(s) they are best advised to purchase, and which particular articles or sections of books will most repay study on each of the various issues (and in which order). To this end I have summarised the most salient points of the majority of the items listed (excepting those that are too wide-ranging to make this feasible), and these summaries are often quite extensive where this has enabled me to spell out how the discussions fit together as parts of a continuing debate, or where the issues are particularly complex. In the case of some very recent items to which appropriate responses have not yet appeared, I have also added some personal suggestions regarding promising lines of criticism.
The whole field of Hume studies is blossoming, with interest in his philosophy stronger than ever and high quality contributions appearing every year. This has enabled me to include here many very recent works, whose citations can therefore in turn be used to identify further topical material for those with time to move beyond my recommendations. Such readers will find some additional suggestions in Beauchamp's bibliography, which in particular lists a number of books that I have omitted not from any adverse judgement on their quality, but usually because they are relatively unfocused on the topic in question. Also useful for older references will be 'Some Notes on the Hume Literature' which appears as an appendix to <NAME>'s *<NAME>: An Introduction to His Philosophical System* (see [§3b](#3b-general-introductory-books-on-humes-philosophy-in-the-enquiry) below).
### 1. Editions of the *Enquiry*
#### 1(a) Printed Editions
For many years the standard edition of the *Enquiry*, used for page references in the vast majority of philosophical and scholarly works on Hume, has been the edition published by Oxford University Press, originally edited by Selby-Bigge and more recently revised by Nidditch:
- <NAME>, *Enquiries concerning Human Understanding and concerning the Principle of Morals* (1777), ed. L. <NAME>, 3<sup>rd</sup> edn. rev. P. <NAME> (Oxford: Clarendon Press, 1975)
The text is based on the 1777 edition, which was the last to contain new authorial corrections (Hume having died in 1776). However it is far from perfect, containing well over 1,000 small inaccuracies, mostly of punctuation. Moreover Sel<NAME>'s editorial additions are generally best ignored, with the possible exceptions of the annotated index and the comparative table of contents with the *Treatise*. In particular, his Introduction is dated and totally misrepresents Hume's intentions, while the 'section' numbers which he inserted within the text simply invite misunderstanding because they are so easily confused with page numbers.
The page numbering of the Selby-Bigge edition will continue to be important for the foreseeable future, given the sheer number of books and articles on Hume (including those in Millican (2001)) which use it to make reference to the two *Enquiries*. Readers of other editions are therefore well advised to write the Selby-Bigge page numbers at the relevant points in the margin of whatever edition they use themselves - the location of the Selby-Bigge page breaks can be found not only from the printed edition itself, but also from the appropriate version of the Leeds electronic edition of the *Enquiry*, available freely on this website at [www.davidhume.org/texts/e/]({{ site.baseurl }}/texts/e) (see [§1b](#1b-electronic-editions) below).
Most printed editions of the *Enquiry* are textually even less accurate than the Selby-Bigge, but a number of them have useful editorial notes to supplement the text, such as elucidations of Hume's terms and explanations of his references. Though by now rather dated, the one by Hendel is particularly worthy of mention, because it also contains details of the various editions of the *Enquiry* that appeared in Hume's lifetime, together with the text of footnotes and other passages that were omitted from the 1777 edition:
- <NAME>, *An Inquiry concerning Human Understanding* (1777), ed. <NAME> (Indianapolis: Bobbs-Merrill Educational Publishing, 1955)
By far the best printed edition of the *Enquiry* currently available, however, has only recently appeared in the Oxford Philosophical Texts series: (Note that this is Beauchamp's *student* edition of the *Enquiry*, shortly due to be joined by a Clarendon *critical* edition with the same editor and based on the same text, which will be of particular interest to specialist scholars but significantly more expensive.)
- <NAME>, *An Enquiry concerning Human Understanding* (1772), ed. <NAME> (Oxford and New York: Oxford University Press, 1999)
Beauchamp's editorial material is in general first rate. It includes a detailed introduction describing the background to the *Enquiry* and giving an outline of each section, an excellent survey of supplementary reading, an extensive and well-organised appendix of annotations to the text, and a useful glossary. The text is also highly reliable, though based on the 1772 edition which is arguably less authoritative than the 1777 preferred by most other editors. The main difference between the two is Hume's deletion from the latter of the majority of Section III, which he presumably excised from the edition left to posterity because he appreciated its lack of philosophical relevance to the main project of the *Enquiry* as a whole. Beauchamp notes the deletion,{[endnote 1](#note1)} so in this respect readers are free to take their choice, but it is perhaps a shame that other significant omissions, from previous editions of the *Enquiry*, are not also noted by him (hence the continuing value of Hendel's edition, which does record them). The last and major criticism of Beauchamp's edition is its lack of Selby-Bigge page numbering. No doubt from a purist point of view the strict paragraph numbering introduced in Beauchamp's edition (as in the other new Oxford editions of Hume's works) is superior, but the inclusion of Selby-Bigge numbers in the margin would have greatly facilitated the usefulness of this edition for study, given that they have for so long been the *de facto* standard for references to the *Enquiry* in philosophical and scholarly works. Again, however, the solution is straightforward, and readers who wish to remedy this omission in their copy of the Beauchamp edition can easily do so by hand.
#### 1(b) Electronic Editions
For students and scholars, the two most obvious potential virtues of electronic texts are cheapness and ease of manipulation (the latter including ease of reproduction, distribution, excerpting, and searching). Many free versions of the *Enquiry* are available from the World Wide Web, but most are of dubious quality, being based on old printed editions that are now in the public domain. There is, however, a highly reliable version of the 1777 edition published by the University of Leeds Electronic Text Centre, and made freely available for non-profit academic purposes.
- <NAME>, *An Enquiry concerning Human Understanding* (1777), ed. <NAME> (Leeds Electronic Text Centre, 2000), available on this web site at [www.davidhume.org/texts/e/]({{ site.baseurl }}/texts/e)
This site is the 'home page' of a recently established but long-term project devoted to works on, and by, Hume, focusing on the publication of high quality texts and bibliographic materials together with search and other facilities. These facilities include the ability to display the texts in a number of formats, for example unpaginated, paginated as in Hume's original edition, or paginated according to the *de facto* standard edition. The last of these is particularly useful in the current context, since it enables the Selby-Bigge pagination to be freely consulted over the Web.
Currently the best search facilities available for Hume's works in general are provided by:
- *Complete Works & Correspondence of David Hume*, CD-ROM in the Past Masters series, published by InteLex Corporation, Charlottesville, Virginia (Web address _www.nlx.com_)
The texts used by InteLex are not of high quality (e.g. the *Enquiry* is taken from the 1898 Green and Grose edition), and the CD-ROM is far too expensive for most students, but the search facilities make it invaluable for those engaged in serious research on Hume, especially as it includes not only Hume's philosophical works, but also his *History of England* and his correspondence.
### 2. Hume's Other Works
#### 2(a) A Treatise of Human Nature
Exactly as with the two *Enquiries*, the standard edition of the *Treatise* has for many years been the Oxford University Press edition originally edited by Selby-Bigge, and more recently revised by Nidditch:
- <NAME>, *A Treatise of Human Nature* (1739-40), ed. <NAME>, 2nd edn. rev. <NAME> (Oxford: Clarendon Press, 1978)
As with the Selby-Bigge *Enquiries*, the text is of reasonable quality but far from perfect, and the annotated index is the most useful of the editorial additions. And again the Selby-Bigge has recently been effectively supplanted (for all purposes other than page references) by a far superior new edition in the Oxford Philosophical Texts series:
- <NAME>, *A Treatise of Human Nature* (1739-40), ed. <NAME> and <NAME> (Oxford and New York: Oxford University Press, 2000)
David Norton's introduction is particularly valuable, providing an excellent outline of this complex and difficult work. Other useful editorial material includes a section of comprehensive annotations to the *Treatise* and to the *Abstract* (the text of which is included with the *Treatise* in both the editions mentioned here), and a glossary of 'potentially puzzling words and phrases'. Again the major criticism of the new Oxford edition is its lack of Selby-Bigge page numbering, but again this can easily be remedied by hand.
#### 2(b) An Enquiry concerning the Principles of Morals
Hume's second *Enquiry* is included with the first in the Selby-Bigge edition discussed in [§1a](#1a-printed-editions) above, but yet again the best modern edition is in the Oxford Philosophical Texts series:
- <NAME>, *An Enquiry concerning the Principles of Morals* (1751), ed. <NAME>. Beauchamp (Oxford and New York: Oxford University Press, 1998)
This has similar virtues to Beauchamp's companion edition of the first *Enquiry* (see [§1a](#1a-printed-editions) above), and is therefore highly recommended.
#### 2(c) Dialogues concerning Natural Religion
For understanding the *Enquiry*, Hume's posthumously published *Dialogues* have an importance surpassed only by the *Treatise*. They are also the most cleverly constructed and entertaining of all his works, and perhaps the funniest truly great work of philosophy ever written by anyone. The standard edition referred to in most articles and books on Hume is the one edited by <NAME>:
- <NAME>, *Dialogues concerning Natural Religion* (1779), ed. <NAME>, 2nd edn. (Edinburgh: Nelson, 1947)
This edition is particularly highly respected for two reasons. First, <NAME> carefully examined Hume's manuscript (even to the extent of studying the watermarks of the sheets on which it is written), and in his edition highlights the important changes that Hume made to the *Dialogues* between its original composition (in the early 1750s) and his death in 1776 (when he evidently took great care in preparing it for posthumous publication). Secondly, Kemp Smith provides a great deal in addition to Hume's text, including sections on various aspects of Hume's general views on religion, a short discussion of Sections X and XI of the *Enquiry*, a famous interpretative essay entitled 'The Argument of the *Dialogues Concerning Natural Religion*', a detailed critical analysis of the argument of the *Dialogues*, and some further appendices and textual supplements of related historical material. It is a great shame that at the time of writing, this excellent and standard edition (though reprinted by Bobbs-Merrill of Indianapolis from 1962 to 1980) is out of print.
Those seeking a reasonably priced and reliable modern edition of the *Dialogues* are probably best advised to choose one of the following:
- <NAME>, *Dialogues concerning Natural Religion* (1779) and *The Natural History of Religion* (1757), ed. <NAME> (Oxford and New York: Oxford University Press, 1993)
- <NAME>, *Dialogues concerning Natural Religion* (1779), ed. <NAME> (Harmondsworth: Penguin, 1990)
Gaskin uses Kemp Smith's text, and also his footnotes which highlight what he took to be Hume's most significant manuscript alterations. Hence this edition will particularly appeal to those with interest in these scholarly issues, and it also has the significant benefit of including Hume's *Natural History of Religion* together with a short editorial introduction and useful explanatory notes on both works. Bell's edition seems to be targeted more at the general reader - it is, for example, less densely printed and hence much easier on the eye; while its introduction weaves major themes from the philosophy of the *Treatise* and *Enquiry* into the discussion of Hume's life and his views on religion, so as to provide a context for readers unfamiliar with his general epistemology. The editorial notes likewise provide helpful references to quotations from Hume's other writings and from the works of related philosophers and historical sources.
#### 2(d) Hume's Essays
Of Hume's many essays, the ones most directly relevant to the topics of the *Enquiry* are those on religion, in particular 'Of Superstition and Enthusiasm' and 'Of the Immortality of the Soul'. But a number of others, for example 'Of the Dignity or Meanness of Human Nature', 'The Sceptic', 'Of the Standard of Taste', 'Of Essay Writing', and 'Of Suicide', also cover themes that are pertinent to the *Enquiry*, either in respect of its philosophical content or the context and manner of its composition. The standard modern edition of Hume's *Essays* is the following:
- <NAME>, *Essays, Moral, Political, and Literary* (1741-83), ed. <NAME>, 2nd edn. (Indianapolis: Liberty Classics, 1987)
Most of the essays, including all those mentioned above, are also included in a companion volume to Gaskin's edition of the *Dialogues*, in Oxford's *World's Classics* series:
- <NAME>, *Selected Essays* (1741-83), ed. <NAME> and <NAME> (Oxford and New York: Oxford University Press, 1993)
#### 2(e) Other Writings by Hume
Apart from Hume's major works dealt with above, and the *Abstract* and *My Own Life* reprinted in Millican (2001), his writings most relevant to the *Enquiry* are:
- <NAME>, *A Letter from a Gentleman to his Friend in Edinburgh* (1745), ed. <NAME> and <NAME> (Edinburgh: Edinburgh University Press, 1967)
- *The Letters of <NAME>*, ed. <NAME>, 2 vols. (Oxford: Clarendon Press, 1932)
- *New Letters of <NAME>*, ed. <NAME> and <NAME> (Oxford: Clarendon Press, 1954)
Only two other significant works remain to be mentioned, namely the largely forgotten *Dissertation on the Passions*, which currently has no modern printed edition,{[endnote 2](#note2)} and the *History of England*, which fortunately does:
- <NAME>, *The History of England* (1754-62), ed. <NAME>, 6 vols. (Indianapolis: Liberty Classics, 1983)
Full of historical insight and wry humour, *The History of England* will be particularly fascinating for the Hume scholar attuned to his characteristic comments and turns of phrase. However it was written for a more leisured age, and its six volumes will probably strike most modern readers as rather heavy going.
### 3. General Secondary Literature on Hume and the *Enquiry*
#### 3(a) Recent General Collections of Scholarly Work on Hume
Four of the best-known collections of advanced papers on Hume---edited by Chappell (1968), Livingston and King (1976), Morice (1977), and Norton, Capaldi and Robison (1979)---are now all more than twenty years old, though still well worth consulting. Relevant papers from them are listed in the sections that follow, as also from the 1990 collection *Studies in the Philosophy of the Scottish Enlightenment*, edited by Stewart. Of far more general interest for the study of the *Enquiry* is another recent Stewart volume:
- <NAME>. and <NAME>. (eds.), *Hume and Hume's Connexions* (Edinburgh: Edinburgh University Press, 1994)
whose twelve papers include discussions of Hume's attempts to become a professor, the influences on his thought, his conception of 'the science of the mind' and of 'probable reasoning', his early attacks on the Design Argument, his treatment of miracles, and his other writings on religion.
The papers in *Hume and Hume's Connexions* all present new research, and are therefore not ideally suited for students. A less scholarly but far more systematic overview of Hume's philosophy, at a relatively introductory level, is provided by:
- Norton, <NAME> (ed.), *The Cambridge Companion to Hume* (Cambridge: Cambridge University Press, 1993)
This contains extremely useful papers by a number of distinguished authors, covering a wide range of topics including Hume's overall approach to philosophy, his science of the mind, his philosophy of science, his scepticism, and his view of religion, as well as others less relevant to the *Enquiry* (e.g. on Hume's moral, political, aesthetic and historical work).
Two other recent collections are particularly useful for the purposes of this survey, and will be mentioned frequently below. Unfortunately both are expensive, and targeted for library rather than for individual purchase, but both include a wide range of important reprints which are well worth consulting and are sometimes hard to obtain elsewhere. In what follows, these will be referred to as 'Tweyman (1995)' and 'Owen (2000)' respectively:
- <NAME> (ed.), *<NAME>: Critical Assessments* (London and New York: Routledge, 1995), six volumes
- Owen, <NAME>. (ed.), *Hume: General Philosophy* (Aldershot and Burlington, Vermont: Ashgate, 2000)
Tweyman's massive collection aims to cover the whole range of Hume's philosophy including, amongst many others, sections devoted to Hume's views on epistemology (17 papers), reason (7 papers), induction (7 papers), scepticism (9 papers), naturalism (7 papers), causality (19 papers), the external world (4 papers), and religion (34 papers). Many of the papers are well-known 'classics', but a high proportion date from the 1980s or later, and although the editor's selection is inevitably controversial in parts, the collection as a whole undoubtedly provides the most valuable single resource currently available for articles on Hume.
Owen's collection is a single volume of 'facsimile' reprints, divided into eight sections of which all but the one on personal identity have immediate relevance to the *Enquiry* (being respectively on methodology, ideas and impressions, logic and demonstrative reasoning, belief and probable reasoning, miracles, causation and the 'New Hume', and scepticism). For each section the editor has selected between two and four papers, aiming to give good coverage of major areas of recent scholarly debate, and with particular points of interest and disagreement being highlighted by his introduction. The papers are of a very high standard, and the collection is highly topical (with only 3 of the 21 selections predating 1985). It is therefore likely to prove particularly useful for readers wishing to get up to date with recent scholarship on Hume's epistemology and metaphysics, and to acquaint themselves in reasonable detail with some of the major issues that are currently exciting most controversy.
To keep abreast with ongoing developments in Hume scholarship, by far the most valuable resource is the journal of the Hume Society:
- *Hume Studies*, published by the Hume Society twice yearly (April and November)
Most of the major contributors to the Hume literature have presented at least some of their work through *Hume Studies*, which is now highly respected in the philosophical community. Moreover it attracts papers not only from specialist scholars, but also from notable contributors to contemporary thought - one recent issue, for example, included articles by <NAME>, <NAME>, <NAME>, and <NAME>.
#### 3(b) General Introductory Books on Hume's Philosophy in the *Enquiry*
The only major single-author work devoted to the philosophy of the *Enquiry* is still Antony Flew's classic:
- Flew, Antony, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961)
Though extremely dated, and therefore to be treated with caution, this still repays reading on topics where Hume's purposes have long been well understood. The book as a whole is difficult for beginners, partly because Flew engages in so many detours to point out (often in characteristically forthright terms) the anti-metaphysical and anti-theological implications of Hume's views. However these detours themselves give the book a distinctive value, especially in Flew's chapters on Hume's Fork (ch. 3), on liberty and necessity (ch. 7), and on the Design Argument (ch. 9), in all of which his broad sympathy with Hume's views are very evident. Also worth consulting are his chapters on 'the objects of the exercise' (ch. 1), on belief (ch. 5), on scepticism (ch. 10), and on the Copy Principle (ch. 2), in the last of which he takes a somewhat similar line to Bennett in Chapter 3 of Millican (2001). The book is weakest where Flew has least sympathy with what he takes to be Hume's position, most notably in the case of his deductivist interpretation of the famous argument concerning induction (which also unfortunately distorts his otherwise useful treatment of miracles - hence my preference in [§9a](#9a-miracles) below for his 1959 article on the topic).
An engaging introduction to most of the central aspects of Hume's philosophy in the *Enquiry*, which combines the text of Sections II, III, IV, VII and XI (and of two second *Enquiry* appendices) with editorial commentary at a level suitable for beginners, is:
- <NAME>, *<NAME>: An Introduction to His Philosophical System* (West Lafayette, Indiana: Purdue University Press, 1992)
Penelhum's account of Hume's motivations (which he developed in the article cited in [§10c](#10c-the-nature-of-humes-scepticism) below) will be of interest to scholars as well as students: he identifies the essence of Hume's 'sceptical' view as being that philosophy itself should not be taken too seriously, since so far from bringing inner peace and tranquillity - as often traditionally claimed - it can instead lead to bewilderment and despair. Penelhum's discussions of the theory of ideas, cause and effect, and the Design Argument are less distinctive, but are all very clear and philosophically well-informed. His appendix 'Some Notes on the Hume Literature' is also useful, if rather dated (containing very few reference beyond 1985).
#### 3(c) Hume's Life, his Aims in the *Enquiry*, and its Relation to the *Treatise*
The standard biography of Hume, which is thorough, generally accurate, and provides valuable discussion concerning the background to his publications, is:
- Mossner, <NAME>, *The Life of David Hume*, 2nd edn. (Oxford: Clarendon Press, 1980)
The traditional accusation that Hume was led to write the *Enquiry* for vulgar motives of popular notoriety (discussed in §4 of Chapter 1 of Millican (2001)) has long since been thoroughly disposed of, the two best-known refutations being:
- <NAME>, Norman, *The Philosophy of David Hume* (London: Macmillan, 1941), ch. 24
- Mossner, <NAME>, 'Philosophy and Biography: The Case of David Hume', *Philosophical Review* 59 (1950), 184-201; repr. in V. C. Chappell (ed.), *Hume* (London and Melbourne: Macmillan, 1968), 6-34
More recently the same ground has been covered by:
- Buckle, Stephen, 'Hume's Biography and Hume's Philosophy', *Australasian Journal of Philosophy* 77 (1999), 1-25
Buckle presents the *Enquiry* as a coherent and unified work, distinguished from the *Treatise* primarily in its greater focus on an 'experimentalism' inspired by Newtonian science. Humean experimentalism involves a preference for mechanistic explanations and an eschewal of speculation about ultimate causes, both of which are prominent themes in the *Enquiry*, from the theory of association of ideas with which it begins (in Sections II and III) to the mitigated scepticism with which it ends (in Section XII).
Although Buckle seems to suggest that the move from the *Treatise* to the *Enquiry* is primarily a change of focus rather than of philosophical position, he approvingly mentions (p. 17) an article by Immerwahr whose aim is to provide a deeper account:
- Immerwahr, John, 'A Skeptic's Progress: Hume's Preference for the First *Enquiry*', in <NAME>, <NAME>, and <NAME> (eds.), *McGill Hume Studies* (San Diego: Austin Hill Press, 1979), 227-38
Immerwahr draws attention to Hume's distinction in the *Treatise* between the 'general and more establish'd properties of the imagination' and the 'trivial properties of the fancy' (T225, 267-8). The latter are the dubious source of much theology and rationalist metaphysics, but in the *Treatise* Hume is unable consistently to condemn them, because (as made clear at T185-6 and T268) they also play a crucial role in avoiding the corrosive scepticism to which the 'general properties' give rise in *Treatise* I iv 1. Immerwahr sees the *Enquiry* as providing Hume with a more satisfactory basis for his critical purposes, avoiding radical scepticism not by reliance on the 'trivial properties', but instead by limiting the 'general properties' to the subjects appropriate for human investigation. Other writers too - notably Penelhum, Norton and Fogelin - have viewed the sceptical outlook of the two works as significantly different, contrasting the calm mitigated scepticism of the *Enquiry* with the unstable 'on-again-off-again' Pyrrhonism of the *Treatise* (the works of all three authors are discussed in [§10c](#10c-the-nature-of-humes-scepticism) below). But this picture has recently been contested by:
- <NAME>, 'A Change in Manner: Hume's Scepticism in the *Treatise* and the first *Enquiry*', *Canadian Journal of Philosophy* 29 (1999), 431-47
McCormick stresses instead the continuity between the *Treatise* and the *Enquiry*, by arguing that the sceptical attitude of the *Treatise* is (despite some appearances to the contrary) virtually identical to that which is expressed much more clearly in the *Enquiry*.
Differences between the *Treatise* and the *Enquiry* are not, of course, confined to Hume's account of scepticism. One very significant change in the *Enquiry*, to which Noxon draws attention, is the separation of philosophical from psychological theorising, which in the *Treatise* were densely intertwined:
- Noxon, James, *Hume's Philosophical Development* (Oxford: Clarendon Press, 1973), especially 12-26, 153-65, 180-7
On Noxon's account, Hume's later works quite generally separate the critical from the constructive elements of his philosophy, a separation most evident in his later moral and political writings which (unlike the *Treatise*) tend to establish their positions on the basis of direct observation rather than psychological theory. This separation leaves the *Enquiry* focusing on the critical aspects of Hume's philosophy, with little attempt to forge any connexion (e.g. through the theory of association -- cf. Dauer's paper in [§4a](#4a-impressions-and-ideas-force-and-vivacity) below) with the psychological complexities that had figured so prominently in the *Treatise*, but which had ultimately, and inevitably, proved incapable of providing a criterion for distinguishing science from superstition. Noxon sees Hume in the *Enquiry* as adopting a new criterion, a 'Principle of Methodological Consistency', based on the idea that legitimate science is a development of the methods 'of common life, methodized and corrected' (E162). Such a principle obviously harmonises well with the mitigated scepticism emphasised by Buckle and Immerwahr, but its adoption need not in itself imply any doubts about the psychological theories of the *Treatise*, even if Hume now sees them as largely irrelevant to his main critical purposes. Nelson, however, argues that the divide between the *Treatise* and the *Enquiry* goes deeper still, with Hume's repudiation of the earlier work being motivated by the recognition that it is contaminated with metaphysics of the very kind that he would later famously condemn in *Enquiry* XII:
- <NAME>., 'Two Main Questions concerning Hume's *Treatise* and *Enquiry*', *Philosophical Review* 81 (1972), 333-7
Nelson's theory is itself forcefully repudiated by:
- Cummins, <NAME>., 'Hume's Disavowal of the *Treatise*', *Philosophical Review* 82 (1973), 371-9
who argues that the *Enquiry* differs from the *Treatise* in respect of its psychology rather than its metaphysics. Indeed the only major Humean metaphysical doctrine whose absence from the *Enquiry* Cummins acknowledges (p. 379, note 35) is the bundle theory of the self, though he downplays even this by suggesting that Hume's famous difficulties with that theory (expressed in the Appendix to the *Treatise*) are relatively superficial, concerning only the explanation of *our belief* in personal identity. Flage, by contrast, takes Hume's difficulties with the bundle theory to be fundamental, even to the extent of providing the main reason for his dissatisfaction with the theory of mind in the *Treatise*, and motivating his move in the *Enquiry* to a far less ambitious theory which aspires only to lawful description of the mind's operations and makes no attempt to draw conclusions about the nature of the mind itself:
- Flage, <NAME>., *<NAME>'s Theory of Mind* (London and New York: Routledge, 1990), ch. 8; also available on this website at [davidhume.org/papers/flage.pdf]({{ site.baseurl }}/papers/flage.pdf)
Flage's account also implies that Hume's problems with personal identity were the primary reason for his apparent loss of confidence in associationism (as documented in §4 of Chapter 1 of Millican (2001)). However Broackes (in Chapter 6) argues that despite these problems the bundle theory continued to underlie Hume's psychological theorising, while Bell (in Chapter 5) suggests that much of Hume's associationism may simply have been omitted from the *Enquiry* rather than rejected. As this wide range of different views testifies, we are still some way from any consensus on what lies behind the differences between the *Treatise* and the *Enquiry*. Nor should we restrict our attention here to philosophical considerations, for as Stewart makes clear in Chapter 2, at least some aspects of the *Enquiry* were significantly influenced not only by literary considerations, but also by some more personal and historical concerns.
### 4. The Nature and Origin of Ideas
#### 4(a) Impressions and Ideas, Force and Vivacity
An excellent introduction to Hume's theory of ideas, and also his theory of belief, appears in a volume aimed at pre-university students. In this paper, Craig also explicitly relates these theories to his 'Image of God' interpretation as discussed in Chapter 7 of Millican (2001).
- <NAME>, 'Hume on Thought and Belief', in Godfrey Vesey (ed.), *Philosophers Ancient and Modern* (Cambridge: Cambridge University Press, 1986), 93-110
Stroud's well-known book provides a rather more advanced discussion of the main features of Hume's theory of ideas, though it is generally focused far more on the *Treatise* than on the *Enquiry*:
- Stroud, Barry, *Hume* (London and Boston: Routledge & Kegan Paul, 1977), ch. 2
Hume's fundamental distinction between impressions and ideas is founded on the notion of 'force and vivacity', which Stroud - like Bennett in Chapter 3 of Millican (2001) - interprets in the most straightforward way, as phenomenological intensity. Both Bennett and Stroud accordingly find Hume's distinction inadequate to capture the difference he intends, between feeling and thinking. Govier suggests that a more satisfactory position can be developed by recognising forcefulness and vivacity as two distinguishable characteristics of Humean perceptions, with a forceful perception being one that has a sustained causal influence, and a vivacious perception being one that is clear and intense. Then 'force' corresponds to distinctions related to degrees of belief, and 'vivacity' to the distinction between impressions and ideas:
- <NAME>, 'Variations on Force and Vivacity in Hume', *Philosophical Quarterly* 22 (1972), 44-52
Govier thus differs from Stroud and Bennett in taking 'force and vivacity' to be functional as much as phenomenological. Everson goes even further, arguing that Humean 'force and vivacity' should be interpreted exclusively in functional rather than phenomenological terms:
- <NAME>, 'The Difference between Feeling and Thinking', *Mind* 97 (1988), 401-13; repr. in Tweyman (1995) vol. I, 10-24 and in Owen (2000), 57-69
However a functional interpretation of force and vivacity makes its availability to consciousness problematic, and therefore seems hard to square with Hume's use of the notion. A recent discussion of the issue, proposing an alternative account according to which the 'force and vivacity' of impressions involves their sense of 'presentedness', is provided by:
- <NAME>., 'Force and Vivacity in the *Treatise* and the *Enquiry*', *Hume Studies* 25 (1999), 83-99
Dauer's account has the implication that the 'force and vivacity' of impressions, memories and beliefs, though somewhat analogous, are nevertheless distinct. He sees this as motivating Hume's move away from the 'hydraulic' model of belief (as outlined in §7 of Chapter 1 of Millican (2001)) and therefore having significance in respect of the philosophical differences between the *Treatise* and the *Enquiry*.
Hume's hydraulic language may itself have even more direct relevance to the interpretation of his conception of force and vivacity (at least in the *Treatise*), for Wright draws on eighteenth century physiology to suggest that he may have intended such language to be understood quite literally:
- <NAME>., *The Sceptical Realism of <NAME>* (Manchester: Manchester University Press, 1983), §19
In the wake of twentieth-century philosophy it is natural to dismiss such a literalistic account as too crude to be worth considering. But a striking corrective is provided by recent work on neurophysiology, which suggests that Hume's admittedly simplistic theories of mental activity may contain a germ of truth. As Damasio, a prominent neurologist, puts it (p. 108): 'The images reconstituted from the brain's interior are less vivid than those prompted by the exterior. They are "faint", as David Hume put it, in comparison with the "lively" images generated by stimuli from outside the brain. But they are images nonetheless.'
- Damasio, <NAME>., *Descartes' Error*, Papermac edition (London and Basingstoke: Macmillan, 1996), ch. 5
Later in his book (especially chapters 8, 9 and 11), Damasio emphasises another more fundamental respect in which Hume anticipated modern neuroscience: his insistence on the essential role of feeling within human reasoning, evident in his theory of belief in *Enquiry* V (and even more so in the *Treatise*, e.g. T103 and T183). There is, of course, an intimate connexion between Hume's theory of ideas and his theory of belief, as brought out in a rich discussion by Flage which takes the 'force and vivacity' issue close to the territory covered by Broackes in Chapter 6 of Millican (2001):
- Flage, <NAME>., *David Hume's Theory of Mind* (London and New York: Routledge, 1990), appendix entitled 'Force and Vivacity'; an adapted version appears in Tweyman (1995), vol. I, 56-74
To explore further in this direction, see the items listed in [§6a](#6a-humes-theory-of-belief) below (most notably MacNabb's chapter and the end of the chapter by Bricke, both of which discuss the 'force and vivacity' of beliefs).
#### 4(b) The Copy Principle
Bennett, in Chapter 3 of Millican (2001), casts serious doubt on the arguments that Hume presents for his Copy Principle, but nevertheless finds philosophical value in it by fundamentally reinterpreting it away from the idiom of 'ideas'. A recent book which spells out Bennett's approach at a more elementary level is:
- <NAME>, *Hume's Epistemology & Metaphysics* (London and New York: Routledge, 1998), 5-14
Others have attempted to defend Hume in ways that do less violence to his professed philosophical foundations. Garrett, in a thought-provoking examination of the whole issue, maintains that Hume consistently treats the Copy Principle as a well-confirmed empirical generalisation, and counters Bennett's negative assessment of Hume's arguments for it when thus interpreted:
- Garrett, Don, *Cognition and Commitment in Hume's Philosophy* (Oxford and New York: Oxford University Press, 1997), ch. 2
One notorious puzzle for making sense of Hume's position is posed by his dismissive reaction to an apparent counterexample to the Copy Principle, the 'missing shade of blue' (E20-1). Bennett's reinterpretation of the principle may seem to explain this away, but the adequacy of such a solution is challenged by:
- <NAME>, 'The Missing Shade of Blue', *Philosophical Review* 87 (1978), 548-65
who interprets the having of a Humean idea not as *understanding* a term, but as the possession of a *recognitional capacity*. Garrett's alternative solution is based on the natural resemblances which Hume acknowledges between simple ideas. For those seeking a summary of the debate, Bennett's approach and that of Fogelin (which is similar to Garrett's) are outlined by Noonan:
- Noonan, <NAME>., *Hume on Knowledge* (London and New York: Routledge, 1999), ch. 2
However Noonan's chapter is valuable more as an introduction to the general topic than as an account of Hume's thinking in the *Enquiry*, for it focuses as least as much on the philosophical as on the scholarly issues, and is explicitly concerned with the *Treatise*. Another work devoted to the *Treatise* provides a philosophically deep discussion of the Copy Principle, aiming to steer a course between the positivist approach favoured by Bennett, and the naturalism exemplified by Garrett:
- <NAME>, *Hume's System* (Oxford and New York: Oxford University Press, 1990), ch. 1 and 2
Noxon takes a very different view of the Copy Principle, proposing an 'instrumentalist' interpretation according to which the principle is a 'rule of procedure for analysis' rather than a universal generalization:
- <NAME>, *Hume's Philosophical Development* (Oxford: Clarendon Press, 1973), 138-48
Livingston provides yet another perspective, relating the Copy Principle, as a criterion of 'internal' conceptual mastery, to a general interpretation of Hume which sees him primarily as a historically rather than scientifically oriented philosopher:
- Livingston, <NAME>., *Hume's Philosophy of Common Life* (Chicago and London: University of Chicago Press, 1984), ch. 3-4
Livingston does not accept any need for the sort of rational reconstruction undertaken by Bennett, for on his account, Hume's understanding of language is already far more sophisticated than the simplistic traditional interpretation - according to which Hume takes word meanings to be images copied from impressions - from which Bennett begins. In challenging this traditional interpretation Livingston draws on an influential paper by Árdal, which discusses Hume's account of abstract ideas and moral conventions (though this obviously moves the discussion a long way from the direct concerns of the *Enquiry*):
- <NAME>., 'Convention and Value', in <NAME> (ed.), *<NAME>: Bicentenary Papers* (Edinburgh: Edinburgh University Press, 1977), 51-68; repr. in Tweyman (1995) vol. IV, 61-77
Those wishing to follow up these issues through contemporary discussions in the philosophy of language will find that much recent work is fearsomely difficult. However Blackburn and Miller provide two relatively accessible introductions, which take highly contrasting approaches while both giving significant attention to Humean issues:
- <NAME>, *Spreading the Word* (Oxford and New York: Clarendon Press, 1984)
- <NAME>, *Philosophy of Language* (London: UCL Press, 1998)
Blackburn's treatment of the general problem of meaning occupies his first four chapters, with chapter 2 explaining the inadequacies of the Locke/Hume theory of ideas in this context. But whereas Blackburn starts from the empiricists and takes a broadly Gricean 'convention-belief' (or 'communication-intention') approach, Miller starts from Frege and prefers the more fashionable 'truth-conditional' style of meaning theory, explicitly opposing (in his chapter 7) some of Blackburn's arguments. Miller's chapter 3 is of particular interest for its discussion of the verification principle, around which the logical positivists - claiming inspiration from Hume's Copy Principle - built their theory of meaning (however their claim to be Hume's heirs is certainly disputable, as made clear for example by Craig's book mentioned in 9c below).
### 5. Reason and Induction
#### 5(a) Hume's Philosophical Logic
Though fundamental to his philosophy, there has been relatively little detailed discussion of Hume's distinction between 'relations of ideas' and 'matters of fact'. Flew's chapter in his 1961 book remains valuable for a general introduction to the status and philosophical point of what he named 'Hume's Fork':
- <NAME>, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961), ch. 3
A thorough recent discussion of the distinction appears in an introductory text:
- <NAME>, *Hume's Epistemology & Metaphysics* (London and New York: Routledge, 1998), ch. 2
Both Flew and Dicker relate Hume's Fork to Kant's analytic-synthetic distinction; indeed Dicker gives Hume's position a surprisingly Kantian flavour, by suggesting that it leaves room for synthetic a priori principles (including, on his account, Hume's Fork itself), since he interprets Hume's 'matters of fact' as being restricted to propositions that either assert or deny existence. Most have instead taken Hume's Fork to correspond to the analytic-synthetic distinction as understood by the logical positivists such as Ayer, according to whom 'a proposition is analytic when its validity depends solely on the definitions of the symbols it contains [or in Humean language, the nature of the ideas], and synthetic when its validity is determined by the facts of experience.' (p. 105):
- <NAME>., *Language, Truth and Logic*, 2nd edn. (Harmondsworth: Penguin, 1971), ch. 4
The analytic-synthetic distinction, thus understood, was famously criticised by Quine and then defended by Grice and Strawson:
- Quine, <NAME>, 'Two Dogmas of Empiricism', in *From a Logical Point of View* (Cambridge, Massachusetts: Harvard University Press, 1953), 20-46; repr. in <NAME>oser (ed.), *A Priori Knowledge* (Oxford and New York: Oxford University Press, 1987), 42-67
- <NAME>. and <NAME>., 'In Defense of a Dogma', *Philosophical Review* 65 (1956), 141-58; repr. in Paul Grice, *Studies in the Way of Words* (Cambridge, Massachusetts and London: Harvard University Press, 1989), 196-212
Miller provides an up-to-date commentary on this debate, also introducing some important related issues (notably Quine's thesis of the indeterminacy of translation) and giving advice for further reading:
- Miller, Alexander, *Philosophy of Language* (London: UCL Press, 1998), ch. 4
Also of particular interest is the 'pragmatic' approach to analyticity taken by Aune, in his attempt to develop a 'reformed' Humean empiricism on the way to solving the problem of the external world:
- Aune, Bruce, *Knowledge of the External World* (London and New York: Routledge, 1991), 57-9, 86-90, 144-56
Along with the famous Quinean objections, some more recent issues in the theory of reference---associated with the work of Kripke---pose new difficulties for any simple binary distinction such as Hume's Fork. Since, however, these technical difficulties are unlikely to carry significant implications for Hume's philosophical purposes, it will suffice here to mention one article that usefully introduces the logical issues, reprinted within a topical collection which provides a good starting point for those wishing to dig deeper:
- <NAME>., 'Analyticity, Necessity, and Apriority', *Mind* 84 (1975), 225-43; repr. in <NAME> (ed.), *A Priori Knowledge* (Oxford and New York: Oxford University Press, 1987), 170-89
A potentially more serious problem for Hume concerns the adequacy of his famous maxim that whatever is conceivable is possible---the Conceivability Principle---which serves as his principal criterion for distinguishing between relations of ideas and matters of fact (A650, E25-6, E35, E48). Hume has often been supposed to accept in addition the (far more questionable) Inconceivability Principle, that whatever is inconceivable is impossible, which would have significant implications for his views on such things as the possibility of alternative senses (E20), causal realism (E33, E67-8), the external world (E154-5), and infinite divisibility (E155-8). Lightner argues forcefully that such an attribution would be incorrect:
- <NAME>, 'Hume on Conceivability and Inconceivability', *Hume Studies* 23 (1997), 113-32
But the Conceivability Principle is itself controversial. Tidman considers various possible interpretations of 'conceivable', concluding that none of them can justify Hume's maxim because 'merely conceiving of a state of affairs gives us no reason whatsoever to think that state of affairs to be possible' (p. 298):
- <NAME>, 'Conceivability as a Test for Possibility', *American Philosophical Quarterly* 31 (1994), 297-309
Tidman attributes the appeal of the maxim to a confusion between conceiving of a state of affairs, and having a modal intuition (which sometimes accompanies such conceiving). Yablo implicitly disputes, however, whether this is indeed a confusion if 'conceiving' is interpreted in the appropriate manner:
- <NAME>, 'Is Conceivability a Guide to Possibility?', *Philosophy and Phenomenological Research* 53 (1993), 1-42
On this account, 'I find *p* conceivable if I can imagine ... a situation ... *of* which I truly believe that *p*' (p. 26), and 'to imagine an *X* is *thereby* to enjoy the appearance that an *X* could exist' (p. 30). Hence conceivability itself (in the appropriate sense) involves modal intuition, though Yablo concedes that such intuition is not infallible. Nor is it always available, and his corresponding account of inconceivability---as inability to imagine a situation 'that I don't take to falsify *p*' (p. 29)---leaves room for states of affairs that are neither conceivable nor inconceivable, and hence can be classed as 'undecidable'. This provides a straightforward way of dealing with alleged counterexamples to the Conceivability Principle including mathematical propositions (e.g. Goldbach's Conjecture) whose necessary truth or necessary falsehood is currently unknown. An alternative approach to such mathematical objections (which were first raised by <NAME>) is suggested by Casullo, who recommends revising the Conceivability and Inconceivability principles in a way that harmonises with Hume's distinction between intuition and demonstration:
- Casullo, Albert, 'Reid and Mill on Hume's Maxim of Conceivability', *Analysis* 39 (1979), 212-9
Casullo's proposal is to treat inconceivability as a criterion of impossibility only in the case of propositions knowable by intuition (those simple enough to enable the mind to 'see' directly the relationship between the ideas involved). More complex propositions - those knowable only by demonstration - will then be necessarily true (and hence classed as relations of ideas) if and only if they are 'derivable from other propositions whose denials describe inconceivable states of affairs, using only principles of inference whose denials are inconceivable' (p. 215).
Despite all these complications, Hume's distinction between 'analytic' relations of ideas and 'synthetic' matters of fact is widely accepted and taken for granted, at least for the general run of propositions (leaving aside, for example, difficult problem cases involving theoretical terms whose meaning can evolve as science develops). However other aspects of Hume's philosophical logic are far more problematic, partly because his evident contempt for scholastic syllogism in particular seems to have given him a mistakenly dismissive attitude to formal rigour in general. Two searching discussions of his 'logic' are now rather dated, but still extremely helpful for highlighting some of the resulting difficulties:
- Bennett, Jonathan, *<NAME>, Hume: Central Themes* (Oxford: Clarendon Press, 1971), ch. 10
- Passmore, John, *Hume's Intentions*, 3rd edn. (London: Duckworth, 1980), ch. 2
Fortunately, many of the issues to which Bennett and Passmore draw attention (e.g. in Hume's theory of relations) impact more on the *Treatise* than on the *Enquiry*, but a notable exception is Hume's distinction between 'demonstrative' and 'probable' reasoning, which plays a fundamental role in *Enquiry* IV and XII. My own attempt to clarify Hume's understanding of this distinction is most concisely presented in §2 of:
- <NAME>., 'Hume's Argument concerning Induction: Structure and Interpretation', in Tweyman (1995), vol. II, 91-144; repr. in Owen (2000), 165-218
and more extensively developed in Chapter 4 of Millican (2001) (§3.1 and §7.1). Here I argue---against the general trend---that Hume's distinction corresponds quite closely to the modern distinction between 'deductive' and 'inductive' reasoning, where the former is understood in an *informal* (i.e. semantic rather than syntactic) manner. The most thorough recent discussions on the other side of this debate are:
- <NAME>, 'Hume on Demonstration', in Patric<NAME>on (ed.), *Logic and the Workings of the Mind: the Logic of Ideas and Faculty Psychology in Early Modern Philosophy*, North American Kant Society Studies in Philosophy 5 (Atascadero, California: Ridgeview Publishing Company, 1997), 153-74; repr. in Owen (2000), 109-30
- <NAME>, *Hume's Reason* (Oxford and New York: Oxford University Press, 1999), ch. 5
However it is important to note that Owen tends to interpret 'deductive' as meaning *formally* deductive, a concept admittedly quite foreign to Hume's philosophy given his contempt for formal logic.
#### 5(b) The Structure of Hume's Argument concerning Induction
For many years Stove's analysis of Hume's famous argument, which interpreted it as relying on the implicit premise of deductivism, was commonly taken to be authoritative:
- <NAME>., 'Hume, Probability, and Induction', *Philosophical Review* 74 (1965), 160-77; repr. in V. C. Chappell (ed.), *Hume* (London and Melbourne: Macmillan, 1968), 187-212 and in Tweyman (1995), vol. II, 29-43
- Stove, <NAME>., *Probability and Hume's Inductive Scepticism* (Oxford: Clarendon Press, 1973)
Detailed criticisms of Stove's interpretation, together with alternative accounts of the structure of Hume's argument, are provided by:
- Morris, <NAME>, 'Hume's Refutation of Inductive Probabilism', in <NAME> (ed.), *Probability and Causality* (Dordrecht: Reidel, 1988), 43-77
- <NAME>., 'Hume's Argument concerning Induction: Structure and Interpretation', in Tweyman (1995), vol. II, 91-144; repr. in Owen (2000), 165-218
Both focus mainly on the *Enquiry*, and although broadly similar in spirit, they differ significantly both in the points made and in the structure diagrams they propose for Hume's argument. Morris concentrates his fire on Mackie and Stove before presenting his own analysis. My own article is more wide-ranging in its criticisms of earlier authors, but says virtually nothing about Mackie and gives less textual detail on Stove. However it includes (in §11) a discussion of Stove's probabilistic account of Hume's conclusion, arguing that this is implausible quite independently of the defects of his structural analysis. Note that there is no need to consult this paper for my own structural analysis of Hume's argument, which Chapter 4 of Millican (2001) repeats in an improved form (in other respects the papers are very different, and only the detailed textual commentary - most of which I saw no reason to change - contains a high proportion of material in common).
#### 5(c) Interpretations of Hume on Reason and Induction
Together with the work listed in [§5b](#5b-the-structure-of-humes-argument-concerning-induction) above, Chapter 4 of Millican (2001), and the appendix to Don Garrett's Chapter 11 (which reproduces two sections from his 1997 book), the following represent the main contemporary currents of thought in the interpretation of Hume's argument concerning induction:
- Beauchamp, Tom and Rosenberg, Alexander, *Hume and the Problem of Causation* (Oxford and New York: Oxford University Press, 1981), ch. 2
- Broughton, Janet, 'Hume's Skepticism about Causal Inferences', *Pacific Philosophical Quarterly* 64 (1983), 3-18; repr. in Owen (2000), 149-64
- Noonan, <NAME>., *Hume on Knowledge* (London and New York: Routledge, 1999), 110-34
- <NAME>, *Hume's Reason* (Oxford and New York: Oxford University Press, 1999), ch. 6
- Winkler, Kenneth, 'Hume's Inductive Skepticism', in Margaret Atherton (ed.), *The Empiricists* (Lanham, Maryland: Rowman & Littlefield, 1999), 183-212
All those listed here except Winkler interpret Hume's argument as non-sceptical, and therefore depart radically from the traditional view of his intentions. Winkler aims to re-establish the traditional sceptical view with reference both to the writings of Hume's contemporaries and to other parts of the *Treatise* and *Enquiry* (including in particular Section XII).
Beauchamp, Rosenberg and Broughton see Hume as opposing only a narrowly rationalist conception of induction; so when he denies that induction is founded on reason, they take him to be understanding 'reason' in a deductivist sense. But since elsewhere Hume frequently operates with a notion of reason that embraces 'probable' as well as 'demonstrative' inference, this implies an ambiguity in his use of the term, as spelt out in the following well-known article:
- <NAME>, 'Hume on Reason', *Hume Studies* 5 (1979), 20-35; repr. in Owen (2000), 133-48
However an anti-deductivist conception of Hume's argument is vulnerable to objections of a fairly straightforward kind, as presented in §14 of my 1995 paper and developed at greater length in:
- <NAME>, *Cognition and Commitment in Hume's Philosophy* (Oxford and New York: Oxford University Press, 1997), 83-91
§13 of my own paper suggests a different ambiguity, interpreting 'reason' within Hume's argument as a notion involving quasi-perceptual insight, and detecting two other notions of reason elsewhere in Hume's writings (for further development of the perceptual notion, but without discussion of the ambiguity thesis, see §2 of Chapter 4 of Millican (2001)). Garrett denies any ambiguity in Hume's notion, as do Owen and Noonan - all three see the intention of Hume's argument as being to deny the dependence of inductive inferences on *ratiocination*, rather than to prove such inferences' unreasonableness (on *any* conception of 'reason').
As the dates of many of these contributions make clear, this is a very active area of current debate amongst Hume scholars. Part of that ongoing debate can be found in the pages of *Hume Studies*, which remains the obvious place to look for further developments:
- <NAME>, 'Hume on Reason and Induction: Epistemology or Cognitive Science?', *Hume Studies* 24 (1998), 141-59
- <NAME>, 'Ideas, Reason, and Skepticism: Replies to my Critics', *Hume Studies* 24 (1998), 171-94 especially 177-88
Here Garrett mounts a spirited and uncompromising defence against my attack on his 1997 interpretation, and moreover goes onto the offensive against my 1995 paper. My latest response to him and to Noonan's and Owen's recent work is, of course, to be found in Chapter 4 of Millican (2001), §10.3 of which develops detailed logical objections to all non-sceptical interpretations of Hume's argument.
#### 5(d) Inductive Scepticism
An undemanding but philosophically deep introduction to the general issue of inductive scepticism, eminently suitable for beginning students but entertaining at any level, is:
- <NAME>, *An Encounter with <NAME>*, in <NAME> (ed.), *Reason and Responsibility*, 3rd edn. (Encino and Belmont, California: Dickenson Publishing Company, 1975), 190-208
Whether Hume was himself an inductive sceptic is, as we have seen, a very controversial issue, but whatever his own views, the famous 'problem of induction' is probably his most celebrated philosophical legacy. A good background for exploring the issues, starting with the editor's introduction, is provided by:
- <NAME> (ed.), *The Justification of Induction* (Oxford: Oxford University Press, 1974)
Swinburne considers three traditional methods of attempting to justify induction - the 'analytic', the 'pragmatic', and the 'inductive' - and the same three methods are also discussed by Skyrms' book mentioned in [§6b](#6b-probability-of-chances-and-probability-of-causes) below (which is particularly useful for its detailed treatment of the inductive justification, perhaps the most challenging of the traditional methods and of particular recent interest because of its application to 'abduction' or 'inference to the best explanation', for which see Psillos' book in [§10a](#10a-scepticism-regarding-the-external-world) below). Neither Swinburne nor Skyrms, however, considers attempts to justify induction by appeal to a priori probability, which (for reasons explained in §7.2 of Chapter 4 of Millican (2001)) would neatly sidestep Hume's negative argument if only they could be made to work. They would also pose an unambiguous challenge to Hume, unlike the 'analytic' and 'pragmatic' justifications, which both contain elements of similarity with Hume's own views. Two interesting attempts to develop such a probabilistic justification of induction, which combine accessibly presented technical ideas with illuminating philosophical discussion, are provided by:
- <NAME>, *Reason and Prediction* (Cambridge: Cambridge University Press, 1973), ch. 7
- <NAME>., 'A Defence of Induction', in <NAME> (ed.),* Perception and Identity* (Ithaca: Cornell University Press, 1979), 113-30; repr. in *Logic and Knowledge* (Oxford and New York: Clarendon Press, 1985), 159-77
Both Blackburn and Mackie aim to justify induction through the extrapolation of general uniformity, but historically a more popular way of attempting a probabilistic justification is by applying a statistical 'law of large numbers' to specific events. Such attempts date back to Laplace, and the most persuasive are perhaps those of De Finetti and D. C. Williams. Stove has recently developed Williams' argument further, and presented it in a form suitable for a non-technical audience. (But note that Stove gives two distinct probabilistic arguments against Hume, the first of which - in chapter 5 of his book - is far less interesting, depending as it does on his questionable analysis of Hume's conclusion mentioned in [§5b](#5b-the-structure-of-humes-argument-concerning-induction) above.)
- <NAME>., *The Rationality of Induction* (Oxford and New York: Clarendon Press, 1986), ch. 6
Although most modern philosophers would be highly sceptical about the possibility of any such justification of induction, no clear refutation of Blackburn, De Finetti, or Williams/Stove has yet been published (for criticism of Mackie, see <NAME>, 'Mackie's Defence of Induction', *Analysis* 42 (1982), 19-24). The question of whether Humean inductive scepticism can be overcome using probability theory remains open.
### 6. Belief, Probability, Rationality, and the Reason of Animals
This section covers four aspects of Hume's thought which are quite closely interrelated and a full understanding of which requires reference to the *Treatise*, where Hume's theories of the mechanics of belief, and of the criteria for acceptable and unacceptable probable inference, are far more elaborate than in the *Enquiry*. In the *Treatise*, belief is explained using an explicit 'hydraulic' model which in the *Enquiry* is quietly dropped (see the reference to Dauer's paper in [§4a](#4a-impressions-and-ideas-force-and-vivacity) above). Partly as a result of this, the detailed sections on 'the probability of chances' (I iii 11), 'the probability of causes' (I iii 12), 'unphilosophical probability' (I iii 13), and 'rules by which to judge of causes and effects' (I iii 15), which together constitute around a third of the central part of *Treatise* Book I, are reduced in the *Enquiry* to the small Section VI 'Of Probability' and the long footnote to Section IX 'Of the Reason of Animals'. Apparently Hume considered these details inessential to his main philosophical purposes in the *Enquiry*, and although many would agree - especially in respect of his simplistic theory of the mechanics of belief - nevertheless his treatment of the criteria for correct probable reasoning remains of great importance in assessing the implications of the mitigated scepticism which he develops in Section XII.
#### 6(a) Hume's Theory of Belief
A dated but still philosophically interesting overview of sections V and VI of the *Enquiry* is provided by:
- <NAME>, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961), ch. 5
The essays in Millican (2001) by Bell and Broackes (Chapters 5 and 6) dig deeper, addressing changes in Hume's account of belief between the *Treatise* and the *Enquiry*, and drawing attention to many relevant interpretative and philosophical issues. For further investigation of these issues the following are helpful, though they pay relatively little attention to the development of Hume's thought:
- <NAME>. and <NAME>., 'Hume on Belief', *Review of Metaphysics* 30 (1976), 3-18; repr. in Tweyman (1995), vol. I, 144-57
- <NAME>., 'Hume's Theory of Belief', *Hume Studies* 19 (1993), 89-101
- <NAME>., *<NAME>: His Theory of Knowledge and Morality*, 2nd edn. (Oxford: Blackwell, 1966), ch. 5
- <NAME>, *Hume's System* (Oxford and New York: Oxford University Press, 1990), ch. 4 and 5
- Bricke, John, *Hume's Philosophy of Mind* (Edinburgh: Edinburgh University Press, 1980), ch. 6
Hodges and Lachs, like Broackes, find systematic inconsistencies in Hume's theory, but relate these to his need for a effective critique of religious belief (e.g. alleged lively perceptions of God) rather than to his view on personal identity. They also see the problems as symptomatic of an underlying tension in his philosophy between two empiricist tendencies, one phenomenological and the other naturalistically realist. Gorman disagrees with them, claiming that a more charitable reading of Hume's (admittedly poorly expressed) words reveals a consistent view of belief as 'a perception that has a certain feeling to the mind, which is the same as saying that it is a perception that is conceived in a certain manner' (p. 99). MacNabb also accepts that belief may involve a characteristic feeling, but argues that what is really essential to Humean belief is firmness and steadiness (cf. the issue of force and vivacity in [§4a](#4a-impressions-and-ideas-force-and-vivacity) above, and Loeb's use of steadiness as a criterion of rational belief in his papers mentioned in [§6c](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry) below, a use anticipated by MacNabb in §3 of his chapter 6). Pears' fourth chapter provides a philosophical critique of Hume's theory in the *Treatise*, generally treating it as a unified whole; his next chapter then addresses a problem highlighted by Bell, of why causation is the only one of Hume's three associative relations able to generate belief. Finally, Bricke discusses Hume's treatment of belief in the context of his theory of thought and judgement, and thereby raises additional issues similar to some of those dealt with by Passmore's chapter referenced in [§5a](#5a-humes-philosophical-logic) above (note also that Passmore's fifth chapter, especially from page 92 onwards, is highly relevant here).
Smith and Jones' introduction to the philosophy of mind provides an accessible link between Hume's theory of belief and modern discussions of the topic, in a chapter that focuses on Hume and Ryle:
- <NAME> and <NAME>., *The Philosophy of Mind* (Cambridge, New York and Melbourne: Cambridge University Press, 1986), ch. 10
In subsequent chapters they go on to develop a functionalist account of belief, drawing particularly on the influential work of Armstrong, but also making connexions with adjacent areas in the philosophy of mind.
#### 6(b) Probability of Chances and Probability of Causes
For an initial outline of Hume's treatment of probability, see Garrett's section on 'Cognitive Psychology and Probability' in Chapter 11 of Millican (2001). Given the importance of the topic and its close historical association with the celebrated Humean problem of induction, there have been surprisingly few significant discussions in the literature, the following being amongst the most notable exceptions:
- Kemp Smith, Norman, *The Philosophy of David Hume* (London: Macmillan, 1941), ch. 19
- <NAME>., *David Hume: His Theory of Knowledge and Morality*, 2nd edn. (Oxford: Blackwell, 1966), ch. 6
- <NAME>, 'Hume's Species of Probability', *Philosophical Studies* 33 (1978), 21-37
- <NAME>, 'Hume on Probability', *British Journal for the Philosophy of Science* 42 (1991), 1-19
<NAME> provides a useful critical introduction to the account of probability in the *Treatise*, highlighting some of its crucial defects (Hume's awareness of which, he suggests, may account for the brevity of the *Enquiry* account), and explaining how Hume's theory of belief leads him to treat both 'probability of chances' and 'probability of causes' as involving the same associationist mechanism. MacNabb likewise focuses on the *Treatise*, but gives more attention to the philosophical issues than to the details of Hume's own account, being (understandably) dismissive of some of its intricacies. Hacking praises Hume for noting the distinction between the two species of probability, but regrets that this insight was then erased by his conflation of the two, and was not pursued further either by Hume himself or by subsequent pioneers of the theory of probability. Gower, unlike these other commentators, takes seriously the additive account of probability measures suggested by Hume's talk (at T138 and E127) of *subtracting* the weight of evidence against a hypothesis from that in favour (so that a probability of zero represents indifference rather than certain falsehood). As Gower points out, this distinctive approach to probability tends to be overlooked given the modern enthusiasm for analysing some of Hume's arguments in standard Bayesian terms, but those responsible would no doubt see such analysis as charitable interpretation rather than oversight, given that Hume in the relevant contexts (e.g. T127-42 and E56-8) also uses terms implying proportionality, while the literal additive account is dubiously coherent (however Gower discusses its application to Hume's essay on miracles in 'David Hume and the Probability of Miracles', *Hume Studies* 16 (1990), 17-31).
Contemporary philosophy of probability tends to be fearsomely technical, and additionally complicated by the multiplicity of different interpretations of the relevant concepts, some of which also go together with different formal treatments. For an informal philosophical discussion of probability concepts, see:
- <NAME>., *Truth, Probability, and Paradox* (Oxford: Clarendon Press, 1973), ch. 5
A straightforward classification of different formal approaches to probability, together with a sketch of some influential previous taxonomies, is given by:
- <NAME>, *Philosophical Foundations of Probability Theory* (London, Boston and Melbourne: Routledge & Kegan Paul, 1982), ch. 1
Those with the technical competence to dig deeper will find a useful survey of modern developments in:
- <NAME>, 'Theories of Probability', *British Journal for the Philosophy of Science* 46 (1995), 1-32
To explore the relationship between probability and induction, a useful start is Gillies' encyclopaedia article, which outlines the historical development of theories of probability, introducing some of the influential technical issues (such as the paradoxes of indifference, Dutch book arguments, Bayesian conditionalisation, and the Carnap-Hesse thesis) and relating them to the philosophy of induction:
- <NAME>., 'Induction and Probability', in <NAME> (ed.), *An Encyclopaedia of Philosophy* (London and New York: Routledge, 1988), 179-204
Application of the probability calculus to inductive inference is problematic not only for Humean reasons (i.e. the apparent impossibility of a priori probability assignments, and sceptical doubts about inductive uniformity), but also because any such 'inductive logic' presupposes a grasp of 'natural kinds' or real uniformities in nature and therefore cannot---unlike deductive logic---be purely formal. The classic presentation of this 'new riddle of induction' is:
- <NAME>, *Fact, Fiction, and Forecast*, 4th edn. (Cambridge, Massachusetts and London: Harvard University Press, 1983), ch. 3
Skyrms' introduction to inductive logic provides a useful discussion of Goodman's 'riddle', as also of Mill's methods of induction and of modern responses to Humean inductive scepticism. However in a brief discussion on the interpretation of probability he acknowledges the uncertain basis of the entire enterprise of inductive logic, given the resilience of the fundamental problems of induction:
- Skyrms, Brian, *Choice and Chance* (Belmont, California: Dickenson Publishing Company, 1966)
#### 6(c) Probability and Rationality in the *Treatise* and the *Enquiry*
Traditionally there has been little interest in those sections of the *Treatise* (notably sections 9-13 of Book I Part iii) where Hume discusses probabilistic inferential processes including a number that he considers dubious. A fairly detailed survey of the various Humean belief-forming mechanisms is provided by §1 of Falkenstein's paper listed later in this section, but for a brief review see:
- <NAME>, *Hume's Skepticism in the Treatise of Human Nature* (London, Boston and Melbourne: Routledge & Kegan Paul, 1985), ch. 5
The most interesting of the mechanisms that Hume discusses is our tendency to seek and apply 'general rules', which though often leading to unwarranted prejudices also provides the only solution to such prejudices through reflection upon them (a point expressed dramatically at T150). Hearn's well-known article surveys Hume's treatment of general rules, showing how they perform an important role not only in his epistemology, but also in his philosophy of the passions and of morals:
- <NAME>r., <NAME>., '"General Rules" in Hume's *Treatise*', *Journal of the History of Philosophy* 8 (1970), 405-22
The recent growth of interest in *Treatise* I iii 9-13 has resulted from an appreciation that neither Hume's scepticism nor his naturalism are undiscriminating -- within these sections but also elsewhere (e.g. *Enquiry* VIII to XII), he repeatedly endorses certain factual beliefs and methods of enquiry (notably those characteristic of empirical science), while dismissing others as spurious (e.g. those characteristic of superstition). As long as the orthodox interpretation took Hume to be a deductivist sceptic regarding induction, such judgements were themselves typically dismissed as mere inconsistencies on his part, but once it became generally accepted that he is no crude deductivist (see [§5b](#5b-the-structure-of-humes-argument-concerning-induction) and [§5c](#5c-interpretations-of-hume-on-reason-and-induction) above), the question of whether his philosophy can sustain a plausible theory of normative discrimination came to prominence. However the suggestion that it might do so is in some tension not only with his inductive scepticism, but also with his central thesis that belief is involuntary. In Chapter 14 of Millican (2001) Norton seeks to alleviate this latter tension, by showing how even if beliefs are indeed 'proximately involuntary', it is still possible for reflective philosophical doubt to alter the context in which they arise and thus to influence what we believe. Norton develops this position further in his book, arguing that a proper recognition of the role of reflective thought in Hume's philosophy comprehensively undermines Kemp Smith's influential claim that Hume's key principle is the subordination of reason to feeling:
- Norton, <NAME>, *<NAME>: Common-Sense Moralist, Sceptical Metaphysician* (Princeton and Guildford: Princeton University Press, 1982), ch. 5 part 2
Passmore's paper 'Hume and the Ethics of Belief' takes a similar approach, explaining how Hume's theory of belief, whilst implying its involuntary nature, can nevertheless allow us to have some control over what we believe by adopting a 'belief policy' involving such things as attention to and critical examination of evidence. Hence normative recommendations become at least a meaningful possibility, though the third chapter of Passmore's book casts doubt on whether such recommendations can be given any adequate basis using the resources at Hume's disposal in the *Treatise* (in particular his notion of general rules):
- Passmore, John, *Hume's Intentions*, 3rd edn. (London: Duckworth, 1980), ch. 3 and the appendix entitled 'Hume and the Ethics of Belief', whose original version appeared in <NAME> (ed.), *David Hume: Bicentenary Papers* (Edinburgh: Edinburgh University Press, 1977), 77-92
Other discussions of the *Treatise* treatment of probability are more optimistic, seeing it as providing not only a rich source of apparently normative judgements, but also a plausible Humean attempt at a theoretical foundation for such judgements based on the empirical assessment of our reasoning methods. However as the following summaries make clear, there is relatively little agreement regarding the nature of this empirical assessment, and the criteria to which it answers:
- <NAME>, 'Hume's Argument for the Superiority of Natural Instinct', *Dialogue* 20 (1981), 635-43; repr. in Tweyman (1995), vol. III, 262-70
Winters takes Hume's problem to be that of justifying a preference for the 'general and more establish'd properties of the imagination' over the 'trivial properties of the fancy' (cf. Immerwahr's paper in [§3c](#3c-humes-life-his-aims-in-the-enquiry-and-its-relation-to-the-treatise) above). Hume's preference for the former, she suggests, is founded on two main considerations, namely their relative efficiency (deriving from their immediacy, irresistibility and durability) and their naturalness (which makes them easy and satisfying to apply).
- <NAME>., 'Hume and Justified Belief', *Canadian Journal of Philosophy* 11 (1981), 219-28; repr. in Tweyman (1995), vol. I, 174-82
Costa shares Winters' conception of Hume's problem, but sees his preference for disciplined causal reasoning (that which conforms to his 'rules by which to judge of causes and effects') as founded on its superior reliability compared with other inferential mechanisms. He ends by suggesting that Hume's philosophy thus contains the seeds of modern 'externalist' or 'reliabilist' epistemology, which likewise assesses epistemic justification according to the reliability of the belief-forming mechanisms involved.
- Baier, <NAME>., *A Progress of Sentiments: Reflections on Hume's Treatise* (Cambridge, Massachusetts and London: Harvard University Press, 1991), ch. 4
Baier, in tune with the overall theme of her book, takes Hume's approval of causal norms of reasoning to derive from their reflexive application, whereby causal reasoning is applied to vindicate the very causal norms that it employs. Pithily summarised, '*Successful reflexivity is normativity*' (pp. 99-100). (The third part of Winkler's paper referenced in [§5c](#5c-interpretations-of-hume-on-reason-and-induction) above follows Baier in emphasising the role of reflection in Hume's '*normalising of the natural*' (p. 204), but in Winkler's view Hume fails to resolve the underlying tension between his inductive scepticism and his desire for normative discrimination.)
- <NAME>., 'Hume on Stability, Justification, and Unphilosophical Probability', *Journal of the History of Philosophy* 33 (1995), 101-32
- <NAME>., 'Instability and Uneasiness in Hume's Theories of Belief and Justification', *British Journal for the History of Philosophy* 3 (1995), 301-27
Loeb views Hume's discussions of 'unphilosophical probability' as fitting into a general framework of inductive assessment of inferential processes, but differs from Baier in taking the appropriate criterion to be stability of belief rather than successful reflexivity. In his second paper, he explains the motivation for seeking such stability as being the avoidance of uneasiness, and thus attributes Hume with a theory of justification which has close affinities to Peirce's theory of belief.
- Wilson, Fred, 'Hume's Defence of Causal Inference', *Dialogue* 22 (1983), 661-94
- Wilson, Fred, *Hume's Defence of Causal Inference* (Toronto, Buffalo and London: University of Toronto Press, 1997), especially ch. 2 §3
Wilson, on Hume's behalf, appeals to the (arguable) principle that 'must implies ought' to justify the basic practice of inductive causal reasoning over which we have no choice. He then interprets Hume's discussion of the various particular mechanisms of causal inference---and the formulating of 'general rules' about these mechanisms---as intended to yield an inductive assessment of their capacity to satisfy the natural passion of curiosity, this passion providing our motive for reasoning in accordance with those mechanisms that have proved most reliable.
- Falkenstein, Lorne, 'Naturalism, Normativity, and Scepticism in Hume's Account of Belief', *Hume Studies* 23 (1997), 29-72; repr. in Owen (2000), 219-62
Falkenstein follows Wilson in focusing on Hume's appeal to general rules, but puts particular emphasis on the formulation of second-order rules that assess the reliability of first-order rules. Such second-order reflection requires time and effort, suggesting that the relatively weak passion of curiosity may be insufficient to motivate it. Instead, Falkenstein argues, Hume sees such reflection as being motivated by the contemplation of sceptical arguments, which initially undermine all our beliefs but from which some beliefs---notably those that are frequently reinforced in common life---are quickly able to recover. Thus it is that the Pyrrhonian arguments lead naturally to both normative discrimination and mitigated scepticism.
All of the above summarised accounts imply that at least some of the material of *Treatise* I iii 9, 10 and 13 is crucial for the understanding of Hume's attitude to science and scepticism, and hence that a fundamental constituent of his philosophy is almost entirely absent from his later writings. Relatively few commentators have tried to avoid this uncomfortable conclusion by finding an adequate basis for normative discrimination within the text of the *Enquiry* and *Dialogues*, something which I attempt in §11 of Chapter 4 of Millican (2001) (a similar account, but focusing more on the *Treatise* and stressing common elements with several of the discussions above, is in §13 of my paper mentioned in [§5b](#5b-the-structure-of-humes-argument-concerning-induction) above). What I take to be the key passage from the *Enquiry* is Hume's suggestion that science involves 'nothing but the reflections of common life, methodized and corrected' (E162), a passage which is---perhaps significantly---very clearly echoed in the *Dialogues* (D134), and which Noxon likewise sees as expressing a general 'Principle of Methodological Consistency' (see the reference to his book in [§3c](#3c-humes-life-his-aims-in-the-enquiry-and-its-relation-to-the-treatise) above). A quite different approach, but one which also draws on both the *Treatise* and the *Enquiry*, is taken by:
- Ferreira, <NAME>, 'Hume's Naturalism - "Proof" and Practice', *Philosophical Quarterly* 35 (1985), 45-57; repr. in Tweyman (1995), vol. III, 271-83
Ferreira argues that Hume's distinction between mere 'probabilities' and 'proofs' (T124, E56n) is epistemologically very significant, separating those beliefs which in Hume's view can reasonably be doubted from those which cannot. She thus places Hume within a tradition of 'reasonable doubt' naturalism, a tradition whose progress from Wilkins to Newman she recounts in her book *Scepticism and Reasonable Doubt* (Oxford and New York: Clarendon Press, 1986), and which she there contrasts (p. 234) with both 'sceptical' naturalism and 'justifying' naturalism. Her interpretation has the implication that Hume is rather close to Reid---the central representative of this tradition---in ruling out any reasonable ground for doubt about the fundamental beliefs derived from our natural faculties. For a strongly contrasting view, to which Ferreira herself alludes, see part 1 of Norton's chapter mentioned earlier in this section.
Moving on to contemporary discussions of human rationality, the question of how far our natural inferential methods conform to theoretical ideals has attracted much attention since the work of Kahneman and Tversky, who devised a range of experiments revealing various 'heuristics' that we use in our thinking, and 'biases' to which these lead. Their main papers are collected in:
- <NAME>., <NAME>., and <NAME>. (eds.), *Judgement Under Uncertainty: Heuristics and Biases* (Cambridge: Cambridge University Press, 1982)
There is, however, debate over how some of the results of Kahneman and Tversky should be interpreted (as exemplified by Cohen's criticism of their taxicab example, discussed by Owen in Chapter 12 of Millican (2001)). Both their results and some of this debate are summarised in the chapter on probability in a book whose theme is precisely what Hume addressed in the sections of the *Treatise* that we have been discussing: the subtle interplay between rational norms and our inferential practices.
- <NAME>. and <NAME>., *Inference and Understanding: A Philosophical and Psychological Perspective* (London and New York: Routledge, 1990), ch. 7
#### 6(d) The Reason of Animals
Despite its importance for his anti-rationalist and naturalising philosophical project, very little has been written on Hume's discussion of animals (indeed not one paper out of nearly two hundred in Tweyman's six volumes is devoted to the topic!). What little has been written, moreover, has tended to focus on the moral rather than the epistemological aspects of Hume's position. With this reservation, a useful recent paper is:
- <NAME>., 'The Nature of Humean Animals', *Hume Studies* 19 (1993), 301-16
Hume's view of animal and human reason as differing in degree rather than in their essential nature obviously fits very comfortably with the theory of evolution, and it is interesting to note that *Enquiry* IX is explicitly mentioned by Darwin in a manuscript dating from the time when he was developing that theory:
- <NAME>., '<NAME> and <NAME>', *Journal of the History of Ideas* 33 (1972), 457-70
In this context it is understandable that the book on Hume which most emphasises the topic was written over a century ago by the man known as 'Darwin's bulldog':
- <NAME>., *Hume* (London: Macmillan, 1886), ch. 5, 'the mental phenomena of animals'
Since then the overwhelming success of evolutionary theory as an explanatory framework for biology has, of course, led to its almost universal acceptance in scientific circles. Yet perhaps surprisingly, Hume's bold claim that animals can reason in a way closely analogous to ourselves remains controversial. For an engaging account of some striking recent evidence in favour of Hume's position, see:
- <NAME>, Marian, *Through our eyes only?* (Oxford, New York and Tokyo: Oxford University Press, 1998)
### 7. Causation
#### 7(a) Hume's Account of Causation
In Chapter 7 of Millican (2001), Craig describes Hume's hunt for the impression of necessary connexion, and introduces some of the complex issues raised by it and by Hume's notorious two definitions of cause. Two other useful discussions of Hume's corresponding account in the *Treatise*, providing different perspectives on some of the same issues but also raising some new ones, are:
- <NAME>, *Hume* (London and Boston: Routledge & Kegan Paul, 1977), ch. 4
- Noonan, <NAME>., *Hume on Knowledge* (London and New York: Routledge, 1999), 140-57
In the course of his discussion, Stroud influentially takes on the question of what Hume's elusive impression of necessary connexion might be, concluding that it is just a certain feeling that accompanies our causal inferences, which because of its simplicity must be indefinable. His view is critically examined at length, in the context of a general treatment of Hume's theory of causation, by:
- <NAME>, *Hume's System* (Oxford and New York: Oxford University Press, 1990), ch. 7
Stroud responds to Pears in a paper which considers the more general issue of whether any Humean internal impression (such as of necessity, or of moral sentiments) can coherently be projected onto the world in the way that Hume supposes (the problem being that such projection takes for granted the prior availability within the mind of something which in fact seems to make sense only after the projection has taken place):
- <NAME>, '"Gilding or Staining" the World with "Sentiments" and "Phantasms"', *Hume Studies* 19 (1993), 253-72; repr. in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 16-30
Hume's notorious 'two definitions of cause' have provoked numerous discussions over many years because the two apparently conflict. Craig's response is to demote them from the status of strict *definitions* of causation, and to see them instead as general encapsulations of two different aspects of Hume's conclusions about our causal beliefs. A less compromising approach is taken by Beauchamp, who sees Hume's definitions as capturing two different theories of causation, which Hume tries in vain to reconcile:
- <NAME>, 'Hume's Two Theories of Causation', *Archiv für Geschichte der Philosophie* 55 (1973), 281-300; repr. in Tweyman (1995), vol. III, 303-21
In his later book with Rosenberg the development of this position is more extensive, and provides useful detailed discussion of a number of previous commentators' views:
- Beauchamp, Tom and Rosenberg, Alexander, *Hume and the Problem of Causation* (Oxford and New York: Oxford University Press, 1981), ch. 1
A different perspective is brought to the issue by Russell, who sees Hume's two definitions as giving accounts of causation as it exists in the material world and in our perceptions respectively:
- <NAME>, 'Hume's "Two Definitions" of Cause and the Ontology of "Double Existence"', *Hume Studies* 10 (1984), 1-25; repr. in Tweyman (1995), vol. III, 416-33
- <NAME>, *Freedom and Moral Sentiment* (Oxford and New York: Oxford University Press, 1995), ch. 2
Another insightful recent analysis first gives an overview of the various types of position that commentators have taken on the two definitions, and the general evidence for and against them. It then presents Hume as having a thoroughly coherent position based around his theory of abstract ideas and their definition:
- Garrett, Don, *Cognition and Commitment in Hume's Philosophy* (Oxford and New York: Oxford University Press, 1997), ch. 5
Perhaps the most obvious objection to Garrett is that Hume does not explicitly mention his theory of abstract ideas in the context of his two definitions; moreover that theory does not feature at all in the *Enquiry* (except in a footnote at E158), although the two definitions are just as prominent there as in the *Treatise*. Much of what Garrett says, however---in particular, his claim that the two definitions are co-extensive if properly understood---is plausible quite independently of any such connexion with abstract ideas.
It should be noted that Beauchamp, Rosenberg, Russell and Garrett all focus predominantly on the *Treatise*, so parts of their discussions are less directly appropriate to the *Enquiry* where Hume's two definitions are somewhat different. Their most important omission is any mention of the puzzle concerning Hume's 'other words' appended to his first definition in the *Enquiry* ('Or in other words *where, if the first object had not been, the second never had existed*.' - E76), which have often been interpreted (e.g. by Vesey in the article listed in [§8b](#8b-free-will-and-determinism) below) in a counterfactual manner that seems straightforwardly to conflict with the definition that they supposedly paraphrase. For a statement of the simplest solution to this puzzle, which interprets the conditional as merely tensed rather than counterfactual, see:
- Jacobson, <NAME>, 'From Cognitive Science to a Post-Cartesian Text', in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 156-66
In addition to her comments on the two definitions, Jacobson raises important criticisms of Stroud's view of the impression of necessity. Her more general thesis that the *Enquiry* is to be read in a postmodern fashion, as developing different (and incompatible) perspectives rather than seeking for determinate conclusions, is interestingly provocative but likely to be seen by most Hume interpreters as a premature counsel of despair.
#### 7(b) Humean Theories of Causation
Hume's theory of causation has become so influential that philosophical discussions of his views tend at the same time to be contributions to the contemporary philosophy of causation. This can make entry into the literature rather daunting, but fortunately a recent student text provides a relatively gentle introduction to some of the major issues:
- <NAME>, *Hume's Epistemology & Metaphysics* (London and New York: Routledge, 1998), ch. 4
The outstanding modern contribution to the philosophy of causation in the Humean tradition is:
- <NAME>., *The Cement of the Universe* (Oxford and New York: Clarendon Press, 1974)
The paperback edition (published in 1980) adds a useful preface, summarising Mackie's position and the book's contents. Though inspired by Hume, Mackie departs significantly from what he takes to be the Humean position (but his detailed analysis of Hume's arguments is questionable -- see Morris's article in [§5b](#5b-the-structure-of-humes-argument-concerning-induction) above). Another major book, more textually sensitive and faithful to Hume than Mackie's though less philosophically groundbreaking, has already been mentioned in [§5c](#5c-interpretations-of-hume-on-reason-and-induction) and [§7a](#7a-humes-account-of-causation) above:
- Beauchamp, Tom and Rosenberg, Alexander, *Hume and the Problem of Causation* (Oxford and New York: Oxford University Press, 1981)
Beauchamp and Rosenberg present a rational reconstruction of Hume's view (ridding him of the 'two definitions' inconsistency that they ascribe to him), which they then defend against Mackie's criticisms and others. One author discussed both by them and by Mackie is Anscombe, whose Cambridge inaugural lecture is probably the best known radical attack on the entire Humean position:
- <NAME>., *Causality and Determination* (Cambridge: Cambridge University Press, 1971); repr. in *Metaphysics and the Philosophy of Mind: Collected Philosophical Papers Vol. II* (Oxford: Blackwell, 1981), 133-47
Anscombe's lecture is also reprinted in a collection which starts from Mackie's seminal paper 'Causes and Conditions' (1965) and contains other important articles on the nature of causation:
- Sosa, Ernest and <NAME> (eds.), *Causation* (Oxford and New York: Oxford University Press, 1993)
#### 7(c) Causal Realism and the 'New Hume'
In Chapter 8 of Millican (2001), <NAME> presents a summarised account---with particular reference to the *Enquiry*---of the substantial case for Hume's causal realism which he made at far greater length in:
- <NAME>, *The Secret Connexion* (Oxford and New York: Clarendon Press, 1989)
Strawson's book is given an elegant summary and a judicious critical assessment by:
- <NAME>, 'Did Hume hold a Regularity Theory of Causation?', *British Journal for the History of Philosophy* 1 (1993), 99-114
Broackes packs a multitude of points into his fifteen pages, making this a particularly efficient introduction to the issues which, while generally disputing the evidence for the causal realist interpretation, nevertheless expresses sufficient sympathy with it to conclude that Hume probably had no completely settled view (a conclusion interestingly similar to the one Broackes draws about Hume's theory of belief in Chapter 6 of Millican (2001)).
Although he developed his position quite independently of these other authors, Strawson's book acknowledges that similar views had already been presented (albeit in very different style) by:
- <NAME>., *The Sceptical Realism of David Hume* (Manchester: Manchester University Press, 1983), ch. 4
- Livingston, <NAME>., *Hume's Philosophy of Common Life* (Chicago and London: University of Chicago Press, 1984), ch. 6
Less detailed but perhaps more widely known than the earlier work of Wright and Livingston, Craig's chapter on Hume (from parts of which his essay in Chapter 7 of Millican (2001) is developed), presents a general picture of his thought which is particularly congenial for the causal realist interpretation:
- <NAME>, *The Mind of God and the Works of Man* (Oxford and New York: Clarendon Press, 1987), ch. 2
The first chapter of Craig's book is also of great interest, giving a survey of rationalist writings prior to Hume that exemplify the 'Image of God' conception of human reason which Craig sees as Hume's principal target. The upshot of Craig's thesis is that the traditional reading of Hume as a positivist is totally wrong-headed; far preferable is the kind of 'sceptical realism' attributed to him by Wright and Strawson.
Together with Blackburn's article in Chapter 9 of Millican (2001), which defends a 'projectivist' reading of Hume, the most influential critique of the causal realist interpretation is:
- Winkler, Kenneth P., 'The New Hume', *Philosophical Review* 100 (1991), 541-79; repr. in Owen (2000), 347-85 and in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 52-74
The reprint of Winkler's paper in *The New Hume Debate* adds a postscript entitled 'Intelligibility and the Theory of Ideas' (pages 74-87). Also in this recent collection are a number of new papers, including a direct reply to many of the points made by Winkler:
- <NAME>., 'Hume's Causal Realism: Recovering a Traditional Interpretation', in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 88-99
Three other new papers in the collection, by <NAME>, and Flage, are of more specific interest in the causal realism debate:
- <NAME>, 'Projectivist *and* Realist?', in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 113-21
Craig here suggests that Hume may be *both* a projectivist *and* a realist about causation - projectivist about our everyday understanding of it (founded on 'the Imagination'), but realist about causes in nature. He then, however, goes on to question whether such realism may be just as incompatible with Hume's epistemology as it apparently is with his theory of ideas, because neither 'Reason' nor 'the Senses' can provide it with any basis ('Reason' here being rejected as a basis simply because uncaused regularity is conceivable). But since Craig detects traces, at the end of *Enquiry* V, of a *non*-demonstrative argument for realism based on the regularity of nature, his negative conclusion might be avoidable by adopting one of the non-rationalistic conceptions of reason favoured by most of the works discussed in [§5c](#5c-interpretations-of-hume-on-reason-and-induction) above.
- <NAME>, 'Sceptical Doubts concerning Hume's Causal Realism', in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 122-37
Bell attacks both Strawson's book and Wright's response to Winkler. Against Strawson he alleges a conflict between causal realism and Hume's inductive scepticism, given Strawson's apparent endorsement of the idea (alluded to by Craig) that realist causation can explain, and hence can be reasonably inferred from, the regularity of nature (but see the Introduction to Millican (2001), note 15, for doubts whether Strawson is indeed committed, as Bell implies, to what Blackburn in Chapter 9 calls a 'straitjacket'). Against Wright, Bell continues a debate on the interpretation of Hume's divergences from Malebranche, which started with:
- <NAME>., 'Hume's Criticism of Malebranche's Theory of Causation: A Lesson in the Historiography of Philosophy', in <NAME> (ed.), *Nicolas Malebranche: His Philosophical Critics and Successors* (Assen, Netherlands: Van Gorcum, 1991), 116-30
- Bell, Martin, 'Hume and Causal Power: the Influences of Malebranche and Newton', *British Journal for the History of Philosophy* 5 (1997), 67-86
Wright (like Strawson in ch. 11 of his book) sees Hume as adopting Malebranche's aprioristic criterion of causation---as what would license a priori inference from cause to effect---and takes his divergence from Malebranche to involve (sceptical) realism about causes so conceived. Bell sees Hume as rejecting Malebranche's entire notion, and replacing it with one that can be applied only on the basis of experience and whose instances are metaphysically quite distinct. However Bell ends his later paper by observing a resulting tension in Hume's thought, since such distinctness sits uneasily with the generality that is characteristic of necessity. This tension, Bell suggests, may explain the acknowledged imperfection in Hume's two definitions of cause (T170, E76-7), which New Humeans have taken as strong evidence of causal realism.
- <NAME>, 'Relative Ideas Re-Viewed', in Rupert Read and <NAME> (eds.), *The New Hume Debate* (London and New York: Routledge, 2000), 138-55
If Hume believes in truly *objective* causal powers, then he must be able to maintain a belief about something for which---as he shows in *Enquiry* VII---there is no corresponding impression (and hence, according to his Copy Principle, no idea). Strawson, Wright and other New Humeans have seen the solution to this puzzle in his notion of 'relative ideas' (cf. [§10a](#10a-scepticism-regarding-the-external-world) below), but Flage, author of a number of earlier articles on the notion, here argues that it is inadequate to play such a role. He draws attention to similar notions in the work of Locke, Berkeley, Arnauld and Reid, which however require clear understanding of the relation involved, something unachievable in the current case. He also argues that there is no evidence that Hume's 'relative ideas' can support a belief, for in the *Treatise* and *Enquiry*, force and vivacity attach only to positive ideas.
### 8. Liberty and Necessity
#### 8(a) Hume's Treatment of Liberty and Necessity
Given its enormous importance for Hume, it is surprising that the literature on his treatment of liberty and necessity is so meagre. Moreover what little has been written has tended to focus on his discussion in the *Treatise*, which (as Botterill explains in Chapter 10 of Millican (2001)) is significantly different from that in the *Enquiry* and in some ways quite misleading. In particular, the distinction between two types of liberty in the *Treatise* has encouraged many past commentators (for example Stroud in ch. 7 of his 1977 book) to interpret Hume as a straightforward classical compatibilist, a view exploded both by Botterill and by Russell (see his 1995 book below). Kemp Smith's short but influential chapter on the topic, though useful as an account of Hume's main points in the *Treatise*, exemplifies this misleading emphasis on the two liberties:
- <NAME>, Norman, *The Philosophy of David Hume* (London: Macmillan, 1941), ch. 20
For the student of the *Enquiry*, perhaps the most interesting of the traditional compatibilist accounts is:
- <NAME>, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961), ch. 7
The recent recognition that Hume's compatibilism is more distinctive and subtle than previously assumed, and rooted at least as much in his naturalist project as in conceptual concerns, is due largely to Russell's work, brought together in what is undoubtedly the most important book on the topic:
- <NAME>, *Freedom and Moral Sentiment* (Oxford and New York: Oxford University Press, 1995)
Most relevant for the interpretation of the *Enquiry* are chapters 1, 3, 4, and 7 (chapter 2 has already been mentioned in [§7a](#7a-humes-account-of-causation) above). Rejecting, like Botterill, the traditional focus on the contrast between the two types of 'liberty' mentioned in the *Treatise*, Russell emphasises instead Hume's analyses of necessity and of the conditions for moral responsibility. His densely argued work provides the best available account of how all these important strands in Hume's philosophy weave together. For another perspective on Hume's view of the relationships between liberty, necessity, and moral responsibility, see:
- <NAME>., 'Hume, Freedom to Act, and Personal Evaluation', *History of Philosophy Quarterly* 5 (1988), 141-56; repr. in Tweyman (1995), vol. IV, 175-91
Garrett's recent book provides a general problem-orientated discussion of liberty and necessity, nicely complementing Russell's approach (though unfortunately not discussing it) by focusing in turn on specific interpretative difficulties rather than explicitly developing an integrated overall perspective:
- <NAME>, *Cognition and Commitment in Hume's Philosophy* (Oxford and New York: Oxford University Press, 1997), ch. 6
Garrett highlights a range of apparent inconsistencies and other problems that various commentators have identified in Hume's account, and then with characteristic ingenuity proceeds to explain them away.
#### 8(b) Free Will and Determinism
There is, of course, a far wider range of material on the general philosophical topic of free will and determinism than on the detailed interpretation of Hume's position. A very brief introduction, approaching the topic through Hume's *Enquiry* in a (now rather dated) Wittgensteinian spirit, is provided by:
- <NAME>, 'Hume on Liberty and Necessity', in Godfrey Vesey (ed.), *Philosophers Ancient and Modern* (Cambridge: Cambridge University Press, 1986), 111-27
A particularly clear defence of Humean compatibilism, which helpfully introduces the contributions of contemporary philosophers such as <NAME> and Frankfurt, occurs in a chapter of a book on artificial intelligence whose aim is to refute the general claim that a robot could not be free:
- Copeland, Jack, *Artifical Intelligence: A Philosophical Introduction* (Oxford and Cambridge, Massachusetts: Blackwell, 1993), ch. 7
Honderich provides a more detailed but still introductory discussion, which (though misinterpreting Hume in the traditional manner) sets out many of the surrounding issues with great clarity while developing his own 'theory of determinism', a theory which rejects both compatibilism and incompatibilism:
- Honderich, Ted, *How Free Are You?* (Oxford and New York: Oxford University Press, 1993)
The concept of free will is intimately connected with that of intentional action, and both impinge on moral theory. Mackie provides an accessible general treatment of these issues, from the viewpoint of a broadly Humean approach to morality:
- <NAME>., *Ethics: Inventing Right and Wrong* (Harmondsworth: Penguin, 1977), ch. 9
Turning now to more detailed treatments, the following are amongst the most influential book-length presentations of the case for compatibilism and for libertarianism respectively:
- Dennett, <NAME>., *Elbow Room: The Varieties of Free Will Worth Wanting* (Oxford: Clarendon Press, 1984)
- <NAME>, Peter, *An Essay on Free Will* (Oxford: Clarendon Press, 1983)
A contrasting and very uncompromising approach can be found in Galen Strawson's book on the topic, which rejects both Humean compatibilism and traditional libertarianism on the ground that *irrespective* of the truth or falsity of determinism, our belief that we are truly free and responsible agents is false:
- <NAME>, *Freedom and Belief* (Oxford and New York: Clarendon Press, 1986)
Other contemporary approaches are represented in Watson's useful collection, including two of the best-known compatibilist contributions, 'Freedom of the Will and the Concept of a Person' by <NAME>, and 'Freedom and Resentment' by <NAME> (the latter of which is discussed at some length in chapter 5 of Russell's book, finding illuminating parallels with Hume):
- <NAME> (ed.), *Free Will* (Oxford and New York: Oxford University Press, 1982)
Understanding how all these different views relate to each other is a complex matter, but the first part of a recent book - written from a libertarian perspective - draws the threads of contemporary debate into a coherent pattern:
- <NAME>, *The Significance of Free Will* (Oxford and New York: Oxford University Press, 1996), part I
Hume ends his section on liberty and necessity by hinting that his compatibilist account leaves God as the author of sin. Kenny provides a contemporary discussion of this issue, with the same conclusion:
- <NAME>, *The God of the Philosophers* (Oxford and New York: Clarendon Press, 1979), ch. 6
### 9. Hume's Philosophy of Religion
The best general account of Hume's philosophy of religion is:
- <NAME>., *Hume's Philosophy of Religion*, 2nd edn. (Basingstoke and London: Macmillan, 1988)
The same author provides an excellent overview in Norton's *Cambridge Companion*:
- <NAME>., 'Hume on Religion', in David Fate Norton (ed.), *The Cambridge Companion to Hume* (Cambridge: Cambridge University Press, 1993), 313-344
Leaving aside Gaskin's book, probably the most widely respected contribution on the topic is <NAME>'s editorial material in his standard edition of the *Dialogues*, discussed in [§2c](#2c-dialogues-concerning-natural-religion) above:
- <NAME>, *Dialogues concerning Natural Religion* (1779), ed. <NAME>, 2nd edn. (Edinburgh: Nelson, 1947)
Penelhum's 1975 book on Hume is unusual in giving explicit attention to the arguments of *Enquiry* XI as well as those of *Enquiry* X, offering a convenient summary and a brief philosophical discussion of each:
- <NAME>, *Hume* (London and Basingstoke: Macmillan, 1975), ch. 8 especially 175-80
When reading Hume's writings on religion, it is important to remain alert to the possibility of irony in his apparent declarations of theistic belief (e.g. in the concluding paragraph of *Enquiry* Sections VIII and X). Berman's discussion of contemporary deist writings sets Hume in context, showing how widely practised - and widely recognised - was the art of 'theological lying':
- Berman, David, 'Deism, Immortality, and the Art of Theological Lying', in <NAME> (ed.), *Deism, Masonry, and the Enlightenment* (London and Toronto: Associated University Presses, 1987), 61-78
Fieser illustrates how this context was taken for granted by Hume's early critics, who clearly recognised the need to 'decode' his writings in order to reveal their hidden meaning:
- <NAME>, 'Hume's Concealed Attack on Religion and His Early Critics', *Journal of Philosophical Research* 20 (1995), 83-101
Given this background, it is a genuine puzzle to identify Hume's real views on religion, a puzzle which has generated a great deal of literature especially in relation to the interpretation of his *Dialogues* (as discussed in [§9b](#9b-hume-on-the-design-argument) below). It seems clear that Hume himself held at most a very minimal deism, which raises the question of why he should have devoted so much attention to the topic. Noxon suggests that his fascination with it derived from his perception of religious belief itself as an extraordinary phenomenon:
- Noxon, James, 'Hume's Concern with Religion', in <NAME> and <NAME> (eds.), *<NAME>: Many-sided Genius* (Norman, Oklahoma: University of Oklahoma Press, 1976), 59-82; repr. in Tweyman (1995), vol. V, 3-25
The most obvious alternative explanation---that Hume was motivated by the desire to oppose superstition---is rejected by Noxon (following Wollheim) by appeal to Hume's pessimism and conservative temperament. Hume was indeed pessimistic about the power of philosophy to undermine the religious commitments of 'the vulgar', but this does not imply that he had no such reformative ambition in respect of his more discerning readers. Quite the contrary is suggested by his manifesto in *Enquiry* I, which explicitly advocates that we 'cultivate true metaphysics ... in order to destroy the false and adulterate' (E12), and also by his posthumously published essay 'Of Suicide', whose first paragraph describes philosophy as a 'sovereign antidote ... to superstition and false religion' (see §3 of Chapter 1 of Millican (2001) for other relevant references). Moreover his concern with religion was very far from being the relatively detached curiosity suggested by Noxon, though as Siebert shows, his passionate moral opposition to religion is more clearly manifested in the *History of England* than in his philosophical writings:
- <NAME>., *The Moral Animus of <NAME>* (London and Toronto: Associated University Presses, 1990), ch. 2
#### 9(a) Miracles
The historical context of Hume's essay on miracles has become much better understood over recent years. Chapter 8 of Gaskin's book (listed above) is useful, but the most detailed treatment of both the prior debate and of Hume's arguments is:
- <NAME>., *The Great Debate on Miracles* (London and Toronto: Associated University Presses, 1981)
Two recent articles are also particularly noteworthy:
- <NAME>, 'Hume's "Of Miracles": Probability and Irreligion', in <NAME> (ed.), *Studies in the Philosophy of the Scottish Enlightenment* (Oxford and New York: Clarendon Press, 1990), 191-229
- <NAME>., 'Hume's Historical View of Miracles', in <NAME> and <NAME> (eds.), *Hume and Hume's Connexions* (Edinburgh: Edinburgh University Press, 1994), 171-200
Gaskin locates Hume's essay within an ongoing English debate centring around <NAME>'s famous *Tryal of the Witnesses of the Resurrection*, in which Sherlock defended the Gospel resurrection stories as historically well-founded. Burns discusses a wider variety of English authors, finding parallels to the arguments of both Sherlock and Hume which make it harder to identify Sherlock as Hume's specific target, and also suggest that Hume's arguments may be less original than is often supposed (with similarities to those of deists such as <NAME>). Wootton stresses the influence on Hume's thinking of less familiar French sources, which Hume is likely to have encountered during his time in France working on the *Treatise*. Stewart, while acknowledging both French and English sources, argues that Locke was the primary influence on Hume's thinking about the topic. Locke's views are put into context by Jones, who surveys how the topics of testimony and miracles were treated by British philosophers from Bacon to Hume:
- <NAME>, *Hume's Sentiments* (Edinburgh: Edinburgh University Press, 1982), 45-56
There are numerous discussions of the philosophical merits of what has been, ever since its publication, one of Hume's most controversial arguments. Some early responses and relevant reviews have recently become easily available in a useful collection (see *Hume Studies* 24 (1998), 198 for details):
- <NAME> (ed.), *Hume on Miracles* (Bristol: Thoemmes Press, 1996)
One particularly entertaining piece, unfortunately long since out of print and not included in Tweyman's collection, is a spoof by Archbishop <NAME> which was initially published (anonymously) in 1819. Here Whately aims to demonstrate the absurdity of Hume's criteria for judging miracle stories by showing that the history of Napoleon's exploits would, on these criteria, appear equally incredible:
- Whately, Richard, *Historic Doubts relative to Napoleon Buonaparte* (London: <NAME> and Son, 1859)
Moving on to modern interpretations and assessments of Hume's argument, the first section of Garrett's Chapter 11 of Millican (2001) gives some indication of their large number and considerable variety, and his lists of references can easily be used to identify works which diverge from his interpretation in particular respects. Rather than duplicate this resource, I here pick out only a few highlights from the immense literature. To begin with those that have attained 'classic' status, the following short general discussions of Hume's essay are still well worth reading, even though they may look slightly dated in the light of more recent scholarship:
- <NAME>., 'Hume's Theory of the Credibility of Miracles', *Proceedings of the Aristotelian Society* 17 (1916-17), 77-94; repr. in Tweyman (1995), vol. V, 444-55
- Flew, Antony, 'Hume's Check', *Philosophical Quarterly* 9 (1959), 1-18
- <NAME>., *The Miracle of Theism* (Oxford and New York: Clarendon Press, 1982), ch. 1
Broad is sympathetic but ultimately critical of the strength of Hume's conclusion, and sees it as inconsistent with his inductive scepticism (see [§6c](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry) for suggested reading on this crucial issue). Flew takes Hume to be less ambitious, aiming to provide only a 'check' to the 'impertinent solicitations' of 'bigotry and superstition' addressed to 'the wise and learned' rather than a more general offensive criterion; however he too sees the essay as inconsistent with Hume's account of induction. Mackie is less textually focused, and therefore less faithful to the details of Hume's treatment, but his discussion---which generally supports a Humean point of view---is philosophically interesting in its own right (for criticism, see <NAME>, 'Mackie on Miracles', *Australasian Journal of Philosophy* 66 (1988), 368-75).
Perhaps not surprisingly, the most substantial contributions are on the theistic side of the debate, with two books being particularly noteworthy:
- <NAME>, *The Concept of Miracle* (London and Basingstoke: Macmillan, 1970)
Swinburne's well-known study starts by analysing how the notions of 'miracle' and 'law of nature' should be understood (criticising Hume for ignoring the relevance of an event's religious significance), then considers the appropriate criteria for weighing of evidence and for preferring a purposive to a scientific explanation. Overall Swinburne finds Hume's conclusion simplistic, in that it fails to take into account both the full range of possible evidence, and also how miracles can fit into a pattern of explanation within a theistic world-view in which miracles and other evidence for God's existence are mutually supporting.
- <NAME>., *Reported Miracles: A Critique of Hume* (Cambridge: Cambridge University Press, 1994)
Houston's book is more theologically informed than Swinburne's, but just as philosophically sensitive, reaching conclusions in a similar spirit but adding more incisive criticism of Hume. It starts with a historical survey of views on the miraculous, ranging through Augustine, Aquinas, Locke, Hume, Bradley and Troeltsch, and ends with two chapters on the epistemological and theological implications of taking miracles seriously. But the heart of the book consists of two chapters on the concept of a miracle (one on theological conceptions, the other on Hume's) followed by three in which 'Hume's case' is assessed. Houston's primary criticism (ch. 9) questions Hume's assumption 'that the evidence for the relevant law(s) of nature is, in the overall dialectical context, undeniably relevant to an assessment of the probability (or improbability) that a reported putative miracle actually took place' (p. 133). This threatens to undercut Hume's entire argument in Part i of his essay, the point being that if the theist himself takes the reported event to be a *violation* of what, in other instances, has been a universal law, then the evidence for that law garnered from those other instances is exactly in accord with what the theist claims - Hume is apparently simply begging the question against the possibility of a miracle by presuming that the general rule must extend to the event in question. Houston follows up with a secondary objection (ch. 10), against Hume's aprioristic assumption that a report of an improbable event must itself inherit that improbability. For it would be perfectly possible that mankind in general - like the proverbial Edinburgh solicitor to whom Houston alludes - should be *more* reliable when reporting unusual events than when reporting relatively everyday happenings. Of course Hume, in Part ii of his essay, argues strongly that the facts of human nature are otherwise, but the point remains that on Hume's own principles such facts can be known only a posteriori. For his argument is founded on an inductive conception of testimony, according to which its reliability can be known only through experience; hence experience alone can tell us under what circumstances different types of testimony are more, or less, reliable.{[endnote 3](#note3)}
Hume's inductive conception of testimony is itself attacked by Coady in an article and in a recent book:
- <NAME>., 'Testimony and Observation', *American Philosophical Quarterly* 10 (1973), 149-55
- <NAME>., *Testimony* (Oxford and New York: Clarendon Press, 1992), especially ch. 4 and ch. 10
The tenth chapter of Coady's book deals with the topic of 'astonishing reports', describing some of the complexities of assessing such evidence and concluding that no simple rule of assessment, such as Hume's, is likely to be universally applicable. But he addresses more basic concerns in his fourth chapter (as in his article), attacking Hume's 'reductive approach' whereby testimony is viewed as simply a species of inductive evidence, which therefore needs to be grounded on an observed correlation between reports and facts if it is to provide an adequate basis for belief. He argues for the incoherence of this view (which, for example, seems to imply the possibility of testimony's existing in a community but yet having no connection with reality), and concludes that testimonial evidence must instead be seen as a fundamental category of evidence that is not reducible to other kinds. Hume is defended against this attack in:
- Traiger, Saul, 'Humean Testimony', *Pacific Philosophical Quarterly* 74 (1993), 135-49
where Traiger argues that the traditional attribution to Hume of an epistemically individualist and purely inductivist conception of testimony is incorrect.
Yet another book-length attack on Hume, which has appeared very recently, has the merit of giving detailed attention not only to Hume's own argument, but to four 'reconstructions' of it by Mackie, Mill, Flew, and Sobel:
- <NAME>, *Hume, Holism, and Miracles* (Ithaca and London: Cornell University Press, 1999), especially 5-33
Johnson provides forceful criticisms of many distinctive points - made by Mill and Flew in particular - that are somewhat distant from Hume's own words and so tend not to be addressed by other authors. However his principal criticism of all five versions of Hume's argument is that they ultimately beg the question against the miraculous, either by defining miracles out of existence (e.g. as exceptions to an exceptionless law of nature), or by taking for granted without argument that the inductive balance of evidence against any miracle cannot be outweighed by testimony on the other side. Johnson maintains that the inductive evidence can be so outweighed, even in principle by the testimony of a single witness, and he supports this claim with illustrations involving selection of marbles from an urn (pp. 25, 56) and reports of unusual weather (p. 31). These illustrations indeed appear initially very convincing, but it is a shame that Johnson does not consider some possible objections, for which we must turn to another strand of recent debate.
As Owen makes clear in Chapter 12 of Millican (2001), illustrations in a similar spirit to those used by Johnson - often involving lotteries, urns and other probabilistically calculable scenarios - date right back to Hume's contemporary Richard Price. But after many years of relative neglect they have recently inspired great interest in the formal analysis of Hume's argument, largely with the aim of clarifying their true force against it. The standard lottery example involves a report (e.g. from a newspaper which is normally 99% reliable in such matters) that the winning ticket in a lottery of, say, 10,000 tickets was ticket number 297 (or whatever). In this situation, it seems that Hume's argument would advise us to reject the report, on the grounds that it is more probable that the report should be false (probability 1%) than that ticket 297 should really have won the lottery (probability 0.01%). But intuitively this seems quite wrong -- if the newpaper is 99% reliable in such matters, then surely we should have 99% confidence that the winning ticket was indeed 297. As Hambourger shows, such points can also be made in respect of many other types of report, even something as mundane as someone's reporting their own name:
- Hambourger, Robert, 'Belief in Miracles and Hume's Essay', *Noûs* 14 (1980), 587-604
Owen hints (in his footnote 12) that this problem for Hume is solvable by taking into account that in such a lottery, an incorrect report of the winning number can be wrong in 9,999 different ways (hence if some ticket other than 297 actually won but the newspaper reported it wrongly, the chance that it would report the particular number 297 is only 1 in 9,999). However a formal treatment of this solution requires a Bayesian analysis more complex than Owen's simplified version -- two such treatments (the first involving non-standard infinitesimals and the second more straightforward) are presented by:
- Sobel, <NAME>, 'On the Evidence of Testimony for Miracles: A Bayesian Interpretation of David Hume's Analysis', *Philosophical Quarterly* 37 (1987), 166-86
- <NAME> and <NAME>, 'A Bayesian Analysis of Hume's Argument concerning Miracles', *Philosophical Quarterly* 39 (1989), 57-65
However Olin points out that matters are not quite this straightforward, because an exactly parallel move is possible with respect to miracle reports on the basis that if the reported event did not happen, then it would be extremely unlikely that *this* particular thing would be reported:
- <NAME>., 'Hume, Miracles, and Prior Probabilities', in Tweyman (1995), vol. V, 416-26
Nevertheless there remains, as Hambourger stresses, an evident disanalogy between the case of the lottery and the miracle -- in the lottery the *particular* event reported may be initially improbable, but the *type* of event reported is not. Schlesinger provides a formal analysis which is able to take this into account, by explicitly giving a low value to the probability that *any kind* of miracle has occurred in a specific situation:
- Schlesinger, <NAME>., 'Miracles and Probabilities', *Noûs* 21 (1987), 219-32; repr. in Owen (2000), 265-78
Schlesinger goes on to argue that miracle reports can nevertheless raise the probability of God's existence (though highly paradoxically, he suggests that on the assumption that God exists, such reports need not raise the probability of the miracle itself!).
The continuing debate over lottery and related examples is not of merely technical interest, for it has brought into the open many issues of more general relevance. Olin, for example, lays the blame for Hume's problems on his failure to distinguish statistical from epistemic probability, and on his key presumption that evidence is additive. Hambourger too sees Hume's treatment of evidence as simplistic, in particular his supposition that the likelihood of the reported event can be factored out separately from the credibility of the report (a point which also seems to lie behind some criticisms that Johnson makes in his book, for example in chapter 7). If indeed the two cannot be separated, then the only coherent way of interpreting Hume's rule for the assessment of miracle reports may be to reduce it to a triviality, though arguably this need not be objectionable (for a sketch of this issue, and some implications for attempts to formalise Hume's position, see <NAME>, '"Hume's Theorem" concerning Miracles', *Philosophical Quarterly* 43 (1993), 489-95).
#### 9(b) Hume on the Design Argument
In terms of their direct impact on the secondary literature, Sections X and XI of the *Enquiry* could hardly be further apart. With Section X the problem is one of selection from a vast range of critiques and replies; with Section XI the problem is to find even a handful of contributions that directly address the specific issues that Hume raises there. A notable exception is the relevant chapter of Flew's classic book:
- <NAME>, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961), ch. 9
Flew generally supports Hume's contention that it is illegitimate to infer qualities in the cosmic Designer beyond those that are manifested in the experienced cosmos, and he also agrees with Hume's closing hint that the supposed Deity's uniqueness is a decisive obstacle to viewing theism as a hypothesis open to confirmation from the empirical evidence. Both principles are challenged forcefully by Swinburne, who argues that they are contrary to standard criteria of scientific inference:
- <NAME>., 'The Argument from Design', *Philosophy* 43 (1968), 199-212; repr. in Tweyman (1995), vol. V, 197-209 (see especially Swinburne's itemised points 1 to 3)
These general issues are explored by Gaskin in Chapter 13 of Millican (2001), and a detailed reply to Swinburne has recently appeared in a new journal published by the Council for Secular Humanism, which is named after Philo, Hume's sceptical spokesman in the *Dialogues*:
- Beaudoin, John, 'On Some Criticisms of Hume's Principle of Proportioning Cause to Effect', *Philo* 2 (1999), 26-40; also available on this website at [davidhume.org/papers/beaudoin.pdf]({{ site.baseurl }}/papers/beaudoin.pdf)
We must now turn to the *Dialogues* themselves, which have attracted the vast majority of scholarly interest regarding Hume's criticisms of the Design Argument. What follows is only a very brief review of a massive debate, for the puzzle of how far the *Dialogues* reveal Hume's own views on religion has for many years been one of the most discussed issues of Hume interpretation. There are several detailed commentaries on the *Dialogues* available, of which Kemp Smith's (referred to in [§9](#9-humes-philosophy-of-religion) above) is certainly the most influential. Two others of particular interest are:
- <NAME>, 'Hume on the Argument from Design', in Pike (ed.), *David Hume: Dialogues concerning Natural Religion* (Indianapolis: Bobbs-Merrill, 1970), 125-238
- <NAME>, introduction to Tweyman (ed.), *David Hume: Dialogues concerning Natural Religion in Focus* (London and New York: Routledge, 1991), 1-94
Kemp Smith's uncompromising interpretation provides the background to the subsequent debate: 'I shall contend that Philo [the sceptic], from start to finish, represents Hume; and that Cleanthes [the advocate of the Design Argument] can be regarded as Hume's mouthpiece only in those passages in which he is explicitly agreeing with Philo, or in those other passages in which, while refuting Demea [the mystically inclined a priori theist], he is also being used to prepare the way for one or other of Philo's independent conclusions.' (D59). Pike (pp. 224-34) disputes this sceptical reading, highlighting Cleanthes' rejoinder in Dialogue III where he says to Philo that if he contemplates the structure of an eye, the idea of a designer will 'immediately flow in upon you with a force like that of sensation' (D154). Philo makes no reply at this point, but Pike suggests that it is his acceptance of this 'irregular' but 'irresistible' argument that forms the basis for his famously puzzling 'confession' at the beginning of Dialogue XII (D214-7). Tweyman develops this idea further, relating it to Hume's discussion of scepticism in the *Enquiry*. He suggests that Philo's argumentation itself exemplifies the Humean transition, discussed by Norton in Chapter 14 of Millican (2001), from Pyrrhonian scepticism (which though unsustainable performs the useful service of undermining our initial dogmatic confidence) to mitigated scepticism (which corrects the Pyrrhonian doubts with 'common sense and reflection' - E161). According to Tweyman, in Dialogues I to VIII Philo argues as a Pyrrhonian, aiming for suspense of judgement, but thereafter he mitigates his scepticism and by Dialogue XII is prepared to acknowledge the natural force of Cleanthes' 'irregular' argument.
Since Hume is famous for affirming the power of nature to compel belief beyond the reach of reason, it is not surprising that many commentators have seen a similar pattern in the *Dialogues*, with Cleanthes' irresistible inference of Dialogue III and Philo's confession of Dialogue XII indicating that theism may be a Humean 'natural belief' (the term is Kemp Smith's) alongside those in inductive uniformity, the reliability of our senses, and the independent continuity of the external world. Butler and Penelhum have been perhaps the strongest advocates of this idea, and Gaskin its most resolute opponent, with the following works (in order) giving the essence of their debate:
- <NAME>., 'Natural Belief and the Enigma of Hume', *Archiv für Geschichte der Philosophie* 42 (1960), 73-100
- <NAME>., 'God, Hume and Natural Belief', *Philosophy* 49 (1974), 281-94; repr. in Tweyman (1995), vol. V, 150-63 (this article is reproduced, largely verbatim, on pages 129-39 of the first edition of his book *Hume's Philosophy of Religion*, London and Basingstoke: Macmillan, 1978)
- Penelhum, Terence, 'Natural Belief and Religious Belief in Hume's Philosophy', *Philosophical Quarterly* 33 (1983), 266-82; repr. in Tweyman (1995), vol. V, 164-80
- <NAME>., *Hume's Philosophy of Religion*, 2nd edn. (Basingstoke and London: Macmillan, 1988), 116-31
Gaskin objects to the classification of theism as a 'natural belief' on the grounds that it does not seem to be a belief of common life, is not irresistible and independent of reasoning, is not necessary for action in the world, and is not universal. In response to these criticisms, Penelhum suggests a modified position according to which the belief in God, though potentially requiring reasoning to bring it about (and hence not 'natural' in the strict sense) nevertheless is like the natural beliefs in being, *once acquired*, beyond the power of reason to dislodge. But given the very minimal theism which Penelhum ascribes to Hume, his difference from Gaskin reduces to the question of whether, in Hume's view, such 'attenuated deism' may be, after all, a reasonable conclusion to draw from the Design Argument. Gaskin maintains that it is, though since this reasonable belief is easily conflated with a natural and non-rational *feeling for design*, the psychological upshot of Penelhum's and Gaskin's positions may ultimately be hard to distinguish. Another subtle variation on the same general theme is provided by:
- <NAME>., 'Hume on Religious Belief', in <NAME> and <NAME> (eds.), *Hume: a Re-evaluation* (New York: Fordham University Press, 1976), 109-25; repr. in Tweyman (1995), vol. V, 36-55
who seeks illumination by starting from the *Natural History of Religion* instead of the highly ambiguous *Dialogues*. Yandell's Hume accepts that some minimal religious principle is part of human nature, though it is not irresistible and is often intermixed with more primitive religious feelings arising from ignorant hopes and fears. Although the Design Argument is unsound, contemplation of the order of the world can trigger our innate propensity to believe in a Designer, and Yandell maintains that this propensity - despite its instinctive nature - is appropriately judged to be part of our *rational* capacity. *Why* such an instinct should be appropriately called 'rational' is, however, unclear, and one might suspect that Yandell has here gone too far in attempting to find a genuine reconciliation between Hume's refutation of the Design Argument and his endorsements of the design hypothesis in the *Natural History* and elsewhere. For a more straightforward explanation of Hume's position suggests itself -- that his declarations of belief are simply instances of the 'theological lying' discussed by Berman and Fieser in their essays mentioned in [§9](#9-humes-philosophy-of-religion) above. Faced with this possibility, the only way of revealing Hume's true opinions seems to be to follow where his most forceful arguments lead, and to try to identify the targets at which they are aimed.
With this in mind, many authors have attempted to identify the real archetypes behind the characters of the *Dialogues*. Pakaluk takes all three to be representive of abstract philosophical 'types', with Philo being a mitigated sceptic or 'true philosopher', Cleanthes a 'false philosopher', and Demea a 'vulgar reasoner'. Like Tweyman, Pakaluk sees Philo's eventual acceptance of the design hypothesis as exemplifying a Humean transition of thought, though not a change of theory so much as a change of temper, when the natural sentiments of the mind that have hitherto been suppressed return after the sceptical duelling ceases. In developing this account, he also draws various interesting parallels between the *Dialogues* and *Enquiry* XII (especially Hume's discussion of the external world in *Enquiry* XII Part i):
- Pakaluk, Michael, 'Philosophical "Types" in Hume's *Dialogues*', in V. Hope (ed.), *Philosophers of the Scottish Enlightenment* (Edinburgh: Edinburgh University Press, 1984), 116-32; repr. in Tweyman (1995), vol. V, 323-38
A more concrete identification of Hume's characters was influentially made by Mossner very soon after the first appearance of Kemp Smith's edition. Accepting Kemp Smith's identification of Philo with Hume, Mossner argues that Cleanthes and Demea represent respectively <NAME> and <NAME>:
- Mossner, <NAME>., 'The Enigma of Hume', *Mind* 45 (1936), 334-349
All three of Mossner's identifications are challenged, however, by a comprehensive comparative study of Hume and Butler:
- Jeffner, Anders, *Butler and Hume on Religion* (Stockholm: Diakonistyrelsens Bokförlag, 1966), especially 131-43, 169-71, 180-209
According to Jeffner, although Butler is indeed a primary target of the *Dialogues*, he is not represented directly by any of the characters. Instead, Cleanthes is modelled on a type of scientific theologian associated with the Royal Society (most famously Boyle and Newton, but also <NAME>, <NAME>, <NAME>, <NAME>, and <NAME>), who were enthusiastic advocates of the analogical Design Argument. Here Jeffner draws on:
- <NAME>, <NAME>., '<NAME> and Scientific Theism', *Journal of the History of Ideas* 17 (1956), 486-97
who quotes passages from Cheyne and Maclaurin strikingly similar to Cleanthes' words (including his famous appeal to the 'force like that of sensation' in Dialogue III which has inspired so much interest in the natural belief interpretation). Jeffner goes on to suggest that Demea is modelled on the theological school of <NAME>, <NAME>, and <NAME>, who denied that we have understanding of the supposed analogical similarity between God's and man's attributes and who were accordingly inclined to prefer the aprioristic reasoning of <NAME>. Finally, Jeffner identifies Philo not with Hume himself but with Bayle, combining scepticism and mysticism with apparently devout fideism. On this reading, it is the combinations of the characters rather than their individual positions that display Hume's true views and spell defeat for Butler's theism. Philo and Demea combine to portray the evil of the world and the impossibility of an analogical argument for a good God; Cleanthes and Philo combine to reject a priori natural theology; while Cleanthes and Demea combine to insist that faith, if it is to be intellectually respectable, should be founded on reason. Taken together, these results imply the impossibility of any defensible theism.
#### 9(c) The Contemporary Design Argument
Although for many years the Design Argument lay under the cloud of Hume's critique, and perhaps even more influentially the undermining of its biological aspect through the theory of evolution, it has recently enjoyed something of a renaissance. The first wave of this rebirth came from philosophers who advocated treating the argument not as decisive in itself, but as part of a *cumulative case* in which a wide range of considerations are adduced to show the overall plausibility of a theistic world view. The roots of this approach go back to Hume's contemporary Joseph Butler, but its modern pioneer was Mitchell, soon to be followed by Swinburne:
- <NAME>, *The Justification of Religious Belief* (London and Basingstoke: Macmillan, 1973), especially chapters 2 and 3
- <NAME>, *The Existence of God*, (Oxford and New York: Clarendon Press, 1979), especially ch. 8 (chapters 10 and 11 consider the Problem of Evil)
The best-known critique of Swinburne is by Mackie, who starts by explicitly following Hume's objections to the logic of the Design Argument. He then---like Philo in Dialogues X and XI---presses home his attack by emphasising the Problem of Evil, which aims to turn the tables by confronting the theist with empirical evidence that is far less favourable to his optimistic conclusions:
- <NAME>., *The Miracle of Theism* (Oxford and New York: Clarendon Press, 1982), chapters 8 and 9
The revised edition of Swinburne's book adds a direct reply to Mackie in a new appendix:
- <NAME>, *The Existence of God*, revised edition (Oxford and New York: Clarendon Press, 1991), appendix A
The second wave of the Design Argument's renaissance has come, perhaps surprisingly, from the same arena that inspired the Enlightenment vision of a divine clockmaker, namely the heavens. Modern discoveries in physics and cosmology suggest that the Universe began with a 'Big Bang', and that the initial conditions of this Big Bang, and the laws of nature that have governed the Universe since, must have been impressively 'finely tuned' to permit the evolution of stars, planets, and hence---ultimately---life. For a fairly detailed (and moderately technical) outline of this apparent 'fine tuning', see:
- <NAME>., *The Accidental Universe* (Cambridge, New York and Melbourne: Cambridge University Press, 1982), especially chapters 3 and 4
Less detailed overviews are provided by two philosophical discussions from strong advocates of the Fine Tuning Argument, who draw the inference that unless the Universe were designed with life in mind, the existence of this favourable fine tuning would be vanishingly improbable:
- <NAME>, *The Existence of God*, revised edition (Oxford and New York: Clarendon Press, 1991), appendix B
- Craig, <NAME>, 'The Teleological Argument and the Anthropic Principle', in W. <NAME> and M. McLeod (eds.), *The Logic of Rational Theism: Exploratory Essays* (Lewiston, New York: Edwin Mellen, 1990), 127-53
All three of these writers make reference to the (rather unfortunately named, and variously interpreted) 'Anthropic Principle', which has been used to explain away the apparent fine tuning---or 'anthropic coincidences'---as a selection effect. This idea can be summed up as a retort to the theist: 'You shouldn't find it surprising to observe that the Universe is "fine tuned" for life, because if it weren't, you wouldn't be here to observe anything'. As the discussions above make clear, however, this retort seems dubious unless there is a 'population' of universes for the selection effect to work on, for if there is only one universe, then it does indeed appear surprising (and hence crying out for explanation) that this sole universe should happen to be 'finely tuned' in a way that makes possible the existence of observers. (The atheist's retort conflates the unsurprising fact that we fail to observe a universe *unsuitable* for life, with the surprising fact that we observe a universe suitable for life - indeed that we are here to observe anything at all.) This constitutes a serious problem for the atheist, for it seems to put the boot of metaphysical extravagance---traditionally one of the very strongest objections to theism---on the other foot. For if the only reasonable alternative to the hypothesis of a divine Fine Tuner is a massive ensemble of universes, with life emerging only in the minute proportion that happen to be 'finely tuned', then arguably theism has now become the more modest and metaphysically economical of the available hypotheses. All of these themes are engagingly developed at length in the most extensive philosophical treatment of the issue so far published:
- <NAME>, *Universes* (London and New York: Routledge, 1989)
Leslie is not, however, a conventional theist, for the 'God' to whose action he attributes the creation of the Universe is a Neoplatonic 'ethical requiredness' rather than a divine person.
The recent discovery of the Fine Tuning Argument is perhaps the most significant development in natural theology since Hume's *Dialogues*, and it is too early yet to attempt any general assessment of its merits (not least because the physical theory on which it is based is very far from being solidly established). One notable advantage that it has over traditional versions of the Design Argument is to point unambiguously to *advance planning* as the ultimate source of order in the Universe, thus bypassing Hume's objection (D147-8, 170-85) that it is mere bias to prefer intelligence over the other potential sources of order that we experience, such as vegetation, generation, and the emergence of patterns from chaos. The cosmological scale of the argument also seems to lend support to the theist's desired conclusions about the Designer's unity and supremacy (cf. D166-8). But other Humean objections remain strong, particularly his insistence (E143-8, D149-50) that, without experience of the origin of worlds, we are unable to make any proper assessment of the probability that a life-favouring universe (whether like ours or profoundly different) might exist without being expressly designed. Indeed this point gains even more force in the light of modern physics, which has repeatedly demonstrated the unreliability of our intuitive judgements when applied beyond the human scale of things, to atoms and the cosmos. Another Humean objection (D191) highlights our ignorance of the underlying structure of the world, suggesting that for all we know there may be some deep reason why it *has to be* structured as it is. Applied to the Fine Tuning Argument, this draws attention to the possibility of a future theory that will provide a clear explanation for what at present seem surprising coincidences. Such objections, like those made by Philo to the traditional Design Argument a century before the theory of evolution, may appear 'mere cavils and sophisms' (D202), being based on promissory notes and appeals to ignorance rather than offering any explicit alternative theory. But just like Philo, the atheist can effectively force his adversary onto the defensive by turning instead to the ancient Problem of Evil, where the anthropic coincidences are of no help to the theist. A malevolent spirit, just as much as a benevolent one, can be expected to favour a Universe conducive to life, because as Smith points out, life is a prerequisite of moral evil as well as of moral good:
- Smith, Quentin, 'The Anthropic Coincidences, Evil and the Disconfirmation of Theism', *Religious Studies* 28 (1992), 347-50
For an extended development of this 'antitheistic' strategy, which applies it to a wide range of traditional theistic arguments and to Swinburne's Design Argument in particular detail, see:
- <NAME>., 'The Devil's Advocate', *Cogito* 3 (1989), 193-207; also available on this website at [www.davidhume.org/papers/millican/1989DevAdv.doc]({{ site.baseurl }}/papers/millican/1989DevAdv.doc)
Presumably Hume himself - like Philo - viewed the Problem of Evil as the theist's most formidable obstacle, obliging him 'to tug the labouring oar, and to support [his] philosophical subtilties against the dictates of plain reason and experience' (D202). To explore the prospects for a successful theistic defence, see (in addition to the books by Mitchell and Swinburne mentioned above):
- Taliaferro, Charles, *Contemporary Philosophy of Religion* (Oxford and Malden, Massachusetts: Blackwell, 1998), ch. 9
- Adams, <NAME> and Adams, <NAME> (eds.), *The Problem of Evil* (Oxford and New York: Oxford University Press, 1990)
Taliaferro gives a wide-ranging overview of contemporary approaches, while the Adams' collection contains many of the most important pieces, including a number discussed by Taliaferro.
### 10. Scepticism
Section XII of the *Enquiry* is particularly complex, since as Norton makes clear in Chapter 14 of Millican (2001) it not only discusses a wide range of sceptical positions and arguments, but also makes reference (either implicitly or explicitly) to many other aspects of Hume's philosophy. Any proper understanding of Hume's scepticism must therefore take account of a number of important issues discussed earlier, most notably the relationship between the *Enquiry* and the *Treatise* ([§3c](#3c-humes-life-his-aims-in-the-enquiry-and-its-relation-to-the-treatise)), Hume's argument concerning induction ([§5b](#5b-the-structure-of-humes-argument-concerning-induction) and [§5c](#5c-interpretations-of-hume-on-reason-and-induction)), and his discussions of philosophical and unphilosophical probability ([§6c](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry)), but also his alleged causal realism ([§7c](#7c-causal-realism-and-the-new-hume)) and his religious scepticism ([§9](#9-humes-philosophy-of-religion)).
Though seriously dated in some matters of interpretation, each of the following provides a stimulating discussion of the wide range of issues that arise in this complex section:
- <NAME>, *Hume's Philosophy of Belief* (London: Routledge & Kegan Paul, 1961), ch. 10
- <NAME>, *Hume's Intentions*, 3rd edn. (London: Duckworth, 1980), ch. 7
The most prominent of the topics raised for the first time in *Enquiry* XII are scepticism with regard to the external world and with regard to infinite divisibility. The literature on each of these is sufficiently rich to merit separate consideration before we turn to discuss more general perspectives on Hume's scepticism.
#### 10(a) Scepticism Regarding the External World
The first major sceptical topic in Section XII is the external world - which also incorporates the primary/secondary quality distinction - though this *Enquiry* discussion (E151-5) is drastically scaled down from that in the *Treatise* (T187-231). No doubt for this reason, most commentators have focused almost exclusively on the far more sophisticated *Treatise* account, the interpretation of which poses severe problems not only because of its complexity but also because Hume's ultimate view has proved so elusive. Good presentations of this *Treatise* account have appeared in a number of general books on Hume:
- <NAME>, *Hume* (London and Boston: Routledge & Kegan Paul, 1977), ch. 5
- Noonan, <NAME>., *Hume on Knowledge* (London and New York: Routledge, 1999), ch. 4
- <NAME>, *Hume's System* (Oxford and New York: Oxford University Press, 1990), ch. 10 and 11
- <NAME>, *Hume's Skepticism in the Treatise of Human Nature* (London, Boston and Melbourne: Routledge & Kegan Paul, 1985), chapters 6 and 7
Stroud, whose entire book follows <NAME> in stressing Hume's naturalism in opposition to his scepticism, interprets the discussion of *Treatise* I iv 2 as an attempt to explain the origin of our idea of continued and distinct existence, with the aim of showing that this idea is not innate. The apparently sceptical outcome of the discussion may be unsettling, but again its point is naturalistic, 'to show that reason, as traditionally understood, is not the dominant force in human life' (pp. 116-7). Noonan starts his chapter in a similar spirit, by emphasising the naturalistic purposes of Hume's sceptical arguments, but unlike Stroud he goes on to consider the deeper sceptical problems raised by *Treatise* I iv 4 (concerning the primary/secondary quality distinction, cf. E154-5), and ends with the comment that Hume's sceptical conclusions here undermine his earlier attempt to give a consistent account of the distinction between the principles of the understanding and those of the narrow imagination: 'Thus our common belief in an external world is indubitable, but in no way justified and, being false, incapable of any justification' (p. 186). Pears restricts his attention to *Treatise* I iv 2, dissecting Hume's arguments in detail and blaming his conclusion 'that our belief in body is intellectually indefensible' (p. 196) on an inadequate recognition of the distinction between impressions and physical objects, both in Hume's own view and in that which he attributes to the vulgar. Pears thus interprets Hume as seriously sceptical about (both the tenability and content of) our belief in body even before the primary/secondary quality objection of *Treatise* I iv 4 which according to the *Enquiry* 'goes farther' (E155). Fogelin sees all this scepticism as fundamental to Hume's intentions, taking him to be a committed Pyrrhonian who deliberately aims to highlight irreconcilable differences between the various points of view described in his 'natural history' of philosophy, with none of these providing a stable outcome. (Fogelin very clearly spells out this position - which he calls 'radical perspectivism' - in a later critique of Garrett: 'Garrett on the Consistency of Hume's Philosophy', *Hume Studies* 24 (1998), 161-9.)
Probably the two best-known discussions of these sections of the *Treatise* are:
- <NAME>., *Hume's Theory of the External World* (Oxford: Clarendon Press, 1940)
- <NAME>, *Locke, Berkeley, Hume: Central Themes* (Oxford: Clarendon Press, 1971), ch. 13 and pp. 91-4
Neither of these is particularly scholarly by modern standards, but both are serious and illuminating attempts to address the philosophical issues. Price's book is very dated, relating Hume's views to positions that were influential at the time such as those of Kant, Russell and the logical positivists. However this in itself gives the book a distinctive value, because Price's elegant writing makes its age no obstacle to comprehension, while some parts of Hume's theory (e.g. his claim that perceptions can exist independently) can be usefully illuminated by being put alongside their early twentieth century descendants (e.g. Russell's notion of sensibilia). Bennett's discussion is far shorter, and probably for that reason more intense as he grapples philosophically with Hume's problems in an effort to avoid his apparently despairing conclusion. Though rewarding this makes for difficult reading, but Bennett's views are given a relatively simple critical discussion in an introductory book which also provides its own analysis of Hume's argument:
- <NAME>, *Hume's Epistemology & Metaphysics* (London and New York: Routledge, 1998), ch. 6
Dicker's chapter ends with a sketch of the Kantian response to this form of scepticism, which again will prove useful for students needing a straightforward introduction to a very complex issue.
From the point of view of a student of the *Enquiry*, perhaps the three most thought-provoking recent discussions of Hume's scepticism about the external world are:
- <NAME>, *Hume's Philosophy of Mind* (Edinburgh: Edinburgh University Press, 1980), ch. 1
- <NAME>, *Cognition and Commitment in Hume's Philosophy* (Oxford and New York: Oxford University Press, 1997), ch. 10 especially 209-220
- <NAME>., *The Sceptical Realism of David Hume* (Manchester: Manchester University Press, 1983), ch. 2 and §11
Bricke is unusual in giving serious attention to the *Enquiry* as well as to the *Treatise*, and he provides a careful and philosophically sensitive discussion of both. However he concurs with other commentators in finding Hume's position ultimately unstable, showing sympathy with the perspectival view championed by Fogelin before finally concluding that Hume is himself probably a representative realist, whose sceptical attack on such realism is intended not to refute it outright but only to undermine our confidence in building theories that stray too far from the vulgar perspective. Garrett goes further in attempting to develop a consistent Humean position, based on his view of Hume as primarily a cognitive scientist rather than a sceptical philosopher. He does this by thoroughly downplaying the apparent extreme scepticism which has proved so puzzling for Stroud and other previous commentators in the 'naturalist' tradition: 'Nowhere does Hume claim that most of our beliefs in the existence of continued and distinct existences are unworthy of assent, nor that such beliefs should be rejected or suspended.' (p. 220). This claim involves some delicate interpretation of Hume's statements, some of which superficially appear to tell strongly in the opposite direction. But at least some of this appearance can be explained away, as Wright also does in an account which considers the background to Hume's views in physiological theories of perception deriving in large part from Malebranche. According to Wright, most of Hume's *Treatise* discussion is devoted to explaining - in terms that are at least implicitly physiological - the 'vulgar' belief in external objects that are supposedly identical to our perceptions. *This* belief Hume takes to be clearly false, though it importantly paves the way *psychologically* for representative realism by setting the scene for the 'obvious' argument from sensory variation that is presented most clearly at E152 (cf. T193). Representative realism is thus an example of those 'reflections of common life, methodized and corrected' (E162) which Hume commends, and he can consistently endorse it because its dependence on the false vulgar view is psychological rather than logical. Such realism might seem to be contradicted (as Fogelin and Noonan suppose) by Hume's scepticism concerning the primary/secondary quality distinction. But although this indeed implies that we are unable to conceive distinctly of objects 'specifically different from our perceptions', it does not prevent our forming a bare 'relative idea' of them (T68) and thus maintaining a form of realism even though we lack any distinct conception of the objects concerned. As we have seen in [§7c](#7c-causal-realism-and-the-new-hume) above, this notion of relative ideas also plays a major role in Wright's account of Hume's 'sceptical realism' with regard to causation; indeed it is the similarity between the two cases which provides much of the attraction for his interpretation.
Unfortunately neither Garrett nor Wright says much about Hume's discussion in the *Enquiry*, but both suggest the possibility of a non-sceptical reading. And if, like Garrett, we are prepared to entertain the possibility that some of Hume's statements have an import rather different from their superficial impression, then this may cast new light on, for example, the crucial final paragraph of *Enquiry* XII Part i. This contains both the conditional clause: 'at least, if it be a principle of reason, that all sensible qualities are in the mind, not in the object'; and also a concluding comment that the notion of 'a certain unknown, inexplicable *something*' is 'so imperfect, that no sceptic will think it worth while to contend against it'. These have generally been read in what is probably the most natural way, as respectively *endorsing* the 'principle of reason' and *rejecting* the imperfect notion, but they can be read in a very different way, as *raising a genuine question* about the alleged principle (which fits well with the agnosticism about objects' natures implied by both Garrett and Wright) and as *accepting* the admittedly imperfect notion of an 'unknown, inexplicable *something*'. There is no doubt that Hume was capable of artful composition (as witnessed supremely by his *Dialogues*), but why should he wish to present his views in such an obscure and misleading manner? Perhaps this too can be explained given the context in which he wrote and his purposes in the *Enquiry*. For a prominent theme in British philosophy at the time was the pursuit of metaphysics based on supposed insight into the nature of matter. An accessible discussion of this tradition is in a book by Yolton:
- Yolton, <NAME>., *Thinking Matter* (Minneapolis: University of Minnesota Press, 1983), ch. 5
which particularly singles out <NAME> as an influential exponent of this style of metaphysics, who like others in the tradition maintained the intrinsic inertness of matter as a means of drawing religious conclusions. Hume knew Baxter's work, and it has even recently been argued that Baxter may lie behind the vitriolic attack which, as Stewart explains in Chapter 2 of Millican (2001), ruined Hume's attempt to gain appointment to an Edinburgh chair at just the time when he was writing the *Enquiry*:
- <NAME>, '<NAME> and Hume's *Letter from a Gentleman*', *Hume Studies* 23 (1997), 245-76
In this context, Hume may have seen good reason for stressing the sceptical implications of his arguments concerning matter, so as to wreck the prospects for any attempt to build a solid metaphysics on insight into its nature (which the primary/secondary quality distinction was supposed by some to exemplify). As suggested in §12 of Chapter 4 of Millican (2001), a confused and obscure notion of matter would leave empirical induction as the only remaining basis for scientific progress, a result which seems to harmonise perfectly with the overall intention and design of the *Enquiry* as interpreted in Chapter 1 (see especially the end of that chapter).
Contemporary attacks on scepticism regarding the external world have tended to avoid disputing with Hume on his own ground, preferring to rely on more fundamental objections to the very coherence of the sceptical position. For example both Hookway, and Bell and McGinn (referenced in [§10c](#10c-the-nature-of-humes-scepticism) below) follow Wittgenstein's *On Certainty* in seeing the existence of external objects as a 'framework' judgement presupposed by our thinking, rather than as a potentially questionable factual statement in need of evidential support. Nevertheless there are exceptions to this general trend, in particular two discussions in a Humean spirit, one on each side of the sceptical debate:
- Mates, Benson, *Skeptical Essays* (Chicago and London: Chicago University Press, 1981), ch. 3
- Aune, Bruce, *Knowledge of the External World* (London and New York: Routledge, 1991), especially chapters 3, 6 and 7
Mates engagingly elaborates Humean objections to the external world, concluding that they are ultimately unanswerable. Aune sets out to answer them, based on 'reformed' empiricist principles that in part claim inspiration directly from Hume. At the end of his discussion Aune touches on issues of scientific realism, which are central to modern philosophy of science. To explore these issues further, see:
- <NAME>, *Scientific Realism: How Science Tracks Truth* (London and New York: Routledge, 1999)
Particularly relevant here are Psillos' fourth and ninth chapters. The former provides a defence of 'abduction' or 'inference to the best explanation' which is strongly reminiscent of the 'inductive' justification of induction discussed in [§5d](#5d-inductive-scepticism) above. The latter defends scientific realism against Van Fraassen's 'constructive empiricism' largely on grounds that echo the Humean claim that science is 'nothing but the reflections of common life, methodized and corrected' (E162).
#### 10(b) Scepticism Regarding Infinite Divisibility
Few would argue that Hume's work in the philosophy of mathematics is of great lasting significance, for here his confident and sometimes almost heroic commitment to empiricism leads him to draw conclusions well beyond the bounds of his technical expertise. Confirmation of this assessment can be drawn from the minor role which Hume is given in a relatively accessible guide to the history and philosophy of the infinite (one which ultimately advocates a finitist position, though on Wittgensteinian rather than Humean grounds):
- <NAME>., *The Infinite* (London and New York: Routledge, 1990), especially 80-3, 205
Perhaps not surprisingly, most authors of books on Hume have ignored the topic, a notable exception being Fogelin, who also followed up his book with an article explaining both the proposed proofs of infinite divisibility to which Hume alludes and also his debt to Berkeley's earlier critique:
- <NAME>, *Hume's Skepticism in the Treatise of Human Nature* (London, Boston and Melbourne: Routledge & Kegan Paul, 1985), ch. 3
- Fogelin, Robert, 'Hume and Berkeley on the Proofs of Infinite Divisibility', *Philosophical Review* 97 (1988), 47-69
Fogelin's book concentrates entirely on the *Treatise* and his article says little about the *Enquiry*, whose treatment of infinite divisibility is significantly different. Fortunately a recent paper is able to fill the gap:
- <NAME>, 'Infinite Divisibility in Hume's First *Enquiry*', *Hume Studies* 20 (1994), 219-40
This is one of a number of useful papers on the topic to have appeared recently in *Hume Studies*. Another aims to assess the philosophical value of Hume's contribution:
- <NAME>, 'Achievements and Fallacies in Hume's Account of Infinite Divisibility', *Hume Studies* 20 (1994), 85-101
Though disagreeing with Hume's would-be refutation of infinite divisibility, Franklin is broadly sympathetic even to the extent of maintaining (p. 87) that Hume's conclusions about the discreteness of space are consistent with standard geometry. (For a contrary view see <NAME>, 'Hume on Geometry and Infinite Divisibility in the *Treatise*', *Hume Studies* 23 (1997), 227-44 especially 239-41.) However Franklin is dismissive of Hume's attempts to draw conclusions about space from the nature of our ideas, which he sees as involving the crude fallacy 'it is not conceivable by the human mind, therefore it cannot be.' (p. 93). Hume is defended against this charge of crudeness by:
- <NAME>, 'The Psychologistic Foundations of Hume's Critique of Mathematical Philosophy', *Hume Studies* 22 (1996), 123-67
who finds Hume's argument to be a consistent following-through of his theories of relations and abstraction from *Treatise* Book I Part i and of his Separability Principle. How far all this applies to the *Enquiry* is unclear, since neither the theory of relations nor the Separability Principle figure explicitly in the later work, while the theory of abstraction appears only at E158n, in a role for which it is not used in the *Treatise* (as Jacquette observes). There is work to be done on how far the truncated *Enquiry* account can make sense without the metaphysical commitments of the *Treatise* - whether, for example, the argument at E156n is intended to involve a conclusion beyond what Waxman calls the 'perceptible manifold', in which case the Separability Principle would seem to be required (note that the reference to 'physical points' does not decide this issue in the way that might be expected, given Hume's only other uses of the phrase, at T40 and T112).
#### 10(c) The Nature of Hume's Scepticism
Many discussions of Hume's scepticism draw comparisons between his views and those of the ancient sceptics, either the Pyrrhonists (whose pre-eminent spokesman was Sextus Empiricus) or the Academics (whose doctrines became known primarily through the works of Cicero). The views of both of these schools and their relationship to Hume are outlined in the final chapter of Norton's book, which also provides the basis for some of his discussion in Chapter 14 of Millican (2001):
- Norton, <NAME>, *<NAME>: Common-Sense Moralist, Sceptical Metaphysician* (Princeton and Guildford: Princeton University Press, 1982), 255-69 (on Pyrrhonism) and 269-79 (on Academic scepticism)
Popkin charts the Renaissance rediscovery of Greek scepticism and its influence on subsequent thinkers in his well-known history, which has been largely responsible for the now general appreciation of the sceptical tradition's immense impact on modern thought:
- Popkin, <NAME>., *The History of Scepticism from Erasmus to Spinoza* (Berkeley and London: University of California Press, 1979)
Popkin is also the author of what is probably the best-known discussion of Hume's scepticism, referred to by a number of the works discussed below:
- Popkin, <NAME>., '<NAME>: His Pyrrhonism and his Critique of Pyrrhonism', *Philosophical Quarterly* 1 (1951), 385-407; repr. in V. <NAME> (ed.), *Hume* (London and Melbourne: Macmillan, 1968), 53-98 and in Tweyman (1995), vol. II, 161-87
Although Hume himself in *Enquiry* XII repeatedly describes Pyrrhonism as 'excessive' and criticises it as unlivable (E159-61), Popkin points out that his understanding of it is incomplete, failing to take into account the Pyrrhonian principles---expounded by Sextus Empiricus---of living according to nature and accepting 'evident' appearances undogmatically. However Sextus can still be criticised for not going far enough, and Popkin argues that Hume's position, which goes much further in accepting the natural inevitability of *almost all* our beliefs, is in fact the only consistent development of Pyrrhonism. The Pyrrhonian should admit that both our beliefs and our doubts are determined by nature, and might well vary, according to our mood or situation, quite independently of their epistemological merit. Nature does not allow us to suspend judgement, even about non-evident things, just because a belief is shown to lack rational warrant. So ironically, ancient Pyrrhonism is too dogmatically rationalistic in failing to separate the issue of warrant from that of belief. Popkin believes that Hume is right to criticise it as unlivable, and as a recipe for madness rather than a path to the *ataraxia* (i.e. quietude or unperturbedness) which is its avowed aim. A more detailed discussion of the livability of traditional Pyrrhonism comes to a similar conclusion:
- Burnyeat, <NAME>., 'Can the Skeptic Live His Skepticism?' in Malcolm Schofield, Myles Burnyeat and <NAME> (eds.), *Doubt and Dogmatism* (Oxford and New York: Clarendon Press, 1980), 20-53; repr. in Myles Burnyeat (ed.), *The Skeptical Tradition* (Berkeley and London: University of California Press, 1983), 117-48
Burnyeat starts by criticising Hume for assuming without argument 'that it is impossible to live without reason and belief'. But after a close examination of Sextus' views, including his crucial distinction between belief and merely accepting 'appearances', Burnyeat concludes that this distinction breaks down for 'appearances' that are non-perceptual. The sceptic cannot plausibly deny that *these* 'appearances' - which he himself accepts to be part of a natural life - are epistemic and therefore instances of belief. Living without such beliefs would involve a radical self-detachment which does indeed seem humanly impossible.
The sceptical tradition is given a historically informed though predominantly philosophical treatment by Hookway, who agrees with Popkin in seeing Hume's position as essentially a development of Pyrrhonism, but a development that makes room not only for belief, but also for science:
- Hookway, Christopher, *Scepticism* (London and New York: Routledge, 1990), ch. 5
On Hookway's account, Hume accepts that Pyrrhonian arguments are unanswerable and, like Sextus, rejects 'the propect of achieving an active rational control over our reasonings' (p. 106); instead we must simply yield passively to the beliefs that we naturally find ourselves holding. Hume also follows Sextus in recommending the virtues of detachment from our cognitive faculties on practical grounds, though whereas Sextus sees such detachment---and consequent abandonment of belief and theoretical enquiry---as a route to tranquil *ataraxia*, Hume differs in taking both belief and theoretical enquiry to be part of our nature, so that Pyrrhonian tranquillity is unattainable. The best we can achieve is to make our speculations more tentative, to limit their scope, and - by leaving their most worrying conclusions behind when we quit our study - to prevent them from impinging undesirably on common life. Many similar themes are explored in a rich paper which has as much to say about Hume's scepticism as it does about the *Dialogues* in particular:
- Penelhum, Terence, 'Hume's Skepticism and the *Dialogues*', in <NAME>, <NAME>, and <NAME> (eds.), *McGill Hume Studies* (San Diego: Austin Hill Press, 1979), 253-78; repr. in Tweyman (1995), vol. V, 126-49
Penelhum, like Hookway, sees Hume as advocating a limitation on 'distant and high enquiries' (E162) not on the ground that they are unnatural (for on the contrary, they are all too natural), but rather, to avoid the anxiety that such enquiries can cause. However he finds a major contrast between Hume's response to this problem in the *Treatise* and the *Enquiry* - in the *Treatise*, the damaging effects of excessive scepticism are to be limited by being confined to the study (thus implying the 'on-again-off-again' scepticism which McCormick's paper in [§3c](#3c-humes-life-his-aims-in-the-enquiry-and-its-relation-to-the-treatise) above argues is a misinterpretation), whereas in the *Enquiry*, Hume recommends instead a limitation of subject-matter. The only justification Penelhum can discern for this later limitation is the notion that our cognitive faculties are so imperfect that we should avoid any reliance on them wherever we are able to do so. However he finds this justification objectionably *ad hoc*, for some people might find speculation about theological and metaphysical matters psychologically unavoidable, and as much a part of their nature as more down-to-earth theoretical enquiry. This 'consistency problem' for the mitigated scepticism of the *Enquiry* seems particularly hard to evade if Hume takes theism to be a natural belief, as Penelhum goes on to maintain (though he slightly modifies this view in a later paper - for discussion, see [§9b](#9b-hume-on-the-design-argument) above).
Fogelin answers Penelhum's consistency problem by arguing that Hume does not intend his mitigated scepticism to be *justified* at all -- no such justification could possibly be available, because from a theoretical point of view Hume's scepticism is wholly unmitigated (as demonstrated in particular by his 'scepticism with regard to reason' of *Treatise* I iv 1). Instead, the mitigation is simply a *causal* outcome of our confrontation with Pyrrhonism, in that when we come to appreciate the force of the sceptical arguments, this will naturally have the *effect* of instilling us with modesty, and inducing us to restrict our enquiries in accordance with Hume's recommendation:
- Fogelin, <NAME>., 'The Tendency of Hume's Skepticism', in Myles Burnyeat (ed.), *The Skeptical Tradition* (Berkeley and London: University of California Press, 1983), 397-412
Stroud takes a similar approach, interpreting Hume's mitigated scepticism as 'a state we can find ourselves in, when the reflections leading to excessive scepticism have been tempered or mitigated by our natural inclinations.' (p. 280):
- <NAME>, 'Hume's Scepticism: Natural Instincts and Philosophical Reflection', *Philosophical Topics* 19 (1991), 271-91; repr. in Owen (2000), 471-91
However Stroud emphasises that Hume's mitigated sceptic is not simply the Pyrrhonian slave of nature described by Popkin. An unreflective peasant can equally well live naïvely in accordance with our natural instincts, and what distinguishes the Humean sceptic is a reflective appreciation and acceptance of our subservience to these instincts. Such an acceptance can be an enduring state, very different from the 'on-again-off-again' scepticism seen by Popkin and others as the essence of Hume's scepticism. Moreover this state can lead to something like the *ataraxia* sought by the ancient Pyrrhonians, thus providing a basis for the pragmatic recommendation of Humean philosophy which Stroud finds in the *Treatise* but even more clearly in the *Enquiry* (Sections I, V and XII). This pragmatic theme is developed at greater length by:
- Owen, David, 'Philosophy and the Good Life: Hume's Defence of Probable Reasoning', *Dialogue* 35 (1996), 485-503
- Owen, David, *Hume's Reason* (Oxford and New York: Oxford University Press, 1999), ch. 9 especially 205-6, 211-23
Owen takes very seriously Hume's recommendation in the *Treatise* that since we cannot help pursuing enquiries beyond the realm of common life (a premise which seems in some tension with the mitigated scepticism of the *Enquiry*), 'we ought only to deliberate concerning the choice of our guide, and ought to prefer that which is safest and most agreeable' (T271). Owen interprets Hume's earlier discussions of probable reasoning---and even his apparently approving descriptions of the inferential practices of 'wise' and 'reasonable' people and of 'philosophers'---as having nothing whatever to do with questions of justification or warrant (cf. [§5c](#5c-interpretations-of-hume-on-reason-and-induction) and [§6c](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry) above). They are normative only in the sense of clarifying what 'correct' probable reasoning involves, and it is then a quite different question whether such reasoning is to be preferred to any alternatives (e.g. Roman augury by the inspection of a sacrificed sheep's entrails, which can also be done either 'correctly' or 'incorrectly' -- see Owen's book p. 206). Hume's justification of 'philosophy' comes later and is purely pragmatic, based on the observation that such philosophy is more useful and agreeable than superstition, and therefore conforms to the Humean conception of the virtues. Owen, like Stroud, puts particular weight on Section I of the *Enquiry* in developing his pragmatic interpretation. For a contrasting view, see §4 of Chapter 1 of Millican (2001), which interprets that section as arguing for 'abstruse philosophy' more on the basis of a search after *truth* than a quest for calm.
Most of the works discussed above stress Hume's continuity with the sceptical tradition and with Pyrrhonism in particular. However Hume left his own mark on that tradition, and in summing up this distinctive contribution Hookway (pp. 104-5) emphasises three particular aspects of his thought, namely his emphasis on the irresistibility of belief, his ambition to develop a naturalistic science of man, and his conceptual concern with the limits of our ideas. We have already seen that the first of these plays a central role in several of the works mentioned above, but the second and third have figured less prominently in discussions of his scepticism. However Hume's naturalistic ambitions assume centre stage in a paper which contends that although his *conclusions* were sceptical, his *aims* were not:
- <NAME> and McGinn, Marie, 'Naturalism and Scepticism', *Philosophy* 65 (1990), 399-418
Bell and McGinn argue that Hume's philosophy is intended not so much as a *development* of scepticism as a *rejection* of it, with his fundamental objective being to achieve a naturalistic understanding of our ordinary beliefs that would allow us to see them as entirely legitimate. In the case of induction, they maintain, he succeeds: his account of why we are convinced by causal inferences enables us to see that we are neither absurd nor arbitrary in founding our beliefs on such inferences, and paves the way for a confident endorsement of inductive method. But the anti-sceptical project misfires when Hume's explanation of our belief in the continued and distinct existence of body leads him to the conclusion that this belief is not only unsupported by reason but is actually false, and hence is a belief that we ought not to hold (cf. [§10a](#10a-scepticism-regarding-the-external-world) above). Bell and McGinn therefore interpret the apparent dismay provoked by this result in the *Treatise* (e.g. T217-18, 265-6) as entirely genuine, and not merely a dialectical prelude to a premeditated pragmatic resolution, nor a dramatic wallowing in the excesses of scepticism. However the contrast they draw, between Hume's constructive treatment of causal reasoning on the one hand and his destructive conclusions with regard to the external world on the other, is implicitly contested by Robison, who focuses on the third distinctive feature of Hume's scepticism identified by Hookway, namely its conceptual aspect:
- Robison, <NAME>., '<NAME>: Naturalist and Meta-sceptic', in <NAME> and <NAME> (eds.), *Hume: a Re-evaluation* (New York: Fordham University Press, 1976), 23-49; repr. in Tweyman (1995), vol. V, 36-55
Robison sees the core of Hume's scepticism as involving the realisation that the human mind is *essentially incoherent*: we cannot help applying to our experience various concepts - notably that of continuing objects distinct from our perceptions, and objective necessary connexions between those objects - which his analyses demonstrate to have no legitimate application to it. Even Hume himself, after undertaking these analyses and proving that the concepts in question are illegitimate, cannot help applying them, so there is no philosophical solution to this 'meta-scepticism': all we can do is resort to 'carelessness and inattention' (T218, cf. T268) and ignore the problem. This indeed seems to be Hume's prescription in some relevant parts of the *Treatise*, but obviously such an account fits less comfortably with the *Enquiry*, which ends not on a note of despair, but with a positive endorsement of empirical science within the bounds of a relatively mild mitigated scepticism. However the principal sources of Hume's conceptual scepticism---his Copy Principle, and his attack on the supposed abstract ideas of primary qualities---are still present, so how are we to explain his apparent equanimity in the later work? Assuming that this is not a mere ignoring of inconsistency, we seem to have three main possibilities. The simplest is to follow Stroud in seeing Hume as calmly accepting 'the whimsical condition of mankind' (E160), now that the initial anxiety of his sceptical enquiries in the *Treatise* has subsided. The second is to find ways in which the conceptual scepticism of the *Enquiry* can coexist with that work's endorsement of science; I have tried in §9.2 and §12 of Chapter 4 of Millican (2001) to sketch how such an account might go, accepting the *legitimacy* of causal concepts despite the subjective origin of the relevant idea, and mitigating the negative impact of the confused notion of matter by seeing this confusion as in part a *help* to inductive science (in revealing the lack of any alternative) rather than as a hindrance. The third possibility is to downplay Hume's conceptual scepticism, so that a notion's failure to conform to his theory of ideas remains compatible with that notion's acceptability; as we have already seen in [§7c](#7c-causal-realism-and-the-new-hume) and [§10a](#10a-scepticism-regarding-the-external-world) above, this is the essence of the 'sceptical realism' championed by Wright:
- Wright, <NAME>., 'Hume's Academic Scepticism: A Reappraisal of His Philosophy of Human Understanding', *Canadian Journal of Philosophy* 16 (1986), 407-35; repr. in Tweyman (1995), vol. II, 222-47 and in Owen (2000), 303-31
Wright forcefully rejects Popkin's Pyrrhonist interpretation, arguing that Hume's writings in fact exemplify only one prominent Pyrrhonist theme, namely the conflict between our natural judgements (the 'noumena') and the way things appear to us (the 'phenomena', including the nature of our impressions and ideas). In other respects---his denial that suspension of belief is possible or that it would lead to tranquillity, his quest for a science of man, and his approval of probabilities---Hume leans instead towards Cicero's 'academic' scepticism, a tendency which becomes fully explicit in the *Enquiry*. All of these threads come together in Hume's account of how the imagination leads us mechanically to accept probable beliefs and to make natural judgements beyond the realm of our ideas. These natural judgements include the inconceivable 'suppositions' of causal power and external existence, which Wright discusses briefly in this article but at much greater length in his book (see [§7c](#7c-causal-realism-and-the-new-hume) and [§10a](#10a-scepticism-regarding-the-external-world) above).
Leaving aside the specific topics of induction and the external world ([§5d](#5d-inductive-scepticism) and [§10a](#10a-scepticism-regarding-the-external-world) above), most contemporary discussions of scepticism have moved far from specific Humean concerns. Hookway's book mentioned above provides a useful general overview, but says relatively little about some specific issues that have recently come to prominence, such as Putnam's semantic externalism (which can ground an argument from the theory of reference that some sceptical claims can be meaningful only if they are false) and Goldman's reliabilism (which can be used to deny the inference from 'internalist' doubt to lack of knowledge -- see Costa's paper in [§6c](#6c-probability-and-rationality-in-the-treatise-and-the-enquiry) above for the suggestion that such reliabilism has roots in Hume's own thought). These developments, and others, are explored from a variety of perspectives in:
- DeRose, Keith and Warfield, <NAME>., *Skepticism: A Contemporary Reader* (Oxford and New York: Oxford University Press, 1999)
Particularly helpful is DeRose's introduction, which briefly sketches the issues and thus provides a context for the subsequent papers together with a summary of their main themes.
---
### Endnotes
1. <a id="endnote1"></a>In his note on the text (p.80) Beauchamp calls it 'a major and unexplained deletion', thereby perhaps suggesting doubt regarding its authority. My own view is that the deletion was entirely judicious, and totally in line with the sort of streamlining outlined in §6 of Chapter 1 of Millican (2001) on 'The Context, Aims, and Structure of Hume's First *Enquiry*'.
2. <a id="endnote2"></a>The *Dissertation on the Passions*, like most of Hume's other works, is available in *The Philosophical Works of <NAME>* edited by <NAME> and <NAME>, 4 vols. (London: Longmans, 1882-6), which has recently been reprinted in facsimile (Bristol: Thoemmes, 1996). Like other works the *Dissertation* is also destined to appear in the Clarendon Hume series of critical editions from Oxford University Press. In the meantime, the best practical source for Hume's more obscure works is probably the InteLex electronic edition mentioned in [§1b](#1b-electronic-editions) above.
3. <a id="endnote3"></a>Houston's book has yet to receive a substantial answer, and he efficiently dismisses the various Humean responses that he himself considers. Hence it may be helpful to suggest some other possible lines of reply. One response to his primary criticism may be implicit in Hume's comment that 'it is impossible for us to know the attributes or actions of such a Being [i.e. God], otherwise than from the experience which we have of his productions, in the usual course of nature. This still reduces us to past observation, and obliges us to compare the instances of the violation of truth in the testimony of men, with those of the violation of the laws of nature by miracles, in order to judge which of them is most likely and probable.' (E129). Thus the postulation of divine intentions that go beyond what is manifest in common experience will be gratuitous (a message spelt out explicitly in *Enquiry* XI), undermining any attempts to use the theistic hypothesis to go further than the conclusions of ordinary induction from experienced regularities. Development of this debate is likely to move beyond the single issue of miracles to the general explanatory value of a theistic world-view (including the Problem of Evil), somewhat confirming the moral drawn by both Swinburne and Houston. Houston's secondary objection is less fundamental, for although his logical point is well made, from a Humean point of view it remains plausible that inductive evidence for the reliability of *any* testimony can never exceed the evidence for a law of nature.
© <NAME> 2000
<file_sep>/scholarship/links.md
---
layout: scholarship
subsection: links
---
## Links to Other Hume Resources on the Web
### "Translations" into Modern English
The eminent philosopher and scholar <NAME>---at his excellent site [www.earlymoderntexts.com](http://www.earlymoderntexts.com)---has undertaken the translation of several of Hume's texts into modern English. These translations preserve much of the style of the originals, and their argumentative structure, but replace the eighteenth century words and phrases that can cause serious difficulty for non-specialist readers. The complete files are downloadable as PDFs, and can be found here:
- [www.earlymoderntexts.com/authors/hume](http://www.earlymoderntexts.com/authors/hume)
### Miscellaneous Hume Links
- [The Hume Society](http://www.humesociety.org) - the international society for scholars of <NAME>
- [*Hume Studies*](http://www.humestudies.org) - the scholarly journal for publication about Hume
_We would be glad to receive suggestions for other high-quality sites to which we might helpfully link. Unfortunately, it seems that many previously useful sites are now no longer functional, or else contain a high proportion of outdated references._
<file_sep>/texts/pld/bp.md
---
layout: texts
text: 'BP'
parent: 'PLD'
essay: 6
tab: 'text'
---
<file_sep>/texts/pld/ps.md
---
layout: texts
text: 'PS'
parent: 'PLD'
essay: 11
tab: 'text'
---
<file_sep>/notes/history.md
---
layout: notes
subsection: history
---
## History of this Site
_by <NAME>_
The "Leeds Hume Project" began in May 2000, when as Senior Lecturer in Computing and Philosophy at the University of Leeds, I was working on the [Critical Survey of the Literature]({{ site.baseurl }}{% link scholarship/ehusurvey.md %}) for my book [Reading Hume on Human Understanding](http://humesociety.org/hs/issues/v30n1/falkenstein/falkenstein-v30n1.pdf), which would appear in 2002. I had already produced the first accurate public-domain electronic edition of the *Enquiry Concerning Human Understanding*, and was well aware of the poor quality of other editions. Now, searching through secondary literature for the Critical Survey (with several visits to the Oxford libraries and the British Library at Boston Spa for relatively obscure pieces), it became clear that some excellent material---for example in out-of-print books or defunct journals---was inaccessible to the vast majority of scholars. So I thought it would be a good idea to develop an online Hume archive combining high quality primary and secondary materials, with the crucial virtue of _permanence_ so that academics could safely refer to these resources in scholarly works and student reading lists. This ambition is fully spelled out in the home page of the [Leeds Hume Project]({{ site.baseurl }}{% link notes/leedshume.md %}) from July 2001.
After the 2002 book was completed, pressure of other research and teaching obligations made progress slow, and although the Leeds Electronic Text Centre that I had founded was established as an independent unit in 2003 (having previously been part of the School of Computing), other funding-related projects took priority over the envisaged Hume Project. Then in 2005, I was appointed as <NAME>ellow at Hertford College, Oxford, and accordingly moved the project from the Leeds webserver to a new site on the domain *davidhume.org*, purchased with a view to securing an appropriate permanent home. Then three years later, in July 2008---by chance---a vacancy in the Leeds Electronic Text Centre became available, just when <NAME>, who had studied Hume as a postgraduate under my supervision, had completed his Oxford B.Phil. With a strong background in IT and a serious interest in electronic texts, Amyas was appointed to fill the vacant position on a part-time basis, and at the same time commenced a part-time doctorate on Hume, while to facilitate this I agreed to play the role of informal supervisor on behalf of my old department (on an *ex gratia* basis). Since then we have worked together on the site, making relatively rapid progress on the texts while also (thanks mainly to Amyas's energy and quick learning) developing sophisticated techniques for web presentation. We are both fully committed to the original goal of permanence for *davidhume.org*, and I am delighted that Amyas's involvement looks set to ensure its continuation for at least another generation.
<file_sep>/texts/empl2/bt.md
---
layout: texts
text: 'BT'
parent: 'EMPL2'
essay: 5
tab: 'text'
---
<file_sep>/texts/n/5.md
---
layout: 'texts'
text: 'N.5'
tab: 'text'
---
<file_sep>/texts/h/40.md
---
layout: texts
text: 'H.40'
tab: 'text'
---
<file_sep>/texts/empl1/se.md
---
layout: texts
text: 'SE'
parent: 'EMPL1'
essay: 10
tab: 'text'
---
<file_sep>/texts/n/13.md
---
layout: 'texts'
text: 'N.13'
tab: 'text'
---
<file_sep>/texts/empl1/pd.md
---
layout: texts
text: 'PD'
parent: 'EMPL1'
essay: 19
tab: 'text'
---
<file_sep>/texts/emp/ep.md
---
layout: texts
text: 'Ep'
parent: 'EMP'
essay: 21
tab: 'text'
---
<file_sep>/texts/m/7.md
---
layout: 'texts'
text: 'M.7'
tab: 'text'
---
<file_sep>/texts/pld/pa.md
---
layout: texts
text: 'PA'
parent: 'PLD'
essay: 10
tab: 'text'
---
<file_sep>/texts/empl1/st.md
---
layout: texts
text: 'ST'
parent: 'EMPL1'
essay: 23
tab: 'text'
---
<file_sep>/texts/empw/ew.md
---
layout: 'texts'
text: 'EW'
parent: 'EMPW'
tab: 'text'
---
<file_sep>/_includes/notes/mol.md
## My Own Life (1777)
_prepared by <NAME>_
Written in the year of his death, when Hume was aware of the seriousness of his terminal illness, this was sent to his printer <NAME> for inclusion in the forthcoming final edition of Hume's works, but in the event was published separately in 1777. This text is taken from the original publication, with a few small corrections made by comparison with Hume's handwritten manuscript in the National Library of Scotland. Hume's story of his life is certainly selective (for example it contains no mention of the distasteful quarrel with Rousseau), and his aim seems to be to leave to posterity an appropriate impression of calm philosophical detachment. For a sensitive discussion of the nuances of the piece, see <NAME>, *The Moral Animus of David Hume* (Associated University Presses, 1990), chapter 5.
<file_sep>/texts/m/app3.md
---
layout: 'texts'
text: 'M.App3'
tab: 'text'
---
<file_sep>/texts/h/2.md
---
layout: texts
text: 'H.2'
tab: 'text'
---
<file_sep>/texts/empl1/ip.md
---
layout: texts
text: 'IP'
parent: 'EMPL1'
essay: 6
tab: 'text'
---
<file_sep>/texts/empl1/tr.md
---
layout: texts
text: 'Tr'
parent: 'EMPL1'
essay: 22
tab: 'text'
---
<file_sep>/texts/empl2/ipc.md
---
layout: texts
text: 'IPC'
parent: 'EMPL2'
essay: 16
tab: 'text'
---
<file_sep>/texts/empl1/ep.md
---
layout: texts
text: 'Ep'
parent: 'EMPL1'
essay: 15
tab: 'text'
---
<file_sep>/_includes/notes/t.md
## A Treatise of Human Nature (1739-40)
_prepared by <NAME> and <NAME>_
Though relatively unsuccessful in its own time, Hume's first publication, the *Treatise of Human Nature*, is now widely considered to be a philosophical masterpiece, and it is this work more than any other that has earned Hume his well-deserved reputation as the greatest English-speaking philosopher.
The text here is taken from a scanned copy of the original edition held at Eighteenth Century Collections Online (ECCO). Departures from this copytext, aside from those common to all texts on this site, are as follows:
### 1. ERRATA changes
The original edition came with two ERRATA sheets, one for volumes 1 and 2, and another for volume three. All the changes listed here have been incorporated into our edited text. In a few cases, the page numbers for these changes are wrong, but it is never difficult to find the intended page. For example, one instruction for volume 1 is to delete the word "with" at line 17 of page 24, where that word does not occur. Instead, we have deleted the word "with" at line 17 of page 34, which looks like an obvious candidate for deletion.
### 2. Appendix changes and additions
Volume 3 included an Appendix with instructions for some changes and additions to volume 1. The changes are small (much like those in the ERRATA sheets), while the additions consist of some extra footnotes and paragraphs. Both the changes and the additions have been incorporated into the edited text of volume 1, and removed from the Appendix itself. It is debatable whether the additions, which are quite substantial, should be included in the text of volume 1. Selby-Bigge did not include them; Norton and Norton did, but clearly marked them inline as such. We have elected to include them in our edited version, so as to give the reader as many options as possible: in the original text, they are not present; in the edited text, they are incorporated as Hume instructed; in the edited text with changes shown, they can be clearly seen for what they are.
### 3. Handwritten changes
The scan of volume 3 on ECCO is of the copy held at the British Library, which contains several written changes in Hume's hand. We have incorporated these into our edited text. Where they are illegible, owing to the quality of the scan, Nidditch's textual notes to the revised Selby-Bigge edition have been consulted.
### 4. Cross references
For the reader's convenience, Hume's cross references to other parts of the *Treatise* have been embellished with paragraph numbers or section titles in square brackets.
### 5. Footnotes
There is one anomaly to be noted regarding the footnotes of the *Treatise*. As with all the texts on this site, Hume's footnote markers have been converted to numbers. For ease, the numbers for the *Treatise* footnotes here correspond to those in the Oxford Philosophical Texts edition (edited by <NAME> and <NAME>, OUP, 2000). Norton and Norton delete a note at T 2.2.7.6. Hume instructed that this note be replaced by note 22 (at T 1.3.9.19) while the first two volumes of the *Treatise* were in press. We have retained both notes, but so as not to upset the numbering, the note at T 2.2.7.6 has not been given a number; its marker remains an asterisk, as in the original. Since it is the only footnote in the *Treatise* with this marker, there is no risk of ambiguity.
### 6. Other editorial changes
Unlike his later works, for which there are several editions that were carefully polished over time, the single edition of Hume's *Treatise* contains a number of errors, even after the ERRATA sheet, Appendix, and handwritten changes are taken into account. These include misplaced or incorrect punctuation, spelling mistakes (that look like typographical errors rather than standard variant or old-fashioned spellings), noun and verb pairs that do not agree in number, and also some more substantial errors that change the sense. In many of these cases (especially those of the last kind), it is of course a matter of judgement whether it is indeed an error, and whenever in doubt we have erred on the side of conservatism. Where we have made a change, we have looked for similar phrasing elsewhere in the *Treatise* and, in the case of Book 2, in the *Dissertation on the Passions*, matching these things where possible.
<file_sep>/assets/js/hume.js
---
---
import jump from './jump.js?v={{ site.version }}'
import * as search from './search.js?v={{ site.version }}'
import * as session from './session.js?v={{ site.version }}'
import * as view from './view.js?v={{ site.version }}'
// setup event listeners for toggles
Array.from(document.querySelectorAll('[data-toggle]')).forEach((element) => {
element.addEventListener('click', (e) => { view.toggle(e.currentTarget) })
})
// setup event listeners for tabs
Array.from(document.querySelectorAll('[data-tab]')).forEach((element) => {
element.addEventListener('click', (e) => { view.tab(e.currentTarget) })
})
// setup inputs bound to session variables
Array.from(document.querySelectorAll('[data-session]')).forEach((input) => {
input.addEventListener('change', (e) => { session.toggle(input.dataset.session) })
})
// setup jump form
const jumpForm = document.getElementById('jump-form')
const jumpInput = document.getElementById('jump-input')
if (jumpForm) {
jumpForm.addEventListener('submit', (e) => {
e.preventDefault()
if (jumpInput.value.length > 0) jump(jumpInput.value)
})
}
// setup search form
const searchForm = document.getElementById('search-form')
const subSearch = document.getElementById('sub-search')
const query = document.getElementById('search-input')
const summary = document.getElementById('summary')
const hits = document.getElementById('hits')
if (searchForm) {
// keep reference to previous results around for future sub searches
let results
// define search function
const doSearch = (newSearch) => {
if (query.value.length > 0) {
session.set('last-query', query.value)
summary.innerHTML = 'Searching...'
hits.innerHTML = ''
view.activate('results')
if (newSearch) {
search.newSearch(query.value).then((r) => {
results = r
showSearchResults(results)
})
} else {
results = search.subSearch(query.value, results)
showSearchResults(results)
}
}
}
// define function for displaying search results
const showSearchResults = (results) => {
summary.innerHTML = `Search query matched ${results.length} paragraphs.`
hits.innerHTML = results.map(search.display.bind(null, query.value)).join('')
subSearch.style.display = 'block'
try {
session.set('summary-html', summary.innerHTML)
session.set('hits-html', hits.innerHTML)
} catch (ignore) {
summary.innerHTML += '<br><br><strong>Note:</strong> There are too many results to be saved in this session; leaving this page will clear your results.'
session.set('last-query', null)
session.set('summary-html', null)
session.set('hits-html', null)
}
}
// setup new search
searchForm.addEventListener('submit', (e) => {
e.preventDefault()
doSearch(true)
})
// setup sub search
subSearch.addEventListener('click', (e) => {
e.preventDefault()
doSearch(false)
})
// show results of last search when the page first loads
if (session.get('last-query')) {
query.value = session.get('last-query')
summary.innerHTML = session.get('summary-html')
hits.innerHTML = session.get('hits-html')
view.activate('results')
}
}
<file_sep>/scholarship/bibliographies.md
---
layout: scholarship
subsection: bibliographies
---
## Hume Bibliographies
This section is intended to provide links to useful bibliographic resources on Hume; not mere lists of publications, but helpfully _annotated_ bibliographies. Hume scholars are enthusiastically invited to suggest additions to the page.
### <NAME>'s *Critical Survey of the Literature on Hume and the First Enquiry*
- [*Critical Survey*, First Edition (2000)]({{ site.baseurl }}{% link scholarship/ehusurvey.md %})
Please note that a later version of the *Critical Survey* is in Peter Millican (ed.), *Reading Hume on Human Understanding* (Oxford University Press, 2002)
<file_sep>/texts/empl2/bp.md
---
layout: texts
text: 'BP'
parent: 'EMPL2'
essay: 7
tab: 'text'
---
<file_sep>/texts/a/notes.md
---
layout: 'texts'
text: 'A'
tab: 'notes'
notes: true
---
{% include notes/a.md %}
<file_sep>/texts/l/index.md
---
layout: 'texts'
text: 'L'
tab: 'text'
notes: true
---
<file_sep>/texts/etss/index.md
---
layout: texts
text: 'ETSS'
tab: 'text'
contents: true
notes: true
---
<file_sep>/texts/empw/im.md
---
layout: 'texts'
text: 'IM'
parent: 'EMPW'
tab: 'text'
---
<file_sep>/_includes/notes/a.md
## Abstract of the Treatise (1740)
_prepared by <NAME>_
The *Abstract*, now generally agreed to have been composed by Hume himself, was published anonymously in March 1740 in an attempt to promote and explicate Books 1 and 2 of the *Treatise of Human Nature*, which had been published in January 1739. A valuable resource with elegant and concise presentations of some of Hume's principal arguments, it also indicates which of them he took to be most central and important to his philosophical project. It is striking and significant that the structure, focus, and ordering of the *Abstract*, though ostensibly following the "Chief Argument" of the *Treatise*, actually bears much closer resemblance to a quite different work, the first *Enquiry*, which was still eight years away. For detailed discussion of this matter, setting it in a wider context, see my essay "The Context, Aims, and Structure of Hume's First Enquiry" (chapter 1 of Peter Millican, ed., *Reading Hume on Human Understanding*, OUP, 2002).
The text here is taken from the original 1740 edition. Some alterations have been made to the copytext, in line with some comments in Hume's hand made on a copy held at the British Library.
<file_sep>/notes/copytexts.md
---
layout: notes
subsection: copytexts
---
## Copytexts
In selecting the copytexts for the editions on this site, our general rule is to go with the latest edition that Hume worked on, which in some cases means a posthumous edition that he was preparing shortly before his death. The full list for individual works is given below. Unless otherwise stated below, the particular copy is the scan held at *Eighteenth Century Collections Online*.
Note that some of Hume's works (his essays and dissertations) are presented here more than once, in the *context* of different editions. This is to give a sense of when his works were first published, and how they were differently arranged at different times. The *content* of each work, however, is always the same, reflecting Hume's final polished version.
### 1. List of Editions
The copytexts for the *Treatise of Human Nature* and the *Abstract* of the *Treatise* are the only editions that Hume published (1739 for volumes 1 and 2 of the *Treatise*, 1740 for volume 3 and the *Abstract*).
The copytext for the two *Enquiries*, the *Natural History of Religion*, the *Dissertation on the Passions*, and all of the essays that appeared in this edition, is the posthumous 1777 edition of the *Essays and Treatises on Several Subjects*. The copytext for the *History of England* is the posthumous 1778 edition. Hume was working on these two editions until his death in 1776.
The copytexts for *My Own Life* and the *Dialogues Concerning Natural Religion* are the (first) posthumous publications of 1777 and 1779 respectively.
The copytext for the two essays *Of Suicide* and *Of the Immortality of the Soul* is the proof copy of the *Four Dissertations* held in the National Library of Scotland (this collection was to include these scandalous essays, before Hume suppressed them and supplied the essay *Of the Standard of Taste* in their place). The posthumous 1777 publication departs from this proof in a handful of ways---notably in the absence of several paragraph breaks---and there is no evidence that these changes were ever sanctioned by Hume.
The copytext for the remaining essays---i.e. those published in earlier collections, but withdrawn from the 1777 edition of the *Essays and Treatises*---is in each case the _latest_ published version.
### 2. Explanation of this Selection
The only potentially controversial decision here is the selection, for all of the texts contained within it, of the 1777 edition of the *Essays and Treatises*, rather than the 1772 edition of the same. Hume took great pains over correcting his texts, and there is no doubt that these last two editions are the most authoritative. The 1777 incorporates some corrections made shortly before his death in 1776 (e.g. a substantial deletion from section 3 of the first *Enquiry*, and a new paragraph added near the end of section 3 of the *Dissertation on the Passions*), and has traditionally been taken as the copytext of choice. The Green and Grose edition of Hume's collected works follows this edition, as does Selby-Bigge's edition (later re-edited by Nidditch) of the two *Enquiries*. Miller's edition of the *Essays, Moral, Political, and Literary* does likewise.
Beauchamp, however, in his recent critical editions of the two *Enquiries*, the *Natural History of Religion*, and the *Dissertation on the Passions*, has preferred the 1772 edition, on the grounds that this was "the last edition to be seen through the press with Hume's supervision". While not disputing Beauchamp's general editorial principles and practice (which included properly consulting the 1777 text "for evidence of late authorial changes", p. cv), we have reverted here to the traditionally preferred 1777 edition, in accordance with Hume's own expressed satisfaction with his final editorial changes. This also usefully remedies the lack hitherto of a genuinely reliable published text of the second volume of that edition. (Miller's edition of the *Essays* is excellent, a considerable improvement on the Green and Grose. Selby-Bigge's edition of the two *Enquiries*, however, contains numerous errors (running into thousands), as do the texts of the *Natural History of Religion* and the *Dissertation on the Passions* in the Green and Grose.)
### 3. Volume Breaks
Hume's larger works (the *Treatise* and the *History*) and his collection of *Essays and Treatises* were printed in multi-volume editions. In the case of the *Treatise* and the *History*, this was partly because they were published in stages, but in any case practical printing constraints favoured smaller volumes. Since we have no such constraints, and since the volume breaks are of no intrinsic interest, they are for the most part not reflected in the editions on this site.
The exception to this rule is the *History of England*, which---with its 71 chapters and four appendices---is rather unwieldy as a continuous block, and has therefore been divided up here into six volumes. The 1778 copytext was printed in eight volumes, but this was an economic necessity and does not reflect the structure of the work. Structurally, the work divides into three parts, each further divided here into two volumes. These volume breaks correspond to those that appeared in the first editions that Hume published of each part; it was only when the work was completed that its chapters needed to be redistributed awkwardly among eight volumes.
<file_sep>/texts/n/4.md
---
layout: 'texts'
text: 'N.4'
tab: 'text'
---
<file_sep>/texts/pld/pc.md
---
layout: texts
text: 'PC'
parent: 'PLD'
essay: 8
tab: 'text'
---
<file_sep>/notes/index.md
---
layout: notes
subsection: notes
---
## Notes
*Hume Texts Online* is a free and open access collection of works by the great Enlightenment thinker, <NAME>, together with bibliographies and links to Hume scholarship on the web. The site is developed and maintained by [<NAME>](http://www.merivale.uk), and the texts are edited by [<NAME>](http://www.merivale.uk) and [<NAME>](http://www.millican.org).
The site includes every philosophical text that Hume published, in accurate editions that faithfully represent the original 18th century publications, but without neglecting the advantages of modern online texts. Hume scholars will find, we hope, everything that they would expect from a modern edition, such as standard footnote and paragraph numbers, page numbers for the most frequently cited editions, and some minimal editing in cases of clear error, or for changes sanctioned by Hume himself (in ERRATA sheets or modifications in his own hand on some original copies).
Thanks to the [National Library of Scotland](http://www.nls.uk/) and the [Royal Society of Edinburgh](http://www.royalsoced.org.uk/), we are also able to reproduce here high-quality digital images of Hume's manuscript of the *Dialogues concerning Natural Religion*. These pages are made available alongside the text of the first posthumous 1779 edition.
<file_sep>/texts/emp/sh.md
---
layout: texts
text: 'SH'
parent: 'EMP'
essay: 7
tab: 'text'
---
<file_sep>/scholarship/index.md
---
layout: scholarship
subsection: scholarship
---
## David Hume Scholarship
_Work by the creators of this website (Prof. <NAME> and Dr <NAME>) is collected here, and we also store a few other papers that are hard to obtain elsewhere, so as to make them easily available to Hume scholars. Please contact us if you have recommendations for other papers that could usefully be added to this collection (subject to appropriate copyright agreements)._
- [<NAME>'s Books, Papers, and Talks on Hume]({{ site.baseurl }}{% link scholarship/merivale.md %})
- [<NAME>'s Papers and Talks on Hume]({{ site.baseurl }}{% link scholarship/millican.md %})
- [Various Other Papers on Hume]({{ site.baseurl }}{% link scholarship/other.md %})
### General Sources of Papers on Hume
- [_PhilPapers_ section on Hume](http://philpapers.org/browse/david-hume)
- [<NAME>almers' catalogue of 17th and 18th century scholars](http://consc.net/people.html#british)
- [_Hume Studies_ (Journal)](http://humestudies.org)
<file_sep>/texts/h/vol4/full.md
---
layout: texts
text: 'H.Vol4'
tab: 'text'
---
<file_sep>/texts/e/3.md
---
layout: 'texts'
text: 'E.3'
tab: 'text'
---
<file_sep>/texts/empl1/pgb.md
---
layout: texts
text: 'PGB'
parent: 'EMPL1'
essay: 9
tab: 'text'
---
<file_sep>/_includes/notes/empl.md
## Essays, Moral, and Political, and Literary (1741, 1777)
_prepared by <NAME>_
Disappointed with the poor reception of his *Treatise*, Hume turned to the essay style of writing, and published the first volume of his *Essays, Moral and Political* in 1741, with a second volume following in 1742. Following the success of this collection, Hume published three additional essays in 1748 (*Of National Characters*, *Of the Original Contract*, and *Of Passive Obedience*), and then a third edition of the set, also in 1748, that incorporated these three.
At the start of the 1750s, Hume's reputation as an essay writer was well-established, and his new set of *Political Discourses*, published in 1752, was so successful that a second edition was brought out in the very same year. A third edition was printed in 1754.
In 1758, Hume collected all of his late works together in a collection of *Essays and Treatises on Several Subjects*, the first volume of which contained the *Essays, Moral and Political* followed by the *Political Discourses*. Now, however, the two sets were titled *Essays, Moral, Political, and Literary* parts 1 and 2.
The texts of all of the essays on this site are taken from the 1777 edition of the *Essays and Treatises on Several Subjects*, with the following exceptions: *Of Essay-Writing*, *Of Moral Prejudices*, and *Of the Middle Station of Life* only ever appeared in the 1742 edition of the *Essays, Moral and Political*, and the texts of these are therefore taken from that edition. *Of Impudence and Modesty*, *Of Love and Marriage*, and *Of the Study of History* last appeared in the 1760 edition of the *Essays and Treatises*, and the texts of these are therefore taken from that edition. *Of Avarice* and *A Character of <NAME>* last appeared in the 1768 edition of the *Essays and Treatises*, and the texts of these are therefore taken from that edition. *A Character of <NAME>* first appeared as an essay by itself, but in editions of Hume's essays from 1748 to 1768, it appeared as a footnote at the end of the essay *That Politics may be Reduced to a Science*; from 1770 onwards this note was dropped. The text here is a reproduction of the footnote in the 1768 edition of *That Politics may be Reduced to a Science* (though the text of _that_ essay, note, is taken from the 1777 edition, and therefore does not contain the footnote).
<file_sep>/texts/etss/notes.md
---
layout: 'texts'
text: 'ETSS'
tab: 'notes'
notes: true
---
{% include notes/etss.md %}
<file_sep>/texts/h/vol6/index.md
---
layout: texts
text: 'H.Vol6'
tab: 'text'
contents: true
fulltext: true
---
<file_sep>/texts/empl1/sc.md
---
layout: texts
text: 'Sc'
parent: 'EMPL1'
essay: 18
tab: 'text'
---
<file_sep>/texts/t/0.md
---
layout: 'texts'
text: 'T.0'
tab: 'text'
---
<file_sep>/texts/h/46.md
---
layout: texts
text: 'H.46'
tab: 'text'
---
<file_sep>/texts/empl2/ps.md
---
layout: texts
text: 'PS'
parent: 'EMPL2'
essay: 15
tab: 'text'
---
<file_sep>/texts/emp/se.md
---
layout: texts
text: 'SE'
parent: 'EMP'
essay: 12
tab: 'text'
---
<file_sep>/scholarship/millican.md
---
layout: scholarship
subsection: scholarship
---
## <NAME>'s Papers and Talks on Hume and Early Modern Philosophy
[<NAME>](http://www.millican.org) is <NAME> Fellow and Professor of Philosophy at [Hertford College](http://philosophy.hertford.ox.ac.uk/index.htm), [University of Oxford](http://www.ox.ac.uk/). He is a member of both the Oxford Faculties of Philosophy and Computer Science. From 1985 until 2005 he lectured in Philosophy and Computing at the [University of Leeds](http://www.leeds.ac.uk), where he founded the Electronic Text Centre and started the "Leeds Hume Project" from which **davidhume.org** developed. In 2005 he moved to Oxford University, and from 2005 until 2010 he was Co-Editor of the journal [Hume Studies](http://www.humestudies.org).
_(Please note that this page is under continuous development, and makes no claim to completeness. In particular, I have not yet made any attempt to include unpublished talks beyond 2011, though I hope to do so before too long. Some earlier items are listed but not yet included on the website, usually because they have proved hard to track down. For a selection of papers on other topics - e.g. Ethics, Philosophy of Computing, Philosophy of Language, Philosophy of Religion - please go to [PAPERS ON OTHER TOPICS](http://www.millican.org/research.htm).)_
Most of these files are in "PDF" form, to maintain platform independence. Any PowerPoint slides have been reduced to six or twelve per page, and are available in both a colour and a greyscale form (the former for viewing, the latter for printing).
### 2021
- ["Hume's Pivotal Argument, and His Supposed Obligation of Reason"]({{ site.baseurl }}{% link scholarship/papers/millican/2021_Hume's_Pivotal_Argument.pdf %}), *Hume Studies* 44, pp. 167-208
- ["Hume on Modality"]({{ site.baseurl }}{% link scholarship/papers/millican/2021_Hume_on_Modality.pdf %}), forthcoming in <NAME> and <NAME> (eds), *The Routledge Handbook of Modality*, Routledge, 2021
### 2020
- ["The Relation between Hume's Two Enquiries"]({{ site.baseurl }}{% link scholarship/papers/millican/2020_Hume's_Two_Enquiries.pdf %}), in <NAME> (ed.), *Reading Hume on the Principles of Morals*, Oxford University Press, pp. 273-99
### 2019
- ["What Hume Really Thought about Causation"]({{ site.baseurl }}{% link scholarship/papers/millican/2019_Hume_Causation_Cambridge_Handout.pdf %}) – handout, *Cambridge Moral Sciences Club* (November)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2019_Hume_Causation_Cambridge_ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2019_Hume_Causation_Cambridge_ppt_grey.pdf %})
- ["Hume on the Will, and on Free Will"]({{ site.baseurl }}{% link scholarship/papers/millican/2019_Hume_on_the_Will_ppt.pdf %}), colour slides, *"Recasting the Treatise" Workshop on Book 2*, Oxford (March)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2019_Hume_on_the_Will_ppt_grey.pdf %})
### 2018
- ["Hume's Decisive Turn Away From Egoism"]({{ site.baseurl }}{% link scholarship/papers/millican/2018_Hume's_Decisive_Turn_From_Egoism.pdf %}), *Hume Conference*, Budapest (July)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2018_Hume's_Decisive_Turn_ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2018_Hume's_Decisive_Turn_ppt_grey.pdf %})
### 2017
- ["Defending the Common-Core/Diversity Dilemma: One Author's Reply to <NAME>, Lukasiewicz, Moser, Oppy, Salamon, Senor, Taliaferro & Porot"]({{ site.baseurl }}{% link scholarship/papers/millican/2017_EJPR_Reply.pdf %}), *European Journal for Philosophy of Religion* 9, pp. 81-106
- ["Hume's Fork, and His Theory of Relations"]({{ site.baseurl }}{% link scholarship/papers/millican/2017_Hume's_Fork.pdf %}), *Philosophy and Phenomenological Research* 95, pp. 3-65
- ["Why Hume Disowned His Treatise of Human Nature"]({{ site.baseurl }}{% link scholarship/papers/millican/2017_Edinburgh_Disowning_Treatise_ppt.pdf %}), colour slides, *Scottish Seminar in Early Modern Philosophy*, Edinburgh (April)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2017_Edinburgh_Disowning_Treatise_ppt_grey.pdf %})
- ["Hume's Miracle Maxim: Where It's Right and Where It's Wrong"]({{ site.baseurl }}{% link scholarship/papers/millican/2017_Hume's_Miracle_Maxim_ppt.pdf %}), colour slides, Singapore National University (April)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2017_Hume's_Miracle_Maxim_ppt_grey.pdf %})
### 2016
- ["Hume's Chief Argument"]({{ site.baseurl }}{% link scholarship/papers/millican/2016_Hume's_Chief_Argument.pdf %}), in <NAME> (ed.), *The Oxford Handbook of Hume*, Oxford University Press, pp. 82-108
### 2015
- ["The Common-Core/Diversity Dilemma: Revisions of Humean Thought, New Empirical Research, and the Limits of Rational Religious Belief"]({{ site.baseurl }}{% link scholarship/papers/millican/2015_EJPR_CCDD.pdf %}) (joint with <NAME>), *European Journal for Philosophy of Religion* 7, pp. 1-49
- ["Locke on Substance and Our Ideas of Substances"]({{ site.baseurl }}{% link scholarship/papers/millican/2015_Locke_Substance.pdf %}), in <NAME> and <NAME> (eds), *Locke and Leibniz on Substance*, Routledge, pp. 8-27
### 2014
- ["Skepticism about Garrett's *Hume*: Faculties, Concepts, and Imposed Coherence"]({{ site.baseurl }}{% link scholarship/papers/millican/2014_Garrett's_Hume.pdf %}), *Hume Studies* 40, pp. 205-26
### 2013
- ["Earman on Hume on Miracles"]({{ site.baseurl }}{% link scholarship/papers/millican/2013_Earman_Miracles.pdf %}), in Stew<NAME> and <NAME> (eds), *Debates in Modern Philosophy*, Routledge, pp. 271-83
### 2012
- ["Hume's 'Scepticism' about Induction"]({{ site.baseurl }}{% link scholarship/papers/millican/2012_Induction.pdf %}), in <NAME> and <NAME> (eds), *The Continuum Companion to Hume*, Continuum, pp. 57-103
- ["Hume's Theory of Morals"]({{ site.baseurl }}{% link scholarship/papers/millican/2012_Hume_Ethics.pdf %}), in <NAME> (ed.), *Ethics: The Key Thinkers*, Continuum, pp. 105-31
### 2011
- ["Hume, Causal Realism, and Free Will"]({{ site.baseurl }}{% link scholarship/papers/millican/2011_Causation_FreeWill.pdf %}), in <NAME> and <NAME> (eds), *Causation and Modern Philosophy* (Routledge), pp. 123-65
- "Hume's 'Scepticism' about Induction"<br>Invited talk at [Moscow Conference on "<NAME> and Contemporary Philosophy"](http://www.humesociety.org/conferences/cfp/David.pdf) (November)
- ["Learning from 300 Years of Hume"]({{ site.baseurl }}{% link scholarship/papers/millican/2011_Learning_from_300_years_of_Hume.pdf %})<br>Bentham Lecture at University College, London (November 24th)
- "Norms, Virtue and Autonomy in 17th and 18th-Century Philosophy"<br>Invited talk at Neuchâtel Conference (October)
- "Belief and Doubt in <NAME>"<br>Invited talk at [Prague Conference](http://www.flu.cas.cz/redaction.php?action=showRedaction&id_categoryNode=1768) (September)
- "Recent Books on Hume"<br>Panel Discussion at Hume Society Conference, Edinburgh (July)
- [*Reason, Induction and Causation in Hume's Philosophy*]({{ site.baseurl }}{% link scholarship/papers/millican/2011_Garrett_IASH.pdf %}) (joint with <NAME>), Institute for Advanced Studies in the Humanities, Edinburgh (June 17th)
- "The Significance of David Hume: Scepticism, Science, and Superstition"<br>Royal Society of Edinburgh (May 23rd)
- ["Hume at 300"](/papers/millican/2011_RSA.mp3)<br>Royal Society of Arts, London (May 12th)
- "Hume and the Borders"<br>Lecture at Paxton House, Chirnside Philosophy Festival (April 30th)
- [Hume's Birthday Party - 26th April 2011](http://www.youtube.com/watch?v=ynpBrhxTy0E)<br>Panel discussion at Edinburgh University
- ["Is Hume an Inductive Sceptic?"]({{ site.baseurl }}{% link scholarship/papers/millican/2011_VOX.pdf %}), published in *VOX* 15, Summer 2011.
- ["Finding Inspiration in Hume"]({{ site.baseurl }}{% link scholarship/papers/millican/2011_TPM.pdf %}), published in *The Philosophers' Magazine* 54.3, 2011.
- "Salvaging Hume's Maxim about Miracles"<br>Tercentenary Workshop: Hume on Morality and Religion, St Andrews (March 4th)
- ["Twenty Questions about Hume's 'Of Miracles'"]({{ site.baseurl }}{% link scholarship/papers/millican/2011_20Qs_Miracles.pdf %}), in Antony O'Hear (ed.), *Philosophy and Religion* Cambridge University Press, pp. 151-92- "Hume's Sceptical Stance: 1. Induction"
- "Hume's Sceptical Stance: 2. Miracles"
- "Hume's Sceptical Stance: 3. Scepticism"<br>Extramural Course at Rewley House, Oxford (January)
### 2010
- "Hume on Miracles: A flawed argument, with an enduring moral"<br>Institute for Advanced Studies in the Humanities, Edinburgh (September 22nd)
- ["Hume's Determinism"]({{ site.baseurl }}{% link scholarship/papers/millican/2010_Determinism.pdf %}), *Canadian Journal of Philosophy* 40, pp. 611-42
- ["Comments on <NAME>, 'Hume's Sceptical Solutions'"]({{ site.baseurl }}{% link scholarship/papers/millican/2010 Comments on Perinetti.pdf %})<br>Hume Conference, Antwerp (July)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2010 Comments on Perinetti ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2010 Comments on Perinetti ppt grey.pdf %})
- "Hume's Understanding of the Faculties"<br>Institute for Advanced Studies in the Humanities, Edinburgh (January 26th)
### 2009
- ["Hume on Induction and the Faculties"]({{ site.baseurl }}{% link scholarship/papers/millican/2009 Hume Induction Faculties.pdf %})<br>Draft article (August)
- ["Hume, Causal Realism, and Causal Science"]({{ site.baseurl }}{% link scholarship/papers/millican/2009_Causal_Science.pdf %}), *Mind* 118, pp. 647-712
- ["Religious Belief, Miracles, and <NAME>" - handout]({{ site.baseurl }}{% link scholarship/papers/millican/2009 Religious Belief Miracles <NAME>.pdf %}) (on probability, examples, and bibliography)<br>Royal Institute of Philosophy (February)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2009 Religious Belief Miracles <NAME> ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2009 Religious Belief Miracles <NAME> ppt grey.pdf %})
### 2008
- ["Hume on Causal Science: Sceptical Realist, or Non-Sceptical Anti-Realist?"]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume on Causal Science.pdf %})<br>NYU Conference on "Skepticism" (November)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume on Causal Science ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume on Causal Science ppt grey.pdf %})
- ["Hume, Causal Realism, and Causal Science" (colour slides)]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume Causal Realism Causal Science ppt.pdf %})<br>Oxford Seminar in Early Modern Philosophy (October)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume Causal Realism Causal Science ppt grey.pdf %})
- ["Hume's Idea of Necessary Connexion: Of What is it the Idea?"]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume's Idea of Necessary Connexion.pdf %})<br>Hume Conference, Iceland (August)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume's Idea of Necessary Connexion ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume's Idea of Necessary Connexion ppt grey.pdf %})
- ["The Significance of <NAME>" (recorded interview)](/papers/millican/2008 Millican.mp3) (April, also linked from the [Philosophy Bites](http://nigelwarburton.typepad.com/philosophy_bites/2008/04/peter-millican.html) website)
- ["Hume, Causal Realism, and Free Will: The State of the Debate" (handout)]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume Causal Realism Free Will.pdf %})<br>Conference on Causation, York (March)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume Causal Realism Free Will ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2008 Hume Causal Realism Free Will ppt grey.pdf %})
### 2007
- ["Against the New Hume"]({{ site.baseurl }}{% link scholarship/papers/millican/2007 Against the New Hume.pdf %}), in Rupert Read and <NAME> (eds), *The New Hume Debate: Revised Edition*, Routledge, pp. 211-52
- ["Humes Old and New: Four Fashionable Falsehoods, and One Unfashionable Truth"]({{ site.baseurl }}{% link scholarship/papers/millican/2007_Humes_Old_New.pdf %}), *Proceedings of the Aristotelian Society, Supplementary Volume* 81, pp. 163-99
- [Handout from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2007 Humes Old and New Handout.pdf %})
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2007 Humes Old and New ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2007 Humes Old and New ppt grey.pdf %})
- [Introduction to "World's Classics" Edition of Hume's First *Enquiry*]({{ site.baseurl }}{% link scholarship/papers/millican/2007 Introduction.pdf %}), Oxford University Press, pp. ix-lvi
### 2006
- ["Understanding the World, from Aristotle to Quantum Mechanics: The Significance of <NAME>" (colour slides)]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Understanding the World ppt.pdf %})<br>Hertford to Hartford Lecture, University of Hartford, Connecticut (November)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Understanding the World ppt grey.pdf %})
- ["Hume's 'Compleat Answer to Dr Reid'"]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Hume's Answer to Reid.pdf %})<br>Hume Conference, University of Koblenz, Germany (August)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Hume's Answer to Reid ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Hume's Answer to Reid ppt grey.pdf %})
- ["Kemp Smith on Causation" (colour slides)]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Kemp Smith on Causation ppt.pdf %})<br>Kemp Smith 101 Conference, University of Oxford (May)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Kemp Smith on Causation ppt grey.pdf %})
- ["The Significance of <NAME>" (colour slides)]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Hume's Significance ppt.pdf %})<br>Hertford College Soiree (May)
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2006 Hume's Significance ppt grey.pdf %})
### 2005
- ["Hume's Determinism"]({{ site.baseurl }}{% link scholarship/papers/millican/2005 Hume's Determinism.pdf %})<br>Hume Conference, University of Toronto (July)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2005 Hume's Determinism ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2005 Hume's Determinism ppt grey.pdf %})
### 2004
- [Comments on Houston Smit's "A Priority, Reason, and Induction in Hume"]({{ site.baseurl }}{% link scholarship/papers/millican/2004 Comments on Smit.pdf %})<br>Hume Conference, University of Keio, Tokyo (August)
- ["Hume's 'Compleat Answer to Dr Reid'"]({{ site.baseurl }}{% link scholarship/papers/millican/2004 Hume's Answer to Reid handout.pdf %})<br>Third International Reid Symposium, University of Aberdeen (July)
### 2003
- ["Humes Old and New: Cartesian Fellow-Traveller, or Revolutionary?"]({{ site.baseurl }}{% link scholarship/papers/millican/2003 Humes Old and New.pdf %})<br>Royal Institute of Philosophy Symposium on Descartes and Hume, University of Manchester (December)
- [Colour slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2003 Humes Old and New ppt.pdf %})
- [Greyscale slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2003 Humes Old and New ppt grey.pdf %})
- ["Hume, Miracles, and Probabilities: Meeting Earman's Challenge"]({{ site.baseurl }}{% link scholarship/papers/millican/2003 Hume Miracles Probabilities.pdf %})<br>Hume Conference, University of Las Vegas (July-August)
- [Slides from the above]({{ site.baseurl }}{% link scholarship/papers/millican/2003 Hume Miracles Probabilities slides.pdf %})
### 2002
- *Reading Hume on Human Understanding* (Oxford University Press)
- ["Introduction" to *Reading Hume on Human Understanding*]({{ site.baseurl }}{% link scholarship/papers/millican/2002_Intro.pdf %}), pp.1-26 (plus contents, index)
- ["The Context, Aims, and Structure of Hume's First *Enquiry*]({{ site.baseurl }}{% link scholarship/papers/millican/2002_Chapter1.pdf %}), Chapter 1, pp. 27-65
- ["Hume's Sceptical Doubts Concerning Induction"]({{ site.baseurl }}{% link scholarship/papers/millican/2002_Chapter4.pdf %}), Chapter 4, pp. 107-73
- ["Critical Survey of the Literature on Hume and the First *Enquiry*]({{ site.baseurl }}{% link scholarship/papers/millican/2002_LitSurvey.pdf %}), pp. 413-74
### 2001
- ["The Logic of Hume's Sceptical Doubts"]({{ site.baseurl }}{% link scholarship/papers/millican/2001 Logic of Hume's Doubts.pdf %})<br>Hume Conference, University of Victoria, BC (July)
- ["Beauchamp's Student Editions of the *Enquiries*"]({{ site.baseurl }}{% link scholarship/papers/millican/2001 Beauchamp's Enquiry.pdf %})<br>Hume Conference, University of Victoria, BC (July)
### 2000
- [*Critical Survey of the Literature on Hume and the First Enquiry*](http://www.davidhume.org/bibliographies/ehusurvey.html)<br>First Web edition
- [*Hume's Enquiry concerning Human Understanding*](http://www.davidhume.org/texts/ehu.html)<br>Leeds Web edition
### 1999
- Hume Conference, University of Cork (July)
### 1998
- ["Hume on Reason and Induction: Epistemology or Cognitive Science?"]({{ site.baseurl }}{% link scholarship/papers/millican/1998_Reason_Induction.pdf %}), *Hume Studies* 24, pp. 141-59
- ["The Problem of the First *Enquiry*: Concluding the 1998 Stirling Conference"]({{ site.baseurl }}{% link scholarship/papers/millican/1998Stirling.pdf %})<br>Hume Conference, University of Stirling (July)
### 1997
- ["Induction"]({{ site.baseurl }}{% link scholarship/papers/millican/1997InductionEEmp.pdf %})<br>*Encyclopaedia of Empiricism*, eds. <NAME> and <NAME>, Greenwood Press, pp. 180-8
- ["Knowledge"]({{ site.baseurl }}{% link scholarship/papers/millican/1997KnowledgeEEmp.pdf %})<br>*Encyclopaedia of Empiricism*, eds. <NAME> and <NAME>, Greenwood Press, pp. 202-5
- ["Logic"]({{ site.baseurl }}{% link scholarship/papers/millican/1997LogicEEmp.pdf %})<br>*Encyclopaedia of Empiricism*, eds. <NAME> and <NAME>, Greenwood Press, pp. 215-7
- "Garrett on Reason and Induction"<br>Hume Conference, University of Monterey (July-August)
### 1996
- [*Hume, Induction, and Probability*]({{ site.baseurl }}{% link scholarship/papers/millican/1996PhD.pdf %})<br>PhD thesis, University of Leeds, pp. 294 + xv *(unlike previous versions, this has been carefully prepared to ensure that the pagination corresponds almost exactly with the original, enabling the final indexes to be used)*
- Comments on <NAME>, "Causality as a Philosophical Relation in Hume"<br>Hume Conference, University of Nottingham (July)
### 1995
- ["Hume's Argument concerning Induction: Structure and Interpretation"]({{ site.baseurl }}{% link scholarship/papers/millican/1995Induction.pdf %})<br>in <NAME> (ed) *<NAME>: Critical Assessments*, Routledge, vol. II, pp. 91-144, and reprinted in <NAME> (ed) *Hume: General Philosophy* (2000), Routledge, vol. 2 pp. 165-218 *(marginal page numbers have been added, to facilitate handling of references to the original)*
- ["Hume, Induction and Reason"]({{ site.baseurl }}{% link scholarship/papers/millican/1995InductionReason.pdf %})<br>Hume Conference, University of Utah (July)
### 1993
- ["'Hume's Theorem' concerning Miracles"]({{ site.baseurl }}{% link scholarship/papers/millican/1993_Miracles.pdf %}), *Philosophical Quarterly* 43, pp. 489-95
### 1992
- (paper on induction)<br>Hume Conference, University of Nantes
### 1989
- ["The Devil's Advocate"]({{ site.baseurl }}{% link scholarship/papers/millican/1989_DevAdv.pdf %}), *Cogito* 3, pp. 193-207
- (paper on induction)<br>Hume Conference, Lancaster University (August)
### 1986
- ["Natural Necessity and Induction"]({{ site.baseurl }}{% link scholarship/papers/millican/1986_NatNec.pdf %}), *Philosophy* 61, pp. 395-403
### 1982
- ["Mackie's Defence of Induction"]({{ site.baseurl }}{% link scholarship/papers/millican/1982_Mackie_Induction.pdf %}), *Analysis* 42, pp. 19-24
<file_sep>/texts/h/66.md
---
layout: texts
text: 'H.66'
tab: 'text'
---
<file_sep>/texts/h/65.md
---
layout: texts
text: 'H.65'
tab: 'text'
---
<file_sep>/texts/empl2/index.md
---
layout: texts
text: 'EMPL2'
tab: 'text'
contents: true
fulltext: true
context: 'EMPL2'
notes: true
---
<file_sep>/_includes/notes/fd.md
## Four Dissertations (1757)
_prepared by <NAME>_
The *Natural History of Religion*, the *Dissertation on the Passions*, and *Of Tragedy* were originally intended for a set of four dissertations alongside an essay on the metaphysical principles of geometry. Shortly before publication, however, Hume was persuaded by <NAME> "that either there was some Defect in the Argument [of this fourth dissertation] or in its perspicuity" (*HL* 2, p. 253), and he removed it from the set. Being advised by his publisher that the other three alone were not long enough for publication, Hume sent the two scandalous essays *Of Suicide* and *Of the Immortality of the Soul* to fill the gap. "They were printed;" continued Hume in the letter to <NAME> already quoted, "but it was no sooner done than I repented; and Mr Millar and I agreed to suppress them at common charges, and I wrote a new Essay on the Standard of Taste to supply their place." (ibid.)
<file_sep>/texts/empl1/og.md
---
layout: texts
text: 'OG'
parent: 'EMPL1'
essay: 5
tab: 'text'
---
<file_sep>/texts/n/2.md
---
layout: 'texts'
text: 'N.2'
tab: 'text'
---
<file_sep>/texts/h/47.md
---
layout: texts
text: 'H.47'
tab: 'text'
---
<file_sep>/texts/emp/av.md
---
layout: texts
text: 'Av'
parent: 'EMP'
essay: 13
tab: 'text'
---
<file_sep>/texts/emp/lm.md
---
layout: texts
text: 'LM'
parent: 'EMP'
essay: 6
tab: 'text'
---
<file_sep>/texts/h/vol2/index.md
---
layout: texts
text: 'H.Vol2'
tab: 'text'
contents: true
fulltext: true
---
<file_sep>/texts/h/39.md
---
layout: texts
text: 'H.39'
tab: 'text'
---
<file_sep>/texts/p/3.md
---
layout: 'texts'
text: 'P.3'
tab: 'text'
---
<file_sep>/search.md
---
layout: search
---
## Search Help
There are two kinds of search, _simple_ and _advanced_. The former is intended to help you find a passage or quotation from Hume's works, the location of which you cannot remember. It will look for the complete phrase that you enter, ignoring capitalisation and punctuation. More importantly, it will also broaden your search in straightforward and presumptively helpful ways, to maximise your chance of finding the passage. For example, "it is" will also match "’tis"; "though" will also match "tho'"; "-ed" at the end of a word will also match "-’d"; "-ction" and "-xion" at the end of a word will be treated as equivalent (as in "reflection"/"reflexion", "connection"/"connexion"); and so on.
Advanced search is intended for scholarship purposes, to interrogate Hume's texts for the terms that he used and how often he used them. This type of search treats your input query as a _regular expression_, which is a standard syntax for matching string patterns; if you look it up in your search engine of choice, you will find countless guides and tutorials on the web. For now, the following examples should be enough to get you started:
- "sceptic" - this matches all occurrences of these letters in that order, e.g. "sceptic", "sceptical", "scepticism"
- "\bsceptic\b" - "\b" represents a word boundary, hence this matches only occurrences of the word "sceptic" (i.e. it does not match "sceptical" or "scepticism")
- "govern(ed)?" - the question mark is for optional characters, and the brackets specify its scope, hence this matches both "govern" and "governed"
- "refle(ct\|x)ion" - the pipe symbol is for disjunction, and again the brackets specify its scope, hence this matches both "reflection" and "reflexion"
- "govern(ed\|ment)?" - question marks and pipes can be combined; this matches "govern", "governed", and "government"
- "(govern\|governed\|government)" - this is equivalent to the previous example, but easier to read; in some cases an explicit disjunction may get the job done just as well
- "hypothes.s" - a full stop is a wild-card that matches any character, hence this matches both "hypothesis" and "hypotheses" (as well as, in theory, "hypothesas", "hypothesbs", "hypothescs", etc.)
There is no easy way to perform conjunctive searches using regular expressions. To search for paragraphs containing two or more expressions, search for the first expression, and then search for subsequent expressions within the range of the current results.
<file_sep>/texts/emp/bg.md
---
layout: texts
text: 'BG'
parent: 'EMP'
essay: 9
tab: 'text'
---
<file_sep>/texts/emp/rp.md
---
layout: texts
text: 'RP'
parent: 'EMP'
essay: 20
tab: 'text'
---
<file_sep>/texts/t/1/3/11.md
---
layout: 'texts'
text: 'T.1.3.11'
tab: 'text'
---
<file_sep>/texts/h/71.md
---
layout: texts
text: 'H.71'
tab: 'text'
---
<file_sep>/texts/h/45.md
---
layout: texts
text: 'H.45'
tab: 'text'
---
<file_sep>/texts/h/16.md
---
layout: texts
text: 'H.16'
tab: 'text'
---
<file_sep>/texts/t/3/3/5.md
---
layout: 'texts'
text: 'T.3.3.5'
tab: 'text'
---
<file_sep>/notes/original.md
---
layout: notes
subsection: original
---
## Original Versions
By default, every text is displayed in its edited form. By deselecting the "Edited Text" checkbox at the top of the page, however, you can switch to the original version. (This affects searches as well as the text displayed on the screen.) Original versions aim to be exact reproductions of the copytexts except for the following silent alterations.
### 1. Labels and pagination
Every paragraph and footnote has been given a label. This appears either immediately above or in the margin to the left of the paragraph or footnote (depending on the width of your screen), in red and in a different font, and thus clearly distinguished from the text itself.
Page breaks from the copytexts have been removed. Page references to the most standard modern reference edition---Selby-Bigge and Nidditch for the *Treatise*, *Abstract*, and two *Enquiries*, Miller for the essays and *My Own Life*, Beauchamp for the *Natural History of Religion* and the *Dissertation on the Passions*, and <NAME> for the *Dialogues*---are included following the red paragraph or footnote labels mentioned above. Page breaks from these editions, when they interrupt a paragraph, are represented with the pipe symbol "\|"; this can either be shown or hidden, by toggling the "Show Page Breaks" option at the top of each page.
### 2. Line breaks and hyphens
Hyphens introduced in order to break up a word at the end of a line have been removed, as has the letter "e" sometimes introduced preceding that hyphen (as in "make-\|ing", "take-\|ing"). In some cases, however, it is not obvious whether the "e" preceding the hyphen would have been there anyway: line breaks aside, we find both "where-ever" and "wherever" in Hume's texts, as well as both "falsehood" and "falshood", both "judgement" and "judgment". To settle these cases, we have gone with the most common spelling in the text in question. Consequently we use "falshood" in the *Treatise*, and "falsehood" everywhere else; we use "judgement" in the *Dialogues*, and "judgment" everywhere else; and we use "where-ever" in the *Dialogues*, and "wherever" everywhere else.
Only in one instance does this general principle make us slightly uneasy: there are two instances of "where-\|ever" in the *Treatise*, but also three instances of "where-ever" without a page break (and this hyphenated spelling is also consistently used in the *Dialogues*). That said, "wherever" is consistently used in all Hume's other publications, and vastly more common even in the *Treatise* itself. Where the additional "e" and hyphen occurs at a line break in the *Treatise*, therefore, we have removed it.
### 3. Footnotes and endnotes
Footnote symbols are all converted to numbers, for ease of reference. Footnotes themselves are grouped together at the end of each section, after a horizontal line. Endnotes---in the case of texts from the *Essays and Treatises on Several Subjects*---are placed immediately following the footnote that refers to them (to save the reader from having to click or scroll needlessly). In the 1777 copytext, endnotes appeared at the very end of each volume, after a heading "NOTES TO THE FIRST VOLUME" or "NOTES TO THE SECOND VOLUME".
Footnote anchors are placed within square brackets, and appear in red (as opposed to the original black), indicating a link that can be clicked on to move you to the part of the text being referred to. In the copytexts, footnote anchors sometimes appear between two words, and at a roughly equal distance between the two. It is therefore unclear whether the anchor is meant to be placed at the end of the first word, the start of the second, or in the middle (with a space on either side). To avoid difficult decisions of this kind, and because the issue involves only a typographical convention with no significance for the understanding of the text, in every case we have simply placed the anchor at the end of the first word, in accordance with modern practice.
### 4. Miscellaneous formatting changes
- Decorative first letters at the beginning of some of Hume's texts have been changed to large dropped capitals. Dropped capitals at the start of subsequent sections are as in the copytexts.
- Quotation marks are used in the now standard way, with one at the beginning and one at the end of each quotation. In some original texts, long quotations appear with a quotation mark at the beginning of every line.
- The eighteenth century long "s" (which looks rather like an "f") has been everywhere replaced with an ordinary "s". Ligatures (joining letter combinations such as "ct" and "fi") have been removed. The combinations "æ" and "œ" have, however, been preserved.
- Commas and semicolons do not appear italicised in Hume's texts, even in the context of a quotation or statement that is otherwise all in italics; we treat this as indicating that italicised commas and semicolons are indistinguishable from non-italicised commas and semicolons in the font used by Hume's publishers. Since our own fonts are able to distinguish them, however, we have italicised these punctuation marks when they occur within a phrase that is otherwise all italicised. (Note, by contrast, that colons _are_ sometimes italicised in Hume's texts, typically when they follow an italicised word. The formatting of colons here follows the copytexts.)
- An ordinary lower case (short) "s" is indistinguishable, in the font used by Hume's publishers, from an "s" in small capitals. This raises the question, when a name appears in small capitals, followed by an apostrophe and an "s", whether the trailing "s" should be in small capitals or not. We have here taken the view that the capitalisation should apply only to the name itself, since this seems most logical and is also supported by Hume's texts in the parallel case when names appear in italics, followed by an apostrophe and an "s": in such cases, the "s" is typically not italicised (see, for example, footnotes 11 and 47 of the *Treatise*).
<file_sep>/texts/h/11.md
---
layout: texts
text: 'H.11'
tab: 'text'
---
<file_sep>/texts/h/51.md
---
layout: texts
text: 'H.51'
tab: 'text'
---
<file_sep>/texts/emp/cl.md
---
layout: texts
text: 'CL'
parent: 'EMP'
essay: 15
tab: 'text'
---
<file_sep>/texts/t/3/2/1.md
---
layout: 'texts'
text: 'T.3.2.1'
tab: 'text'
---
<file_sep>/texts/empl2/in.md
---
layout: texts
text: 'In'
parent: 'EMPL2'
essay: 4
tab: 'text'
---
<file_sep>/texts/emp/sr.md
---
layout: texts
text: 'SR'
parent: 'EMP'
essay: 26
tab: 'text'
---
<file_sep>/texts/emp/cr.md
---
layout: texts
text: 'CR'
parent: 'EMP'
essay: 27
tab: 'text'
---
<file_sep>/_includes/notes/m.md
## An Enquiry concerning the Principles of Morals (1751, 1777)
_prepared by <NAME>_
*An Enquiry Concerning the Principles of Morals*---commonly known as Hume's second *Enquiry*---was originally published in 1751, by <NAME> of the Strand, London. A companion work to the first *Enquiry*, it is a recasting of the moral theory of *Treatise* Book 3, which preserves most of the spirit of the original while differing significantly in detail. Some of Hume's most influential and controversial arguments against (what we now call) moral realism and rationalism are removed: a change traditionally considered to be a symptom of shortening and simplifying rather than any change of mind (though this traditional assumption has more recently been questioned). Likewise the associationist psychology of the *Treatise*---such as the explanation of sympathy---fades into the background, and instead Hume focuses on the attempt to find systematic principles for ordering our everyday judgements of virtues and vices, as manifested in common language. This results in a view with strong elements of both utilitarianism and of virtue ethics, characterising the virtues as "mental qualities, useful or agreeable to the person himself, or to others" (M 9.1).
The second edition of *An Enquiry Concerning the Principles of Morals* was in the form of volume III of Hume's four-volume *Essays and Treatises on Several Subjects* in 1753. Its third edition (though not explicitly labelled as such) was in the 1758 *Essays and Treatises*, which combined the constituent works into a single volume. In the four-volume 1760 and 1770 editions of the *Essays and Treatises*, the second *Enquiry* appeared in volume IV before *The Natural History of Religion*. In the two-volume editions of 1764, 1767, 1768, 1772, and 1777, it appeared within volume II, after *An Enquiry concerning Human Understanding* and *A Dissertation on the Passions*, and before *The Natural History of Religion*.
Here a fair number of substantive changes been made to the original copytext, which gives the impression of having been checked far less carefully than that of the first *Enquiry*. _(This text is still subject to editorial checking, and more detail will be added here once that process of checking has been fully completed. Feedback from readers who notice any issues with the text will be particularly welcome.)_
<file_sep>/texts/pld/in.md
---
layout: texts
text: 'In'
parent: 'PLD'
essay: 4
tab: 'text'
---
<file_sep>/texts/empl2/jt.md
---
layout: texts
text: 'JT'
parent: 'EMPL2'
essay: 6
tab: 'text'
---
<file_sep>/texts/empl1/full.md
---
layout: texts
text: 'EMPL1'
tab: 'text'
notes: true
---
<file_sep>/texts/t/1/4/index.md
---
layout: 'texts'
text: 'T.1.4'
tab: 'text'
contents: true
fulltext: true
---
<file_sep>/texts/pld/ta.md
---
layout: texts
text: 'Ta'
parent: 'PLD'
essay: 7
tab: 'text'
---
<file_sep>/texts/d/10m.md
---
layout: 'texts'
text: 'D.10'
tab: 'images'
---
<file_sep>/texts/n/8.md
---
layout: 'texts'
text: 'N.8'
tab: 'text'
---
<file_sep>/texts/pld/ipc.md
---
layout: texts
text: 'IPC'
parent: 'PLD'
essay: 12
tab: 'text'
---
<file_sep>/texts/pld/co.md
---
layout: texts
text: 'Co'
parent: 'PLD'
essay: 1
tab: 'text'
---
<file_sep>/scholarship/other.md
---
layout: scholarship
subsection: scholarship
---
## Various Other Papers on Hume
_Papers that are hard to obtain elsewhere are stored here, so as to make them easily available to Hume scholars. Please contact us if you have recommendations for other papers that could usefully be added to this collection (subject to appropriate copyright agreements)._
- [<NAME>, "On Some Criticisms of Hume's Principle of Proportioning Cause to Effect"]({{ site.baseurl }}{% link scholarship/papers/beaudoin.pdf %})
- [<NAME>, *David Hume's Theory of Mind*, Ch. 8 (1990)]({{ site.baseurl }}{% link scholarship/papers/flage.pdf %})
<file_sep>/texts/d/3.md
---
layout: 'texts'
text: 'D.3'
manuscript: true
tab: 'text'
---
<file_sep>/texts/h/notes.md
---
layout: texts
text: 'H'
tab: 'notes'
notes: true
---
{% include notes/h.md %}
<file_sep>/texts/emp/dt.md
---
layout: texts
text: 'DT'
parent: 'EMP'
essay: 1
tab: 'text'
---
<file_sep>/texts/empl1/bg.md
---
layout: texts
text: 'BG'
parent: 'EMPL1'
essay: 7
tab: 'text'
---
<file_sep>/texts/t/notes.md
---
layout: 'texts'
text: 'T'
tab: 'notes'
notes: true
---
{% include notes/t.md %}
<file_sep>/texts/p/index.md
---
layout: 'texts'
text: 'P'
tab: 'text'
contents: true
fulltext: true
notes: true
---
<file_sep>/texts/pld/mo.md
---
layout: texts
text: 'Mo'
parent: 'PLD'
essay: 3
tab: 'text'
---
<file_sep>/texts/empl1/pg.md
---
layout: texts
text: 'PG'
parent: 'EMPL1'
essay: 8
tab: 'text'
---
<file_sep>/texts/empl2/rc.md
---
layout: texts
text: 'RC'
parent: 'EMPL2'
essay: 10
tab: 'text'
---
<file_sep>/texts/emp/ew.md
---
layout: texts
text: 'EW'
parent: 'EMP'
essay: 16
tab: 'text'
---
<file_sep>/texts/empl1/lp.md
---
layout: texts
text: 'LP'
parent: 'EMPL1'
essay: 2
tab: 'text'
---
<file_sep>/texts/h/35.md
---
layout: texts
text: 'H.35'
tab: 'text'
---
<file_sep>/notes/help.md
---
layout: notes
subsection: help
---
## Help
At the top of each text is a tool box with a breadcrumb, various options, a search box, and icons for switching between different parts of the page. We hope the features here are as self-explanatory as possible, but please take a moment to read through these help notes, to ensure you are getting the most out of this site.
### 1. Breadcrumb and icons
When viewing structured texts (such as the *Treatise*, which is divided into Books, parts, and sections), a "breadcrumb" trail is shown in the red bar at the top of the tool box. Use this to navigate between sections.
At the bottom right of the tool box are various icons representing different parts of the page. Note that not every icon shows up on every page, since some features are not available or relevant to every text.
| <span class="icon"><i class="fas fa-search"></i></span> | Click on this icon to see search results from within the current text.<br> |
| <span class="icon"><i class="fas fa-list"></i></span> | Click on this icon to see a table of contents for the current text. This icon is only available for collections and larger texts made up of more than one part or section.<br> |
| <span class="icon"><i class="fas fa-file-alt"></i></span> | Click on this icon to see the text itself. This icon is not available for collections or larger texts, where you will see the icon for the table of contents instead.<br> |
| <span class="icon"><i class="fas fa-copy"></i></span> | Click on this icon to see any textual variants for the current text, i.e. substantive differences from different editions of the text.<br> |
| <span class="icon"><i class="fas fa-file-image"></i></span> | Click on this icon to see manuscript images for the current text. This only applies to the *Dialogues concerning Natural Religion*, which is sadly the only one of Hume's works for which the manuscript survives.<br> |
| <span class="icon"><i class="fas fa-edit"></i></span> | Click on this icon to see editorial notes pertaining to the current text. |
### 2. Options
By default, the edited version of the text is shown (see the notes on the [Edited Versions]({{ 'notes/edited' | relative_url }})). When displaying the edited text, check "Show Changes" to see the editorial interventions we have made. Deletions will appear with a line through them, and additions underlined; by hovering your mouse over the change, you will see a brief explanation of the edit. Our interventions are minimal, consisting mostly of changes sanctioned by Hume himself, together with corrections of just a few very obvious errors.
Alternatively, you can deselect the "Edited Text" checkbox to see the original edition, a faithful reproduction of the copytext save for some systematic and insignificant changes intended to make the text easier to read and navigate (see the notes on the [Original Editions]({{ '/notes/original' | relative_url }})). Note that this will effect the text against which your search queries are tested as well as the text shown on the screen.
Page numbers from standard editions are shown alongside each paragraph. For paragraphs that range over more than one page, page breaks can be displayed in the text as a pipe (\|), by checking "Show Page Breaks".
### 3. Simple and advanced search
There are two kinds of search, _simple_ and _advanced_. The former is intended to help you find a passage or quotation from Hume's works, the location of which you cannot remember. It will look for the complete phrase that you enter, ignoring capitalisation and punctuation. More importantly, it will also broaden your search in straightforward and presumptively helpful ways, to maximise your chance of finding the passage. For example, "it is" will also match "’tis"; "though" will also match "tho'"; "-ed" at the end of a word will also match "-’d"; "-ction" and "-xion" at the end of a word will be treated as equivalent (as in "reflection"/"reflexion", "connection"/"connexion"); and so on.
Advanced search is intended for scholarship purposes, to interrogate Hume's texts for the terms that he used and how often he used them. This type of search treats your input query as a _regular expression_, which is a standard syntax for matching string patterns; if you look it up in your search engine of choice, you will find countless guides and tutorials on the web. For now, the following examples should be enough to get you started:
- "sceptic" - this matches all occurrences of these letters in that order, e.g. "sceptic", "sceptical", "scepticism"
- "\bsceptic\b" - "\b" represents a word boundary, hence this matches only occurrences of the word "sceptic" (i.e. it does not match "sceptical" or "scepticism")
- "govern(ed)?" - the question mark is for optional characters, and the brackets specify its scope, hence this matches both "govern" and "governed"
- "refle(ct\|x)ion" - the pipe symbol is for disjunction, and again the brackets specify its scope, hence this matches both "reflection" and "reflexion"
- "govern(ed\|ment)?" - question marks and pipes can be combined; this matches "govern", "governed", and "government"
- "(govern\|governed\|government)" - this is equivalent to the previous example, but easier to read; in some cases an explicit disjunction may get the job done just as well
- "hypothes.s" - a full stop is a wild-card that matches any character, hence this matches both "hypothesis" and "hypotheses" (as well as, in theory, "hypothesas", "hypothesbs", "hypothescs", etc.)
There is no easy way to perform conjunctive searches using regular expressions. To search for paragraphs containing two or more expressions, search for the first expression, and then search for subsequent expressions within the range of the current results.
<file_sep>/texts/d/6m.md
---
layout: 'texts'
text: 'D.6'
tab: 'images'
---
<file_sep>/_includes/notes/e.md
## An Enquiry concerning Human Understanding (1748, 1777)
_prepared by <NAME>_
What is now known as Hume's first *Enquiry* was first published in 1748, by <NAME> of the Strand, London, under the title *Philosophical Essays Concerning Human Understanding*. It is described in *My Own Life* as a recasting of the "first part" of the *Treatise*, though it is not confined to topics from *Treatise* Book 1: the long Section 8 "Of Liberty and Necessity" reworks *Treatise* 2.3.1-2 (and incorporates T 1.3.12.5 as E 8.13), while Sections 11 and 12, on Miracles and the Design Argument, have no precedent. Perhaps it is best thought of as a presentation of the core---and some of the more striking applications---of Hume's inductive epistemology and causal metaphysics: the heart of his theoretical philosophy. It thus elaborates what the *Abstract* described as the "Chief Argument" of the *Treatise*, while adding an explicit focus on religious topics (which Hume had deleted from the *Treatise* for reasons of prudence). Although much shorter than the *Treatise*, and omitting most of the detailed associationist psychology (e.g. from the discussions of belief, probability, and the external world), the *Enquiry* expands the central philosophical discussions on induction (Section 4), free-will (Section 8), and scepticism (Section 12) while also polishing significantly the treatment of causation (Section 7). It is therefore an indispensable source for Hume's epistemology and metaphysics, although most scholars have tended to ignore Hume's own request---expressed in the "Advertisement" of 1775---that the *Enquiry* should be taken (together with the other works in his final edition of *Essays and Treatises* Volume 2) as the authoritative statement of his mature "philosophical sentiments and principles", thus supplanting the *Treatise*.
A second edition of the *Philosophical Essays* appeared in 1750, and this was reprinted in 1751 and 1753, the latter in the form of volume II of Hume's four-volume *Essays and Treatises on Several Subjects*. This arrangement was retained in the third edition of 1756, at which point volume II was the only one of the four to be reissued. The next edition of the *Essays and Treatises*, in 1758, combined the constituent works into a single volume, and here Hume permanently changed the title of his *Philosophical Essays* to *An Enquiry Concerning Human Understanding*, thus recognising its systematic nature alongside the *Enquiry Concerning the Principles of Morals*. In the four-volume 1760 and 1770 editions of the *Essays and Treatises*, the *Enquiry* appeared in volume III followed by *A Dissertation on the Passions*. In the two-volume editions of 1764, 1767, 1768, 1772, and 1777, it appeared at the beginning of volume II, followed in order by *A Dissertation on the Passions*, *An Enquiry Concerning the Principles of Morals*, and *The Natural History of Religion*.
Only in three cases have substantive changes been made to the copytext here, where typographical changes were clearly required and could be identified by reference to other editions: these involve the insertion of "[is]" within 3.3 n. 6, "[and]" within endnote [B], and the substitution of "reasoning" for "reasonings" in the first line of endnote [H].
Footnotes have all been numbered, as with all of the editions on this site. This leads to one small complication: Beauchamp's note 5 from the 1772 edition is absent from the 1777 text followed here, but for ease of cross reference I have numbered the notes as Beauchamp does. Thus note 5 only appears in the Textual Variants tab in section 3.
<file_sep>/texts/etss/ad1777.md
---
layout: texts
text: 'Ad1777'
tab: 'text'
---
<file_sep>/texts/n/9.md
---
layout: 'texts'
text: 'N.9'
tab: 'text'
---
|
987fc9ac3783ea5f5c2a2e0be652f01f14096aba
|
[
"Markdown",
"JavaScript"
] | 222
|
Markdown
|
englishphilosophy/hume-texts-online
|
a6423214815f1d89b603b2618d53dabb9c5d9930
|
49a48d4d283c7b268f9e72bdbab6917b732b9712
|
refs/heads/main
|
<file_sep>// Write your code here.
import './index.css'
const WinOrLossCard = props => {
const {currentScore, onClickPlayAgain, isWin} = props
const resultImage = isWin
? 'https://assets.ccbp.in/frontend/react-js/won-game-img.png'
: 'https://assets.ccbp.in/frontend/react-js/lose-game-img.png'
const result = isWin ? 'You Won' : 'You Lose'
const status = isWin ? 'Best Score' : 'Score'
return (
<div className="results-card">
<div>
<h1 className="result">{result}</h1>
<p className="best-score">{status}</p>
<p className="score">{currentScore}/12</p>
<button
type="button"
onClick={onClickPlayAgain}
className="playAgain-button"
>
Play Again
</button>
</div>
<div>
<img src={resultImage} className="result-image" alt="win or lose" />
</div>
</div>
)
}
export default WinOrLossCard
<file_sep>import {Component} from 'react'
import NavBar from '../NavBar'
import EmjoiCard from '../EmojiCard'
import WinOrLoseCard from '../WinOrLoseCard'
import './index.css'
class EmojiGame extends Component {
state = {
clickedEmojisList: [],
HighScore: 0,
isGameIsOn: true,
}
finishEmojiGame = currentScore => {
const {HighScore} = this.state
let newHighScore = HighScore
if (newHighScore < currentScore) {
newHighScore = currentScore
}
this.setState({HighScore: newHighScore, isGameIsOn: false})
}
clickEmoji = id => {
const {emojisList} = this.props
const {clickedEmojisList} = this.state
const isEmojiPresent = clickedEmojisList.includes(id)
const currentScore = clickedEmojisList.length
if (isEmojiPresent) {
this.finishEmojiGame(currentScore)
} else {
if (emojisList.length - 1 === currentScore) {
this.finishEmojiGame(emojisList.length)
}
this.setState(prevState => ({
clickedEmojisList: [...prevState.clickedEmojisList, id],
}))
}
}
shuffledEmojisList = () => {
const {emojisList} = this.props
return emojisList.sort(() => Math.random() - 0.5)
}
toRenderEmojiList = () => {
const shuffledEmojisList = this.shuffledEmojisList()
return (
<>
<ul className="emoji-list-container">
{shuffledEmojisList.map(eachEmoji => (
<EmjoiCard
key={eachEmoji.id}
emojiDetails={eachEmoji}
clickEmoji={this.clickEmoji}
/>
))}
</ul>
</>
)
}
reset = () => {
this.setState({clickedEmojisList: [], isGameIsOn: true})
}
toRenderScoreCard = () => {
const {clickedEmojisList} = this.state
const {emojisList} = this.props
const isWin = clickedEmojisList.length === emojisList.length
console.log(isWin)
return (
<WinOrLoseCard
currentScore={clickedEmojisList.length}
onClickPlayAgain={this.reset}
isWin={isWin}
/>
)
}
render() {
// const {emojisList} = this.props
const {isGameIsOn, clickedEmojisList, HighScore} = this.state
console.log(`High:${HighScore}`)
console.log(`Current:${clickedEmojisList.length}`)
return (
<div className="app-container">
<NavBar
isGameIsOn={isGameIsOn}
currentScore={clickedEmojisList.length}
HighScore={HighScore}
/>
<div className="emojees-list">
{isGameIsOn ? this.toRenderEmojiList() : this.toRenderScoreCard()}
</div>
</div>
)
}
}
export default EmojiGame
|
e4fdcb7c37837d829a3103843eb9343423f55d02
|
[
"JavaScript"
] | 2
|
JavaScript
|
sahusuneel777/Emoji-Game
|
e80dbaccb68dbae1d45faa923c51abdd1d420843
|
ff59b9779e1b955ff3dd438998676afc03772e5a
|
refs/heads/main
|
<repo_name>Reksa4/get<file_sep>/4dz.py
from gpio import GPIO
import time
def runninDark(count,period):
x = 0
GPIO.output(0,1)
GPIO.output(1,1)
GPIO.output(2,1)
GPIO.output(3,1)
GPIO.output(4,1)
GPIO.output(5,1)
GPIO.output(6,1)
GPIO.output(7,1)
for i in range(count):
GPIO.output(x,0)
time.sleep(period)
x += 1
GPIO.output(x-1,1)
if x > 7:
x = 0
runninDark(100,1)<file_sep>/2dz.py
from gpio import GPIO
import time
def blink(lednumber,blinkCout,blinkPeriod):
from i in range(blinkCout):
GPIO.output(lednumber,1)
time.sleep(blinkPeriod)
GPIO.output(lednumber,0)
time.sleep(blinkPeriod)
blink(2,10,2)<file_sep>/ACP.py
import RPi.GPIO as GPIO
import time
bit_depth = 8
def bin_convert(n):
N = bit_depth - 1
p = 0
X = []
while N > 0:
p = int(n/2**N)
if p == 1:
X.append(1)
n-=2**N
else:
X.append(0)
N-=1
X.append(n)
return X
def dac_data(data):
for i in range(0,bit_depth):
GPIO.output(D[i], N[i])
def adc_procedure():
for j in range(0,2**bit_depth):
dac_data(bin_convert(j))
time.sleep(0.1)
m = (3.3 * j)/256
print(j,' ',m)
if GPIO.input(4) == 0:
print(j)
break
return j
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(21,GPIO.OUT)
GPIO.setup(20,GPIO.OUT)
GPIO.setup(16,GPIO.OUT)
GPIO.setup(12,GPIO.OUT)
GPIO.setup(1,GPIO.OUT)
GPIO.setup(7,GPIO.OUT)
GPIO.setup(8,GPIO.OUT)
GPIO.setup(25,GPIO.OUT)
GPIO.setup(4,GPIO.IN)
D=[21,20,16,12,1,7,8,25]
<file_sep>/README.md
1.ining(GET)
2.ka** - семестровый учебный курс для первокурсников, направленный на развитее навыков современного инжинера- исследователя.
<file_sep>/3dz.py
from gpio import GPIO
import time
def runningLight(count,period):
x = 0
for i in range(count):
GPIO.output(x,1)
time.sleep(period)
x += 1
GPIO.output(x-1,0)
if x >7:
x = 0
runningLight(20,1)
|
f4cc7cb41379c699e7433f17bc91e641947c84a8
|
[
"Markdown",
"Python"
] | 5
|
Python
|
Reksa4/get
|
554ab1a816bc1bbf9791fe3acc03b8a215cbe62f
|
46ee0b89849ba50184b60f927a424df47b0bbc24
|
refs/heads/master
|
<repo_name>zjjfx88/demo_pro<file_sep>/webqo/views.py
from django.shortcuts import render, HttpResponse
import time, json
import requests
from bs4 import BeautifulSoup
import difflib
def debug(request):
if request.method == 'GET':
return render(request, 'webqo/debug.html')
elif request.method == 'POST':
ret = {
'status': True,
'error': None,
'data': None
}
inputHost = request.POST.get('inputHost')
inputExpId = request.POST.get('inputExpId')
query_from = request.POST.get('query_from')
query = request.POST.get('query')
if inputExpId == '':
inputExpId = 0
else:
inputExpId = inputExpId
if query_from == '':
query_from = 0
else:
query_from = query_from
query_from = hex(int(query_from)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
query_from = query_from.encode('utf-16LE')
exp_id = hex(int(inputExpId)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
exp_id = exp_id.encode('utf-16LE')
utf16_query = query.encode('utf-16LE', 'ignore')
params = {
'queryString': utf16_query,
'queryFrom': query_from,
'exp_id': exp_id
}
headers = {"Content-type": "application/x-www-form-urlencoded;charset=UTF-16LE"}
try:
resp = requests.post(inputHost, data=params, headers=headers)
status = resp.reason
if status != 'OK':
ret['error'] = 'Error:未知的请求类型'
ret['status'] = False
return ret
data = BeautifulSoup(resp.text,"html.parser")
ret['data'] = data.prettify()
except Exception as e:
ret['error'] = "Error:" + str(e)
ret['status'] = False
return HttpResponse(json.dumps(ret))
def debug_diff(request):
ret = {
'status': True,
'error': None,
'data': None
}
inputHost = request.POST.get('inputHost')
inputExpId = request.POST.get('inputExpId')
query_from = request.POST.get('query_from')
inputHost_diff = request.POST.get('inputHost_diff')
inputExpId_diff = request.POST.get('inputExpId_diff')
query_from_diff = request.POST.get('query_from_diff')
query = request.POST.get('query')
if inputExpId == '':
inputExpId = 0
else:
inputExpId = inputExpId
if inputExpId_diff == '':
inputExpId_diff = 0
else:
inputExpId_diff = inputExpId_diff
if query_from == '':
query_from = 0
else:
query_from = query_from
if query_from_diff == '':
query_from_diff = 0
else:
query_from_diff = query_from_diff
query_from = hex(int(query_from)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
query_from = query_from.encode('utf-16LE')
query_from_diff = hex(int(query_from_diff)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
query_from_diff = query_from_diff.encode('utf-16LE')
exp_id = hex(int(inputExpId)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
exp_id = exp_id.encode('utf-16LE')
exp_id_diff = hex(int(inputExpId_diff)).split('0x')[1] + "^0^0^0^0^0^0^0^0"
exp_id_diff = exp_id_diff.encode('utf-16LE')
utf16_query = query.encode('utf-16LE', 'ignore')
params = {
'queryString': utf16_query,
'queryFrom': query_from,
'exp_id': exp_id
}
params_diff = {
'queryString': utf16_query,
'queryFrom': query_from_diff,
'exp_id': exp_id_diff
}
headers = {"Content-type": "application/x-www-form-urlencoded;charset=UTF-16LE"}
try:
resp = requests.post(inputHost, data=params, headers=headers)
resp_diff = requests.post(inputHost_diff, data=params_diff, headers=headers)
status = resp.reason
status_diff = resp_diff.reason
if status != 'OK' or status_diff != 'OK':
ret['error'] = 'Error:未知的请求类型'
ret['status'] = False
return ret
data = BeautifulSoup(resp.text,"html.parser")
data_diff = BeautifulSoup(resp_diff.text,"html.parser")
diff = difflib.HtmlDiff()
ret['data'] = diff.make_table(data.prettify().splitlines(), data_diff.prettify().splitlines()).replace('nowrap="nowrap"', '')
except Exception as e:
ret['error'] = "Error:" + str(e)
ret['status'] = False
return HttpResponse(json.dumps(ret))
def get_now_time():
timeArray = time.localtime()
return time.strftime("%Y-%m-%d %H:%M:%S", timeArray)
def str_dos2unix(input):
return input.replace('\r\n', '\n').replace(' ', '')
<file_sep>/webqo/templatetags/tag_tools.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'zhangjingjun'
__mtime__ = '2018/3/29'
# ----------Dragon be here!----------
┏━┓ ┏━┓
┏━┛ ┻━━━━━━┛ ┻━━┓
┃ ━ ┃
┃ ━┳━┛ ┗━┳━ ┃
┃ ┻ ┃
┗━━━┓ ┏━━━━┛
┃ ┃神兽保佑
┃ ┃永无BUG!
┃ ┗━━━━━━━━━┓
┃ ┣━┓
┃ ┏━┛
┗━━┓ ┓ ┏━━━┳━┓ ┏━┛
┃ ┫ ┫ ┃ ┫ ┫
┗━┻━┛ ┗━┻━┛
"""
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
import requests
import html
@register.simple_tag
def formatTime(intime):
return intime.strftime("%m%d %H:%M")
@register.simple_tag
def formatIp(inip):
ip = 'http://10.153.51.60:12000/xml'
ip_list = inip.split('/')
return ip_list[2]
@register.simple_tag
def formatStr(htmlStr):
s =html.unescape(htmlStr)
s = s.replace('nowrap="nowrap"','')
with open('diff.html','w',encoding='utf-8') as fw:
fw.write(htmlStr)
return s
@register.simple_tag
def getRate(finishNum,diffNum):
result=0
if finishNum!=0:
result = round(float(diffNum)/float(finishNum)*100,2)
return result
if __name__ == '__main__':
pass<file_sep>/webqo/apps.py
from django.apps import AppConfig
class WebqoConfig(AppConfig):
name = 'webqo'
|
c8589dbaf573acc2263e2b13a3211537775f6e1e
|
[
"Python"
] | 3
|
Python
|
zjjfx88/demo_pro
|
97ead80d504eff4a1bcf32e05eecb9b6a8445510
|
db9c5257af3037442624be32d278bbe5db59f547
|
refs/heads/master
|
<repo_name>Nafiz43/Poritran<file_sep>/app/src/main/java/com/example/poritraanvolunteer/WaitingForApproval.java
package com.example.poritraanvolunteer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class WaitingForApproval extends AppCompatActivity {
Button home, add, pending, approved, submit, my, logout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_waiting_for_approval);
home = findViewById(R.id.homeWA);
}
}
<file_sep>/app/src/main/java/com/example/poritraanvolunteer/MainActivity.java
package com.example.poritraanvolunteer;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import static maes.tech.intentanim.CustomIntent.customType;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
public class MainActivity extends AppCompatActivity {
EditText e1,e2;
Button b;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
e1 = findViewById(R.id.nameEdit);
e2 = findViewById(R.id.idEdit);
b = findViewById(R.id.submitButton);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, AddRequest.class);
startActivity(intent);
customType(MainActivity.this, "left-to-right");
}
});
}
}
|
c36652e0bca47e725c2f6bd110ff21cea70db1cc
|
[
"Java"
] | 2
|
Java
|
Nafiz43/Poritran
|
4f4e86e0828ce2d4ac67ec86f424d306b32b67c0
|
1d2ba817611c005c77825a5fe8c4b21e682ac880
|
refs/heads/master
|
<file_sep>// from data.js
var tableData = data;
console.log('we are totalling running app.js')
// YOUR CODE HERE!
function createtable(data){
var tblbody = document.getElementsByTagName("tbody")[0];
for(var i = 0; i < data.length; i++){
var row = document.createElement("tr");
var cell = document.createElement("th");
var date = document.createTextNode(data[i].datetime);
cell.appendChild(date)
row.appendChild(cell)
var city = document.createTextNode(data[i].city);
var cell_city = document.createElement("th");
cell_city.appendChild(city);
row.appendChild(cell_city);
var state = document.createTextNode(data[i].state);
var cell_state = document.createElement("th");
cell_state.appendChild(state);
row.appendChild(state);
var country = document.createTextNode(data[i].country);
var cell_country = document.createElement("th");
cell_country.appendChild(country);
row.appendChild(cell_country);
var shape = document.createTextNode(data[i].shape);
var cell_shape = document.createElement("th");
cell_shape.appendChild(shape);
row.appendChild(cell_shape);
var time = document.createTextNode(data[i].durationMinutes);
var cell_time = document.createElement("th");
cell_time.appendChild(time);
row.append(cell_time);
var com = document.createTextNode(data[i].comments);
var cell_com = document.createElement("th");
cell_com.appendChild(com);
row.appendChild(cell_com);
//cell.appendChild(date);
//cell.appendChild(city);
//cell.appendChild(state);
//cell.appendChild(country);
//cell.appendChild(shape);
//cell.appendChild(time);
//cell.appendChild(com);
//row.appendChild(cell);
// console.log('works')
tblbody.appendChild(row);
}
//tbl.appendChild(tblbody);
//body.appendChild(tbl);
}
createtable(data)
d3.select("#filter-btn").on("click", function(){
d3.event.preventDefault();
//d3.select("#ufo-table").find("tr:not(:first)").remove();
d3.select('.my_marker').html("")
/*
for (var i = 0; i <= data.length -1 ; i++) {
document.getElementById("ufo-table").deleteRow(1);
}
*/
var inputValue = d3.select("#datetime").property("value");
if(inputValue == ""){
createtable(data)
return
}
console.log(`input value: ${inputValue}`)
// var tblbody = document.getElementsByTagName("tbody")[0];
var filtered_data = data.filter(function (x){
return inputValue == x.datetime
})
createtable(filtered_data)
});
/*
for(var i = 0; i <= data.length - 1; i++){
var row = document.createElement("tr");
if(inputValue === data[i].datetime){
var cell = document.createElement("th");
var date = document.createTextNode(data[i].datetime);
cell.appendChild(date)
row.appendChild(cell)
var city = document.createTextNode(data[i].city);
var cell_city = document.createElement("th");
cell_city.appendChild(city);
row.appendChild(cell_city);
var state = document.createTextNode(data[i].state);
var cell_state = document.createElement("th");
cell_state.appendChild(state);
row.appendChild(state);
var country = document.createTextNode(data[i].country);
var cell_country = document.createElement("th");
cell_country.appendChild(country);
row.appendChild(cell_country);
var shape = document.createTextNode(data[i].shape);
var cell_shape = document.createElement("th");
cell_shape.appendChild(shape);
row.appendChild(cell_shape);
var time = document.createTextNode(data[i].durationMinutes);
var cell_time = document.createElement("th");
cell_time.appendChild(time);
row.append(cell_time);
var com = document.createTextNode(data[i].comments);
var cell_com = document.createElement("th");
cell_com.appendChild(com);
row.appendChild(cell_com);
//cell.appendChild(date);
//cell.appendChild(city);
//cell.appendChild(state);
//cell.appendChild(country);
//cell.appendChild(shape);
//cell.appendChild(time);
//cell.appendChild(com);
//row.appendChild(cell);
// console.log('works')
tblbody.appendChild(row);
}
}
//tbl.appendChild(tblbody);
//body.appendChild(tbl);
*/
|
d9f8efed6a70f51592642a58ddd87e25c0e638f8
|
[
"JavaScript"
] | 1
|
JavaScript
|
anyx8860/javaskscript_intro
|
d0e27b94f9e7662d7bb0c054294e065e2969171e
|
820c0a34ddd43a9035157d5d33245d6177b4f186
|
refs/heads/master
|
<repo_name>iwanbazz/assignPhp<file_sep>/test2/file_types/Type_C.php
<?php
return [
'columns_size' => 5,
'columns_header' => [
'Field_A',
'Field_B',
'#Field_C',
'Field_D',
'Field_D*'
]
];
<file_sep>/test2/src/ExcelValidator.php
<?php
namespace IwanBazz;
use PhpOffice\PhpSpreadsheet\IOFactory;
use jc21\CliTable;
class ExcelValidator
{
public $spreadsheet;
public $allowed_extension = ['xlsx', 'xls'];
private $sheet;
private $extension;
private $errors;
private $config;
private $header;
public function __construct($files)
{
$this->extension = ucfirst(pathinfo($files, PATHINFO_EXTENSION));
$reader = IOFactory::createReader($this->extension);
$reader->setReadDataOnly(true);
$reader->setReadEmptyCells(false);
$this->spreadsheet = $reader->load($files);
}
public function validate($file_type = 'A', $sheet = 0)
{
$this->config = file_type($file_type);
$this->sheet = $this->spreadsheet->getSheet($sheet);
if ($this->validateFileExtension() == false) {
$this->errors[0][] = 'Sorry we only accept ' . implode(', ', $this->allowed_extension) . ' file extenstion';
return false;
}
if ($this->validateColumnSize($this->config['columns_size']) == false) {
$this->errors[0][] = 'Maximum column size for Type ' . $file_type . ' is ' . $this->config['columns_size'];
return false;
}
if ($this->validateHeader($this->config['columns_header']) == false) {
$this->errors[0][] = 'Type ' . $file_type . ' header must follow the following name and order : ' . implode(' | ', $this->config['columns_header']);
return false;
}
foreach ($this->sheet->getRowIterator() as $key => $row) {
$cellIterator = $row->getCellIterator();
foreach ($cellIterator as $column => $cell) {
$cellValue = $cell->getValue();
if ($key == 1) {
if (substr($cellValue, 0, 1) == '#') {
$rule[$column] = 'no_space_allowed';
}
if (substr($cellValue, -1) == '*') {
$rule[$column] = 'required';
}
} else {
$validatedValue = $this->validateValue($cellValue, $column, $rule[$column] ?? null);
if ($validatedValue && $validatedValue['status'] == false) {
$this->errors[$key][] = $validatedValue['message'];
}
}
}
}
}
private function validateValue($value, $column, $rule = null)
{
if ($rule) {
switch ($rule) {
case 'required':
if (!$value) {
return ['status' => false, 'message' => 'Missing value in Field_' . $column];
}
return ['status' => true];
break;
case 'no_space_allowed':
if (strpos($value, ' ')) {
return ['status' => false, 'message' => 'Field_' . $column . ' should not contain any space'];
}
return ['status' => true];
break;
}
}
}
private function validateColumnSize($maxWidth)
{
return $maxWidth >= \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($this->sheet->getHighestColumn());
}
private function validateHeader($headerOrder)
{
$this->setHeader();
return $headerOrder === $this->header;
}
private function setHeader()
{
$row = $this->sheet->getRowIterator(1)->current();
$cell = $row->getCellIterator();
foreach ($cell as $key => $value) {
$header[] = $value->getValue();
}
$this->header = $header;
}
public function printOut()
{
$table = new CliTable();
$table->setTableColor('blue');
$table->setHeaderColor('cyan');
$table->addField('Row', 'row', false, 'white');
$table->addField('Error', 'errors', false, 'white');
foreach ($this->errors as $key => $value) {
$errors[$key]['row'] = $key;
$errors[$key]['errors'] = implode(', ', $value);
}
$table->injectData($errors);
$table->display();
}
private function validateFileExtension()
{
return in_array(strtolower($this->extension), $this->allowed_extension);
}
}
<file_sep>/test2/helpers.php
<?php
if (!function_exists('file_type')) {
function file_type($value)
{
return include './file_types/Type_' . $value . '.php';
}
}
if (!function_exists('diedump')) {
function diedump($value)
{
die(var_dump($value));
}
}
<file_sep>/test2/index.php
<?php
require __DIR__ . '/vendor/autoload.php';
use IwanBazz\ExcelValidator;
echo "Validate Type_A\n";
$excelValidator = new ExcelValidator('./input_file/Type_A.xlsx');
$excelValidator->validate('A', 0);
$excelValidator->printOut();
echo "Validate Type_B\n";
$excelValidator = new ExcelValidator('./input_file/Type_B.xlsx');
$excelValidator->validate('B', 0);
$excelValidator->printOut();
echo "Validate Type_C\n";
$excelValidator = new ExcelValidator('./input_file/Type_C.xls');
$excelValidator->validate('C', 0);
$excelValidator->printOut();
<file_sep>/test1/index.php
<?php
$input1 = "a (b c (d e (f) g) h) i (j k)";
$input2 = 2;
function closeParentIndex($string, $index)
{
$pair = [
'(' => ')',
'{' => '}'
];
$arr = str_split($string);
$parentChar = $string[$index];
$parentPair = $pair[$parentChar];
$charCount = 0;
foreach ($arr as $key => $value) {
if ($key > $index) {
if ($value == $parentChar) {
$charCount++;
}
if ($value == $parentPair && $charCount == 0) {
return $key;
}
if ($value == $parentPair && $charCount != 0) {
$charCount--;
}
}
}
}
echo closeParentIndex($input1, $input2);
<file_sep>/test2/file_types/Type_B.php
<?php
return [
'columns_size' => 2,
'columns_header' => [
'Field_A*',
'#Field_B'
]
];
|
8064d388a990093f1bfbaab1ea3b691fcf88789c
|
[
"PHP"
] | 6
|
PHP
|
iwanbazz/assignPhp
|
d520fd602032e0b6e4e711f75851a9f8af917f8d
|
8c7d7cfcf597845b990fd13da17a8fe011219a5e
|
refs/heads/main
|
<repo_name>Nuglif/TestingComparison<file_sep>/README.md
# TestingComparison
Comparaison de librairies d'assertions sur Kotlin/Android.
<file_sep>/app/src/test/java/com/example/testingcomparison/AssertJTest.kt
package com.example.testingcomparison
import org.assertj.core.api.Assertions
import org.assertj.core.api.ListAssert
import org.junit.Test
class AssertJTest {
private val animals = listOf("Rex", "Caramel", "Joe", "Anna")
@Test
fun assertJ() {
PalindromeAssert.assertThat(animals)
.hasAPalindrome()
Assertions.assertThat(animals)
.hasOnlyElementsOfType(String::class.java) // Pretty weird IMO
.contains("Rex")
.doesNotContain("Snow")
.hasSize(3)
}
private class PalindromeAssert(list: List<String>) :
ListAssert<String>(list) {
companion object {
fun assertThat(actual: List<String>): PalindromeAssert {
return PalindromeAssert(actual)
}
}
fun hasAPalindrome(): PalindromeAssert {
if (!actual.any { it.reversed().equals(it, ignoreCase = true) }) {
failWithMessage("List doesn't contain a palindrome")
}
return this
}
}
}<file_sep>/app/src/test/java/com/example/testingcomparison/StriktTest.kt
package com.example.testingcomparison
import org.junit.Test
import strikt.api.Assertion
import strikt.api.expectThat
import strikt.assertions.contains
import strikt.assertions.doesNotContain
import strikt.assertions.hasSize
import strikt.assertions.isA
class StriktTest {
private val animals = listOf("Rex", "Caramel", "Joe", "Anna")
@Test
fun striktList() {
expectThat(animals)
.isA<List<String>>()
.contains("Rex")
.doesNotContain("Snow")
.hasAPalindrome()
.hasSize(3)
}
@Test
fun striktSucceeds(){
expectThat(animals)
.contains("Rex")
.doesNotContain("Snow")
.hasAPalindrome()
}
@Test
fun striktSoftList() {
expectThat(animals) {
hasSize(3)
contains("Rex")
doesNotContain("Snow")
}
}
private fun <T : Iterable<String>> Assertion.Builder<T>.hasAPalindrome(): Assertion.Builder<T> =
assert("has a palindrome") {
when (it.any { value -> value.reversed().equals(value, ignoreCase = true) }) {
true -> pass()
else -> fail()
}
}
}<file_sep>/settings.gradle
rootProject.name = "TestingComparison"
include ':app'
<file_sep>/app/src/test/java/com/example/testingcomparison/KoTestTest.kt
package com.example.testingcomparison
import io.kotest.assertions.assertSoftly
import io.kotest.matchers.Matcher
import io.kotest.matchers.MatcherResult
import io.kotest.matchers.collections.shouldContain
import io.kotest.matchers.collections.shouldHaveSize
import io.kotest.matchers.collections.shouldNotContain
import io.kotest.matchers.should
import io.kotest.matchers.types.shouldBeInstanceOf
import org.junit.Test
class KoTestTest {
private val animals = listOf("Rex", "Caramel", "Joe", "Anna")
@Test
fun kotest() {
animals should containPalyndrom()
animals
.shouldBeInstanceOf<List<String>>()
.shouldContain("Rex") // Doesn't let me chain here
animals.shouldNotContain("Snow") // Doesn't let me chain here
animals.shouldHaveSize(3)
}
@Test
fun kotestSoftList() {
assertSoftly {
animals.shouldHaveSize(2)
animals
.shouldBeInstanceOf<List<String>>()
.shouldContain("Rex") // Doesn't let me chain here
animals.shouldNotContain("Snow") // Doesn't let me chain here
animals.shouldHaveSize(3)
}
}
fun containPalyndrom() = object : Matcher<List<String>> {
override fun test(value: List<String>): MatcherResult {
return MatcherResult(
value.any { it.reversed().equals(it, ignoreCase = true) },
"List should contain palindrome",
"List shouldn't contain palindrome"
)
}
}
}<file_sep>/app/src/test/java/com/example/testingcomparison/KotlinTest.kt
package com.example.testingcomparison
import org.junit.Test
import kotlin.test.assertContains
import kotlin.test.assertFalse
import kotlin.test.assertIs
import kotlin.test.assertTrue
import kotlin.test.asserter
class KotlinTest {
private val animals = listOf("Rex", "Caramel", "Joe", "Anna")
@Test
fun kotlintest() {
assertIs<List<String>>(animals)
assertContains(animals, "Rex")
assertFalse { animals.contains("Snow") }
assertHasPalindrome(animals)
assertTrue { animals.size == 3 }
}
private fun assertHasPalindrome(iterable: Iterable<String>) {
asserter.assertTrue(
{ "Expected the collection to contain a palindrome.\nCollection <$iterable>" },
iterable.any { it.reversed().equals(it,ignoreCase = true) }
)
}
}
|
ad18ef91ba318bbd1b74de7c8a378689baf13498
|
[
"Markdown",
"Kotlin",
"Gradle"
] | 6
|
Markdown
|
Nuglif/TestingComparison
|
971c23293c88adfd2c33636c2d4e910d67e9d41d
|
66a48455f8756e3b03214f0dbd4887a374800d08
|
refs/heads/master
|
<repo_name>conyourface/pysites<file_sep>/getcontent.py
from requests_html import HTMLSession
session = HTMLSession()
# tlist=[]
# mylist = [ ]
# i=1
# while i<3:
# url='http://www.snqbbs.co/forum.php?mod=forumdisplay&fid=2&orderby=dateline&orderby=dateline&filter=author&page='+str(i)
# i=i+1
# print("正在查询第",i,"页")
# r = session.get(url)
# sel = 'tr > th > div > div.messBox > div.fromText > a'
# #results = r.html.find(sel)
# #print(results)
# #results[0].text
# #print(results[0].text)
# def get_text_link_from_sel(sel):
# #mylist = [ ]
# try:
# results=r.html.find(sel)
# for result in results:
# mytext=result.text
# mylink = list(result.absolute_links)[0]
# mylist.append((mytext,mylink))
# return mylist
# except:
# return none
# tlist.append(get_text_link_from_sel(sel))
# print(tlist)
# import pandas as pd
# #df = pd.DataFrame(get_text_link_from_sel(sel))
# def func3(mylist):
# '''
# 使用列表推导的方式
# '''
# temp_list=[]
# for one in mylist:
# if one not in temp_list:
# temp_list.append(one)
# return temp_list
# df = pd.DataFrame(func3(mylist))
# #df.columns = ['username']
# print (df)
# df.to_excel('e:/code/username.xlsx', encoding='gbk', index=False)
from typing import Any
def getcontent(base_url,sel,page_num):
mylist = []
for i in range (1,page_num):
#base_url+=str(i)
url = base_url + str(i)
print (url)
print("正在查询第", i, "页")
try:
results = session.get(url).html.find(sel)
#print (results)
for result in results:
mytext = result.text
mylink = list(result.absolute_links)[0]
print (mylink)
mylist.append((mytext,mylink))
print (mylist)
#return mylist
except:
print ("第", i, "页查询错误")
#print (mylist)
return mylist
if __name__ == '__main__' :
getcontent('http://www.snqbbs.co/forum.php?mod=forumdisplay&fid=2&orderby=dateline&orderby=dateline&filter=author&page=',' tr > th > div > div.messBox > div.fromText > a',2)
|
8ce9cfcfa7eac45d2c3c6a01a59cbcedf5da45e1
|
[
"Python"
] | 1
|
Python
|
conyourface/pysites
|
625dbf7d6c97ab62ae70767253f9a266ba4e6a32
|
32713dbbfd53fc20d1e1f86da2786631f455c54e
|
refs/heads/master
|
<file_sep>package server;
import com.google.gson.Gson;
import models.Game;
import models.GameStorage;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import java.util.*;
@Controller
@RequestMapping("/api/games")
public class NintendoAPI {
// Create
@PostMapping
@ResponseBody
public ModelAndView createGame (
@RequestParam("title") String title,
@RequestParam("genre") String genre,
@RequestParam("releaseDate") String releaseDate
) {
Game game = new Game(title, genre, releaseDate);
GameStorage.games.put(game.id, game);
return new ModelAndView("redirect:/games");
}
// Read all
@GetMapping
@ResponseBody
public List<Game> getAllGames () {
Collection<Game> games = GameStorage.games.values();
return new ArrayList<>(games);
}
// Read one
@GetMapping("/{id}")
@ResponseBody
public Game getOneGame (@PathVariable("id") int id) {
Game result = GameStorage.games.get(id);
return result;
}
// Update
@PutMapping("/{id}")
@ResponseBody
public Game updateGame (
@PathVariable("id") int id,
@RequestBody String body
) {
Gson gson = new Gson();
Game newGame = gson.fromJson(body, Game.class);
Game game = GameStorage.games.get(id);
game.title = newGame.title;
game.genre = newGame.genre;
game.releaseDate = newGame.releaseDate;
return game;
}
// Destroy
@DeleteMapping("/{id}")
@ResponseBody
public Game deleteGame (@PathVariable("id") int id) {
Game game = GameStorage.games.get(id);
GameStorage.games.remove(id);
return game;
}
}
<file_sep>package models;
import java.util.*;
public class GameStorage {
public static Map<Integer, Game> games;
static {
games = new HashMap<>();
Game breathOfWild = new Game("Zelda: Breath of the Wild", "Adventure", "March 3, 2017");
Game majorasMask = new Game("Zelda: Majora's Mask", "Adventure", "April 27, 2000");
Game smashBros = new Game("Super Smash Bros", "Fighter", "January 21, 1999");
Game starfox = new Game("Star Fox 64", "Shooter", "April 27, 1997");
Game jamesBond = new Game("Goldeneye 007", "Shooter", "August 25, 1997");
games.put(breathOfWild.id, breathOfWild);
games.put(majorasMask.id, majorasMask);
games.put(smashBros.id, smashBros);
games.put(starfox.id, starfox);
games.put(jamesBond.id, jamesBond);
}
}
|
a76b67849fd95fddaf39a497e04ed9593e603d4e
|
[
"Java"
] | 2
|
Java
|
brandon-fenty/12-restful-server
|
cbd18feb0633a9b2727a1c0159b8dc5b9153c612
|
9e85a58ccb738326c7a172ccd259960b5e866d18
|
refs/heads/master
|
<file_sep><?php
namespace yii2patterns\traits;
/**
* Class SplObserver - Трейт для реализации интерфейса \SplObserver
* @package yii2patterns\traits
*/
trait SplObserver
{
public function update(\SplSubject $subject) {
$this->handle($subject->getContent());
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: dmitriy
* Date: 11/30/15
* Time: 6:29 PM
*/
namespace yii2patterns\Contracts\Bus;
interface Handler
{
/**
* @param $object
* @return mixed
*/
public function handle($object);
}<file_sep><?php
namespace yii2patterns\Contracts;
interface Singleton
{
public function getInstance();
}<file_sep><?php
namespace yii2patterns\traits;
/**
* Class SplObserver - Трейт для реализации интерфейса \SplSubject
* @package yii2patterns\traits
*/
trait SplSubject
{
public function attach(\SplObserver $observer)
{
$this->observers[] = $observer;
}
public function detach(\SplObserver $observer)
{
$key = array_search($observer, $this->observers, true);
if ($key) {
unset($this->observers[$key]);
}
}
public function notify($object) {
foreach ($this->observers as $value) {
$value->update($object);
}
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: dmitriy
* Date: 11/30/15
* Time: 6:59 PM
*/
namespace yii2patterns\traits;
trait Singleton
{
private static $instance;
public static function getInstance()
{
if (null === static::$instance) {
static::$instance = new static();
}
return static::$instance;
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: dmitriy
* Date: 11/30/15
* Time: 6:26 PM
*/
namespace yii2patterns\command\handlerclasses;
use yii2patterns\Contracts\Bus\Handler as CommandHandlerContract;
use yii2patterns\Contracts\Singleton as SingletonContract;
use yii2patterns\traits\SplObserver as SplObserverTrait;
use yii2patterns\traits\Singleton as SingletonTrait;
class SelfHandler implements CommandHandlerContract, SingletonContract, \SplObserver
{
use SplObserverTrait;
use SingletonTrait;
public function handle($subject){
$subject->getObject()->handle();
}
}<file_sep><?php
/**
* Created by PhpStorm.
* User: dmitriy
* Date: 11/27/15
* Time: 4:22 PM
*/
namespace yii2patterns\src;
use yii2patterns\Contracts\Bus\Dispatcher as CommandBusContract;
use yii2patterns\Traits\SplSubject as SplSubjectTrait;
use yii2patterns\command\handlerclasses\SelfHandler;
class CommandBus implements \SplSubject, CommandBusContract
{
use SplSubjectTrait;
private $observers = array();
private $object;
public function construct(){
}
/**
* Функция - обработчик команды, создает объект класса команды и передает его слушателям
* @param $command
* @param \ArrayAccess $commandData
*/
public function handle($command, \ArrayAccess $commandData = null)
{
$class = new \ReflectionClass($command);
$this->object = $class->newInstanceArgs($commandData);
/* Если у класса нет интерфейсов, то выполняем его в контексте класса selfHanding, иначе кидаем подписчикам, реализующим интерфейсы */
if(empty($class->getInterfaces())){
SelfHandler::getInstance()->handle($this->object);
}else{
$this->notify();
}
}
public function getObject(){
return $this->object;
}
}<file_sep><?php
namespace yii2patterns\Contracts\Bus;
use Closure;
use ArrayAccess;
interface Dispatcher
{
/**
* @param $command
* @param Closure|null $afterResolving
* @return mixed
*/
public function handle($command, \ArrayAccess $commandData = null);
}
|
e727acb3a32577855f2ca12a95484c576ef163dc
|
[
"PHP"
] | 8
|
PHP
|
kurlovichdv/yiipatterns
|
27f66d3cf1f5a947147e29cc8997d11aafb4e523
|
a0eb4a61bbba2e6c7898a944e54d028edf5b6368
|
refs/heads/main
|
<repo_name>Mati2206/my-first-chess<file_sep>/main.pyw
import pygame
from CONST import *
from Figures import Figures
import os, sys
class Game:
def load_image(self):
self.images = {}
for img in os.listdir("images") :
self.images[img.replace(".png", "")] = pygame.transform.scale(pygame.image.load("images/" + img), (SQUARE_SIZE, SQUARE_SIZE))
def screen(self):
pygame.init()
self.screen = pygame.display.set_mode(SCREEN_SIZE)
def __init__(self):
self.screen()
self.load_image()
self.board = [
["bR", "bN", "bB", "bQ", "bK", "bB", "bN", "bR"],
["bp", "bp", "bp", "bp", "bp", "bp", "bp", "bp"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["--", "--", "--", "--", "--", "--", "--", "--"],
["wp", "wp", "wp", "wp", "wp", "wp", "wp", "wp"],
["wR", "wN", "wB", "wQ", "wK", "wB", "wN", "wR"]]
self.turn = "w"
self.click1 = None
self.click2 = None
self.white = [(192, 192, 192), (192, 255, 255)]
self.black = [(128, 0, 128), (128, 255, 255)]
self.castling_white = [True, True]
self.castling_black = [True, True]
self.second_b = False
self.first = None
self.circle = False
self.main()
def main(self):
while True:
self.load_figures()
self.draw_image()
self.check_events()
def load_figures(self):
self.figures = []
for i in range(8):
self.figures.append([])
for j in range(8):
self.figures[i].append(Figures((j*SQUARE_SIZE, i*SQUARE_SIZE), self.board[i][j], (i, j), (self.castling_white, self.castling_black)))
def mouse(self):
mouse = pygame.mouse.get_pos()
if self.second_b:
moves, castling = self.moves()
for i in range(8):
for j in range(8):
if self.figures[i][j].collidepoint(mouse[0], mouse[1]) and (i, j) in moves:
self.move(self.first.np[0], self.first.np[1], i, j)
if castling[0][0] == True and (i, j) == (7, 2):
self.move(7, 0, 7, 3)
if castling[1][0] == True and (i, j) == (7, 6):
self.move(7, 7, 7, 5)
if castling[0][1] == True and (i, j) == (0, 2):
self.move(0, 0, 0, 3)
if castling[1][1] == True and (i, j) == (0, 6):
self.move(0, 7, 0, 5)
self.click2 = (i, j)
self.second_b = False
if self.first.name == "K" and self.first.color == "w":
self.castling_white = [False, False]
elif self.first.name == "K" and self.first.color == "b":
self.castling_black = [False, False]
if self.first.name == "R" and self.first.color == "w" and self.first.np == (7, 0):
self.castling_white[0] = False
if self.first.name == "R" and self.first.color == "w" and self.first.np == (7, 7):
self.castling_white[1] = False
if self.first.name == "R" and self.first.color == "b" and self.first.np == (0, 0):
self.castling_black[0] = False
if self.first.name == "R" and self.first.color == "b" and self.first.np == (0, 7):
self.castling_black[1] = False
if self.turn == "w":
self.turn = "b"
else:
self.turn = "w"
else:
self.second_b = False
self.click1 = None
else:
for i in range(8):
for j in range(8):
if self.figures[i][j].name != "-" and self.figures[i][j].collidepoint(mouse[0], mouse[1]):
self.click2 = None
self.click1 = (i, j)
self.second_b = True
self.first = self.figures[i][j]
if not self.second_b:
self.click1 = None
self.click2 = None
def check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit(0)
if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
self.mouse()
def move(self, x1, y1, x2, y2):
self.board[x2][y2] = self.board[x1][y1]
self.board[x1][y1] = "--"
def draw_chessboard(self):
self.circle = False
for i in range(8):
for j in range(8):
rect = pygame.Rect(i*SQUARE_SIZE, j*SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)
if i%2 - j%2:
if (j, i) == self.click2:
color = self.black[1]
elif (j, i) == self.click1:
color = self.black[1]
self.circle = True
else:
color = self.black[0]
else:
if (j, i) == self.click1:
color = self.white[1]
self.circle = True
elif (j, i) == self.click2:
color = self.white[1]
else:
color = self.white[0]
pygame.draw.rect(self.screen, color, rect)
def moves(self):
for i in range(8):
for j in range(8):
if (i, j) == self.click1 and self.figures[i][j].name == "p" and self.figures[i][j].color == self.turn:
return self.figures[i][j].pawn(self.figures), ((False, False), (False, False))
elif (i, j) == self.click1 and self.figures[i][j].name == "N" and self.figures[i][j].color == self.turn:
return self.figures[i][j].knight(self.figures), ((False, False), (False, False))
elif (i, j) == self.click1 and self.figures[i][j].name == "B" and self.figures[i][j].color == self.turn:
return self.figures[i][j].bishop(self.figures), ((False, False), (False, False))
elif (i, j) == self.click1 and self.figures[i][j].name == "R" and self.figures[i][j].color == self.turn:
return self.figures[i][j].rock(self.figures), ((False, False), (False, False))
elif (i, j) == self.click1 and self.figures[i][j].name == "Q" and self.figures[i][j].color == self.turn:
return self.figures[i][j].queen(self.figures), ((False, False), (False, False))
elif (i, j) == self.click1 and self.figures[i][j].name == "K" and self.figures[i][j].color == self.turn:
return self.figures[i][j].king(self.figures)
return [], ((False, False), (False, False))
def draw_image(self):
self.draw_chessboard()
for i in range(8):
for j in range(8):
if self.board[i][j] != "--":
self.screen.blit(self.images[self.board[i][j]], (j*SQUARE_SIZE, i*SQUARE_SIZE))
if self.circle:
for i in self.moves()[0]:
pygame.draw.circle(self.screen, (128, 255, 128), (i[1]*SQUARE_SIZE+SQUARE_SIZE/2, i[0]*SQUARE_SIZE+SQUARE_SIZE/2), 10)
pygame.display.flip()
Game()
<file_sep>/Figures.py
import pygame
from CONST import *
class Figures(pygame.Rect):
def __init__(self, xy, name, np, castiling):
self.w = SQUARE_SIZE
self.h = SQUARE_SIZE
self.x = xy[0]
self.y = xy[1]
self.np = np
self.color = name[0]
self.name = name[1]
self.castling_white = castiling[0]
self.castling_black = castiling[1]
def pawn(self, figures):
minus = 1
moves = []
if self.color == "w":
minus = -1
for i in range(8):
for j in range(8):
f = figures[i][j]
if (i-1*minus, j) == self.np and f.name == "-":
moves.append((i, j))
elif (i-2*minus, j) == self.np and f.name == "-" and figures[i-1*minus][j].name == "-" and ((i-2*minus == 6 and self.color == "w") or (i-2*minus == 1 and self.color == "b")):
moves.append((i, j))
elif ((i-1*minus, j+1) == self.np or (i-1*minus, j-1) == self.np) and f.color != self.color and f.name != "-":
moves.append((i, j))
return moves
def rock(self, figures):
minus = 1
moves = []
if self.color == "w":
minus = -1
N = True
E = True
S = True
W = True
for k in range(1,8):
for i in range(8):
for j in range(8):
f = figures[i][j]
if f.name != "-" and (i-k*minus, j) == self.np:
if f.color != self.color and f.color != "-" and N:
moves.append((i, j))
N = False
elif f.name != "-" and (i, j-k*minus) == self.np:
if f.color != self.color and f.color != "-" and E:
moves.append((i, j))
E = False
elif f.name != "-" and (i+k*minus, j) == self.np:
if f.color != self.color and f.color != "-" and S:
moves.append((i, j))
S = False
elif f.name != "-" and (i, j+k*minus) == self.np:
if f.color != self.color and f.color != "-" and W:
moves.append((i, j))
W = False
elif (i-k*minus, j) == self.np and N:
moves.append((i, j))
elif (i, j-k*minus) == self.np and E:
moves.append((i, j))
elif (i+k*minus, j) == self.np and S:
moves.append((i, j))
elif (i, j+k*minus) == self.np and W:
moves.append((i, j))
return moves
def knight(self, figures):
minus = 1
moves = []
if self.color == "w":
minus = -1
for i in range(8):
for j in range(8):
f = figures[i][j]
l1 = 1*minus
l2 = 2*minus
left = (i-l1, j-l2) == self.np or (i+l1, j+l2) == self.np
right = (i+l1, j-l2) == self.np or (i-l1, j+l2) == self.np
top = (i-l2, j-l1) == self.np or (i-l2, j+l1) == self.np
bottom = (i+l2, j-l1) == self.np or (i+l2, j+l1) == self.np
if (top or right or bottom or left) and f.color != self.color:
moves.append((i, j))
return moves
def bishop(self, figures):
minus = 1
moves = []
if self.color == "w":
minus = -1
NW = True
NE = True
SW = True
SE = True
for k in range(1,8):
for i in range(8):
for j in range(8):
f = figures[i][j]
if f.name != "-" and (i-k*minus, j-k*minus) == self.np:
if f.color != self.color and f.color != "-" and NW:
moves.append((i, j))
NW = False
elif f.name != "-" and (i-k*minus, j+k*minus) == self.np:
if f.color != self.color and f.color != "-" and NE:
moves.append((i, j))
NE = False
elif f.name != "-" and (i+k*minus, j-k*minus) == self.np:
if f.color != self.color and f.color != "-" and SW:
moves.append((i, j))
SW = False
elif f.name != "-" and (i+k*minus, j+k*minus) == self.np:
if f.color != self.color and f.color != "-" and SE:
moves.append((i, j))
SE = False
elif (i-k*minus, j-k*minus) == self.np and NW:
moves.append((i, j))
elif (i-k*minus, j+k*minus) == self.np and NE:
moves.append((i, j))
elif (i+k*minus, j-k*minus) == self.np and SW:
moves.append((i, j))
elif (i+k*minus, j+k*minus) == self.np and SE:
moves.append((i, j))
return moves
def queen(self, figures):
moves = []
moves.extend(self.rock(figures))
moves.extend(self.bishop(figures))
return moves
def king(self, figures):
castling_long_white = False
castling_long_black = False
castling_short_white = False
castling_short_black = False
minus = 1
moves = []
if self.color == "w":
minus = -1
for i in range(8):
for j in range(8):
f = figures[i][j]
if (i-1, j) == self.np and f.color != self.color:
moves.append((i, j))
elif (i+1, j) == self.np and f.color != self.color:
moves.append((i, j))
elif (i, j-1) == self.np and f.color != self.color:
moves.append((i, j))
elif (i, j+1) == self.np and f.color != self.color:
moves.append((i, j))
elif (i-1, j-1) == self.np and f.color != self.color:
moves.append((i, j))
elif (i-1, j+1) == self.np and f.color != self.color:
moves.append((i, j))
elif (i+1, j-1) == self.np and f.color != self.color:
moves.append((i, j))
elif (i+1, j+1) == self.np and f.color != self.color:
moves.append((i, j))
if self.castling_white[0]:
f = figures[7]
if f[1].name == "-" and f[2].name == "-" and f[3].name == "-":
moves.append((7, 2))
castling_long_white = True
if self.castling_white[1]:
f = figures[7]
if f[5].name == "-" and f[6].name == "-":
moves.append((7, 6))
castling_short_white = True
if self.castling_black[0]:
f = figures[0]
if f[1].name == "-" and f[2].name == "-" and f[3].name == "-":
moves.append((0, 2))
castling_long_black = True
if self.castling_black[1]:
f = figures[0]
if f[5].name == "-" and f[6].name == "-":
moves.append((0, 6))
castling_short_black = True
return moves, ((castling_long_white, castling_long_black), (castling_short_white, castling_short_black))<file_sep>/CONST.py
SQUARE_SIZE = 90
SCREEN_SIZE = (SQUARE_SIZE * 8, SQUARE_SIZE * 8)
|
8cdf4904951182bb457b3b989d387bafb21b416b
|
[
"Python"
] | 3
|
Python
|
Mati2206/my-first-chess
|
69db0b4ea507bed7ee6a0c58124500c8a4fb9f94
|
a4a2f1fa04ce9241522c3b8a1101844e1f33cb3c
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.