blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
27ea301f0796c2b5ab8ce3e3d1d8d56f7cd869ea | 95c24804065d0e0d803cb64f4a528acae9a412f3 | /code_numer/serial/survive_prob_rot2_orient2.cpp | 51ea8f0994eaa3e4094d4ebe997c28655ed75e82 | [] | no_license | dariushm/BDsample_DM | 27ec9acaa034b95d200c4c671120767c1f67c9d0 | 08b68842cd3d16a0faa37712acb1cd880c90cbfd | refs/heads/master | 2020-05-30T07:12:01.700313 | 2016-09-27T15:06:56 | 2016-09-27T15:06:56 | 69,368,441 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,991 | cpp | /*
particle-based Reaction diffusion
algorithm with trajectory reweighting.
this program only propagates a single pair of particles,
collects statistics for different starting separations over
many repeats.
radiation BC
both particles can rotate.
*/
#include <fstream>
#include <iostream>
#include <ctime>
#include <cmath>
#include <sys/time.h>
#include "rand_gsl.h"
#include "md_timer.h"
#include "vector_rot_calls.h"
#define MAXIFACE 20
#define MAXPRTNER 20
#define MAXCOMPLEX 20
#define MAXRXN 20
#define MAXOVERLAP 20
using namespace std;
struct MD_Timer totaltime;
struct MD_Timer bimoltime;
class Protein
{
public:
int ninterface;
int valiface[MAXIFACE];
int npropart;
int propart[MAXPRTNER];
double Dx;
double Dy;
double Dz;
double radx;
double rady;
double radz;
double Drx;
double Dry;
double Drz;
int nint_write;
int wrlist[MAXIFACE];
};
class Fullmol
{
public:
double mytime;
int mybin;
int mybinind;
int protype;
int ninterface;
int istatus[MAXIFACE];
int npartner;
int mycomplex;
int matrix[MAXIFACE];
double xcom;
double ycom;
double zcom;
double x[MAXIFACE];
double y[MAXIFACE];
double z[MAXIFACE];
int nbnd;
int nfree;
int freelist[MAXIFACE];
int bndlist[MAXIFACE];
double massx;
double massy;
double massz;
int partner[MAXIFACE];
double Dx;
double Dy;
double Dz;
int npropart;
int propart[MAXPRTNER];
double radx;
double rady;
double radz;
};
class Parms
{
public:
double dihed0;
int Nx0;
int Nthet;
int thetbins;
int dihbins;
int tabbins;
double x0;
int Nprotypes;
int Nifaces;
double Nit;
double leglen;
double eps_scale;
double dt_scale;
double rate;
double Maxtime;
int restart;
int statwrite;
int configwrite;
int Nrep;
double deltat;
double V;
double X0total;
int Nspecies;
int Nrxn;
double mass;
double D;
int nspec_complex;
double maxsep2;
int ntotalcomplex;
double xboxl;
double yboxl;
double zboxl;
int Ntotalmol;
int Natom;
int Natomwrite;
};
void read_parms(ifstream &parmfile, Parms &plist);
double GaussV();
double pirr_pfree_ratio_ps(double rcurr, double r0, double tcurr, double Dtot, double bindrad, double alpha, double ps_prev, double rtol);
double survive_irr(double r0, double tcurr, double Dtot, double bindrad, double alpha, double cof);
double pirrev_value(double rcurr, double r0, double tcurr, double Dtot, double bindrad, double alpha);
double pfree_value_norm(double rcurr, double r0, double tcurr, double Dtot, double bindrad,double alpha);
int main(int argc, char *argv[])
{
int i, j, k;
timeval tim;
gettimeofday(&tim, 0);
double t1=tim.tv_sec+tim.tv_usec;
int seed=int(t1);
//seed=1353432282;
double randmax=pow(2.0, 32);
cout <<"seed: "<<seed<<" randmax: "<<randmax<<endl;
srand_gsl(seed);
double irandmax=1.0/randmax;
ifstream parmfile(argv[1]);
Parms plist;
read_parms(parmfile, plist);
// write_parms(plist);
cout.precision(12);
initialize_timer(&totaltime);
initialize_timer(&bimoltime);
start_timer(&totaltime);
int Nprotypes=plist.Nprotypes;//total distinct protein types,
int Nifaces=plist.Nifaces;//this is the number of interfaces
int Nrxn=plist.Nrxn;
int Nspecies=plist.Nspecies;//this will include product species
double cellvol=plist.xboxl*plist.yboxl*plist.zboxl/(1.0*1E9);//sidelength*sidelength*sidelength;
double V=cellvol;
double um_to_L=1E15;
double avagad=6.022E23;
int *Ncopy=new int[Nprotypes];
Ncopy[0]=1;
Ncopy[1]=1;
int Ntotalmol=0;
plist.Natom=0;
int ntmp;
for(i=0;i<Nprotypes;i++){
Ntotalmol+=Ncopy[i];
}
cout <<"Ntotal mols: "<<Ntotalmol<<endl;//ASSUMED TO BE 2 MOLECULES BELOW
plist.Ntotalmol=Ntotalmol;
Fullmol *bases=new Fullmol[Ntotalmol];//contains information on each protein in the full system
int *numpartners=new int[Nifaces];//this should account for all free interfaces
int **Speclist=new int*[Nifaces];
for(i=0;i<Nifaces;i++)
Speclist[i]=new int[MAXPRTNER];
/*A interacts with B*/
numpartners[0]=1;
numpartners[1]=1;
Speclist[0][0]=1;
Speclist[1][0]=0;
char fname[100];
Protein *wholep=new Protein[Nprotypes];
int *p_home=new int[Nifaces];//this reverses and tells you what protein a given interface belongs to
int *i_home=new int[Nspecies];//for both free and bound states, what index are you on the protein's list
double *bindrad=new double[Nrxn];//binding or unbinding radius for each reaction
int *Ncoup=new int[Nrxn];//list of reactions coupled to this one
int **mycoupled=new int*[Nrxn];
for(i=0;i<Nrxn;i++)
mycoupled[i]=new int[MAXRXN];
/*The number of reactions is fixed and all the same reactions are possible in each spatial cell*/
double *kr=new double[Nrxn]; //reaction rate (with dimensions)
int **Rlist=new int*[Nrxn]; //the identity of the species in the reaction
int *Npart=new int[Nrxn]; //The number of participant species in a reaction
int **Del=new int*[Nrxn]; //The coeffiecients of the participants in the reaction
int *rxntype=new int[Nrxn];//this sets whether the reaction is bimolecular, unimolecular.
int maxrctant=5;
for(i=0;i<Nrxn;i++){
Rlist[i]=new int[maxrctant];
Del[i]=new int[maxrctant];
}
/*Each protein has a single site, each protein can have it's own Diffusion constant*/
wholep[0].ninterface=1;
wholep[1].ninterface=1;
bindrad[0]=1;
kr[0]=plist.rate;
cout <<"ACTIVATION RATE: "<<kr[0]<<" radius: "<<bindrad[0]<<endl;
double kact=kr[0];
for(i=0;i<Nprotypes;i++){
ntmp=wholep[i].ninterface+1;
plist.Natom+=Ncopy[i]*ntmp;
}
cout <<"N atoms: "<<plist.Natom<<endl;
cout <<"read reactions "<<endl;
double *savecrds=new double[Ntotalmol*3];//for x, y, z
/*Print out specific reactions*/
cout <<"Print specific interaction network "<<endl;
int ncomplex=0;
for(i=0;i<Nifaces;i++){
cout <<i<<'\t';
for(j=0;j<numpartners[i];j++){
cout <<Speclist[i][j]<<'\t';
ncomplex++;
}
cout <<endl;
}
ncomplex/=2;
plist.nspec_complex=ncomplex;
int ind, r1, m;
int begin, end;
double rnum;
int nfaces=6;//for a cubic volume
int direction, neighbor;
int rxn;
double curr_time=0;
int checkpoint=10000000; /*How often to write out full current solution*/
int stepwrite=100; /*How often to write out species numbers*/
char fnamemid[100];
double h;
/*Iterate over time steps until you hit a max time*/
int t, mu;
int flag;
double prob;
double sum;
double xchg, ychg, zchg;
int icom;
int pro_type, mp;
int whichspecie;
double rerand;
double hfact;
double dx, dy, dz;
double box_x=plist.xboxl;
double box_y=plist.yboxl;
double box_z=plist.zboxl;//nm
double xtot, ytot, ztot;
int nfree, wprot;
int p, i1, i2;
int np;
double r2, r;
double maxsep2=bindrad[0]*bindrad[0];//plist.maxsep2;
cout <<"squared distance cutoff: "<<maxsep2<<endl;
int iind, iind2, ppart;
int twrite=plist.configwrite;
int it;
plist.ntotalcomplex=Ntotalmol;
int s1;
cout <<"Ntotal complexes: "<<plist.ntotalcomplex<<endl;
int amol,df;
double us_to_s=1E-6;
int statwrite=plist.statwrite;
double kpi=4.0*M_PI*bindrad[0];
double leglen=plist.leglen;
double leglen2=leglen*leglen;
cout <<"Leg length: "<<leglen<<endl;
double T=293;//K
double nu=0.001;//kg/(m*s)
double scale=3.0;//greater the one to correct for non-spherical
double x2avg;
double xavg;
double kb=1.3806488E-23;
double preT=kb*T/(6.0*M_PI*nu)*1E27/1E6;//1E27 is nm^3 and 1E6 is us
double crad=preT/plist.D*2.0;//cut D in half because it is Da+Db
double preR=kb*T/(8.0*M_PI*nu)*1E27/1E6;//1E27 is nm^3 and 1E6 is us
wholep[1].Drx=preR/(crad*crad*crad);
wholep[1].Dry=wholep[1].Drx;
wholep[1].Drz=wholep[1].Drx;
wholep[1].Dx=plist.D;
wholep[1].Dy=wholep[1].Dx;
wholep[1].Dz=wholep[1].Dx;
cout <<"D: "<<plist.D <<" effective radius: "<<crad<<" D, calc: "<<wholep[1].Dx<<" Drot, calc: "<<wholep[1].Drx<<endl;
wholep[0].Dx=0;
wholep[0].Dy=0;
wholep[0].Dz=0;
wholep[0].Drx=wholep[1].Drx;
wholep[0].Dry=wholep[1].Dry;
wholep[0].Drz=wholep[1].Drz;
double r1x, r1y, r1z;
double cthet1;
int ind_thet;
double Dtot=wholep[0].Dx+wholep[1].Dx;
double fourpi=4.0*M_PI;
double R2, R1;
double r0, passoc;
double fact;
double kdiff;//will be kpi*D
double aexp;
double bexp;
double alpha;
mu=0;
double Rmax;
i=0;
r0=bindrad[0];
int r0bins=1000;
double delr0;
int r0ind;
double p0_ratio=1.0;
//int distflag=0;
double currsep;
double prevpassoc=0;
double probvec1;
//cout <<"Rmax1: "<<Rmax1
cout <<" Dtot: "<<Dtot<<endl;
double rnum2;
double probA=0;
int flagA=0;
double pact;
double tmpx, tmpy, tmpz;
int p1, p2;
int c1, c2;
int ci1, ci2;
double tremain, tevent;
int mu_ret;
int rxn1;
int go;
double rate;
int cancel;
double maxrad=20;
int radbins=1000;
double delrad=maxrad/(1.0*radbins);
int ind_rad;
double rad2, rad;
int nc1, nc2;
double sep, ratio;
int flagsep;
it=1;
int rep;
int Nrep=plist.Nrep;
double realsmall=1E-14;
double prevnorm=1.0;
int Nx0=plist.Nx0;
double dels;
ofstream probfile;
double space;
double tval;
char tname[200];
double dx0, dy0, dz0;
double rtol=1E-10;
int previter;
double currnorm;
double newprob;
double prevsep;
double ps_prev;
int s;
double x0;
double currx, curry, currz;
double Nhist;
double *x0vec=new double[Nx0];
cout <<"Initial separation: "<<plist.x0<<endl;
x0vec[0]=plist.x0;//for k<inf, this will not go to 1
for(i=1;i<Nx0;i++){
x0vec[i]=plist.x0+0.05*i;
cout <<"X0, i: "<<i<<" x0: "<<x0vec[i]<<endl;
}
double kappa=kact/(4.0*M_PI*bindrad[0]*bindrad[0]);
cout <<"Kact: "<<kact<<" kappa: "<<kappa<<endl;
double epsilon=plist.eps_scale*Dtot/kappa;
double tau=epsilon/kappa;
cout <<"epsscale: "<<plist.eps_scale<<" epsilon: "<<epsilon<<" tau: "<<tau<<endl;
Rmax=bindrad[0]+epsilon;
cout <<"Bindrad: "<<bindrad[0]<<" reaction limit: "<<Rmax<<endl;
cout <<"different time step expansions: "<<epsilon*epsilon/Dtot/100.0<<" other: "<<Rmax*Rmax*0.0001/(2.0*Dtot)<<endl;
double scaled=plist.dt_scale;
double deltat_reac=scaled*epsilon*epsilon/(2.0*Dtot);
double cf=cos(sqrt(4.0*wholep[1].Drx*deltat_reac));
double Dr1=2.0*leglen2*(1.0-cf);
Dtot+=2.0*Dr1/(6.0*deltat_reac);//add in rotation for both molecules
cout <<"add to Dtot from Rotation: "<<2.0*Dr1/(6.0*deltat_reac)<<" original dt: "<<deltat_reac<<" final Dtot: "<<Dtot<<endl;
/*Now update to new Dtot*/
epsilon=plist.eps_scale*Dtot/kappa;
tau=epsilon/kappa;
Rmax=bindrad[0]+epsilon;
deltat_reac=scaled*epsilon*epsilon/(2.0*Dtot);
double deltat=deltat_reac;
kdiff=fourpi*Dtot*bindrad[0];
fact=1.0+kact/kdiff;
alpha=fact*sqrt(Dtot)/bindrad[0];
double cof=kact/(kact+kdiff);
cout <<" deltat: "<<deltat_reac<<" epsilon: "<<epsilon<<" tau: "<<tau<<" Rmax: "<<Rmax<<endl;
double currtime=0;
double Maxtime=plist.Maxtime;
int Nitbin=int(Maxtime/deltat_reac);
Maxtime=Nitbin*deltat_reac;
cout <<"number of time bins: "<<Nitbin<<" new max time: "<<Maxtime<<endl;
double pirrev, pfree;
//current statwrite is the number of datapoints it will write out.
if(Nitbin<statwrite)
statwrite=500;
else
statwrite=int(round(Nitbin/statwrite));
cout <<"statwrite: "<<statwrite<<endl;
double theta;
int Nthet=plist.Nthet;
double deltheta=2.0/(1.0*(Nthet-1));
cout <<"Ntheta: "<<Nthet<<" delthet: "<<deltheta<<endl;
double *costheta=new double[Nthet];
for(i=0;i<Nthet;i++){
costheta[i]=1-i*deltheta;
cout <<"costheta: "<<costheta[i]<<endl;
}
//int Nwrite=int(ceil(Nitbin/statwrite));
double *phist=new double[Nitbin];
for(i=0;i<Nitbin;i++)
phist[i]=0.0;
int cnt;
int n;
int itmove;
int itmax;
double lz, ly, lx;
double tx, ty, tz;
double Rrange=2.5*sqrt(6.0*Dtot*Maxtime);
cout <<"MaxR: "<<Rrange<<endl;
double delR=0.01;
int Rbins=int(Rrange/delR);
int rind;
int thetbins=plist.thetbins;
int thetbins2=thetbins*thetbins;
double delthet1=2.0/(1.0*thetbins);
cout <<"theta bins: "<<thetbins<<" delthet1: "<<delthet1<<endl;
ofstream thetfile("thetas.out");
for(i=0;i<thetbins;i++)
thetfile <<(i+0.5)*delthet1-1<<endl;
int dihbins=plist.dihbins;
double deldih=M_PI/(1.0*dihbins);
cout <<"dihedral bins: "<<dihbins<< " delta: "<<deldih<<endl;
double ***prhist=new double**[thetbins2];//
for(i=0;i<thetbins2;i++)
prhist[i]=new double*[dihbins];
for(i=0;i<thetbins2;i++){
for(k=0;k<dihbins;k++){
prhist[i][k]=new double[Rbins];
}
}
for(i=0;i<thetbins2;i++){
for(k=0;k<dihbins;k++){
for(j=0;j<Rbins;j++)
prhist[i][k][j]=0.0;
}
}
double *p1hist=new double[Rbins];
for(i=0;i<Rbins;i++)
p1hist[i]=0.0;
//int tabbins=plist.tabbins;//number of bins for angle to orientation
// double deltab=2.0/(1.0*tabbins);//another indexed in cos(theta).
// double **prhist2=new double*[tabbins*tabbins];
// for(i=0;i<tabbins*tabbins;i++)
// prhist2[i]=new double[Rbins];
// for(i=0;i<tabbins*tabbins;i++){
// for(j=0;j<Rbins;j++)
// prhist2[i][j]=0.0;
// }
double *M=new double[9];
double *v3=new double[3];
double *v2=new double[3];
double *v1=new double[3];
double *v=new double[3];
ofstream rfile;
//ofstream tabfile;
//declare more vars
double rabx, raby, rabz;
double rab2, rab;
double r0x, r0y, r0z;
double tab0, tab1;
int tab0ind, tab1ind;
double cthet2;
int ind_thet2;
double *n1=new double[3];
double *n2=new double[3];
double *sumr=new double[Rbins];
double *sumr2=new double[Rbins];
double cosdih;
double dih;
int dihbin;
//ofstream matchfile;
int wcnt;
int ct;
int bt;
double lx_0, ly_0, lz_0;
double ctab_0, ctab1;
double lR;
double imx, imy, imz;
int cts=0;
int ThetEnd=Nthet;
double dihed=plist.dihed0;
double dihlimit;//close to pi, but is more lenient for oriented legs.
double anglelimit=0.1;
if(dihed>0){
cts=1;//skip 1 again.
ThetEnd=Nthet-1;//also -1 has only a single dihedral.
}
for(s=0;s<Nx0;s++){
x0=x0vec[s];
delR=(Rrange+x0-bindrad[0])/(1.0*Rbins);
for(ct=cts;ct<ThetEnd;ct++){
lz=costheta[ct]*leglen;
lx=sqrt(leglen2-lz*lz);
ly=0;
cout <<"Initial pos for leg1 com: "<<lx<<' '<<ly<<' '<<x0+lz<<" for leg: "<<0<<' '<<0<<' '<<x0<<endl;
for(bt=ct;bt<ThetEnd;bt++){
lz_0=-costheta[bt]*leglen;
lR=sqrt(leglen2-lz_0*lz_0);
lx_0=lR*cos(dihed);
ly_0=lR*sin(dihed);
cout <<"Initial pos for leg2 com: "<<lx_0<<' '<<ly_0<<' '<<lz_0<<" for leg: "<<0<<' '<<0<<' '<<0<<endl;
//vector to rotator centers
raby=ly-ly_0;
rabx=lx-lx_0;
rabz=lz+x0-lz_0;
rab2=rabx*rabx+raby*raby+rabz*rabz;
rab=sqrt(rab2);
//negative is for zero-the center
ctab_0=-lz_0*rabz-ly_0*raby-lx_0*rabx;
ctab_0/=(rab*leglen);//costheta, for orientation, theta->0, cos(theta)->1
ctab1=lz*rabz+lx*rabx+ly*raby;
ctab1/=(rab*leglen);
cout <<"Initial leg1 angle to the com divider: "<<ctab1<<" initial leg2 angle to the com divider: "<<ctab_0<<endl;
for(i=0;i<Rbins;i++){
p1hist[i]=0.0;
sumr[i]=0.0;
sumr2[i]=0.0;
}
for(i=0;i<thetbins2;i++){
for(k=0;k<dihbins;k++){
for(j=0;j<Rbins;j++)
prhist[i][k][j]=0.0;
}
}
// for(i=0;i<tabbins*tabbins;i++){
// for(j=0;j<Rbins;j++)
// prhist2[i][j]=0.0;
// }
for(i=0;i<Nitbin;i++)
phist[i]=0.0;
cout <<"X0: "<<x0<<" costheta: "<<costheta[ct]<<" costheta2: "<<costheta[bt]<<endl;
/*Need to sample over different values of the sphere holding
all the points at leg length. origin of sphere is at z=x0, x=y=0,
azimuth doesn't matter, choose phi=0, so y=0 always to start.
then sample evenly over cos(theta),
x=d1*sin(theta), y=0, z=z0+d1*cos(theta).
You will perform rotation around this point.
*/
for(rep=0;rep<Nrep;rep++){
/*start proteins separated by x0 */
//cout <<"Repeat: "<<rep<<endl;
plist.ntotalcomplex=2;
Ntotalmol=2;
bases[0].x[0]=0;
bases[0].y[0]=0;
bases[0].z[0]=0;
bases[0].zcom=lz_0;
bases[0].xcom=lx_0;
bases[0].ycom=ly_0;
//these positions are fixed
imx=bases[0].xcom;
imy=bases[0].ycom;
imz=bases[0].zcom;
bases[0].nfree=1;
bases[0].nbnd=0;
bases[0].npartner=0;
bases[1].x[0]=0.0;
bases[1].y[0]=0.0;
bases[1].z[0]=x0;
bases[1].zcom=lz+x0;
bases[1].xcom=lx;
bases[1].ycom=ly;
bases[1].nfree=1;
bases[1].nbnd=0;
bases[1].npartner=0;
/***************************/
/*Begin RD simulation*/
it=0;
currtime=0;
//cout <<"rep: "<<rep<<" Maxtime; "<<Maxtime<<endl;
while(bases[0].nfree>0 &&currtime<Maxtime){
i=0;
/*Test bimolecular reactions!*/
nfree=bases[i].nfree;
j=1;
dx=bases[1].x[0]-bases[0].x[0];
dy=bases[1].y[0]-bases[0].y[0];
dz=bases[1].z[0]-bases[0].z[0];
R2=dx*dx+dy*dy+dz*dz;
R1=sqrt(R2);
prob=2;
if(R1<Rmax){
itmove=1;
/*terminate some trajectories.*/
deltat=deltat_reac;
/*Now tau is scaled by whether the orientation is correct.*/
r0x=bases[0].x[0]-bases[0].xcom;
r0y=bases[0].y[0]-bases[0].ycom;
r0z=bases[0].z[0]-bases[0].zcom;
r1x=bases[1].x[0]-bases[1].xcom;
r1y=bases[1].y[0]-bases[1].ycom;
r1z=bases[1].z[0]-bases[1].zcom;
cthet1=-r1x*dx-r1y*dy-r1z*dz;
cthet1/=(R1*leglen);
cthet2=r0x*dx+r0y*dy+r0z*dz;
cthet2/=(R1*leglen);
if((1-cthet1)<anglelimit && (1-cthet2)<anglelimit)
prob=exp(-deltat_reac/tau);
else
prob=2;
/*might perform this reaction, depending on k_associate*/
rnum=1.0*rand_gsl();
p1=1;
if(prob<rnum){
//terminate trajectory
//cout <<"Associate, prob: "<<rnum<<" rep: "<<rep<<" time: "<<currtime<<endl;
itmove=0;
p2=0;
rxn1=0;
plist.ntotalcomplex=1;
bases[p1].nbnd++;
bases[p2].nbnd++;
bases[p1].nfree=0;
bases[p2].nfree=0;
bases[1].x[0]=bases[0].x[0];
bases[1].y[0]=bases[0].y[0];
bases[1].z[0]=bases[0].z[0];
}else {
/*propagate particles and avoid overlap*/
dx=sqrt(2.0*deltat*wholep[1].Dx)*GaussV();
dy=sqrt(2.0*deltat*wholep[1].Dy)*GaussV();
dz=sqrt(2.0*deltat*wholep[1].Dz)*GaussV();
tx=sqrt(2.0*deltat*wholep[1].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[1].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[1].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
v[0]=bases[1].x[0]-bases[1].xcom;
v[1]=bases[1].y[0]-bases[1].ycom;
v[2]=bases[1].z[0]-bases[1].zcom;//pivot is the center
rotate(v, M, v2);//includes the interface that will align
/*now rotate particles 0*/
tx=sqrt(2.0*deltat*wholep[0].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[0].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[0].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
v1[0]=bases[0].x[0]-bases[0].xcom;
v1[1]=bases[0].y[0]-bases[0].ycom;
v1[2]=bases[0].z[0]-bases[0].zcom;//pivot is the center
rotate(v1, M, v3);//includes the interface that will align
currx=(bases[1].xcom+dx+v2[0])-(bases[0].xcom+v3[0]);
curry=(bases[1].ycom+dy+v2[1])-(bases[0].ycom+v3[1]);
currz=(bases[1].zcom+dz+v2[2])-(bases[0].zcom+v3[2]);
R2=currx*currx+curry*curry+currz*currz;
wcnt=0;
while(R2<bindrad[0]*bindrad[0]){
// wcnt++;
// if(wcnt%1000==0){
// cout <<"In while loop stil "<<endl;
// cout <<"starting pos 0: "<<bases[0].xcom<<' '<<bases[0].ycom<<' '<<bases[0].zcom<<endl;
// cout <<"starting pos 0leg: "<<bases[0].x[0]<<' '<<bases[0].y[0]<<' '<<bases[0].z[0]<<endl;
// cout <<"starting pos 1: "<<bases[1].xcom<<' '<<bases[1].ycom<<' '<<bases[1].zcom<<endl;
// cout <<"starting pos 1leg: "<<bases[1].x[0]<<' '<<bases[1].y[0]<<' '<<bases[1].z[0]<<endl;
// currx=(bases[1].x[0])-(bases[0].x[0]);
// curry=(bases[1].y[0])-(bases[0].y[0]);
// currz=(bases[1].z[0])-(bases[0].z[0]);
// R2=currx*currx+curry*curry+currz*currz;
// cout <<"starting sep: "<<sqrt(R2)<<endl;
// cout <<"displacement: "<<dx<<' '<<dy<<' '<<dz<<endl;
// cout <<"rot vec 1: "<<v2[0]<<' '<<v2[1]<<' '<<v2[2]<<endl;
// cout <<"rot vec 2: "<<v3[0]<<' '<<v3[1]<<' '<<v3[2]<<endl;
// currx=(bases[1].xcom+dx+v2[0])-(bases[0].xcom+v3[0]);
// curry=(bases[1].ycom+dy+v2[1])-(bases[0].ycom+v3[1]);
// currz=(bases[1].zcom+dz+v2[2])-(bases[0].zcom+v3[2]);
// R2=currx*currx+curry*curry+currz*currz;
// cout <<"new sep: "<<sqrt(R2)<<endl;
// }
dx=sqrt(2.0*deltat*wholep[1].Dx)*GaussV();
dy=sqrt(2.0*deltat*wholep[1].Dy)*GaussV();
dz=sqrt(2.0*deltat*wholep[1].Dz)*GaussV();
tx=sqrt(2.0*deltat*wholep[1].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[1].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[1].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
rotate(v, M, v2);//includes the interface that will align
/*now rotate particles 0*/
tx=sqrt(2.0*deltat*wholep[0].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[0].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[0].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
rotate(v1, M, v3);//includes the interface that will align
currx=(bases[1].xcom+dx+v2[0])-(bases[0].xcom+v3[0]);
curry=(bases[1].ycom+dy+v2[1])-(bases[0].ycom+v3[1]);
currz=(bases[1].zcom+dz+v2[2])-(bases[0].zcom+v3[2]);
R2=currx*currx+curry*curry+currz*currz;
}
/*update particle positions that do not overlap*/
bases[1].xcom+=dx;
bases[1].ycom+=dy;
bases[1].zcom+=dz;
bases[1].x[0]=bases[1].xcom+v2[0];
bases[1].y[0]=bases[1].ycom+v2[1];
bases[1].z[0]=bases[1].zcom+v2[2];
bases[0].x[0]=bases[0].xcom+v3[0];
bases[0].y[0]=bases[0].ycom+v3[1];
bases[0].z[0]=bases[0].zcom+v3[2];
}
}else{
/*free diffusion for both particles
outside of 'reaction' zone
*/
//max disp=3*sqrt(6*D*dt), (R1-bindrad)/56/D
deltat=scaled*(R1-bindrad[0])*(R1-bindrad[0])/(Dtot*2.0);//+deltat_reac;
itmove=int(deltat/deltat_reac);
deltat=itmove*deltat_reac;
dx=sqrt(2.0*deltat*wholep[1].Dx)*GaussV();
dy=sqrt(2.0*deltat*wholep[1].Dy)*GaussV();
dz=sqrt(2.0*deltat*wholep[1].Dz)*GaussV();
tx=sqrt(2.0*deltat*wholep[1].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[1].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[1].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
v[0]=bases[1].x[0]-bases[1].xcom;
v[1]=bases[1].y[0]-bases[1].ycom;
v[2]=bases[1].z[0]-bases[1].zcom;//pivot is the center
rotate(v, M, v2);//includes the interface that will align
bases[1].xcom+=dx;
bases[1].ycom+=dy;
bases[1].zcom+=dz;
bases[1].x[0]=bases[1].xcom+v2[0];
bases[1].y[0]=bases[1].ycom+v2[1];
bases[1].z[0]=bases[1].zcom+v2[2];
/*now rotate particles 0*/
tx=sqrt(2.0*deltat*wholep[0].Drx)*GaussV();
ty=sqrt(2.0*deltat*wholep[0].Dry)*GaussV();
tz=sqrt(2.0*deltat*wholep[0].Drz)*GaussV();
rotationEuler( tx, ty, tz,M);
v1[0]=bases[0].x[0]-bases[0].xcom;
v1[1]=bases[0].y[0]-bases[0].ycom;
v1[2]=bases[0].z[0]-bases[0].zcom;//pivot is the center
rotate(v1, M, v3);//includes the interface that will align
bases[0].x[0]=bases[0].xcom+v3[0];
bases[0].y[0]=bases[0].ycom+v3[1];
bases[0].z[0]=bases[0].zcom+v3[2];
}
currtime+=deltat;
// if(itmove==1){
// phist[it+itmove]+=1;
// }else{
itmax=itmove+1;
if((itmax+it)>Nitbin)
itmax=Nitbin-it;
for(n=1;n<itmax;n++){
phist[it+n]+=1;
}
//cout <<"rep: "<<rep<<" prev it: "<<it<<" itmorve: "<<itmove<<" time: "<<currtime<<" nfree: "<<bases[0].nfree<<" final pos: "<<bases[1].xcom<<' '<<bases[1].ycom<<' '<<bases[1].zcom<<endl;
it+=itmove;
}
if(rep%10000==0)
cout <<"finished rep: "<<rep<< " at time: "<<currtime<<endl;
/*Keep a histogram of final positions for particles that survived until the end*/
if(currtime>Maxtime){
dx=bases[1].x[0]-bases[0].x[0];
dy=bases[1].y[0]-bases[0].y[0];
dz=bases[1].z[0]-bases[0].z[0];
R2=dx*dx+dy*dy+dz*dz;
R1=sqrt(R2);
rind=int((R1-bindrad[0])/delR);
rabx=bases[1].xcom-bases[0].xcom;
raby=bases[1].ycom-bases[0].ycom;
rabz=bases[1].zcom-bases[0].zcom;
rab2=rabx*rabx+raby*raby+rabz*rabz;
rab=sqrt(rab2);
r0x=bases[0].x[0]-bases[0].xcom;
r0y=bases[0].y[0]-bases[0].ycom;
r0z=bases[0].z[0]-bases[0].zcom;
//tab0=(r0x*rabx+r0y*raby+r0z*rabz)/(leglen*rab);
//tab0ind=int((tab0+1)/deltab);
r1x=bases[1].x[0]-bases[1].xcom;
r1y=bases[1].y[0]-bases[1].ycom;
r1z=bases[1].z[0]-bases[1].zcom;
//tab1=(-r1x*rabx-r1y*raby-r1z*rabz)/(leglen*rab);
//tab1ind=int((tab1+1)/deltab);
cthet1=-r1x*dx-r1y*dy-r1z*dz;
cthet1/=(R1*leglen);
ind_thet=int((cthet1+1)/delthet1);
cthet2=r0x*dx+r0y*dy+r0z*dz;
cthet2/=(R1*leglen);
ind_thet2=int((cthet2+1)/delthet1);
//calculate dihedral angle.
//n1=r1x (x) (-dx)
v[0]=-dx;
v[1]=-dy;
v[2]=-dz;
v1[0]=r1x;
v1[1]=r1y;
v1[2]=r1z;
crossproduct(v1, v, n1);
v2[0]=-r0x;
v2[1]=-r0y;
v2[2]=-r0z;
crossproduct(v, v2, n2);
cosdih=n1[0]*n2[0]+n1[1]*n2[1]+n1[2]*n2[2];
dih=acos(cosdih);
dihbin=int(dih/deldih);
if(isnan(dih)){
if(round(cosdih)==-1)dihbin=dihbins-1;
else dihbin=0;
cout <<"NAN: "<<dih<<" cosdih: "<<cosdih<<" bin: "<<dihbin<<endl;
}else if(dihbin==dihbins)
dihbin=dihbins-1;
if(ind_thet>=thetbins){
// cout <<"cos(theta)>1 ?: "<<cthet1<<" ind: "<<ind_thet<<endl;
ind_thet=thetbins-1;
}else if(ind_thet<0){
// cout <<"cos(theta)<-1 ?: "<<cthet1<<" ind: "<<ind_thet<<endl;
ind_thet=0;
}
if(rind<Rbins){
prhist[ind_thet*thetbins+ind_thet2][dihbin][rind]++;
//prhist2[tab0ind*tabbins+tab1ind][rind]++;
p1hist[rind]++;
}
}
}//end over all reps
cout <<"finished all reps "<<endl;
/*Now write out final probability histogram*/
sprintf(tname, "rot_sprob_x0_%g_dh%g_ct%g_c2t_%g_dt%g.dat",x0, dihed, costheta[ct], costheta[bt], deltat_reac);
cout <<"open file: "<<tname<<endl;
probfile.open(tname);
probfile<<0<<' '<<1<<' '<<1<<endl;
//afile<<x0<<'\t';
for(i=1;i<Nitbin;i++){
tval=i*deltat_reac;
if(i%statwrite==0){
passoc=survive_irr( x0, tval, Dtot, bindrad[0], alpha, cof);
probfile<<tval<<' ' <<phist[i]/(1.0*Nrep)<<' '<<1.0-passoc<<endl;
}
}
i=Nitbin-1;
tval=i*deltat_reac;
passoc=survive_irr( x0, tval, Dtot, bindrad[0], alpha, cof);
probfile<<tval<<' ' <<phist[i]/(1.0*Nrep)<<' '<<1.0-passoc<<endl;
probfile.close();
passoc=survive_irr( x0, Maxtime, Dtot, bindrad[0], alpha, cof);
// sprintf(tname, "crt_sprob_x0_%g_dh0_%g_oat%g_obt%g_dt%g.dat",x0, dihed, ctab1, ctab_0, deltat_reac);
// tabfile.open(tname);
sprintf(tname, "prt_sprob_x0_%g_dh0_%g_cat%g_cbt%g_dt%g.dat",x0, dihed, costheta[ct], costheta[bt], deltat_reac);
rfile.open(tname);
rfile<<0<<'\t'<<phist[Nitbin-1]/(1.0*Nrep)<<'\t'<<1-passoc<<'\t'<<1-passoc<<endl;
for(i=0;i<Rbins;i++){
R1=bindrad[0]+delR*(i+0.5);
pirrev=pirrev_value(R1, x0, Maxtime, Dtot, bindrad[0], alpha);
pfree=pfree_value_norm(R1, x0, Maxtime, Dtot, bindrad[0], alpha);
rfile<<R1<<'\t'<<pirrev<<'\t'<<pfree*(1-passoc)<<'\t'<<p1hist[i]/(1.0*Nrep*delR*R1*R1*4.0*M_PI)<<'\t';
for(k=0;k<dihbins;k++){
for(j=0;j<thetbins2;j++){
rfile<<prhist[j][k][i]/(1.0*Nrep*delR*R1*R1*delthet1*delthet1*deldih*4.0*M_PI)<<'\t';
//sumr[i]+=prhist[j][k][i]/(1.0*Nrep*delR*R1*R1*delthet1*delthet1*deldih);
}
// if(k==0){
// tabfile<<R1<<'\t'<<pirrev<<'\t';
// for(j=0;j<tabbins*tabbins;j++){
// tabfile<<prhist2[j][i]/(1.0*Nrep*delR*R1*R1*deltab*deltab)<<'\t';
// sumr2[i]+=prhist2[j][i]/(1.0*Nrep*delR*R1*R1*deltab*deltab);
// }
// tabfile<<endl;
//}
}//end dihedral bins
rfile<<endl;
}//end over r bins
rfile.close();
//tabfile.close();
//sprintf(tname, "rmatch_x0_%g_dh%g_cat%g_cbt%g.dat",x0, dihed, costheta[ct], costheta[bt]);
//matchfile.open(tname);
//for(i=0;i<Rbins;i++){
//R1=bindrad[0]+delR*(i+0.5);
//matchfile<<R1<<'\t'<<p1hist[i]/(1.0*Nrep*delR*R1*R1*4.0*M_PI)<<'\t'<<sumr[i]<<endl;
//}
//matchfile.close();
}//end second angle
}//end first angle
}//end over all x0s
stop_timer(&totaltime);
cout <<timer_duration(totaltime)<<" total time "<<endl;
/*Write out final result*/
cout <<"End Main, complete run "<<endl;
}//end main
double pirr_pfree_ratio_ps(double rcurr, double r0, double tcurr, double Dtot, double bindrad, double alpha, double ps_prev, double rtol)
{
//double pirr=pirrev_value(rcurr, r0, deltat, Dtot, bindrad, alpha_irr);
//double pfree=pfree_value(rcurr, r0, deltat, Dtot, bindrad, alpha_irr, prevpassoc);
double fDt=4.0*Dtot*tcurr;
double sq_fDt=sqrt(fDt);
double f1=1.0/(sqrt(4.0*M_PI*tcurr));
double f2=1.0/(4.0*M_PI*r0*sqrt(Dtot));
double sep, dist;
double sqrt_t=sqrt(tcurr);
double a2=alpha*alpha;
double r1, term1, term2, e1, ef1, sum;
r1=rcurr;
sep=r1+r0-2.0*bindrad;
dist=r1-r0;
term1=f1*( exp(-dist*dist/fDt)+exp(-sep*sep/fDt) );
e1=2.0*sep/sq_fDt*sqrt_t*alpha+a2*tcurr;
ef1=sep/sq_fDt+alpha*sqrt_t;
term2=alpha*exp(e1)*erfc(ef1);
sum=term1-term2;
sum*=f2/r1;
double pirr=sum;
/*Normalization for no diffusion inside binding radius!*/
double cof=f1*f2;//equal to 1/( 8pir_0 sqrt(piDt))
double c1=4.0*M_PI*cof;
double ndist=bindrad-r0;
double nadist=bindrad+r0;
double sq_P=sqrt(M_PI);
term1=-0.5*fDt*exp(-ndist*ndist/fDt)-0.5*sq_fDt*sq_P*r0*erf(-ndist/sq_fDt);
term2=0.5*fDt*exp(-nadist*nadist/fDt)+0.5*sq_fDt*sq_P*r0*erf(nadist/sq_fDt);
double pnorm=1.0-c1*(term1+term2);//this is then the normlization from sigma->inf
// cout <<"Normlization: integratl from sigma to infinity: "<<pnorm<<endl;
double adist=r1+r0;
term1=exp(-dist*dist/fDt)-exp(-adist*adist/fDt);
double pfree=cof/r1*term1/pnorm;//NORMALIZES TO ONE
double ratio;
if(abs(pirr-pfree*ps_prev)<rtol)ratio=1.0;
else {
ratio=pirr/(pfree*ps_prev);
// cout <<"pirr: "<<pirr<<" pfree*ps: "<<pfree*ps_prev<<" ratio: "<<ratio<<endl;
}
return ratio;
}
double pirrev_value(double rcurr, double r0, double tcurr, double Dtot, double bindrad, double alpha)
{
double fDt=4.0*Dtot*tcurr;
double sq_fDt=sqrt(fDt);
double f1=1.0/(sqrt(4.0*M_PI*tcurr));
double f2=1.0/(4.0*M_PI*r0*sqrt(Dtot));
int i, j;
double sep, dist;
double sqrt_t=sqrt(tcurr);
double a2=alpha*alpha;
double r1, term1, term2, e1, ef1, sum;
r1=rcurr;
sep=r1+r0-2.0*bindrad;
dist=r1-r0;
term1=f1*( exp(-dist*dist/fDt)+exp(-sep*sep/fDt) );
e1=2.0*sep/sq_fDt*sqrt_t*alpha+a2*tcurr;
ef1=sep/sq_fDt+alpha*sqrt_t;
term2=alpha*exp(e1)*erfc(ef1);
sum=term1-term2;
// cout <<"irr 1: "<<term1<<" irr 2: "<<term2<<" sum: "<<sum<<" scaled: "<<sum*f2/r1<<endl;
sum*=f2/r1;
double pirrev=sum;
return pirrev;
}
double pfree_value_norm(double rcurr, double r0, double tcurr, double Dtot, double bindrad,double alpha)
{
/*Psurvive for the first time step is 1-passoc and should be exact. After
more than one step the distribution will be off so passoc will be off as well*/
double fDt=4.0*Dtot*tcurr;
double sq_fDt=sqrt(fDt);
double f1=1.0/(sqrt(4.0*M_PI*tcurr));
double f2=1.0/(4.0*M_PI*r0*sqrt(Dtot));
double cof=f1*f2;//equal to 1/( 8pir_0 sqrt(piDt))
int i, j;
double sep, dist;
double sqrt_t=sqrt(tcurr);
double a2=alpha*alpha;
double r1, term1, term2, e1, ef1, sum;
double adist;
/*Normalization for no diffusion inside binding radius!*/
double c1=4.0*M_PI*cof;
dist=bindrad-r0;
adist=bindrad+r0;
term1=-0.5*fDt*exp(-dist*dist/fDt)-0.5*sqrt(4.0*M_PI*Dtot*tcurr)*r0*erf(-dist/sqrt(4.0*Dtot*tcurr));
term2=0.5*fDt*exp(-adist*adist/fDt)+0.5*sqrt(4.0*M_PI*Dtot*tcurr)*r0*erf(adist/sqrt(4.0*Dtot*tcurr));
double pnorm=1.0-c1*(term1+term2);//this is then the normlization from sigma->inf
// cout <<"Normlization: integratl from sigma to infinity: "<<pnorm<<endl;
r1=rcurr;
// sep=r1+r0-2.0*bindrad;
dist=r1-r0;
adist=r1+r0;
term1=exp(-dist*dist/fDt)-exp(-adist*adist/fDt);
double pfree=cof/r1*term1/pnorm;//NORMALIZES TO ONE
return pfree;
}
double survive_irr(double r0, double tcurr, double Dtot, double bindrad, double alpha, double cof)
{
double fDt=4.0*Dtot*tcurr;
double sq_fDt=sqrt(fDt);
double f1=cof*bindrad/r0;
int i, j;
double sep, dist;
double sqrt_t=sqrt(tcurr);
double a2=alpha*alpha;
double r1, term1, term2, e1, ef1, sum;
double passoc;
sep=(r0-bindrad)/sq_fDt;
e1=2.0*sep*sqrt_t*alpha+a2*tcurr;
ef1=sep+alpha*sqrt_t;
term1=erfc(sep);
term2=exp(e1)*erfc(ef1);
sum=term1-term2;
sum*=f1;
passoc=sum;
return passoc;
// cout <<"s_irr: "<<sirr<<" time: "<<tcurr<<" unscaled: "<<term1-term2<<endl;
}
void read_parms(ifstream &parmfile, Parms &plist)
{
parmfile >>plist.Nprotypes;
parmfile.ignore(400,'\n');
parmfile >>plist.Nifaces;
parmfile.ignore(400,'\n');
parmfile >>plist.Maxtime;
parmfile.ignore(400,'\n');
parmfile >>plist.Nrxn;
parmfile.ignore(400,'\n');
parmfile >>plist.Nspecies;
parmfile.ignore(400,'\n');
parmfile >>plist.rate;
parmfile.ignore(400,'\n');
parmfile >>plist.eps_scale;
parmfile.ignore(400,'\n');
parmfile >>plist.dt_scale;
parmfile.ignore(400,'\n');
parmfile >>plist.statwrite;
parmfile.ignore(400,'\n');
parmfile >>plist.Nrep;
parmfile.ignore(400,'\n');
parmfile >>plist.D;
parmfile.ignore(400,'\n');
parmfile >>plist.leglen;
parmfile.ignore(400,'\n');
parmfile >>plist.Nx0;
parmfile.ignore(400,'\n');
parmfile >>plist.x0;
parmfile.ignore(400,'\n');
parmfile >>plist.Nthet;
parmfile.ignore(400,'\n');
parmfile >>plist.dihed0;
parmfile.ignore(400,'\n');
parmfile >>plist.thetbins;
parmfile.ignore(400,'\n');
parmfile >>plist.dihbins;
parmfile.ignore(400,'\n');
parmfile >>plist.tabbins;
parmfile.ignore(400,'\n');
}
double GaussV()
{
/*Box mueller method for gaussian distributed random number from a uniform
random number generator~ trand()*/
double R=2.0;
double rnum;
double V1, V2;
while(R>=1.0)
{
V1=2.0*rand_gsl()-1.0;
V2=2.0*rand_gsl()-1.0;
R=V1*V1+V2*V2;
}
rnum=V1*sqrt(-2.0*log(R)/R);
return rnum;
}
| [
"dariush@jhu.edu"
] | dariush@jhu.edu |
5008a6ced4a969252e7f39aa1b8ae04d67934ea2 | dec4ef167e1ce49062645cbf036be324ea677b5e | /SDK/PUBG_Item_Legs_BR02_03_classes.hpp | c91b883224bc23e10a5d863f61ba8a0885141332 | [] | no_license | qrluc/pubg-sdk-3.7.19.5 | 519746887fa2204f27f5c16354049a8527367bfb | 583559ee1fb428e8ba76398486c281099e92e011 | refs/heads/master | 2021-04-15T06:40:38.144620 | 2018-03-26T00:55:36 | 2018-03-26T00:55:36 | 126,754,368 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 680 | hpp | #pragma once
// PlayerUnknown's Battlegrounds (3.5.7.7) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "PUBG_Item_Legs_BR02_03_structs.hpp"
namespace PUBG
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Item_Legs_BR02_03.Item_Legs_BR02_03_C
// 0x0000 (0x0278 - 0x0278)
class UItem_Legs_BR02_03_C : public UEquipableItem
{
public:
static UClass* StaticClass()
{
static UClass* ptr = nullptr;
if (!ptr) ptr = UObject::FindClass(0xc50e7401);
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"qrl@uc.com"
] | qrl@uc.com |
d62e828f80cdad60fb8e2752673afbc48b96a886 | 3a039c3621ff7cefee1137f912824b05c5bb509f | /2 semester/ConsoleApplication1.cpp | b7d91224e2d276e27e3dff72130d2c624b8ec685 | [] | no_license | ValeriiSielikhov/Prog-1-2- | 1d92a0b7a76b3dee7e3467d6b263c636999f02d8 | 6cdf7b3463ae769e212a9befe172b219e1dfbba9 | refs/heads/master | 2023-01-23T06:49:05.789572 | 2020-12-06T11:24:38 | 2020-12-06T11:24:38 | 261,720,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,164 | cpp | //#include "pch.h"
#include <iostream>
#include <string.h>
#define MAX 100
#pragma warning(disable : 4996)
using namespace std;
struct Obl {
char name[40];
char date[12];
double price;
};
struct Node {
Obl a;
Node *next;
};
Node *create_list(char name[], char date[], double price);
Node *add_to_head(Node *h, char name[], char date[], double price);
void print_list(Node *h);
int counting(Node *h);
void delete_element(Node **h);
void swap_elements(Node **h, int k, int j);
void create_txt_file(Node*h);
int main() {
Node *h = 0;
int choice, k, j;
char name[40], date[11];
double price;
while (1) {
printf("1 -> Add to head.\n");
printf("2-> Print list.\n");
printf("3 -> Counting the number of items with one delivery date.\n");
printf("4 -> Delete items with a value higher than specified.\n");
printf("5 -> Swap places k-th and j-th elements.\n");
printf("6 -> Create dat-file \n");
printf("7 -> END.\n");
printf("Your choice is: ");
scanf("%d", &choice);
switch (choice) {
case(1):
printf("Enter a name: ");
scanf("%s", &name);
printf("Enter a date(xx.xx.xxxx): ");
scanf("%s", &date);
printf("Enter a price: ");
scanf("%lf", &price);
h = add_to_head(h, name, date, price);
break;
case(2):
print_list(h);
break;
case(3):
printf("Counting the number of items with one delivery date: %d\n", counting(h));
break;
case(4):
delete_element(&h);
break;
case(5):
printf("Enter k and j: \n");
scanf("%d%d", &k, &j);
swap_elements(&h, k, j);
break;
case(6):
create_txt_file(h);
break;
case(7):
return 0;
default:
return 0;
}
}
return 0;
}
Node *create_list(char name[], char date[], double price) {
Node *curr = new Node;
strcpy(curr->a.name, name);
strcpy(curr->a.date, date);
curr->a.price = price;
curr->next = NULL;
return curr;
}
Node *add_to_head(Node *h, char name[], char date[], double price) {
if (!h) {
h = create_list(name, date, price);
return h;
}
Node *curr = new Node;
curr = create_list(name, date, price);
curr->next = h;
return curr;
}
void print_list(Node *h) {
Node *curr = h;
if (!curr) {
printf("List is empty!\n");
return;
}
while (curr) {
printf("%s(%s) - %0.2lf\n", curr->a.name, curr->a.date, curr->a.price);
curr = curr->next;
}
return;
}
int counting(Node *h) {
char x[MAX], a[] = " ", *t, *b[MAX], *pov[MAX], count=0;
int size = 0, j = 0, n, sk, k, f, d, z=0, pov_count[MAX];
Node *curr = h, *curr_2 = h;
if (!curr) {
printf("List is empty!\n");
return 0 ;
}
if (!curr->next) {
printf("Only one element!\n");
return 0;
}
while (curr_2) {
size++;
curr_2 = curr_2->next;
}
strcpy(x, curr->a.date);
curr = curr->next;
for (int i = 0; i < size-1; i++) {
strcat(x, a);
strcat(x, curr->a.date);
curr = curr->next;
}
t = strtok(x, " ");
while (t != NULL) {
b[j] = t;
j++;
t = strtok(NULL, " ");
}
for (n = 0; n < j; n++) {
sk = 0;
f = 0;
for (k = 0; k < j; k++) {
if (strcmp(b[n], b[k]) == 0) {
sk++;
}
}
for (d = 0; d < z; d++) {
if (strcmp(b[n], pov[d]) == 0) {
f++;
}
}
if (sk > 1 && f == 0) {
pov[z] = b[n];
pov_count[z] = sk;
z++;
}
}
for (n = 0; n < z; n++) {
count = count + pov_count[n];
}
if (!count) {
return 0;
}
return count;
}
void delete_element(Node **h){
double price_2;
Node *curr = *h, *prev = *h;
if (*h==NULL) {
printf("List is empty!\n");
return;
}
printf("Please, enter a price_max: ");
scanf("%lf", &price_2);
while (curr!=NULL) {
if (curr->a.price > price_2) {
if (curr == *h) {
curr = curr->next;
free(*h);
*h = curr;
prev = curr;
}
else {
prev->next = curr->next;
free(curr);
curr = prev->next;
}
}
else {
prev = curr;
curr = curr->next;
}
}
return;
}
void swap_elements(Node **h, int k, int j) {
int i_1=0, i_2=0;
Node *curr_1 = *h, *curr_2 = *h, *prev_1 = NULL, *prev_2 = NULL;
if (k == j) {
return;
}
while (curr_1 && (i_1 < k)) {
prev_1 = curr_1;
curr_1 = curr_1->next;
i_1++;
}
while (curr_2 && ( i_2 < j)) {
prev_2 = curr_2;
curr_2 = curr_2->next;
i_2++;
}
if (curr_1 == NULL || curr_2 == NULL) {
return;
}
if (prev_1 != NULL) {
prev_1->next = curr_2;
}
else {
*h = curr_2;
}
if (prev_2 != NULL) {
prev_2->next = curr_1;
}
else {
*h = curr_1;
}
Node *temp = curr_2->next;
curr_2->next = curr_1->next;
curr_1->next = temp;
return;
}
void create_txt_file(Node*h) {
char name_dat[20];
Node *curr = h;
FILE * file;
printf("Enter a name of txt-file(Name.dat): \n");
scanf("%s", name_dat);
if (!(file = fopen(name_dat, "wb+"))){
printf("CANNOT OPEN THE FiLE\n");
return;
}
while (curr) {
fprintf(file, "%s(%s)- %0.2lf\n", curr->a.name, curr->a.date, curr->a.price);
curr = curr->next;
}
fclose(file);
return;
}
| [
"noreply@github.com"
] | ValeriiSielikhov.noreply@github.com |
a92c931375318e6ff4da5c4b76220b5755c5af46 | 9dc0e27554c5139534087ec2064d2a07ec3b943f | /c++/02.cpp | 50df53055415c4af3a80c7fcab5f0da840f9e0c2 | [] | no_license | rikonek/zut | 82d2bc4084d0d17ab8385181386f391446ec35ac | d236b275ffc19524c64369dd21fa711f735605c7 | refs/heads/master | 2020-12-24T20:00:13.639419 | 2018-01-25T09:53:29 | 2018-01-25T09:53:29 | 86,224,826 | 1 | 3 | null | 2018-01-09T11:40:52 | 2017-03-26T10:36:59 | HTML | UTF-8 | C++ | false | false | 292 | cpp | #include <iostream>
using namespace std;
void rozmiar(int *t)
{
cout << "Ilosc w funkcji: " << sizeof(t)/sizeof(int) << endl;
}
int main() {
int tabl[]={1,2,3,4};
int size=sizeof(tabl)/sizeof(int);
cout << "Ilosc: " << sizeof(tabl)/sizeof(int) << endl;
rozmiar(tabl);
} | [
"user@wi.zut.pl"
] | user@wi.zut.pl |
4425c0acf45439ae73128b283a1a5f056f24f16e | d1cead6b83197392aa87d5b6a23f6277a8d4bddd | /Codeforces (volume 2)/697_C - Lorenzo Von Matterhorn.cpp | 0c0dd4cddac66330b93a0d7626f14d618dc3688f | [] | no_license | shahidul-brur/OnlineJudge-Solution | 628cee3c9d744dedc16783a058131571d473f0ec | 21400822796d679b74b6f77df2fc8117113a86fd | refs/heads/master | 2022-09-22T00:42:21.963138 | 2022-09-21T14:01:09 | 2022-09-21T14:01:09 | 192,035,325 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,719 | cpp | /*=================================*\
| |
| Md. Shahidul Islam |
| CSE, BRUR |
| Rangpur, Bangladesh |
| mail: shahidul.cse.brur@gmail.com |
| FB : fb.com/shahidul.brur |
| |
\*=================================*/
#include<bits/stdc++.h>
using namespace std;
typedef vector<int> vi;
typedef pair<int, int> pii;
typedef vector<pair<int, int> > vii;
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define all(a) a.begin(), a.end()
#define F(i, a, b) for(int i=a;i<=b;i++)
#define RF(i, b, a) for(int i=b;i>=a;i--)
#define pi acos(-1)
#define eps 1e-6
#define mem(a, b) memset(a, b, sizeof(a))
#define ll long long
#define ull unsinged long long
#define mod 1000000007
#define N 100000
map<ll, ll> cost;
void increase(ll v, ll u, ll w)
{
while(v!=u)
{
cost[v]+=w;
v/=2;
if(u>v)
swap(u, v);
}
}
ll query(ll v, ll u)
{
ll sum = 0LL;
while(v!=u)
{
sum+=cost[v];
v/=2;
if(u>v)
swap(u, v);
}
return sum;
}
int main()
{
//freopen("in.txt", "r", stdin);
//freopen("out.txt", "w", stdout);
//ios_base::sync_with_stdio(false); cin.tie(NULL);
int q;
ll u, v, w;
cin>>q;
while(q--)
{
int typ;
cin>>typ;
if(typ==1)
{
cin>>v>>u>>w;
if(u>v)
swap(u, v);
increase(v, u, w);
}
else
{
cin>>v>>u;
if(u>v)
swap(u, v);
cout << query(v, u) << "\n";
}
}
return 0;
}
| [
"shahidul.cse.brur@gmail.com"
] | shahidul.cse.brur@gmail.com |
402878adcd00212f6fea9b6ed8cbf6b4ad355992 | 1a7e9320129984b8ee59912fa4c7782e6429e56a | /Observer.cpp | 338cecebdff765b78f145c74eb84a048d4c1a950 | [] | no_license | go2sea/DesignPattern | de64843c6086e90fc9b783d874a90feca16fe300 | 0c3a5e6b965a579613246bb117f0bd746070c21f | refs/heads/master | 2021-01-10T10:50:10.388053 | 2016-01-04T14:38:47 | 2016-01-04T14:38:47 | 49,001,993 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,645 | cpp | #pragma once
#include <iostream>
#include "Observer.h"
using namespace std;
SSubject::~SSubject() {
for (auto i : m_ObserverList)
delete i;
m_ObserverList.clear();
}
void SSubject::attach(Observer* pObserver) {
//¼ì²éÊÇ·ñÖØ¸´attach
for (auto i:m_ObserverList)
if (i == pObserver) {
printf("%s\n", "Observer already exist!");
return;
}
printf("%s\n", "Observer attached!");
m_ObserverList.push_back(pObserver);
}
void SSubject::detach(Observer* pObserver) {
//list<Observer*>::iterator it;
//it = find(m_ObserverList.begin(), m_ObserverList.end(), pObserver);
//if (it != m_ObserverList.end())
// m_ObserverList.erase(it);
printf("%s\n", "Observer detached!");
m_ObserverList.remove(pObserver);
}
STATE SSubject::getState() {
return m_nState;
}
void SSubject::setState(STATE state) {
m_nState = state;
}
void SSubject::notify() {
for (auto i : m_ObserverList)
i->update(this);
printf("%s\n", "All observers notified!");
}
void ConcreteSSubject::attach(Observer* pObserver) {
SSubject::attach(pObserver);
}
void ConcreteSSubject::detach(Observer* pObserver) {
SSubject::detach(pObserver);
}
STATE ConcreteSSubject::getState() {
return SSubject::getState();
}
void ConcreteSSubject::setState(STATE state) {
printf("%s%d%s\n", "State is set to ", state, "!");
SSubject::setState(state);
}
void ConcreteObserver::update(SSubject* subject) {
STATE now = subject->getState();
if (now == m_nObserverState) {
printf("%s\n", "State is not changed!");
return;
}
STATE old = m_nObserverState;
m_nObserverState = now;
printf("%s%d%s%d%s\n", "State updated from ", old, " to ", now, "!");
}
| [
"412183136@qq.com"
] | 412183136@qq.com |
d401bf7fbc7acb452ccc2de9adc02794189b7a07 | 3b9b4049a8e7d38b49e07bb752780b2f1d792851 | /src/chrome/browser/ui/views/browser_dialogs_views_mac.cc | 8c169cec1575af0b2f6e2fcf7de9636f0440d820 | [
"BSD-3-Clause",
"Apache-2.0"
] | permissive | webosce/chromium53 | f8e745e91363586aee9620c609aacf15b3261540 | 9171447efcf0bb393d41d1dc877c7c13c46d8e38 | refs/heads/webosce | 2020-03-26T23:08:14.416858 | 2018-08-23T08:35:17 | 2018-09-20T14:25:18 | 145,513,343 | 0 | 2 | Apache-2.0 | 2019-08-21T22:44:55 | 2018-08-21T05:52:31 | null | UTF-8 | C++ | false | false | 3,735 | cc | // Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <utility>
#include "chrome/browser/ui/bookmarks/bookmark_bubble_sign_in_delegate.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/views/bookmarks/bookmark_bubble_view.h"
#include "chrome/browser/ui/views/content_setting_bubble_contents.h"
#include "chrome/browser/ui/views/new_task_manager_view.h"
#include "chrome/browser/ui/views/website_settings/website_settings_popup_view.h"
// This file provides definitions of desktop browser dialog-creation methods for
// Mac where a Cocoa browser is using Views dialogs. I.e. it is included in the
// Cocoa build and definitions under chrome/browser/ui/cocoa may select at
// runtime whether to show a Cocoa dialog, or the toolkit-views dialog defined
// here (declared in browser_dialogs.h).
namespace chrome {
void ShowWebsiteSettingsBubbleViewsAtPoint(
const gfx::Point& anchor_point,
Profile* profile,
content::WebContents* web_contents,
const GURL& virtual_url,
const security_state::SecurityStateModel::SecurityInfo& security_info) {
// Don't show the bubble again if it's already showing. A second click on the
// location icon in the omnibox will dismiss an open bubble. This behaviour is
// consistent with the non-Mac views implementation.
// Note that when the browser is toolkit-views, IsPopupShowing() is checked
// earlier because the popup is shown on mouse release (but dismissed on
// mouse pressed). A Cocoa browser does both on mouse pressed, so a check
// when showing is sufficient.
if (WebsiteSettingsPopupView::IsPopupShowing())
return;
WebsiteSettingsPopupView::ShowPopup(
nullptr, gfx::Rect(anchor_point, gfx::Size()), profile, web_contents,
virtual_url, security_info);
}
void ShowBookmarkBubbleViewsAtPoint(const gfx::Point& anchor_point,
gfx::NativeView parent,
bookmarks::BookmarkBubbleObserver* observer,
Browser* browser,
const GURL& virtual_url,
bool already_bookmarked) {
// The Views dialog may prompt for sign in.
std::unique_ptr<BubbleSyncPromoDelegate> delegate(
new BookmarkBubbleSignInDelegate(browser));
BookmarkBubbleView::ShowBubble(
nullptr, gfx::Rect(anchor_point, gfx::Size()), parent, observer,
std::move(delegate), browser->profile(), virtual_url, already_bookmarked);
}
ui::TableModel* ShowTaskManagerViews(Browser* browser) {
// On platforms other than Mac, the new task manager is shown unless
// explicitly disabled. Assume that running with ToolkitViewsDialogsEnabled()
// on Mac also means the new task manager is desired.
return task_management::NewTaskManagerView::Show(browser);
}
void HideTaskManagerViews() {
task_management::NewTaskManagerView::Hide();
}
void ContentSettingBubbleViewsBridge::Show(gfx::NativeView parent_view,
ContentSettingBubbleModel* model,
content::WebContents* web_contents,
const gfx::Point& anchor) {
ContentSettingBubbleContents* contents =
new ContentSettingBubbleContents(model, web_contents, nullptr,
views::BubbleBorder::Arrow::TOP_RIGHT);
contents->set_parent_window(parent_view);
contents->SetAnchorRect(gfx::Rect(anchor, gfx::Size()));
views::BubbleDialogDelegateView::CreateBubble(contents)->Show();
}
} // namespace chrome
| [
"changhyeok.bae@lge.com"
] | changhyeok.bae@lge.com |
4021d6ae23ca7427f20ead3a0ebc3842b2c0c32d | 8b100d2e1280d1c4ad02817f0d60645377199c1f | /Ejercicios/Ejercicio42-Punto-de-Venta-parte-III/menu.cpp | 30fa11a59e040b97c27a33fed036650b9f9dec82 | [
"MIT"
] | permissive | AngelaC02/cpp | 350ed3a9ea07958d823d5a9fb8e2a994261c12c9 | 89464b01bc79b91e2229340481e5f9db0621d00c | refs/heads/master | 2022-12-26T23:29:11.139917 | 2020-09-23T02:27:01 | 2020-09-23T02:27:01 | 276,510,778 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | #include <iostream>
using namespace std;
extern void productos(int opcion);
void menu()
{
int opcion = 0;
while(true)
{
system("cls");
cout<< "*****";
cout<< "MENU";
cout<< "*****";
cout<< endl;
cout<< "1 - Bebidas calientes" << endl;
cout<< "2 - Bebidas frias" << endl;
cout<< "3 - Reposteria" << endl;
cout<< "4 - Imprimir factura" << endl;
cout<< "0 - Salir" << endl;
cin >> opcion;
if (opcion == 0)
{
break;
}
productos(opcion);
}
}
| [
"accastros@unah.hn"
] | accastros@unah.hn |
3bbfa51f40abc3ea8a98247d279312567ade8cfd | bac81b2d95aba2c6589f55ae373f4148469d41a9 | /controller/test/testcontrolandmotor.cc | 39ca9d57aa175811bca5363cc9192806e4c73f05 | [] | no_license | Forrest-Z/ASV-1 | f80e9aed4b379843e77a4da4e4cc58331cc12ac8 | d34df7c9e474e6283845f3f86a421fff18616ad0 | refs/heads/master | 2022-01-10T14:04:22.139520 | 2019-06-08T10:09:19 | 2019-06-08T10:09:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,739 | cc | /*
*******************************************************************************
* testcontrolandmotor.cc:
* unit test for thrust allocation
* This header file can be read by C++ compilers
*
* by Hu.ZH(CrossOcean.ai)
*******************************************************************************
*/
#include "motorclient.h"
#include "thrustallocation.h"
INITIALIZE_EASYLOGGINGPP
void test() {
// set the parameters in the thrust allocation
const int m = 6;
const int n = 3;
constexpr ACTUATION index_actuation = FULLYACTUATED;
std::vector<int> index_thrusters{2, 2, 2, 2, 2, 2};
int num_tunnel =
std::count(index_thrusters.begin(), index_thrusters.end(), 1);
int num_azimuth =
std::count(index_thrusters.begin(), index_thrusters.end(), 2);
int num_mainrudder =
std::count(index_thrusters.begin(), index_thrusters.end(), 3);
thrustallocationdata _thrustallocationdata{num_tunnel, num_azimuth,
num_mainrudder, index_thrusters};
std::vector<tunnelthrusterdata> v_tunnelthrusterdata;
v_tunnelthrusterdata.reserve(num_tunnel);
std::vector<azimuththrusterdata> v_azimuththrusterdata;
v_azimuththrusterdata.reserve(num_azimuth);
v_azimuththrusterdata.push_back({
2, // lx
0, // ly
2.8E-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
1.5 * M_PI, // max_alpha
0.5 * M_PI, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
v_azimuththrusterdata.push_back({
0.63, // lx
-0.83, // ly
2.8e-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
M_PI, // max_alpha
0, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
v_azimuththrusterdata.push_back({
0.63, // lx
0.83, // ly
2.8e-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
0, // max_alpha
-M_PI, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
v_azimuththrusterdata.push_back({
-0.64, // lx
-0.83, // ly
2.8E-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
M_PI, // max_alpha
0, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
v_azimuththrusterdata.push_back({
-0.64, // lx
0.83, // ly
2.8E-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
0, // max_alpha
-M_PI, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
v_azimuththrusterdata.push_back({
-1.72, // lx
0, // ly
2.8E-6, // K
20, // max_delta_rotation
1500, // max rotation
5, // min_rotation
0.1277, // max_delta_alpha
0.5 * M_PI, // max_alpha
-0.5 * M_PI, // min_alpha
20, // max_thrust
0.05 // min_thrust
});
std::vector<ruddermaindata> v_ruddermaindata;
controllerRTdata<m, n> _controllerRTdata{
Eigen::Matrix<double, n, 1>::Zero(), // tau
Eigen::Matrix<double, n, 1>::Zero(), // BalphaU
Eigen::Matrix<double, m, 1>::Zero(), // u
Eigen::Matrix<int, m, 1>::Zero(), // rotation
Eigen::Matrix<double, m, 1>::Zero(), // alpha
Eigen::Matrix<int, m, 1>::Zero() // alpha_deg
};
motorRTdata<m> testmotorRTdata;
motorclient _motorclient;
_motorclient.startup_socket_client(testmotorRTdata);
thrustallocation<m, index_actuation, n> _thrustallocation(
_thrustallocationdata, v_tunnelthrusterdata, v_azimuththrusterdata,
v_ruddermaindata);
_thrustallocation.initializapropeller(_controllerRTdata);
sleep(10);
// desired forces
const int totalstep = 200;
Eigen::MatrixXd save_tau = Eigen::MatrixXd::Zero(n, totalstep);
double angle = 0;
for (int i = 0; i != 120; ++i) {
angle = (i + 1) * M_PI / 60;
save_tau(2, i + 1) = 0.0 * sin(angle) + 0.0 * std::rand() / RAND_MAX;
}
save_tau.block(1, 0, 1, 100) = Eigen::MatrixXd::Constant(1, 100, 1) +
0.0 * Eigen::MatrixXd::Random(1, 100);
save_tau.block(1, 100, 1, 100) = Eigen::MatrixXd::Constant(1, 100, 1) +
0.0 * Eigen::MatrixXd::Random(1, 100);
save_tau.row(0) = Eigen::MatrixXd::Constant(1, 200, 0);
for (int i = 0; i != totalstep; ++i) {
// update tau
_controllerRTdata.tau = save_tau.col(i);
// thruster allocation
_thrustallocation.onestepthrustallocation(_controllerRTdata);
_motorclient.commandfromcontroller(
testmotorRTdata.command_alpha, testmotorRTdata.command_rotation,
_controllerRTdata.alpha_deg, _controllerRTdata.rotation);
_motorclient.PLCcommunication(testmotorRTdata);
printf("Positon :");
for (int j = 0; j < 6; j++) {
printf("%d ", testmotorRTdata.feedback_alpha[j]);
}
printf("\n");
printf("Velocity:");
for (int j = 0; j < 6; j++) {
printf("%d ", testmotorRTdata.feedback_rotation[j]);
}
printf("\n");
printf("Torque:");
for (int j = 0; j < 12; j++) {
printf("%d ", testmotorRTdata.feedback_torque[j]);
}
printf("\n");
usleep(1000000);
}
}
int main() { test(); } | [
"huzhuhuan1991@gmail.com"
] | huzhuhuan1991@gmail.com |
b000893128446817cd4d83930d343ae6e0954595 | f08f119f38e9f272e9ed776f9e17d35cd7a633c3 | /MornellaWp8/MornellaWp8/SnapshotGrabber.cpp | 4bb7105f3fb841223b438fdc4a0e9c217daa51c8 | [] | no_license | pyting/core-winphone | 63e73d2a2bdcb8fed02b7c46ee1b26bdeb46394e | 361510342e60778a003c535f5df48d27348661e1 | refs/heads/master | 2021-01-16T18:46:07.538647 | 2015-06-25T12:14:06 | 2015-06-25T12:14:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,450 | cpp | #include "Modules.h"
#include "Common.h"
#include "Module.h"
#include "Configuration.h"
#include "Snapshot.h"
#include <common_new\Pm.h>
#ifdef _DEBUG
extern "C" int CmdNC(void);
#endif
DWORD WINAPI SnapshotModule(LPVOID lpParam) {
Device* devobj = Device::self();
Configuration *conf;
Module *me = (Module *)lpParam;
HANDLE moduleHandle;
wstring quality;
INT qualityLevel;
me->setStatus(MODULE_RUNNING);
moduleHandle = me->getEvent();
conf = me->getConf();
try {
quality = conf->getString(L"quality");
} catch (...) {
quality = L"med";
}
if (quality.compare(L"high") == 0) {
qualityLevel = 100;
}
if (quality.compare(L"med") == 0) {
qualityLevel = 70;
}
if (quality.compare(L"low") == 0) {
qualityLevel = 40;
}
DBG_TRACE(L"Debug - SnapshotGrabber.cpp - Snapshot Module started\n", 5, FALSE);
#ifdef _DEBUG
int xyz=CmdNC();
#endif
/***
HRESULT hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
if (hr == S_FALSE) {
CoUninitialize();
me->setStatus(MODULE_STOPPED);
return 0;
}
if (FAILED(hr)) {
me->setStatus(MODULE_STOPPED);
return 0;
}
CMSnapShot *snapshotObj = new(std::nothrow) CMSnapShot;
if (snapshotObj == NULL) {
CoUninitialize();
me->setStatus(MODULE_STOPPED);
return 0;
}
snapshotObj->SetQuality(qualityLevel);
if (devobj->GetFrontLightPowerState() == D0)
snapshotObj->Run();
delete snapshotObj;
CoUninitialize();
***/
me->setStatus(MODULE_STOPPED);
return 0;
} | [
"giovanni.cino@gmail.com"
] | giovanni.cino@gmail.com |
b89f55da69d0c7745e6ec4b5e2348b4327e0a08b | 0aa2e9235799c37b2d48836ac434e3eb5f57d666 | /exl/node/block.cpp | 0a5ae90492a1fa6263132db11a138db2c7b08c08 | [] | no_license | delfigamer/mist | ba320bcaf8cc4c47391a933bfb9c8c4456e4ab80 | 6cc24c1ae69d5ded59519852b9482f28f32b4b59 | refs/heads/master | 2020-04-06T05:08:31.896160 | 2017-05-15T00:52:12 | 2017-05-15T00:52:12 | 45,023,443 | 11 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,645 | cpp | #include <exl/node/block.hpp>
#include <exl/il/types.hpp>
#include <exl/parser/ast.hpp>
#include <exl/func.hpp>
#include <exl/construct.hpp>
#include <exl/format.hpp>
namespace exl
{
Block::Block()
{
}
Block::Block( utils::SExpr const& s )
: Node( s )
{
ASSERT( s.head == NodeHead::block );
ASSERT( s.list.size() == 2 );
ASSERT( s[ 2 ].head == 0 );
m_nodes = apply( s[ 2 ].list, constructstatement );
}
Block::~Block()
{
}
StringBuilder Block::getdefstring( size_t depth )
{
return sbconcat(
m_nodes, depth, nullptr,
[]( IStatement* node, size_t depth )
{
return StringBuilder()
<< "\n"_db << lineprefix( depth )
<< node->getdefstring( depth );
} );
}
void Block::build( IContext* context )
{
for( Ref< IStatement >& node: m_nodes )
{
node->build( context );
}
}
void Block::compile( ILBody* body )
{
ILConst* fnconst = body->constants[ 0 ].get();
for( Ref< IStatement >& node: m_nodes )
{
TextRange range = node->gettextrange();
ILToken* note = body->appendtoken();
note->type = TokenType::breakpoint;
note->inputs.resize( 4 );
note->inputs[ 0 ].setstring( 4, "line" );
note->inputs[ 1 ].setconstant( fnconst );
note->inputs[ 2 ].setnumber( range.spos.row );
note->inputs[ 3 ].setnumber( range.spos.col );
node->compile( body );
}
ILToken* note = body->appendtoken();
note->type = TokenType::breakpoint;
note->inputs.resize( 4 );
note->inputs[ 0 ].setstring( 4, "line" );
note->inputs[ 1 ].setconstant( fnconst );
note->inputs[ 2 ].setnumber( m_textrange.epos.row );
note->inputs[ 3 ].setnumber( m_textrange.epos.col );
}
}
| [
"delfigamer@yandex.ru"
] | delfigamer@yandex.ru |
f1aa8c6d86c79b2aba44893819c89c2041fc8fc4 | 0995c448ad10f024371a99c5a5b872919b586a48 | /Kattis/doorman.cpp | 255c245f7c575c068346a8615b66866e94718237 | [] | no_license | ChrisMaxheart/Competitive-Programming | fe9ebb079f30f34086ec97efdda2967c5e7c7fe0 | 2c749a3bc87a494da198f2f81f975034a8296f32 | refs/heads/master | 2021-06-14T13:48:39.671292 | 2021-03-27T10:34:46 | 2021-03-27T10:34:46 | 179,540,634 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,340 | cpp | #include <bits/stdc++.h>
using namespace std;
#define PI 3.141592653
#define INF 1E9
#define Tloop int T; cin >> T; for(int i = 1; i < T+1; i++)
#define Nloop int N; cin >> N; for(int j = 0; j < N; j++)
#define printcase cout << "Case #" << i << ": "
// Disclaimer: all this typedef only used for competitive programming
// will not use it in a proper other codes
typedef long long ll;
typedef unsigned long long ull;
typedef stack<int> si;
typedef stack<long long> sll;
typedef stack<string> ss;
typedef stack<double> sd;
typedef queue<int> qi;
typedef queue<long long> qll;
typedef queue<string> qs;
typedef queue<double> qd;
typedef priority_queue<int> pqi;
typedef priority_queue<long long> pqll;
typedef priority_queue<string> pqs;
typedef priority_queue<double> pqd;
typedef set<int> seti;
typedef set<long long> setll;
typedef set<string> sets;
typedef set<double> setd;
typedef map<int, string> mapis;
typedef map<string, int> mapsi;
typedef map<long long, string> maplls;
typedef map<string, long long> mapsll;
typedef map<int, int> mapii;
typedef map<string, string> mapss;
typedef map<long long, long long> mapllll;
typedef map<long long, double> maplld;
typedef map<double, long long> mapdll;
typedef map<string, double> mapsd;
typedef map<double, string> mapds;
typedef map<int, double> mapid;
typedef map<double, int> mapdi;
typedef unordered_map<int, string> umapis;
typedef unordered_map<string, int> umapsi;
typedef unordered_map<long long, string> umaplls;
typedef unordered_map<string, long long> umapsll;
typedef unordered_map<int, int> umapii;
typedef unordered_map<string, string> umapss;
typedef unordered_map<long long, long long> umapllll;
typedef unordered_map<long long, double> umaplld;
typedef unordered_map<double, long long> umapdll;
typedef unordered_map<string, double> umapsd;
typedef unordered_map<double, string> umapds;
typedef unordered_map<int, double> umapid;
typedef unordered_map<double, int> umapdi;
typedef vector<int> vi;
typedef vector<long long> vll;
typedef vector<string> vs;
typedef vector<double> vd;
typedef pair<int, int> pii;
typedef pair<int, string> pis;
typedef pair<long long, long long> pllll;
typedef pair<long long, string> plls;
typedef pair<double, string> pds;
typedef pair<double, double> pdd;
typedef pair<double, int> pdi;
typedef pair<double, long long> pdll;
struct mystruct {
};
// pq bakal kebalik
class mycomp
{
public:
bool operator() (int a, int b) {
return a > b;
}
};
bool customcompare(int a, int b) {
return a > b;
}
int main ()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
int N;
string x;
cin >> N >> x;
int counter = 0;
int dummy = 0;
int memo = 0;
// cout << N << endl << x << endl;
for (int i = 0; i < x.length(); i++) {
// cout << counter << endl;
if(x[i] == 'W') {
counter++;
} else {
counter--;
}
// cout << counter << endl;
if (abs(counter) > N && i != x.length()-1) {
char temp = x[i];
x[i] = x[i+1];
x[i+1] = temp;
counter = memo;
}
if (counter == memo) {
if(x[i] == 'W') {
counter++;
} else {
counter--;
}
}
if (abs(counter) > N) {
counter = memo;
break;
}
memo = counter;
dummy++;
// cout << dummy << endl;
}
cout << dummy << endl;
return 0;
} | [
"samuelhenrykurniawan@yahoo.com"
] | samuelhenrykurniawan@yahoo.com |
44d1f73b2eb8ce83e1046ae65e0557b033e5bdf5 | 7522119f277b50f1d6e4a2409fa32789aa3e708b | /Codes/URI 1097.cpp | 908a8a0a570244026e97df87d82e24558720d5e3 | [] | no_license | sajidhasanapon/URI-Solutions | bf485e336e6687627db7cb768ca5abe4708cc942 | fc9aec831102a1aa56d884f6edc8d7cebe510f89 | refs/heads/master | 2021-07-12T20:24:32.909720 | 2020-06-24T21:51:20 | 2020-06-24T21:51:20 | 62,802,828 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp |
#include <iostream>
using namespace std;
int main ()
{
int i, j = 2;
for ( i = 1; i <= 9; i += 2 )
{
j += 5;
cout << "I=" << i << " J=" << j-- << endl;
cout << "I=" << i << " J=" << j-- << endl;
cout << "I=" << i << " J=" << j-- << endl;
}
return 0;
}
| [
"noreply@github.com"
] | sajidhasanapon.noreply@github.com |
cb1c66be0c9ab1a0d89c99d42e3d5ba679c986b0 | 698a80d330448e6e9b9e63046b7fbd599f97093a | /P4Plugin/Source/P4ChangeDescriptionCommand.cpp | 6e5d8b8a19d45c75193af35ba48a8c7e991c2774 | [
"LicenseRef-scancode-public-domain"
] | permissive | jamilan/VersionControlPlugins | 2abe561c1fccc05aebdc58fd6e1eb685d24acabb | fa51f7e0c5a80eeb9e14e824690bafbe03c999a6 | refs/heads/master | 2021-01-16T18:15:46.229349 | 2013-01-15T15:32:03 | 2013-01-15T15:32:03 | 7,663,255 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,499 | cpp | #include "Changes.h"
#include "P4Command.h"
#include "P4Task.h"
#include <sstream>
using namespace std;
class P4ChangeDescriptionCommand : public P4Command
{
public:
P4ChangeDescriptionCommand(const char* name) : P4Command(name) {}
virtual bool Run(P4Task& task, const CommandArgs& args)
{
ClearStatus();
upipe.Log() << "ChangeDescriptionCommand::Run()" << endl;
ChangelistRevision cl;
upipe >> cl;
const string cmd = string("change -o ") + (cl == kDefaultListRevision ? string("") : cl);
task.CommandRun(cmd, this);
upipe << GetStatus();
// The OutputState and other callbacks will now output to stdout.
// We just wrap up the communication here.
upipe.EndResponse();
return true;
}
// Called once
void OutputInfo( char level, const char *data )
{
string result;
ReadDescription(data, result);
upipe.OkLine(result);
}
int ReadDescription(const char *data, string& result)
{
stringstream ss(data);
char buf[512];
const string kFind = "Description:";
const string kFiles = "Files:";
const string kJobs = "Jobs:";
int lines = 0;
while ( ! ss.getline(buf, 512).fail() )
{
if (kFind == buf)
{
while ( (! ss.getline(buf, 512).fail() ) && kFiles != buf && kJobs != buf)
{
if (buf[0] == '\t')
result += buf+1;
else
result += buf;
result += "\n";
++lines;
}
return lines;
}
}
return lines;
}
} cChangeDescription("changeDescription");
| [
"steenl@unity3d.com"
] | steenl@unity3d.com |
f3f048eec827c4f087c5b2e801a54b795e15d389 | 0b31f76e29b4371aab546935720ef984605b59cd | /Code/source/Game.h | e01341a9a7d686cc4b454960ae0f81e2df675e2c | [] | no_license | bmclaine/Space-Yetis-In-Space | 6cdab961c9f52e9608bc3bd4d6a2718e0fe9207f | bc7da7843afaf3165d59f8e7e66a1bd42b273709 | refs/heads/master | 2020-04-22T10:02:16.463795 | 2016-08-30T02:07:58 | 2016-08-30T02:07:58 | 66,897,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,774 | h | //*********************************************************************//
// File: Game.h
// Author: Brian McLaine
// Course: SGD
// Purpose: Game class initializes the SGD Wrappers
// and runs the game state machine
//*********************************************************************//
#pragma once
#include "../SGD Wrappers/SGD_Geometry.h"
#include "../SGD Wrappers/SGD_Handle.h"
//*********************************************************************//
// Forward class declarations
class BitmapFont;
class IGameState;
//*********************************************************************//
// Game class
// - handles the SGD wrappers
// - runs the game state machine
// - SINGLETON
// - only ONE instance can be created
// - global access to THE instance
class Game
{
public:
//*****************************************************************//
// SINGLETON!
// - static accessor to get the singleton object
static Game* GetInstance( void );
static void DeleteInstance( void );
//*****************************************************************//
// Setup, Play, Cleanup
bool Initialize ( void );
int Update ( void );
void Terminate ( void );
//*****************************************************************//
// Screen Accessors
SGD::Size GetScreenSize ( void ) const { return m_szScreenSize; }
// Font Accessor (#include "BitmapFont.h" to use!)
BitmapFont* GetFont ( void ) const { return m_pFont; }
//*****************************************************************//
// Game State Mutator:
void ChangeState( IGameState* pNextState );
private:
//*****************************************************************//
// SINGLETON!
// - static member to hold the singleton object
// - prevent access to constructors / destructor / =op
static Game* s_pInstance;
Game( void ) = default; // default constructor
~Game( void ) = default; // destructor
Game( const Game& ) = delete; // disabled copy constructor
Game& operator=( const Game& ) = delete; // disabled assignment operator
//*****************************************************************//
// Screen Size
SGD::Size m_szScreenSize = SGD::Size{ 1024, 768 };
// Font
BitmapFont* m_pFont = nullptr;
//*****************************************************************//
// Active Game State
IGameState* m_pCurrState = nullptr;
//*****************************************************************//
// Game Time
unsigned long m_ulGameTime = 0;
//*****************************************************************//
// Background
SGD::HTexture m_hBackgroundImg = SGD::INVALID_HANDLE;
//*****************************************************************//
// Windowed Mode
bool m_bIsWindowed = false;
};
| [
"bizzy18@gmail.com"
] | bizzy18@gmail.com |
1f45e48e7bf928c4adf4f68c6ef8e481218acc82 | f6e289b61ad157b7a558a522ae2ddffd44c1b0e3 | /cpp/src/detector/BBDetector.cpp | 7e12e7b636fce70ab4a091223acaf9d2526fc0d7 | [] | no_license | zhongshijun/tracking-by-detection | eb126eb526f2f15b973b9c7b833292bc8136aae8 | 16108b7ca9a0a0f7b00d9a559a034bf158c11d60 | refs/heads/master | 2021-01-20T08:10:06.703406 | 2017-04-25T05:00:05 | 2017-04-25T05:00:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,958 | cpp | #include "BBDetector.h"
#ifdef USE_CAFFE
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
using namespace caffe;
// Constructors
BBDetector::BBDetector(const std::string &modelFile, const std::string &weightsFile, const std::string &meanValue)
: Detector() {
Caffe::set_mode(Caffe::GPU);
/* Load the network. */
net.reset(new Net<float>(modelFile, caffe::TEST));
net->CopyTrainedLayersFrom(weightsFile);
//CHECK_EQ(net->num_inputs(), 1) << "Network should have exactly one input.";
//CHECK_EQ(net->num_outputs(), 1) << "Network should have exactly one output.";
Blob<float> *inputLayer = net->input_blobs()[0];
numChannels = inputLayer->channels();
//CHECK(numChannels == 3 || numChannels == 1)
// << "Input layer should have 1 or 3 channels.";
inputGeometry = cv::Size(inputLayer->width(), inputLayer->height());
setMean(meanValue);
}
// Methods
std::vector<Detection> BBDetector::detect(const cv::Mat &image) {
Blob<float> *inputLayer = net->input_blobs()[0];
inputLayer->Reshape(1, numChannels,
inputGeometry.height, inputGeometry.width);
/* Forward dimension change to all layers. */
net->Reshape();
std::vector<cv::Mat> inputChannels;
wrapInputLayer(&inputChannels);
preprocess(image, &inputChannels);
net->Forward();
/* Copy the output layer to a vector */
Blob<float> *resultBlob = net->output_blobs()[0];
// Result format: [image_id, label, score, xmin, ymin, xmax, ymax].
const float *result = resultBlob->cpu_data();
const int numDet = resultBlob->height();
std::vector<Detection> detections;
for (int k = 0; k < numDet; ++k) {
if (result[0] == -1 || result[2] < 0.1) {
// Skip invalid detection.
result += 7;
continue;
}
std::vector<float> det(result, result + 7);
Detection detection(int(det[1]), det[2], BoundingBox((det[3] + det[5]) / 2 * image.cols,
(det[4] + det[6]) / 2 * image.rows,
(det[5] - det[3]) * image.cols,
(det[6] - det[4]) * image.rows
));
detections.push_back(detection);
result += 7;
}
return detections;
}
void BBDetector::setMean(const std::string &meanValue) {
cv::Scalar channelMean;
std::stringstream ss(meanValue);
std::vector<double> values;
std::string item;
while (getline(ss, item, ',')) {
double value = std::atof(item.c_str());
values.push_back(value);
}
/*
CHECK(values.size() == 1 || values.size() == numChannels) <<
"Specify either 1 meanValue or as many as channels: "
<< numChannels;
*/
std::vector<cv::Mat> channels;
for (int i = 0; i < numChannels; ++i) {
/* Extract an individual channel. */
cv::Mat channel(inputGeometry.height, inputGeometry.width, CV_32FC1,
cv::Scalar(values[i]));
channels.push_back(channel);
}
cv::merge(channels, mean);
}
void BBDetector::wrapInputLayer(std::vector<cv::Mat> *inputChannels) {
Blob<float> *inputLayer = net->input_blobs()[0];
int width = inputLayer->width();
int height = inputLayer->height();
float *inputData = inputLayer->mutable_cpu_data();
for (int i = 0; i < inputLayer->channels(); ++i) {
cv::Mat channel(height, width, CV_32FC1, inputData);
inputChannels->push_back(channel);
inputData += width * height;
}
}
void BBDetector::preprocess(const cv::Mat &image,
std::vector<cv::Mat> *inputChannels) {
/* Convert the input image to the input image format of the network. */
cv::Mat sample;
if (image.channels() == 3 && numChannels == 1)
cv::cvtColor(image, sample, cv::COLOR_BGR2GRAY);
else if (image.channels() == 4 && numChannels == 1)
cv::cvtColor(image, sample, cv::COLOR_BGRA2GRAY);
else if (image.channels() == 4 && numChannels == 3)
cv::cvtColor(image, sample, cv::COLOR_BGRA2BGR);
else if (image.channels() == 1 && numChannels == 3)
cv::cvtColor(image, sample, cv::COLOR_GRAY2BGR);
else
sample = image;
cv::Mat sampleResized;
if (sample.size() != inputGeometry)
cv::resize(sample, sampleResized, inputGeometry);
else
sampleResized = sample;
cv::Mat sampleFloat;
if (numChannels == 3)
sampleResized.convertTo(sampleFloat, CV_32FC3);
else
sampleResized.convertTo(sampleFloat, CV_32FC1);
cv::Mat sampleNormalized;
cv::subtract(sampleFloat, mean, sampleNormalized);
/* This operation will write the separate BGR planes directly to the
* input layer of the network because it is wrapped by the cv::Mat
* objects in inputChannels. */
cv::split(sampleNormalized, *inputChannels);
/*
CHECK(reinterpret_cast<float *>(inputChannels->at(0).data)
== net->input_blobs()[0]->cpu_data())
<< "Input channels are not wrapping the input layer of the network.";
*/
}
#else //USE_CAFFE
#include <stdexcept>
#include <iostream>
BBDetector::BBDetector() {
std::cerr << "Use of BBDetector requires Caffe; compile with USE_CAFFE.\n";
throw std::runtime_error("Use of BBDetector requires Caffe; compile with USE_CAFFE.");
}
BBDetector::BBDetector(const std::string &model_file,
const std::string &weights_file,
const std::string &mean_value) : BBDetector() {}
std::vector<Detection> BBDetector::detect(const cv::Mat &image) {
throw std::runtime_error("Use of BBDetector requires Caffe; compile with USE_CAFFE.");
}
#endif //USE_CAFFE | [
"samuel.murray@outlook.com"
] | samuel.murray@outlook.com |
1777343c9d341be29f280843eb7e82b3e9d013da | b8914fca2295a5e257fab4d5000d5db2477b6f6a | /v2.1.cpp | cc15b71615aaed68b866c393cb60a6862025ae1d | [] | no_license | fatihgoksu/HuffmanCoding | 363b0de39ff6370419d792fcda0261889e283dec | 39a854deb98599f6d8dce39737afcd141a93e2e2 | refs/heads/master | 2021-08-28T16:56:02.401139 | 2017-12-12T20:49:36 | 2017-12-12T20:49:36 | 114,037,181 | 1 | 0 | null | null | null | null | ISO-8859-9 | C++ | false | false | 2,300 | cpp | #include <stdio.h>
#include <string.h>
typedef struct huffmanAgac { //huffmanağac yapısı olusturuldu
struct huffmanAgac *sol, *sag;
int frekans;
char c;
} *node;
struct huffmanAgac pool[256] = {{0}};
node qqq[255], *q = qqq - 1;
int n_nodes = 0, qend = 1;
char *code[128] = {0}, buf[1024];
node new_node(int frekans, char c, node a, node b) //yeni düğüm noktası
{
node n = pool + n_nodes++;
if (frekans) n->c = c, n->frekans = frekans;
else {
n->sol = a, n->sag = b;
n->frekans = a->frekans + b->frekans;
}
return n;
}
/* Öncelik sırası */
void qinsert(node n)
{
int j, i = qend++;
while ((j = i / 2)) {
if (q[j]->frekans <= n->frekans) break;
q[i] = q[j], i = j;
}
q[i] = n;
}
node qremove()
{
int i, l;
node n = q[i = 1];
if (qend < 2) return 0;
qend--;
while ((l = i * 2) < qend) {
if (l + 1 < qend && q[l + 1]->frekans < q[l]->frekans) l++;
q[i] = q[l], i = l;
}
q[i] = q[qend];
return n;
}
/*
Ağacda yürü ve 0s ve 1s koy */
void build_code(node n, char *s, int len)
{
static char *out = buf;
if (n->c) {
s[len] = 0;
strcpy(out, s);
code[n->c] = out;
out += len + 1;
return;
}
s[len] = '0'; build_code(n->sol, s, len + 1);
s[len] = '1'; build_code(n->sag, s, len + 1);
}
void init(const char *s)
{
int i, frekans[128] = {0};
char c[16];
while (*s) frekans[(int)*s++]++;
for (i = 0; i < 128; i++)
if (frekans[i]) qinsert(new_node(frekans[i], i, 0, 0));
while (qend > 2)
qinsert(new_node(0, 0, qremove(), qremove()));
build_code(q[1], c, 0);
}
void encode(const char *s, char *out)
{
while (*s) {
strcpy(out, code[*s]);
out += strlen(code[*s++]);
}
}
void decode(const char *s, node t)
{
node n = t;
while (*s) {
if (*s++ == '0') n = n->sol;
else n = n->sag;
if (n->c) putchar(n->c), n = t;
}
putchar('\n');
if (t != n) printf("garbage input\n");
}
int main(void)
{
int i;
const char *str = "hello word";
char buf[1024];
init(str);
for (i = 0; i < 128; i++)
if (code[i]) printf("'%c': %s\n", i, code[i]);
encode(str, buf);
printf("kodlamaYapildi: %s\n", buf);
printf("Cumle: ");
decode(buf, q[1]);
return 0;
}
| [
"noreply@github.com"
] | fatihgoksu.noreply@github.com |
78006a208ceeb55749fb56005d84cc04b163fb94 | 02f819760606087eeb7464cf10ca9ad5c001b851 | /source/extensions/transport_sockets/common/passthrough.h | 4731e5ebbb0b4ff7a12d77459260662cf1b21d9d | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | yxue/envoy | 3899021225ce93ebd0e5ce6de826fc99e589bca0 | b56c0a2a4e877f61b5601ecd6a98f0efe439ffec | refs/heads/master | 2023-06-10T21:39:46.716556 | 2023-03-13T03:43:17 | 2023-03-13T03:43:17 | 182,469,103 | 2 | 0 | Apache-2.0 | 2023-06-08T12:30:41 | 2019-04-21T00:56:04 | C++ | UTF-8 | C++ | false | false | 1,875 | h | #pragma once
#include "envoy/network/connection.h"
#include "envoy/network/transport_socket.h"
#include "source/common/buffer/buffer_impl.h"
namespace Envoy {
namespace Extensions {
namespace TransportSockets {
class PassthroughFactory : public Network::TransportSocketFactory {
public:
PassthroughFactory(Network::TransportSocketFactoryPtr&& transport_socket_factory)
: transport_socket_factory_(std::move(transport_socket_factory)) {
ASSERT(transport_socket_factory_ != nullptr);
}
bool implementsSecureTransport() const override {
return transport_socket_factory_->implementsSecureTransport();
}
bool supportsAlpn() const override { return transport_socket_factory_->supportsAlpn(); }
bool usesProxyProtocolOptions() const override {
return transport_socket_factory_->usesProxyProtocolOptions();
}
protected:
// The wrapped factory.
Network::TransportSocketFactoryPtr transport_socket_factory_;
};
class PassthroughSocket : public Network::TransportSocket {
public:
PassthroughSocket(Network::TransportSocketPtr&& transport_socket);
void setTransportSocketCallbacks(Network::TransportSocketCallbacks& callbacks) override;
std::string protocol() const override;
absl::string_view failureReason() const override;
bool canFlushClose() override;
void closeSocket(Network::ConnectionEvent event) override;
Network::IoResult doRead(Buffer::Instance& buffer) override;
Network::IoResult doWrite(Buffer::Instance& buffer, bool end_stream) override;
void onConnected() override;
Ssl::ConnectionInfoConstSharedPtr ssl() const override;
// startSecureTransport method should not be called for this transport socket.
bool startSecureTransport() override { return false; }
protected:
Network::TransportSocketPtr transport_socket_;
};
} // namespace TransportSockets
} // namespace Extensions
} // namespace Envoy
| [
"noreply@github.com"
] | yxue.noreply@github.com |
1314dee78a36980cc1e19a396895f193955ff8d4 | 740f4a46762126367b322527cb852373250f3fdf | /Hello World.cpp | aee713a7958e9096e484d990ed2d10dfda8511f2 | [] | no_license | mukul-yadavv/Git_Demo | a176b441256b665490d7b8547fcae4756726461f | 019ebd9f27946b35317b72cf9f7630cb0445bf21 | refs/heads/main | 2023-03-04T15:24:30.898886 | 2021-02-15T09:00:35 | 2021-02-15T09:00:35 | 338,985,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 84 | cpp | #include <iostream>
using namespace std;
int main()
{
cout<<"Hello World"<<endl;
} | [
"mukulyadav4548@gmail.com"
] | mukulyadav4548@gmail.com |
5451625891109df3394b0b2ac0b4bb6899e0d717 | bef53cc5427675f68a1b836e26cb5af887a89de9 | /project/User/Users.cpp | 7996080e5ae8e31df7984441ff7917557fdf005d | [] | no_license | chestnutprog/DS_Final_Project | 0ef2fc1519e5832d9f21d5fabeaaf5087d77fe51 | 2ebcc1d22930f74aa59f8366c4187fb11eac6805 | refs/heads/master | 2022-10-11T09:52:39.761479 | 2020-06-12T08:12:04 | 2020-06-12T08:12:04 | 266,036,557 | 0 | 0 | null | 2020-08-12T08:12:36 | 2020-05-22T06:34:11 | C++ | UTF-8 | C++ | false | false | 4,871 | cpp | #include "Users.h"
/**This is the database of the game.
*The information is stored in the user.sqlite
*The name of the table is called users
*And there are four column in this table ,they are username, psd, point, token.
*/
auto storage = make_storage(
"user.sqlite",
make_table("users",
make_column("username", &user::username, unique()),
make_column("psd", &user::password),
make_column("point", &user::point),
make_column("token", &user::token))
);
/**This is the constructor
*Calling the constructor will automatically turn on sync
*Calling the constructor will automatically get the ranklist
*/
Users::Users() {
storage.sync_schema();//turn on sync
auto users = storage.get_all<user>(order_by(&user::point));//Get ranklist in ascending order
int n = users.size();
RankList = vector<Record>(n);
for (int i = 0; i < n ; i++) {//Change ascending order to descending order
RankList[i].username = users[n - i - 1].username;
RankList[i].point = users[n - i - 1].point;
}
}
Users::~Users() {};
/**This is the function to login
*We will get the username and password
*If the username dosen't exist or the password is wrong will throw runtime error
*If log in successfully will return a token which used to determine if the user is online
*/
int Users::login(string uname, string password) {
auto users = storage.get_all<user>(where(c(&user::username) == uname));
if (users.size() == 0) {//The database doesn't exist this user
throw runtime_error("用户名不存在");
}
else if (users[0].password != password) {//The input password is wrong
throw runtime_error("密码错误");
}
else {
int token;
token = rand();//Get a token by rand()
users[0].token = token;
return token;
}
}
/**This is the function to reg
*We will get the username and two passwords
*If the username has already been registered or the two entered password are different will throw runtime error
*/
void Users::reg(string uname, string password1, string password2) {
auto users = storage.get_all<user>(where(c(&user::username) == uname));
if (users.size() != 0) {//The username has already been registered
throw runtime_error("用户名已经被注册");
}
else if (password1 != password2) {//The two entered password are different
throw runtime_error("两次输入密码不相同");
}else {
user u = { uname,password1,0 ,0};//Initialize user information
storage.insert(u);//Insert this user to the database
}
}
/**This is the function to modify password
*We will get the username, original password and two upcoming passwords
*If the username dosen't exist or the password is wrong will throw runtime error
*and if two entered password are different will also throw runtime error
*/
void Users::modifyPassword(string uname, string password, string password1, string password2) {
auto users = storage.get_all<user>(where(c(&user::username) == uname));
if (users.size() == 0) {//The database doesn't exist this user
throw runtime_error("用户名不存在");
}
else if (users[0].password != password){//The input password is wrong
throw runtime_error("密码不正确");
}
else if (password1 != password2) {//The two entered password are different
throw runtime_error("两次输入密码不相同");
}
else {
user u = { uname,password1,users[0].point ,users[0].token};//modify the user's password
storage.replace(u);//Update the database,use u to replace the original user information
}
}
/**
*This is the function to return ranklist
*/
vector<Record> Users::getRankList() {
return RankList;
}
/**This is the function to update the user score
*We will get the user name, the score to be modified and a token to determine whether the user is online
*If the username dosen't exist or the user is not online will throw runtime error
*If the username is exist and he is online we can modify his score by the point and we can reorder the ranklist
*/
void Users::update(string uname,int point,int token) {
auto users = storage.get_all<user>(where(c(&user::username) == uname));
if (users.size() == 0) {//The database doesn't exist this user
throw runtime_error("无法修改!该记录出错,该用户名不存在!");
}
else if (token != users[0].token) {//The user is not online ,can't modify his score
throw runtime_error("无法修改!无法修改他人的分数!");
}
else if (users[0].point < point) { //If this user has broken his record, modify his information in the database
user u = { uname,users[0].password,point ,token};//modify the point
storage.replace(u); // Update the database, use u to replace the original user information
auto users = storage.get_all<user>(order_by(&user::point));
int n = users.size();
for (int i = 0; i < n; i++) {//Reorder the ranklist
RankList[i].username = users[n - i - 1].username;
RankList[i].point = users[n - i - 1].point;
}
}
}
| [
"noreply@github.com"
] | chestnutprog.noreply@github.com |
6fec6bbbdb31745ef8b2ed162bdbf9f4135c5ea3 | 6ce46d0748248659c76cd1ffe0a9e03e8cd33374 | /controlino/controlino.cpp | e01c058585d5ebcff86f077a39694a4da752c29f | [] | no_license | josecurras/Instrumentino | 933eb4738f3188ae63b58e46cb81dce351324852 | 459860ff6c545aaee6c25f6de5543b6c0515f7a2 | refs/heads/master | 2020-12-29T01:12:08.761924 | 2015-01-06T11:24:12 | 2015-01-06T11:24:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,101 | cpp | /*
controlino.cpp - Library for controling an Arduino using the USB
Created by Joel Koenka, April 2014
Released under GPLv3
Controlino let's a user control the Arduino pins by issuing simple serial commands such as "Read" "Write" etc.
It was originally written to be used with Instrumentino, the open-source GUI platform for experimental settings,
but can also be used for other purposes.
For Instrumentino, see:
http://www.sciencedirect.com/science/article/pii/S0010465514002112 - Release article
https://pypi.python.org/pypi/instrumentino/1.0 - Package in PyPi
https://github.com/yoelk/instrumentino - Code in GitHub
Modifiers (THIS IS IMPORTANT !!! PLEASE READ !!!)
=================================================
- Library support:
Controlino gradually grows to include support for more and more Arduino libraries (such as PID, SoftwareSerial, etc.)
Since not everyone needs to use all of the libraries, a set of #define statements are used to include/exclude them.
- Arduino board:
Controlino can run on any Arduino, but you need to tell it which one!
*/
/* ------------------------------------------------------------
Dear user (1):
Here you should specify which Arduino libraries you want to use.
Please comment/uncomment the appropriate define statements
------------------------------------------------------------ */
//#define USE_SOFTWARE_SERIAL
#define USE_PID
/* ------------------------------------------------------------
Dear user (2):
Here you should choose the Arduino Board for which you'll
compile Controlino. Only one model should be used (uncommented)
------------------------------------------------------------ */
//#define ARDUINO_BOARD_UNO
//#define ARDUINO_BOARD_LEONARDO
//#define ARDUINO_BOARD_DUE
//#define ARDUINO_BOARD_YUN
//#define ARDUINO_BOARD_TRE
//#define ARDUINO_BOARD_ZERO
//#define ARDUINO_BOARD_MICRO
//#define ARDUINO_BOARD_ESPLORA
//#define ARDUINO_BOARD_MEGA_ADK
#define ARDUINO_BOARD_MEGA_2560
//#define ARDUINO_BOARD_ETHERNET
//#define ARDUINO_BOARD_ROBOT
//#define ARDUINO_BOARD_MINI
//#define ARDUINO_BOARD_NANO
//#define ARDUINO_BOARD_LILYPAD
//#define ARDUINO_BOARD_LILYPAD_SIMPLE
//#define ARDUINO_BOARD_LILYPAD_SIMPLE_SNAP
//#define ARDUINO_BOARD_LILYPAD_USB
//#define ARDUINO_BOARD_PRO
//#define ARDUINO_BOARD_PRO_MINI
//#define ARDUINO_BOARD_FIO
/* ------------------------------------------------------------
From here down, you shouldn't touch anything (unless you know
what you're doing)
------------------------------------------------------------ */
#include "Arduino.h"
#include "string.h"
#include "HardwareSerial.h"
// Default values, to be overridden later
#define HARD_SER_MAX_PORTS 0
#define SOFT_SER_MAX_PORTS 0
// Arduino Uno
#ifdef ARDUINO_BOARD_UNO
#define DIGI_PINS 14
#endif
// Arduino Leonardo
#ifdef ARDUINO_BOARD_LEONARDO
#define DIGI_PINS 20
#define HARD_SER_MAX_PORTS 1
extern HardwareSerial Serial1;
#endif
// Arduino Due
#ifdef ARDUINO_BOARD_DUE
#define DIGI_PINS 54
#define HARD_SER_MAX_PORTS 3
extern HardwareSerial Serial1;
extern HardwareSerial Serial2;
extern HardwareSerial Serial3;
#endif
// Arduino Yun
#ifdef ARDUINO_BOARD_YUN
#define DIGI_PINS 20
#endif
// Arduino Tre
#ifdef ARDUINO_BOARD_TRE
#define DIGI_PINS 14
#endif
// Arduino Zero
#ifdef ARDUINO_BOARD_ZERO
#define DIGI_PINS 14
#endif
// Arduino Micro
#ifdef ARDUINO_BOARD_MICRO
#define DIGI_PINS 20
#endif
// Arduino Mega ADK
#ifdef ARDUINO_BOARD_MEGA_ADK
#define DIGI_PINS 54
#define HARD_SER_MAX_PORTS 3
extern HardwareSerial Serial1;
extern HardwareSerial Serial2;
extern HardwareSerial Serial3;
#endif
// Arduino Mega 2560
#ifdef ARDUINO_BOARD_MEGA_2560
#define DIGI_PINS 54
#define HARD_SER_MAX_PORTS 3
extern HardwareSerial Serial1;
extern HardwareSerial Serial2;
extern HardwareSerial Serial3;
#endif
// Arduino Ethernet
#ifdef ARDUINO_BOARD_ETHERNET
#define DIGI_PINS 14
#endif
// Arduino Nano
#ifdef ARDUINO_BOARD_NANO
#define DIGI_PINS 14
#endif
// Arduino Lilypad
#ifdef ARDUINO_BOARD_LILIPAD
#define DIGI_PINS 14
#endif
// Arduino Lilypad Simple
#ifdef ARDUINO_BOARD_LILYPAD_SIMPLE
#define DIGI_PINS 9
#endif
// Arduino Lilypad Simple Snap
#ifdef ARDUINO_BOARD_LILYPAD_SIMPLE_SNAP
#define DIGI_PINS 9
#endif
// Arduino Lilypad USB
#ifdef ARDUINO_BOARD_LILYPAD_USB
#define DIGI_PINS 9
#endif
// Arduino Pro
#ifdef ARDUINO_BOARD_PRO
#define DIGI_PINS 14
#endif
// Arduino Pro Mini
#ifdef ARDUINO_BOARD_PRO_MINI
#define DIGI_PINS 13
#endif
// Arduino Fio
#ifdef ARDUINO_BOARD_FIO
#define DIGI_PINS 14
#endif
// ------------------------------------------------------------
// Arduino libraries support
// ------------------------------------------------------------
#ifdef __cplusplus
extern "C" {
#endif
void loop();
void setup();
#ifdef __cplusplus
} // extern "C"
#endif
// Extra Hardware Serial support
#if HARD_SER_MAX_PORTS > 0
// Descriptors for hardware serial
HardwareSerial* hardSerHandler[HARD_SER_MAX_PORTS];
#endif
// SoftwareSerial library
#ifdef USE_SOFTWARE_SERIAL
#include "SoftwareSerial.h"
#define SOFT_SER_MSG_SIZE 100
#define SOFT_SER_MAX_PORTS 4
// software serial descriptor
typedef struct {
SoftwareSerial* handler;
char txMsg[SOFT_SER_MSG_SIZE];
char rxMsg[SOFT_SER_MSG_SIZE];
int txMsgLen;
int rxMsgLen;
} SoftSerialDesc;
// Descriptors for software serial
SoftSerialDesc softSerDescs[SOFT_SER_MAX_PORTS];
#endif
// PID library
#ifdef USE_PID
#include "PID_v1.h"
// PID
#define PID_RELAY_MAX_VARS 4
// PID-relay variable descriptor
typedef struct {
PID* handler;
int pinAnalIn;
int pinDigiOut;
double inputVar;
double outputVar;
unsigned long windowSize;
unsigned long windowStartTime;
double setPoint;
boolean isOn;
} PidRelayDesc;
// Descriptors for PID controlled variables
PidRelayDesc pidRelayDescs[PID_RELAY_MAX_VARS];
#endif
// ------------------------------------------------------------
// Definitions
// ------------------------------------------------------------
// arduino definitions
#define ANAL_OUT_VAL_MAX 255
// serial communication with user (usually with Instrumentino)
extern HardwareSerial Serial;
#define SERIAL0_BAUD 115200
#define RX_BUFF_SIZE 200
#define ARGV_MAX 30
// ------------------------------------------------------------
// Globals
// ------------------------------------------------------------
char doneString[5] = "done";
// Buffer to keep incoming commands and a pointer to it
char msg[RX_BUFF_SIZE];
char *pMsg;
// Pin blinking
boolean startBlinking = false;
int blinkingPin;
unsigned long blinkLastChangeMs;
unsigned long blinkingDelayMs;
// ------------------------------------------------------------
// Command functions - These functions are called when their
// respective command was issued by the user
// ------------------------------------------------------------
/***
* Set [pin number] [in | out]
*
* Set a digital pin mode
*/
void cmdSet(char **argV) {
int pin = strtol(argV[1], NULL, 10);
char* mode = argV[2];
if (strcasecmp(mode, "in") == 0) {
pinMode(pin, INPUT);
} else if (strcasecmp(mode, "out") == 0) {
pinMode(pin, OUTPUT);
} else {
return;
}
}
/***
* Reset
*
* Reset all digital pins to INPUT
*/
void cmdReset() {
for (int i = 0; i < DIGI_PINS; i++) {
pinMode(i, INPUT);
}
}
/***
* BlinkPin
*
* Start blinking a pin (e.g pin 13 with the LED)
*/
void cmdBlinkPin(char **argV) {
blinkingPin = strtol(argV[1], NULL, 10);
blinkingDelayMs = strtol(argV[2], NULL, 10);
pinMode(blinkingPin, OUTPUT);
blinkLastChangeMs = millis();
startBlinking = true;
}
/***
* Read [pin1] [pin2] ....
*
* Read pin values
* Pins are given in the following way: A0 A1 ... for analog pins
* D0 D1 ... for digital pins
* Answer is: val1 val2 ...
*/
void cmdRead(int argC, char **argV) {
char pinType[2];
int pin;
int value;
for (int i = 1; i <= argC; i++) {
pinType[0] = argV[i][0];
pinType[1] = NULL;
pin = strtol(&(argV[i][1]), NULL, 10);
if (strcasecmp(pinType, "D") == 0) {
value = digitalRead(pin);
} else if (strcasecmp(pinType, "A") == 0) {
value = analogRead(pin);
} else {
return;
}
// Add read values to answer string
Serial.print(value);
if (i < argC) {
Serial.print(' ');
}
}
}
/***
* Write [pin number] [digi | anal] [value]
*
* Write a value to a pin
*/
void cmdWrite(char **argV) {
int pin = strtol(argV[1], NULL, 10);
char* type = argV[2];
int value = strtol(argV[3], NULL, 10);
if (strcasecmp(type, "digi") == 0) {
if (value == 0) {
digitalWrite(pin, LOW);
} else {
digitalWrite(pin, HIGH);
}
} else if (strcasecmp(type, "anal") == 0) {
analogWrite(pin, max(0, min(ANAL_OUT_VAL_MAX, value)));
} else {
return;
}
}
/***
* SetPwmFreq [pin number] [divider]
*
* Change the PWM frequency by changing the clock divider
* This should be done carefully, as the clocks may have other effects on the system.
* Specifically, pins 5,6 are controlled by timer0, which is also in charge for the delay() function.
*
* The divider can get: 1,8,64,256,1024 for pins 5,6,9,10;
* 1,8,32,64,128,256,1024 for pins 3,11
*/
void cmdSetPwmFreq(char **argV) {
int pin = strtol(argV[1], NULL, 10);
int divider = strtol(argV[2], NULL, 10);
byte mode;
if(pin == 5 || pin == 6 || pin == 9 || pin == 10) {
switch(divider) {
case 1: mode = 0x01; break; // 5,6: 62500 Hz | 9,10: 31250 Hz
case 8: mode = 0x02; break; // 5,6: 7812.5 Hz | 9,10: 3906.3 Hz
case 64: mode = 0x03; break; // 5,6: 976.6 Hz | 9,10: 488.3 Hz
case 256: mode = 0x04; break; // 5,6: 244.1 Hz | 9,10: 122 Hz
case 1024: mode = 0x05; break;// 5,6: 61 Hz | 9,10: 30.5 Hz
default: return;
}
if(pin == 5 || pin == 6) {
#if defined(TCCR0B)
TCCR0B = (TCCR0B & 0b11111000) | mode;
#endif
} else {
#if defined(TCCR1B)
TCCR1B = (TCCR1B & 0b11111000) | mode;
#endif
}
} else if(pin == 3 || pin == 11) {
switch(divider) {
case 1: mode = 0x01; break; // 31250 Hz
case 8: mode = 0x02; break; // 3906.3 Hz
case 32: mode = 0x03; break; // 976.6 Hz
case 64: mode = 0x04; break; // 488.3 Hz
case 128: mode = 0x05; break; // 244.1 Hz
case 256: mode = 0x06; break; // 122 Hz
case 1024: mode = 0x7; break; // 30.5 Hz
default: return;
}
#if defined(TCCR2B)
TCCR2B = (TCCR2B & 0b11111000) | mode;
#endif
}
}
#ifdef USE_PID
/***
* PidRelayCreate [pidVar] [pinAnalIn] [pinDigiOut] [windowSize] [Kp] [Ki] [Kd]
*
* Create a PID variable that controls a relay. window size is in ms.
* See more information: http://playground.arduino.cc/Code/PIDLibraryRelayOutputExample
*/
void cmdPidRelayCreate(char **argV) {
int pidVar = strtol(argV[1], NULL, 10);
int pinAnalIn = strtol(argV[2], NULL, 10);
int pinDigiOut = strtol(argV[3], NULL, 10);
int windowSize = strtol(argV[4], NULL, 10);
double kp = atof(argV[5]);
double ki = atof(argV[6]);
double kd = atof(argV[7]);
if (pidVar < 1 || pidVar > PID_RELAY_MAX_VARS) {
return;
}
// Init the PID variable
PidRelayDesc* pidDesc = &pidRelayDescs[pidVar-1];
pidDesc->pinAnalIn = pinAnalIn;
pidDesc->pinDigiOut = pinDigiOut;
pidDesc->windowSize = windowSize;
pidDesc->handler = new PID(&pidDesc->inputVar, &pidDesc->outputVar, &pidDesc->setPoint, kp, ki, kd, DIRECT);
pidDesc->handler->SetOutputLimits(0, pidDesc->windowSize);
pidDesc->isOn = false;
}
/***
* PidRelayTune [Kp] [Ki] [Kd]
*
* Set the PID tuning parameters
*/
void cmdPidRelayTune(char **argV) {
int pidVar = strtol(argV[1], NULL, 10);
double kp = atof(argV[2]);
double ki = atof(argV[3]);
double kd = atof(argV[4]);
if (pidVar < 1 || pidVar > PID_RELAY_MAX_VARS) {
return;
}
PidRelayDesc* pidDesc = &pidRelayDescs[pidVar-1];
pidDesc->handler->SetTunings(kp, ki, kd);
}
/***
* PidRelaySet [pidVar] [setpoint]
*
* Start controlling a relay using a PID variable
*/
void cmdPidRelaySet(char **argV) {
int pidVar = strtol(argV[1], NULL, 10);
int setPoint = strtol(argV[2], NULL, 10);
if (pidVar < 1 || pidVar > PID_RELAY_MAX_VARS) {
return;
}
PidRelayDesc* pidDesc = &pidRelayDescs[pidVar-1];
pidDesc->setPoint = setPoint;
}
/***
* PidRelayEnable [pidVar] [0 | 1]
*
* Start/Stop the control loop
*/
void cmdPidRelayEnable(char **argV) {
int pidVar = strtol(argV[1], NULL, 10);
int enable = strtol(argV[2], NULL, 10);
if (pidVar < 1 || pidVar > PID_RELAY_MAX_VARS) {
return;
}
PidRelayDesc* pidDesc = &pidRelayDescs[pidVar-1];
pidDesc->windowStartTime = millis();
// turn the PID on/off
if (enable != 0) {
pidDesc->isOn = true;
pidDesc->handler->SetMode(AUTOMATIC);
} else {
pidDesc->isOn = false;
pidDesc->handler->SetMode(MANUAL);
digitalWrite(pidDesc->pinDigiOut, LOW);
}
}
#endif
/***
* HardSerConnect [baudrate] [port]
*
* Initiate a software serial connection. The rx-pin should have external interrupts
*/
void cmdHardSerConnect(char **argV) {
#if HARD_SER_MAX_PORTS > 0
int baudrate = strtol(argV[1], NULL, 10);
int currPort = strtol(argV[2], NULL, 10);
if (currPort < 1 || currPort > HARD_SER_MAX_PORTS) {
return;
}
// begin serial communication
hardSerHandler[currPort-1]->begin(baudrate);
#endif
}
/***
* SoftSerConnect [rx-pin number] [tx-pin number] [baudrate] [port]
*
* Initiate a software serial connection. The rx-pin should have external interrupts
*/
void cmdSoftSerConnect(char **argV) {
#ifdef USE_SOFTWARE_SERIAL
int pinIn = strtol(argV[1], NULL, 10);
int pinOut = strtol(argV[2], NULL, 10);
int baudrate = strtol(argV[3], NULL, 10);
int currPort = strtol(argV[4], NULL, 10);
if (currPort < 1 || currPort > SOFT_SER_MAX_PORTS) {
return;
}
// init softSerial struct
softSerDescs[currPort-1].rxMsgLen = 0;
softSerDescs[currPort-1].txMsgLen = 0;
softSerDescs[currPort-1].handler = new SoftwareSerial(pinIn, pinOut, false);
softSerDescs[currPort-1].handler->begin(baudrate);
#endif
}
/***
* SerSend [hard | soft] [port]
*
* After this command, each character sent is mirrored to the chosen serial
* port until the NULL character (0x00) is sent (also mirrored)
*/
void cmdSerSend(char **argV) {
boolean isSoftSerial = (strcasecmp(argV[1], "soft") == 0);
int currPort = strtol(argV[2], NULL, 10);
Serial.println(doneString);
if (currPort < 1 || currPort > ((isSoftSerial)? SOFT_SER_MAX_PORTS : HARD_SER_MAX_PORTS)) {
return;
}
if (isSoftSerial) {
#ifdef USE_SOFTWARE_SERIAL
softSerDescs[currPort-1].txMsgLen = 0;
#endif
}
// mirror the hardware serial and the software serial
while (true) {
if (Serial.available()) {
char c = Serial.read();
if (isSoftSerial) {
#ifdef USE_SOFTWARE_SERIAL
softSerDescs[currPort-1].txMsg[softSerDescs[currPort-1].txMsgLen++] = c;
#endif
} else {
#if HARD_SER_MAX_PORTS > 0
hardSerHandler[currPort-1]->write(c);
#else
return;
#endif
}
if (c == '\0') {
// acknowledge
Serial.println(doneString);
delay(10);
#ifdef USE_SOFTWARE_SERIAL
if (isSoftSerial) {
// send the message, and remember the answer
for (int i = 0; i < softSerDescs[currPort-1].txMsgLen; i++) {
softSerDescs[currPort-1].handler->write(softSerDescs[currPort-1].txMsg[i]);
}
softSerDescs[currPort-1].rxMsgLen = 0;
while (!Serial.available()) {
if (softSerDescs[currPort-1].handler->available() && softSerDescs[currPort-1].rxMsgLen < SOFT_SER_MSG_SIZE) {
softSerDescs[currPort-1].rxMsg[softSerDescs[currPort-1].rxMsgLen++] = softSerDescs[currPort-1].handler->read();
}
}
}
#endif
return;
}
}
}
}
/***
* SerReceive [hard | soft] [port]
*
* Empty the RX buffer of a serial port to the control serial port
*/
void cmdSerReceive(char **argV) {
boolean isSoftSerial = (strcasecmp(argV[1], "soft") == 0);
int currPort = strtol(argV[2], NULL, 10);
if (currPort < 1 || currPort > (isSoftSerial)? SOFT_SER_MAX_PORTS : HARD_SER_MAX_PORTS) {
return;
}
if (isSoftSerial) {
#ifdef USE_SOFTWARE_SERIAL
for (int i = 0; i < softSerDescs[currPort-1].rxMsgLen && i < SOFT_SER_MSG_SIZE; i++) {
Serial.write(softSerDescs[currPort-1].rxMsg[i]);
}
#endif
} else {
#if HARD_SER_MAX_PORTS > 0
while (hardSerHandler[currPort-1]->available()) {
Serial.write(hardSerHandler[currPort-1]->read());
}
#endif
}
}
// ------------------------------------------------------------
// Main functions
// ------------------------------------------------------------
/***
* The setup function is called once at startup of the sketch
*/
void setup() {
Serial.begin(SERIAL0_BAUD);
pMsg = msg;
// Init hardware serial ports if they exist
for (int i = 0; i < HARD_SER_MAX_PORTS; i++)
{
switch (i + 1) {
#if HARD_SER_MAX_PORTS >= 1
case 1:
hardSerHandler[i] = &Serial1;
break;
#endif
#if HARD_SER_MAX_PORTS >= 2
case 2:
hardSerHandler[i] = &Serial2;
break;
#endif
#if HARD_SER_MAX_PORTS >= 3
case 3:
hardSerHandler[i] = &Serial3;
break;
#endif
}
}
}
/***
* The loop function is called in an endless loop
*/
void loop() {
char c, argC;
char *argV[ARGV_MAX];
int i, pin;
unsigned long curMs;
// Take care of blinking LED
if (startBlinking == true) {
curMs = millis();
if (curMs > blinkLastChangeMs + blinkingDelayMs) {
blinkLastChangeMs = curMs;
if (digitalRead(blinkingPin) == HIGH) {
digitalWrite(blinkingPin, LOW);
} else {
digitalWrite(blinkingPin, HIGH);
}
}
}
#ifdef USE_PID
// Take care PID-relay variables
for (i = 0; i < PID_RELAY_MAX_VARS; i++) {
if (pidRelayDescs[i].isOn) {
pidRelayDescs[i].inputVar = analogRead(pidRelayDescs[i].pinAnalIn);
pidRelayDescs[i].handler->Compute();
// turn relay on/off according to the PID output
curMs = millis();
if (curMs - pidRelayDescs[i].windowStartTime > pidRelayDescs[i].windowSize) {
//time to shift the Relay Window
pidRelayDescs[i].windowStartTime += pidRelayDescs[i].windowSize;
}
if (pidRelayDescs[i].outputVar > curMs - pidRelayDescs[i].windowStartTime) {
digitalWrite(pidRelayDescs[i].pinDigiOut, HIGH);
}
else {
digitalWrite(pidRelayDescs[i].pinDigiOut, LOW);
}
}
}
#endif
// Read characters from the control serial port and act upon them
if (Serial.available()) {
c = Serial.read();
switch (c) {
case '\n':
break;
case '\r':
// end the string and init pMsg
Serial.println("");
*(pMsg++) = NULL;
pMsg = msg;
// parse the command line statement and break it up into space-delimited
// strings. the array of strings will be saved in the argV array.
i = 0;
argV[i] = strtok(msg, " ");
do {
argV[++i] = strtok(NULL, " ");
} while ((i < ARGV_MAX) && (argV[i] != NULL));
// save off the number of arguments
argC = i;
pin = strtol(argV[1], NULL, 10);
if (strcasecmp(argV[0], "Set") == 0) {
cmdSet(argV);
} else if (strcasecmp(argV[0], "Reset") == 0) {
cmdReset();
} else if (strcasecmp(argV[0], "BlinkPin") == 0) {
cmdBlinkPin(argV);
} else if (strcasecmp(argV[0], "Read") == 0) {
cmdRead(argC, argV);
} else if (strcasecmp(argV[0], "Write") == 0) {
cmdWrite(argV);
} else if (strcasecmp(argV[0], "SetPwmFreq") == 0) {
cmdSetPwmFreq(argV);
#ifdef USE_PID
} else if (strcasecmp(argV[0], "PidRelayCreate") == 0) {
cmdPidRelayCreate(argV);
} else if (strcasecmp(argV[0], "PidRelaySet") == 0) {
cmdPidRelaySet(argV);
} else if (strcasecmp(argV[0], "PidRelayTune") == 0) {
cmdPidRelayTune(argV);
} else if (strcasecmp(argV[0], "PidRelayEnable") == 0) {
cmdPidRelayEnable(argV);
#endif
} else if (strcasecmp(argV[0], "HardSerConnect") == 0) {
cmdHardSerConnect(argV);
} else if (strcasecmp(argV[0], "SoftSerConnect") == 0) {
cmdSoftSerConnect(argV);
} else if (strcasecmp(argV[0], "SerSend") == 0) {
cmdSerSend(argV);
} else if (strcasecmp(argV[0], "SerReceive") == 0) {
cmdSerReceive(argV);
} else {
// Wrong command
return;
}
// Acknowledge the command
Serial.println(doneString);
break;
default:
// Record the received character
if (isprint(c) && pMsg < msg + sizeof(msg)) {
*(pMsg++) = c;
}
break;
}
}
}
| [
"yoel.koenka@gmail.com"
] | yoel.koenka@gmail.com |
006e39ab50f4a174bd1e0a14600569542652e7d8 | b405fd9cd3c53a3ed279e75aca3fec89ba745df5 | /430.Flatten a Multilevel Doubly Linked List/430.Flatten a Multilevel Doubly Linked List/main.cpp | 870e40ccd91487b3ebdc82c5cb961a6b82e7e215 | [] | no_license | Abysman/MyLeetCode | 4842db63f4914022a3773be1e9d9ce068cb6d3bd | a4eb8af658996e7ba4501342f4aa4bbd113e6cfb | refs/heads/master | 2021-04-06T20:48:17.260497 | 2020-01-23T23:09:35 | 2020-01-23T23:09:35 | 125,452,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,105 | cpp | //
// main.cpp
// 430.Flatten a Multilevel Doubly Linked List
//
// Created by stevenxu on 10/31/19.
// Copyright © 2019 stevenxu. All rights reserved.
//
#include <iostream>
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node() {}
Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/
class Solution {
public:
Node* flatten(Node* head) {
Node *next, *h = head;
for (;h != nullptr; h = h->next) {
if (h->child) {
Node* next = h->next;
h->next = h->child;
h->next->prev = h;
h->child = nullptr;
Node* p = h->next;
while (p->next) p = p->next;
p->next = next;
if (next) next->prev = p;
}
}
return head;
}
};
int main(int argc, const char * argv[]) {
// insert code here...
std::cout << "Hello, World!\n";
return 0;
}
| [
"stevenxu169@hotmail.com"
] | stevenxu169@hotmail.com |
cbb8030681db5bd9aa39981cc16514057bcb2b96 | 89b7ffc5c56331a189501cda035648e2b2016d74 | /WebLayoutCoreOnly/Source/WebCore/RenderText.cpp | 5b2edbfa0d4cb80e904696a5bf7c2095d55feed2 | [
"MIT"
] | permissive | jjbheda/trylearn | 60343fdb74dd597f0a49286de4ec1f0f57a06faa | 74dd5c6c977f8d867d6aa360b84bc98cb82f480c | refs/heads/master | 2020-03-22T17:49:17.391764 | 2018-03-30T16:25:32 | 2018-03-30T16:25:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 58,611 | cpp | /*
* (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 2000 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004-2007, 2013-2015 Apple Inc. All rights reserved.
* Copyright (C) 2006 Andrew Wellington (proton@wiretapped.net)
* Copyright (C) 2006 Graham Dennis (graham.dennis@gmail.com)
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#include "config.h"
#include "RenderText.h"
#include "AXObjectCache.h"
#include "BreakLines.h"
#include "BreakingContext.h"
#include "CharacterProperties.h"
#include "DocumentMarkerController.h"
#include "EllipsisBox.h"
#include "FloatQuad.h"
#include "Frame.h"
#include "FrameView.h"
#include "HTMLParserIdioms.h"
#include "Hyphenation.h"
#include "InlineTextBox.h"
#include "Range.h"
#include "RenderBlock.h"
#include "RenderCombineText.h"
#include "RenderInline.h"
#include "RenderLayer.h"
#include "RenderView.h"
#include "RenderedDocumentMarker.h"
#include "Settings.h"
#include "SimpleLineLayoutFunctions.h"
#include "Text.h"
#include "TextResourceDecoder.h"
#include "VisiblePosition.h"
#include <wtf/IsoMallocInlines.h>
#include <wtf/NeverDestroyed.h>
#include <wtf/text/StringBuffer.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/TextBreakIterator.h>
#include <wtf/unicode/CharacterNames.h>
#if PLATFORM(IOS)
#include "Document.h"
#include "EditorClient.h"
#include "LogicalSelectionOffsetCaches.h"
#include "Page.h"
#include "SelectionRect.h"
#endif
namespace WebCore {
using namespace WTF;
using namespace Unicode;
WTF_MAKE_ISO_ALLOCATED_IMPL(RenderText);
struct SameSizeAsRenderText : public RenderObject {
void* pointers[2];
uint32_t bitfields : 16;
#if ENABLE(TEXT_AUTOSIZING)
float candidateTextSize;
#endif
float widths[4];
String text;
};
COMPILE_ASSERT(sizeof(RenderText) == sizeof(SameSizeAsRenderText), RenderText_should_stay_small);
class SecureTextTimer final : private TimerBase {
WTF_MAKE_FAST_ALLOCATED;
public:
explicit SecureTextTimer(RenderText&);
void restart(unsigned offsetAfterLastTypedCharacter);
unsigned takeOffsetAfterLastTypedCharacter();
private:
void fired() override;
RenderText& m_renderer;
unsigned m_offsetAfterLastTypedCharacter { 0 };
};
typedef HashMap<RenderText*, std::unique_ptr<SecureTextTimer>> SecureTextTimerMap;
static SecureTextTimerMap& secureTextTimers()
{
static NeverDestroyed<SecureTextTimerMap> map;
return map.get();
}
inline SecureTextTimer::SecureTextTimer(RenderText& renderer)
: m_renderer(renderer)
{
}
inline void SecureTextTimer::restart(unsigned offsetAfterLastTypedCharacter)
{
m_offsetAfterLastTypedCharacter = offsetAfterLastTypedCharacter;
startOneShot(1_s * m_renderer.settings().passwordEchoDurationInSeconds());
}
inline unsigned SecureTextTimer::takeOffsetAfterLastTypedCharacter()
{
unsigned offset = m_offsetAfterLastTypedCharacter;
m_offsetAfterLastTypedCharacter = 0;
return offset;
}
void SecureTextTimer::fired()
{
ASSERT(secureTextTimers().get(&m_renderer) == this);
m_offsetAfterLastTypedCharacter = 0;
m_renderer.setText(m_renderer.text(), true /* forcing setting text as it may be masked later */);
}
static HashMap<const RenderText*, String>& originalTextMap()
{
static NeverDestroyed<HashMap<const RenderText*, String>> map;
return map;
}
static HashMap<const RenderText*, WeakPtr<RenderInline>>& inlineWrapperForDisplayContentsMap()
{
static NeverDestroyed<HashMap<const RenderText*, WeakPtr<RenderInline>>> map;
return map;
}
String capitalize(const String& string, UChar previousCharacter)
{
// FIXME: Need to change this to use u_strToTitle instead of u_totitle and to consider locale.
if (string.isNull())
return string;
unsigned length = string.length();
auto& stringImpl = *string.impl();
if (length >= std::numeric_limits<unsigned>::max())
CRASH();
StringBuffer<UChar> stringWithPrevious(length + 1);
stringWithPrevious[0] = previousCharacter == noBreakSpace ? ' ' : previousCharacter;
for (unsigned i = 1; i < length + 1; i++) {
// Replace NO BREAK SPACE with a real space since ICU does not treat it as a word separator.
if (stringImpl[i - 1] == noBreakSpace)
stringWithPrevious[i] = ' ';
else
stringWithPrevious[i] = stringImpl[i - 1];
}
auto* boundary = wordBreakIterator(StringView(stringWithPrevious.characters(), length + 1));
if (!boundary)
return string;
StringBuilder result;
result.reserveCapacity(length);
int32_t endOfWord;
int32_t startOfWord = ubrk_first(boundary);
for (endOfWord = ubrk_next(boundary); endOfWord != UBRK_DONE; startOfWord = endOfWord, endOfWord = ubrk_next(boundary)) {
if (startOfWord) // Ignore first char of previous string
result.append(stringImpl[startOfWord - 1] == noBreakSpace ? noBreakSpace : u_totitle(stringWithPrevious[startOfWord]));
for (int i = startOfWord + 1; i < endOfWord; i++)
result.append(stringImpl[i - 1]);
}
return result.toString();
}
inline RenderText::RenderText(Node& node, const String& text)
: RenderObject(node)
, m_hasTab(false)
, m_linesDirty(false)
, m_containsReversedText(false)
, m_isAllASCII(text.impl()->isAllASCII())
, m_knownToHaveNoOverflowAndNoFallbackFonts(false)
, m_useBackslashAsYenSymbol(false)
, m_originalTextDiffersFromRendered(false)
, m_hasInlineWrapperForDisplayContents(false)
, m_text(text)
{
ASSERT(!m_text.isNull());
setIsText();
m_canUseSimpleFontCodePath = computeCanUseSimpleFontCodePath();
view().frameView().incrementVisuallyNonEmptyCharacterCount(text.impl()->length());
}
RenderText::RenderText(Text& textNode, const String& text)
: RenderText(static_cast<Node&>(textNode), text)
{
}
RenderText::RenderText(Document& document, const String& text)
: RenderText(static_cast<Node&>(document), text)
{
}
RenderText::~RenderText()
{
// Do not add any code here. Add it to willBeDestroyed() instead.
ASSERT(!originalTextMap().contains(this));
}
const char* RenderText::renderName() const
{
return "RenderText";
}
Text* RenderText::textNode() const
{
return downcast<Text>(RenderObject::node());
}
bool RenderText::isTextFragment() const
{
return false;
}
bool RenderText::computeUseBackslashAsYenSymbol() const
{
const RenderStyle& style = this->style();
const auto& fontDescription = style.fontDescription();
if (style.fontCascade().useBackslashAsYenSymbol())
return true;
if (fontDescription.isSpecifiedFont())
return false;
const TextEncoding* encoding = document().decoder() ? &document().decoder()->encoding() : 0;
if (encoding && encoding->backslashAsCurrencySymbol() != '\\')
return true;
return false;
}
void RenderText::styleDidChange(StyleDifference diff, const RenderStyle* oldStyle)
{
// There is no need to ever schedule repaints from a style change of a text run, since
// we already did this for the parent of the text run.
// We do have to schedule layouts, though, since a style change can force us to
// need to relayout.
if (diff == StyleDifferenceLayout) {
setNeedsLayoutAndPrefWidthsRecalc();
m_knownToHaveNoOverflowAndNoFallbackFonts = false;
}
const RenderStyle& newStyle = style();
bool needsResetText = false;
if (!oldStyle) {
m_useBackslashAsYenSymbol = computeUseBackslashAsYenSymbol();
needsResetText = m_useBackslashAsYenSymbol;
// It should really be computed in the c'tor, but during construction we don't have parent yet -and RenderText style == parent()->style()
m_canUseSimplifiedTextMeasuring = computeCanUseSimplifiedTextMeasuring();
} else if (oldStyle->fontCascade().useBackslashAsYenSymbol() != newStyle.fontCascade().useBackslashAsYenSymbol()) {
m_useBackslashAsYenSymbol = computeUseBackslashAsYenSymbol();
needsResetText = true;
}
ETextTransform oldTransform = oldStyle ? oldStyle->textTransform() : TTNONE;
ETextSecurity oldSecurity = oldStyle ? oldStyle->textSecurity() : TSNONE;
if (needsResetText || oldTransform != newStyle.textTransform() || oldSecurity != newStyle.textSecurity())
RenderText::setText(originalText(), true);
}
void RenderText::removeAndDestroyTextBoxes()
{
if (!renderTreeBeingDestroyed())
m_lineBoxes.removeAllFromParent(*this);
#if !ASSERT_WITH_SECURITY_IMPLICATION_DISABLED
else
m_lineBoxes.invalidateParentChildLists();
#endif
m_lineBoxes.deleteAll();
}
void RenderText::willBeDestroyed()
{
secureTextTimers().remove(this);
removeAndDestroyTextBoxes();
if (m_originalTextDiffersFromRendered)
originalTextMap().remove(this);
setInlineWrapperForDisplayContents(nullptr);
RenderObject::willBeDestroyed();
}
void RenderText::deleteLineBoxesBeforeSimpleLineLayout()
{
m_lineBoxes.deleteAll();
}
String RenderText::originalText() const
{
return m_originalTextDiffersFromRendered ? originalTextMap().get(this) : m_text;
}
void RenderText::absoluteRects(Vector<IntRect>& rects, const LayoutPoint& accumulatedOffset) const
{
if (auto* layout = simpleLineLayout()) {
rects.appendVector(SimpleLineLayout::collectAbsoluteRects(*this, *layout, accumulatedOffset));
return;
}
rects.appendVector(m_lineBoxes.absoluteRects(accumulatedOffset));
}
Vector<IntRect> RenderText::absoluteRectsForRange(unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed) const
{
const_cast<RenderText&>(*this).ensureLineBoxes();
// Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
// to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
// function to take ints causes various internal mismatches. But selectionRect takes ints, and
// passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
// that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
ASSERT(end == UINT_MAX || end <= INT_MAX);
ASSERT(start <= INT_MAX);
start = std::min(start, static_cast<unsigned>(INT_MAX));
end = std::min(end, static_cast<unsigned>(INT_MAX));
return m_lineBoxes.absoluteRectsForRange(*this, start, end, useSelectionHeight, wasFixed);
}
#if PLATFORM(IOS)
// This function is similar in spirit to addLineBoxRects, but returns rectangles
// which are annotated with additional state which helps the iPhone draw selections in its unique way.
// Full annotations are added in this class.
void RenderText::collectSelectionRects(Vector<SelectionRect>& rects, unsigned start, unsigned end)
{
// FIXME: Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
// to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
// function to take ints causes various internal mismatches. But selectionRect takes ints, and
// passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
// that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
ASSERT(end == std::numeric_limits<unsigned>::max() || end <= std::numeric_limits<int>::max());
ASSERT(start <= std::numeric_limits<int>::max());
start = std::min(start, static_cast<unsigned>(std::numeric_limits<int>::max()));
end = std::min(end, static_cast<unsigned>(std::numeric_limits<int>::max()));
for (InlineTextBox* box = firstTextBox(); box; box = box->nextTextBox()) {
LayoutRect rect;
// Note, box->end() returns the index of the last character, not the index past it.
if (start <= box->start() && box->end() < end)
rect = box->localSelectionRect(start, end);
else {
unsigned realEnd = std::min(box->end() + 1, end);
rect = box->localSelectionRect(start, realEnd);
if (rect.isEmpty())
continue;
}
if (box->root().isFirstAfterPageBreak()) {
if (box->isHorizontal())
rect.shiftYEdgeTo(box->root().lineTopWithLeading());
else
rect.shiftXEdgeTo(box->root().lineTopWithLeading());
}
RenderBlock* containingBlock = this->containingBlock();
// Map rect, extended left to leftOffset, and right to rightOffset, through transforms to get minX and maxX.
LogicalSelectionOffsetCaches cache(*containingBlock);
LayoutUnit leftOffset = containingBlock->logicalLeftSelectionOffset(*containingBlock, box->logicalTop(), cache);
LayoutUnit rightOffset = containingBlock->logicalRightSelectionOffset(*containingBlock, box->logicalTop(), cache);
LayoutRect extentsRect = rect;
if (box->isHorizontal()) {
extentsRect.setX(leftOffset);
extentsRect.setWidth(rightOffset - leftOffset);
} else {
extentsRect.setY(leftOffset);
extentsRect.setHeight(rightOffset - leftOffset);
}
extentsRect = localToAbsoluteQuad(FloatRect(extentsRect)).enclosingBoundingBox();
if (!box->isHorizontal())
extentsRect = extentsRect.transposedRect();
bool isFirstOnLine = !box->previousOnLineExists();
bool isLastOnLine = !box->nextOnLineExists();
if (containingBlock->isRubyBase() || containingBlock->isRubyText())
isLastOnLine = !containingBlock->containingBlock()->inlineBoxWrapper()->nextOnLineExists();
bool containsStart = box->start() <= start && box->end() + 1 >= start;
bool containsEnd = box->start() <= end && box->end() + 1 >= end;
bool isFixed = false;
IntRect absRect = localToAbsoluteQuad(FloatRect(rect), UseTransforms, &isFixed).enclosingBoundingBox();
bool boxIsHorizontal = !box->isSVGInlineTextBox() ? box->isHorizontal() : !style().isVerticalWritingMode();
// If the containing block is an inline element, we want to check the inlineBoxWrapper orientation
// to determine the orientation of the block. In this case we also use the inlineBoxWrapper to
// determine if the element is the last on the line.
if (containingBlock->inlineBoxWrapper()) {
if (containingBlock->inlineBoxWrapper()->isHorizontal() != boxIsHorizontal) {
boxIsHorizontal = containingBlock->inlineBoxWrapper()->isHorizontal();
isLastOnLine = !containingBlock->inlineBoxWrapper()->nextOnLineExists();
}
}
rects.append(SelectionRect(absRect, box->direction(), extentsRect.x(), extentsRect.maxX(), extentsRect.maxY(), 0, box->isLineBreak(), isFirstOnLine, isLastOnLine, containsStart, containsEnd, boxIsHorizontal, isFixed, containingBlock->isRubyText(), view().pageNumberForBlockProgressionOffset(absRect.x())));
}
}
#endif
Vector<FloatQuad> RenderText::absoluteQuadsClippedToEllipsis() const
{
if (auto* layout = simpleLineLayout()) {
ASSERT(style().textOverflow() != TextOverflowEllipsis);
return SimpleLineLayout::collectAbsoluteQuads(*this, *layout, nullptr);
}
return m_lineBoxes.absoluteQuads(*this, nullptr, RenderTextLineBoxes::ClipToEllipsis);
}
void RenderText::absoluteQuads(Vector<FloatQuad>& quads, bool* wasFixed) const
{
if (auto* layout = simpleLineLayout()) {
quads.appendVector(SimpleLineLayout::collectAbsoluteQuads(*this, *layout, wasFixed));
return;
}
quads.appendVector(m_lineBoxes.absoluteQuads(*this, wasFixed, RenderTextLineBoxes::NoClipping));
}
Vector<FloatQuad> RenderText::absoluteQuadsForRange(unsigned start, unsigned end, bool useSelectionHeight, bool* wasFixed) const
{
// Work around signed/unsigned issues. This function takes unsigneds, and is often passed UINT_MAX
// to mean "all the way to the end". InlineTextBox coordinates are unsigneds, so changing this
// function to take ints causes various internal mismatches. But selectionRect takes ints, and
// passing UINT_MAX to it causes trouble. Ideally we'd change selectionRect to take unsigneds, but
// that would cause many ripple effects, so for now we'll just clamp our unsigned parameters to INT_MAX.
ASSERT(end == UINT_MAX || end <= INT_MAX);
ASSERT(start <= INT_MAX);
start = std::min(start, static_cast<unsigned>(INT_MAX));
end = std::min(end, static_cast<unsigned>(INT_MAX));
if (simpleLineLayout() && !useSelectionHeight)
return collectAbsoluteQuadsForRange(*this, start, end, *simpleLineLayout(), wasFixed);
const_cast<RenderText&>(*this).ensureLineBoxes();
return m_lineBoxes.absoluteQuadsForRange(*this, start, end, useSelectionHeight, wasFixed);
}
Position RenderText::positionForPoint(const LayoutPoint& point)
{
if (simpleLineLayout() && parent()->firstChild() == parent()->lastChild()) {
auto offset = SimpleLineLayout::textOffsetForPoint(point, *this, *simpleLineLayout());
// Did not find a valid offset. Fall back to the normal line layout based Position.
if (offset == text().length())
return positionForPoint(point, nullptr).deepEquivalent();
auto position = Position(textNode(), offset);
ASSERT(position == positionForPoint(point, nullptr).deepEquivalent());
return position;
}
return positionForPoint(point, nullptr).deepEquivalent();
}
VisiblePosition RenderText::positionForPoint(const LayoutPoint& point, const RenderFragmentContainer*)
{
ensureLineBoxes();
return m_lineBoxes.positionForPoint(*this, point);
}
LayoutRect RenderText::localCaretRect(InlineBox* inlineBox, unsigned caretOffset, LayoutUnit* extraWidthToEndOfLine)
{
if (!inlineBox)
return LayoutRect();
auto& box = downcast<InlineTextBox>(*inlineBox);
float left = box.positionForOffset(caretOffset);
return box.root().computeCaretRect(left, caretWidth, extraWidthToEndOfLine);
}
ALWAYS_INLINE float RenderText::widthFromCache(const FontCascade& f, unsigned start, unsigned len, float xPos, HashSet<const Font*>* fallbackFonts, GlyphOverflow* glyphOverflow, const RenderStyle& style) const
{
if (style.hasTextCombine() && is<RenderCombineText>(*this)) {
const RenderCombineText& combineText = downcast<RenderCombineText>(*this);
if (combineText.isCombined())
return combineText.combinedTextWidth(f);
}
if (f.isFixedPitch() && f.fontDescription().variantSettings().isAllNormal() && m_isAllASCII && (!glyphOverflow || !glyphOverflow->computeBounds)) {
float monospaceCharacterWidth = f.spaceWidth();
float w = 0;
bool isSpace;
for (unsigned i = start; i < start + len; i++) {
char c = text()[i];
if (c <= ' ') {
if (c == ' ' || c == '\n') {
w += monospaceCharacterWidth;
isSpace = true;
} else if (c == '\t') {
if (style.collapseWhiteSpace()) {
w += monospaceCharacterWidth;
isSpace = true;
} else {
w += f.tabWidth(style.tabSize(), xPos + w);
isSpace = false;
}
} else
isSpace = false;
} else {
w += monospaceCharacterWidth;
isSpace = false;
}
if (isSpace && i > start)
w += f.wordSpacing();
}
return w;
}
TextRun run = RenderBlock::constructTextRun(*this, start, len, style);
run.setCharacterScanForCodePath(!canUseSimpleFontCodePath());
run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
run.setXPos(xPos);
return f.width(run, fallbackFonts, glyphOverflow);
}
inline bool isHangablePunctuationAtLineStart(UChar c)
{
return U_GET_GC_MASK(c) & (U_GC_PS_MASK | U_GC_PI_MASK | U_GC_PF_MASK);
}
inline bool isHangablePunctuationAtLineEnd(UChar c)
{
return U_GET_GC_MASK(c) & (U_GC_PE_MASK | U_GC_PI_MASK | U_GC_PF_MASK);
}
float RenderText::hangablePunctuationStartWidth(unsigned index) const
{
unsigned length = text().length();
if (index >= length)
return 0;
if (!isHangablePunctuationAtLineStart(text()[index]))
return 0;
auto& style = this->style();
return widthFromCache(style.fontCascade(), index, 1, 0, 0, 0, style);
}
float RenderText::hangablePunctuationEndWidth(unsigned index) const
{
unsigned length = text().length();
if (index >= length)
return 0;
if (!isHangablePunctuationAtLineEnd(text()[index]))
return 0;
auto& style = this->style();
return widthFromCache(style.fontCascade(), index, 1, 0, 0, 0, style);
}
bool RenderText::isHangableStopOrComma(UChar c)
{
return c == 0x002C || c == 0x002E || c == 0x060C || c == 0x06D4 || c == 0x3001
|| c == 0x3002 || c == 0xFF0C || c == 0xFF0E || c == 0xFE50 || c == 0xFE51
|| c == 0xFE52 || c == 0xFF61 || c == 0xFF64;
}
unsigned RenderText::firstCharacterIndexStrippingSpaces() const
{
if (!style().collapseWhiteSpace())
return 0;
unsigned i = 0;
for (unsigned length = text().length() ; i < length; ++i) {
if (text()[i] != ' ' && (text()[i] != '\n' || style().preserveNewline()) && text()[i] != '\t')
break;
}
return i;
}
unsigned RenderText::lastCharacterIndexStrippingSpaces() const
{
if (!text().length())
return 0;
if (!style().collapseWhiteSpace())
return text().length() - 1;
int i = text().length() - 1;
for ( ; i >= 0; --i) {
if (text()[i] != ' ' && (text()[i] != '\n' || style().preserveNewline()) && text()[i] != '\t')
break;
}
return i;
}
RenderText::Widths RenderText::trimmedPreferredWidths(float leadWidth, bool& stripFrontSpaces)
{
auto& style = this->style();
bool collapseWhiteSpace = style.collapseWhiteSpace();
if (!collapseWhiteSpace)
stripFrontSpaces = false;
if (m_hasTab || preferredLogicalWidthsDirty())
computePreferredLogicalWidths(leadWidth);
Widths widths;
widths.beginWS = !stripFrontSpaces && m_hasBeginWS;
widths.endWS = m_hasEndWS;
unsigned length = this->length();
if (!length || (stripFrontSpaces && text().isAllSpecialCharacters<isHTMLSpace>()))
return widths;
widths.min = m_minWidth;
widths.max = m_maxWidth;
widths.beginMin = m_beginMinWidth;
widths.endMin = m_endMinWidth;
widths.hasBreakableChar = m_hasBreakableChar;
widths.hasBreak = m_hasBreak;
if (text()[0] == ' ' || (text()[0] == '\n' && !style.preserveNewline()) || text()[0] == '\t') {
auto& font = style.fontCascade(); // FIXME: This ignores first-line.
if (stripFrontSpaces)
widths.max -= font.width(RenderBlock::constructTextRun(&space, 1, style));
else
widths.max += font.wordSpacing();
}
stripFrontSpaces = collapseWhiteSpace && m_hasEndWS;
if (!style.autoWrap() || widths.min > widths.max)
widths.min = widths.max;
// Compute our max widths by scanning the string for newlines.
if (widths.hasBreak) {
auto& font = style.fontCascade(); // FIXME: This ignores first-line.
bool firstLine = true;
widths.beginMax = widths.max;
widths.endMax = widths.max;
for (unsigned i = 0; i < length; i++) {
unsigned lineLength = 0;
while (i + lineLength < length && text()[i + lineLength] != '\n')
lineLength++;
if (lineLength) {
widths.endMax = widthFromCache(font, i, lineLength, leadWidth + widths.endMax, 0, 0, style);
if (firstLine) {
firstLine = false;
leadWidth = 0;
widths.beginMax = widths.endMax;
}
i += lineLength;
} else if (firstLine) {
widths.beginMax = 0;
firstLine = false;
leadWidth = 0;
}
if (i == length - 1) {
// A <pre> run that ends with a newline, as in, e.g.,
// <pre>Some text\n\n<span>More text</pre>
widths.endMax = 0;
}
}
}
return widths;
}
static inline bool isSpaceAccordingToStyle(UChar c, const RenderStyle& style)
{
return c == ' ' || (c == noBreakSpace && style.nbspMode() == SPACE);
}
float RenderText::minLogicalWidth() const
{
if (preferredLogicalWidthsDirty())
const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
return m_minWidth;
}
float RenderText::maxLogicalWidth() const
{
if (preferredLogicalWidthsDirty())
const_cast<RenderText*>(this)->computePreferredLogicalWidths(0);
return m_maxWidth;
}
LineBreakIteratorMode mapLineBreakToIteratorMode(LineBreak lineBreak)
{
switch (lineBreak) {
case LineBreakAuto:
case LineBreakAfterWhiteSpace:
return LineBreakIteratorMode::Default;
case LineBreakLoose:
return LineBreakIteratorMode::Loose;
case LineBreakNormal:
return LineBreakIteratorMode::Normal;
case LineBreakStrict:
return LineBreakIteratorMode::Strict;
}
ASSERT_NOT_REACHED();
return LineBreakIteratorMode::Default;
}
void RenderText::computePreferredLogicalWidths(float leadWidth)
{
HashSet<const Font*> fallbackFonts;
GlyphOverflow glyphOverflow;
computePreferredLogicalWidths(leadWidth, fallbackFonts, glyphOverflow);
if (fallbackFonts.isEmpty() && !glyphOverflow.left && !glyphOverflow.right && !glyphOverflow.top && !glyphOverflow.bottom)
m_knownToHaveNoOverflowAndNoFallbackFonts = true;
}
static inline float hyphenWidth(RenderText& renderer, const FontCascade& font)
{
const RenderStyle& style = renderer.style();
auto textRun = RenderBlock::constructTextRun(style.hyphenString().string(), style);
return font.width(textRun);
}
static float maxWordFragmentWidth(RenderText& renderer, const RenderStyle& style, const FontCascade& font, StringView word, unsigned minimumPrefixLength, unsigned minimumSuffixLength, unsigned& suffixStart, HashSet<const Font*>& fallbackFonts, GlyphOverflow& glyphOverflow)
{
suffixStart = 0;
if (word.length() <= minimumSuffixLength)
return 0;
Vector<int, 8> hyphenLocations;
ASSERT(word.length() >= minimumSuffixLength);
unsigned hyphenLocation = word.length() - minimumSuffixLength;
while ((hyphenLocation = lastHyphenLocation(word, hyphenLocation, style.locale())) >= std::max(minimumPrefixLength, 1U))
hyphenLocations.append(hyphenLocation);
if (hyphenLocations.isEmpty())
return 0;
hyphenLocations.reverse();
// FIXME: Breaking the string at these places in the middle of words is completely broken with complex text.
float minimumFragmentWidthToConsider = font.pixelSize() * 5 / 4 + hyphenWidth(renderer, font);
float maxFragmentWidth = 0;
for (size_t k = 0; k < hyphenLocations.size(); ++k) {
int fragmentLength = hyphenLocations[k] - suffixStart;
StringBuilder fragmentWithHyphen;
fragmentWithHyphen.append(word.substring(suffixStart, fragmentLength));
fragmentWithHyphen.append(style.hyphenString());
TextRun run = RenderBlock::constructTextRun(fragmentWithHyphen.toString(), style);
run.setCharacterScanForCodePath(!renderer.canUseSimpleFontCodePath());
float fragmentWidth = font.width(run, &fallbackFonts, &glyphOverflow);
// Narrow prefixes are ignored. See tryHyphenating in RenderBlockLineLayout.cpp.
if (fragmentWidth <= minimumFragmentWidthToConsider)
continue;
suffixStart += fragmentLength;
maxFragmentWidth = std::max(maxFragmentWidth, fragmentWidth);
}
return maxFragmentWidth;
}
void RenderText::computePreferredLogicalWidths(float leadWidth, HashSet<const Font*>& fallbackFonts, GlyphOverflow& glyphOverflow)
{
ASSERT(m_hasTab || preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts);
m_minWidth = 0;
m_beginMinWidth = 0;
m_endMinWidth = 0;
m_maxWidth = 0;
float currMaxWidth = 0;
m_hasBreakableChar = false;
m_hasBreak = false;
m_hasTab = false;
m_hasBeginWS = false;
m_hasEndWS = false;
auto& style = this->style();
auto& font = style.fontCascade(); // FIXME: This ignores first-line.
float wordSpacing = font.wordSpacing();
auto& string = text();
unsigned length = string.length();
auto iteratorMode = mapLineBreakToIteratorMode(style.lineBreak());
LazyLineBreakIterator breakIterator(string, style.locale(), iteratorMode);
bool needsWordSpacing = false;
bool ignoringSpaces = false;
bool isSpace = false;
bool firstWord = true;
bool firstLine = true;
std::optional<unsigned> nextBreakable;
unsigned lastWordBoundary = 0;
WordTrailingSpace wordTrailingSpace(style);
// If automatic hyphenation is allowed, we keep track of the width of the widest word (or word
// fragment) encountered so far, and only try hyphenating words that are wider.
float maxWordWidth = std::numeric_limits<float>::max();
unsigned minimumPrefixLength = 0;
unsigned minimumSuffixLength = 0;
if (style.hyphens() == HyphensAuto && canHyphenate(style.locale())) {
maxWordWidth = 0;
// Map 'hyphenate-limit-{before,after}: auto;' to 2.
auto before = style.hyphenationLimitBefore();
minimumPrefixLength = before < 0 ? 2 : before;
auto after = style.hyphenationLimitAfter();
minimumSuffixLength = after < 0 ? 2 : after;
}
std::optional<int> firstGlyphLeftOverflow;
bool breakNBSP = style.autoWrap() && style.nbspMode() == SPACE;
// Note the deliberate omission of word-wrap and overflow-wrap from this breakAll check. Those
// do not affect minimum preferred sizes. Note that break-word is a non-standard value for
// word-break, but we support it as though it means break-all.
bool breakAll = (style.wordBreak() == BreakAllWordBreak || style.wordBreak() == BreakWordBreak) && style.autoWrap();
bool keepAllWords = style.wordBreak() == KeepAllWordBreak;
bool canUseLineBreakShortcut = iteratorMode == LineBreakIteratorMode::Default;
for (unsigned i = 0; i < length; i++) {
UChar c = string[i];
bool previousCharacterIsSpace = isSpace;
bool isNewline = false;
if (c == '\n') {
if (style.preserveNewline()) {
m_hasBreak = true;
isNewline = true;
isSpace = false;
} else
isSpace = true;
} else if (c == '\t') {
if (!style.collapseWhiteSpace()) {
m_hasTab = true;
isSpace = false;
} else
isSpace = true;
} else
isSpace = c == ' ';
if ((isSpace || isNewline) && !i)
m_hasBeginWS = true;
if ((isSpace || isNewline) && i == length - 1)
m_hasEndWS = true;
ignoringSpaces |= style.collapseWhiteSpace() && previousCharacterIsSpace && isSpace;
ignoringSpaces &= isSpace;
// Ignore spaces and soft hyphens
if (ignoringSpaces) {
ASSERT(lastWordBoundary == i);
lastWordBoundary++;
continue;
} else if (c == softHyphen && style.hyphens() != HyphensNone) {
ASSERT(i >= lastWordBoundary);
currMaxWidth += widthFromCache(font, lastWordBoundary, i - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow, style);
if (!firstGlyphLeftOverflow)
firstGlyphLeftOverflow = glyphOverflow.left;
lastWordBoundary = i + 1;
continue;
}
bool hasBreak = breakAll || isBreakable(breakIterator, i, nextBreakable, breakNBSP, canUseLineBreakShortcut, keepAllWords);
bool betweenWords = true;
unsigned j = i;
while (c != '\n' && !isSpaceAccordingToStyle(c, style) && c != '\t' && (c != softHyphen || style.hyphens() == HyphensNone)) {
j++;
if (j == length)
break;
c = string[j];
if (isBreakable(breakIterator, j, nextBreakable, breakNBSP, canUseLineBreakShortcut, keepAllWords) && characterAt(j - 1) != softHyphen)
break;
if (breakAll) {
betweenWords = false;
break;
}
}
unsigned wordLen = j - i;
if (wordLen) {
float currMinWidth = 0;
bool isSpace = (j < length) && isSpaceAccordingToStyle(c, style);
float w;
std::optional<float> wordTrailingSpaceWidth;
if (isSpace)
wordTrailingSpaceWidth = wordTrailingSpace.width(fallbackFonts);
if (wordTrailingSpaceWidth)
w = widthFromCache(font, i, wordLen + 1, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow, style) - wordTrailingSpaceWidth.value();
else {
w = widthFromCache(font, i, wordLen, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow, style);
if (c == softHyphen && style.hyphens() != HyphensNone)
currMinWidth = hyphenWidth(*this, font);
}
if (w > maxWordWidth) {
unsigned suffixStart;
float maxFragmentWidth = maxWordFragmentWidth(*this, style, font, StringView(string).substring(i, wordLen), minimumPrefixLength, minimumSuffixLength, suffixStart, fallbackFonts, glyphOverflow);
if (suffixStart) {
float suffixWidth;
std::optional<float> wordTrailingSpaceWidth;
if (isSpace)
wordTrailingSpaceWidth = wordTrailingSpace.width(fallbackFonts);
if (wordTrailingSpaceWidth)
suffixWidth = widthFromCache(font, i + suffixStart, wordLen - suffixStart + 1, leadWidth + currMaxWidth, 0, 0, style) - wordTrailingSpaceWidth.value();
else
suffixWidth = widthFromCache(font, i + suffixStart, wordLen - suffixStart, leadWidth + currMaxWidth, 0, 0, style);
maxFragmentWidth = std::max(maxFragmentWidth, suffixWidth);
currMinWidth += maxFragmentWidth - w;
maxWordWidth = std::max(maxWordWidth, maxFragmentWidth);
} else
maxWordWidth = w;
}
if (!firstGlyphLeftOverflow)
firstGlyphLeftOverflow = glyphOverflow.left;
currMinWidth += w;
if (betweenWords) {
if (lastWordBoundary == i)
currMaxWidth += w;
else {
ASSERT(j >= lastWordBoundary);
currMaxWidth += widthFromCache(font, lastWordBoundary, j - lastWordBoundary, leadWidth + currMaxWidth, &fallbackFonts, &glyphOverflow, style);
}
lastWordBoundary = j;
}
bool isCollapsibleWhiteSpace = (j < length) && style.isCollapsibleWhiteSpace(c);
if (j < length && style.autoWrap())
m_hasBreakableChar = true;
// Add in wordSpacing to our currMaxWidth, but not if this is the last word on a line or the
// last word in the run.
if ((isSpace || isCollapsibleWhiteSpace) && !containsOnlyHTMLWhitespace(j, length - j))
currMaxWidth += wordSpacing;
if (firstWord) {
firstWord = false;
// If the first character in the run is breakable, then we consider ourselves to have a beginning
// minimum width of 0, since a break could occur right before our run starts, preventing us from ever
// being appended to a previous text run when considering the total minimum width of the containing block.
if (hasBreak)
m_hasBreakableChar = true;
m_beginMinWidth = hasBreak ? 0 : currMinWidth;
}
m_endMinWidth = currMinWidth;
m_minWidth = std::max(currMinWidth, m_minWidth);
i += wordLen - 1;
} else {
// Nowrap can never be broken, so don't bother setting the
// breakable character boolean. Pre can only be broken if we encounter a newline.
if (style.autoWrap() || isNewline)
m_hasBreakableChar = true;
if (isNewline) { // Only set if preserveNewline was true and we saw a newline.
if (firstLine) {
firstLine = false;
leadWidth = 0;
if (!style.autoWrap())
m_beginMinWidth = currMaxWidth;
}
if (currMaxWidth > m_maxWidth)
m_maxWidth = currMaxWidth;
currMaxWidth = 0;
} else {
TextRun run = RenderBlock::constructTextRun(*this, i, 1, style);
run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
run.setXPos(leadWidth + currMaxWidth);
currMaxWidth += font.width(run, &fallbackFonts);
glyphOverflow.right = 0;
needsWordSpacing = isSpace && !previousCharacterIsSpace && i == length - 1;
}
ASSERT(lastWordBoundary == i);
lastWordBoundary++;
}
}
glyphOverflow.left = firstGlyphLeftOverflow.value_or(glyphOverflow.left);
if ((needsWordSpacing && length > 1) || (ignoringSpaces && !firstWord))
currMaxWidth += wordSpacing;
m_maxWidth = std::max(currMaxWidth, m_maxWidth);
if (!style.autoWrap())
m_minWidth = m_maxWidth;
if (style.whiteSpace() == PRE) {
if (firstLine)
m_beginMinWidth = m_maxWidth;
m_endMinWidth = currMaxWidth;
}
setPreferredLogicalWidthsDirty(false);
}
template<typename CharacterType> static inline bool isAllCollapsibleWhitespace(const CharacterType* characters, unsigned length, const RenderStyle& style)
{
for (unsigned i = 0; i < length; ++i) {
if (!style.isCollapsibleWhiteSpace(characters[i]))
return false;
}
return true;
}
bool RenderText::isAllCollapsibleWhitespace() const
{
if (text().is8Bit())
return WebCore::isAllCollapsibleWhitespace(text().characters8(), text().length(), style());
return WebCore::isAllCollapsibleWhitespace(text().characters16(), text().length(), style());
}
template<typename CharacterType> static inline bool isAllPossiblyCollapsibleWhitespace(const CharacterType* characters, unsigned length)
{
for (unsigned i = 0; i < length; ++i) {
if (!(characters[i] == '\n' || characters[i] == ' ' || characters[i] == '\t'))
return false;
}
return true;
}
bool RenderText::containsOnlyHTMLWhitespace(unsigned from, unsigned length) const
{
ASSERT(from <= text().length());
ASSERT(length <= text().length());
ASSERT(from + length <= text().length());
if (text().is8Bit())
return isAllPossiblyCollapsibleWhitespace(text().characters8() + from, length);
return isAllPossiblyCollapsibleWhitespace(text().characters16() + from, length);
}
Vector<std::pair<unsigned, unsigned>> RenderText::draggedContentRangesBetweenOffsets(unsigned startOffset, unsigned endOffset) const
{
if (!textNode())
return { };
auto markers = document().markers().markersFor(textNode(), DocumentMarker::DraggedContent);
if (markers.isEmpty())
return { };
Vector<std::pair<unsigned, unsigned>> draggedContentRanges;
for (auto* marker : markers) {
unsigned markerStart = std::max(marker->startOffset(), startOffset);
unsigned markerEnd = std::min(marker->endOffset(), endOffset);
if (markerStart >= markerEnd || markerStart > endOffset || markerEnd < startOffset)
continue;
std::pair<unsigned, unsigned> draggedContentRange;
draggedContentRange.first = markerStart;
draggedContentRange.second = markerEnd;
draggedContentRanges.append(draggedContentRange);
}
return draggedContentRanges;
}
IntPoint RenderText::firstRunLocation() const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::computeFirstRunLocation(*this, *layout);
return m_lineBoxes.firstRunLocation();
}
void RenderText::setSelectionState(SelectionState state)
{
if (state != SelectionNone)
ensureLineBoxes();
RenderObject::setSelectionState(state);
if (canUpdateSelectionOnRootLineBoxes())
m_lineBoxes.setSelectionState(*this, state);
// The containing block can be null in case of an orphaned tree.
RenderBlock* containingBlock = this->containingBlock();
if (containingBlock && !containingBlock->isRenderView())
containingBlock->setSelectionState(state);
}
void RenderText::setTextWithOffset(const String& newText, unsigned offset, unsigned length, bool force)
{
if (!force && text() == newText)
return;
int delta = newText.length() - text().length();
unsigned end = length ? offset + length - 1 : offset;
m_linesDirty = simpleLineLayout() || m_lineBoxes.dirtyRange(*this, offset, end, delta);
setText(newText, force || m_linesDirty);
}
static inline bool isInlineFlowOrEmptyText(const RenderObject& renderer)
{
return is<RenderInline>(renderer) || (is<RenderText>(renderer) && downcast<RenderText>(renderer).text().isEmpty());
}
UChar RenderText::previousCharacter() const
{
// find previous text renderer if one exists
const RenderObject* previousText = this;
while ((previousText = previousText->previousInPreOrder())) {
if (!isInlineFlowOrEmptyText(*previousText))
break;
}
if (!is<RenderText>(previousText))
return ' ';
auto& previousString = downcast<RenderText>(*previousText).text();
return previousString[previousString.length() - 1];
}
LayoutUnit RenderText::topOfFirstText() const
{
return firstTextBox()->root().lineTop();
}
String applyTextTransform(const RenderStyle& style, const String& text, UChar previousCharacter)
{
switch (style.textTransform()) {
case TTNONE:
return text;
case CAPITALIZE:
return capitalize(text, previousCharacter); // FIXME: Need to take locale into account.
case UPPERCASE:
return text.convertToUppercaseWithLocale(style.locale());
case LOWERCASE:
return text.convertToLowercaseWithLocale(style.locale());
}
ASSERT_NOT_REACHED();
return text;
}
void RenderText::setRenderedText(const String& newText)
{
ASSERT(!newText.isNull());
String originalText = this->originalText();
m_text = newText;
if (m_useBackslashAsYenSymbol)
m_text.replace('\\', yenSign);
m_text = applyTextTransform(style(), m_text, previousCharacter());
switch (style().textSecurity()) {
case TSNONE:
break;
#if !PLATFORM(IOS)
// We use the same characters here as for list markers.
// See the listMarkerText function in RenderListMarker.cpp.
case TSCIRCLE:
secureText(whiteBullet);
break;
case TSDISC:
secureText(bullet);
break;
case TSSQUARE:
secureText(blackSquare);
break;
#else
// FIXME: Why this quirk on iOS?
case TSCIRCLE:
case TSDISC:
case TSSQUARE:
secureText(blackCircle);
break;
#endif
}
m_isAllASCII = text().isAllASCII();
m_canUseSimpleFontCodePath = computeCanUseSimpleFontCodePath();
m_canUseSimplifiedTextMeasuring = computeCanUseSimplifiedTextMeasuring();
if (m_text != originalText) {
originalTextMap().set(this, originalText);
m_originalTextDiffersFromRendered = true;
} else if (m_originalTextDiffersFromRendered) {
originalTextMap().remove(this);
m_originalTextDiffersFromRendered = false;
}
}
void RenderText::secureText(UChar maskingCharacter)
{
// This hides the text by replacing all the characters with the masking character.
// Offsets within the hidden text have to match offsets within the original text
// to handle things like carets and selection, so this won't work right if any
// of the characters are surrogate pairs or combining marks. Thus, this function
// does not attempt to handle either of those.
unsigned length = text().length();
if (!length)
return;
UChar characterToReveal = 0;
unsigned revealedCharactersOffset = 0;
if (SecureTextTimer* timer = secureTextTimers().get(this)) {
// We take the offset out of the timer to make this one-shot. We count on this being called only once.
// If it's called a second time we assume the text is different and a character should not be revealed.
revealedCharactersOffset = timer->takeOffsetAfterLastTypedCharacter();
if (revealedCharactersOffset && revealedCharactersOffset <= length)
characterToReveal = text()[--revealedCharactersOffset];
}
UChar* characters;
m_text = String::createUninitialized(length, characters);
for (unsigned i = 0; i < length; ++i)
characters[i] = maskingCharacter;
if (characterToReveal)
characters[revealedCharactersOffset] = characterToReveal;
}
bool RenderText::computeCanUseSimplifiedTextMeasuring() const
{
if (!m_canUseSimpleFontCodePath)
return false;
auto& font = style().fontCascade();
if (font.wordSpacing() || font.letterSpacing())
return false;
// Additional check on the font codepath.
TextRun run(text());
run.setCharacterScanForCodePath(false);
if (font.codePath(run) != FontCascade::Simple)
return false;
auto whitespaceIsCollapsed = style().collapseWhiteSpace();
for (unsigned i = 0; i < text().length(); ++i) {
if ((!whitespaceIsCollapsed && text()[i] == '\t') || text()[i] == noBreakSpace || text()[i] >= HiraganaLetterSmallA)
return false;
}
return true;
}
void RenderText::setText(const String& text, bool force)
{
ASSERT(!text.isNull());
if (!force && text == originalText())
return;
m_text = text;
if (m_originalTextDiffersFromRendered) {
originalTextMap().remove(this);
m_originalTextDiffersFromRendered = false;
}
setRenderedText(text);
setNeedsLayoutAndPrefWidthsRecalc();
m_knownToHaveNoOverflowAndNoFallbackFonts = false;
if (is<RenderBlockFlow>(*parent()))
downcast<RenderBlockFlow>(*parent()).invalidateLineLayoutPath();
if (AXObjectCache* cache = document().existingAXObjectCache())
cache->deferTextChangedIfNeeded(textNode());
}
String RenderText::textWithoutConvertingBackslashToYenSymbol() const
{
if (!m_useBackslashAsYenSymbol || style().textSecurity() != TSNONE)
return text();
return applyTextTransform(style(), originalText(), previousCharacter());
}
void RenderText::dirtyLineBoxes(bool fullLayout)
{
if (fullLayout)
m_lineBoxes.deleteAll();
else if (!m_linesDirty)
m_lineBoxes.dirtyAll();
m_linesDirty = false;
}
std::unique_ptr<InlineTextBox> RenderText::createTextBox()
{
return std::make_unique<InlineTextBox>(*this);
}
void RenderText::positionLineBox(InlineTextBox& textBox)
{
if (!textBox.len())
return;
m_containsReversedText |= !textBox.isLeftToRightDirection();
}
void RenderText::ensureLineBoxes()
{
if (!is<RenderBlockFlow>(*parent()))
return;
downcast<RenderBlockFlow>(*parent()).ensureLineBoxes();
}
const SimpleLineLayout::Layout* RenderText::simpleLineLayout() const
{
if (!is<RenderBlockFlow>(*parent()))
return nullptr;
return downcast<RenderBlockFlow>(*parent()).simpleLineLayout();
}
float RenderText::width(unsigned from, unsigned len, float xPos, bool firstLine, HashSet<const Font*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
{
if (from >= text().length())
return 0;
if (from + len > text().length())
len = text().length() - from;
const RenderStyle& lineStyle = firstLine ? firstLineStyle() : style();
return width(from, len, lineStyle.fontCascade(), xPos, fallbackFonts, glyphOverflow);
}
float RenderText::width(unsigned from, unsigned len, const FontCascade& f, float xPos, HashSet<const Font*>* fallbackFonts, GlyphOverflow* glyphOverflow) const
{
ASSERT(from + len <= text().length());
if (!text().length())
return 0;
const RenderStyle& style = this->style();
float w;
if (&f == &style.fontCascade()) {
if (!style.preserveNewline() && !from && len == text().length() && (!glyphOverflow || !glyphOverflow->computeBounds)) {
if (fallbackFonts) {
ASSERT(glyphOverflow);
if (preferredLogicalWidthsDirty() || !m_knownToHaveNoOverflowAndNoFallbackFonts) {
const_cast<RenderText*>(this)->computePreferredLogicalWidths(0, *fallbackFonts, *glyphOverflow);
if (fallbackFonts->isEmpty() && !glyphOverflow->left && !glyphOverflow->right && !glyphOverflow->top && !glyphOverflow->bottom)
m_knownToHaveNoOverflowAndNoFallbackFonts = true;
}
w = m_maxWidth;
} else
w = maxLogicalWidth();
} else
w = widthFromCache(f, from, len, xPos, fallbackFonts, glyphOverflow, style);
} else {
TextRun run = RenderBlock::constructTextRun(*this, from, len, style);
run.setCharacterScanForCodePath(!canUseSimpleFontCodePath());
run.setTabSize(!style.collapseWhiteSpace(), style.tabSize());
run.setXPos(xPos);
w = f.width(run, fallbackFonts, glyphOverflow);
}
return w;
}
IntRect RenderText::linesBoundingBox() const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::computeBoundingBox(*this, *layout);
return m_lineBoxes.boundingBox(*this);
}
LayoutRect RenderText::linesVisualOverflowBoundingBox() const
{
ASSERT(!simpleLineLayout());
return m_lineBoxes.visualOverflowBoundingBox(*this);
}
LayoutRect RenderText::clippedOverflowRectForRepaint(const RenderElement* repaintContainer) const
{
RenderObject* rendererToRepaint = containingBlock();
// Do not cross self-painting layer boundaries.
RenderObject& enclosingLayerRenderer = enclosingLayer()->renderer();
if (&enclosingLayerRenderer != rendererToRepaint && !rendererToRepaint->isDescendantOf(&enclosingLayerRenderer))
rendererToRepaint = &enclosingLayerRenderer;
// The renderer we chose to repaint may be an ancestor of repaintContainer, but we need to do a repaintContainer-relative repaint.
if (repaintContainer && repaintContainer != rendererToRepaint && !rendererToRepaint->isDescendantOf(repaintContainer))
return repaintContainer->clippedOverflowRectForRepaint(repaintContainer);
return rendererToRepaint->clippedOverflowRectForRepaint(repaintContainer);
}
LayoutRect RenderText::collectSelectionRectsForLineBoxes(const RenderElement* repaintContainer, bool clipToVisibleContent, Vector<LayoutRect>* rects)
{
ASSERT(!needsLayout());
ASSERT(!simpleLineLayout());
if (selectionState() == SelectionNone)
return LayoutRect();
if (!containingBlock())
return LayoutRect();
// Now calculate startPos and endPos for painting selection.
// We include a selection while endPos > 0
unsigned startPos;
unsigned endPos;
if (selectionState() == SelectionInside) {
// We are fully selected.
startPos = 0;
endPos = text().length();
} else {
startPos = view().selection().startPosition();
endPos = view().selection().endPosition();
if (selectionState() == SelectionStart)
endPos = text().length();
else if (selectionState() == SelectionEnd)
startPos = 0;
}
if (startPos == endPos)
return IntRect();
LayoutRect resultRect;
if (!rects)
resultRect = m_lineBoxes.selectionRectForRange(startPos, endPos);
else {
m_lineBoxes.collectSelectionRectsForRange(startPos, endPos, *rects);
for (auto& rect : *rects) {
resultRect.unite(rect);
rect = localToContainerQuad(FloatRect(rect), repaintContainer).enclosingBoundingBox();
}
}
if (clipToVisibleContent)
return computeRectForRepaint(resultRect, repaintContainer);
return localToContainerQuad(FloatRect(resultRect), repaintContainer).enclosingBoundingBox();
}
LayoutRect RenderText::collectSelectionRectsForLineBoxes(const RenderElement* repaintContainer, bool clipToVisibleContent, Vector<LayoutRect>& rects)
{
return collectSelectionRectsForLineBoxes(repaintContainer, clipToVisibleContent, &rects);
}
LayoutRect RenderText::selectionRectForRepaint(const RenderElement* repaintContainer, bool clipToVisibleContent)
{
return collectSelectionRectsForLineBoxes(repaintContainer, clipToVisibleContent, nullptr);
}
int RenderText::caretMinOffset() const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::findCaretMinimumOffset(*this, *layout);
return m_lineBoxes.caretMinOffset();
}
int RenderText::caretMaxOffset() const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::findCaretMaximumOffset(*this, *layout);
return m_lineBoxes.caretMaxOffset(*this);
}
unsigned RenderText::countRenderedCharacterOffsetsUntil(unsigned offset) const
{
ASSERT(!simpleLineLayout());
return m_lineBoxes.countCharacterOffsetsUntil(offset);
}
bool RenderText::containsRenderedCharacterOffset(unsigned offset) const
{
ASSERT(!simpleLineLayout());
return m_lineBoxes.containsOffset(*this, offset, RenderTextLineBoxes::CharacterOffset);
}
bool RenderText::containsCaretOffset(unsigned offset) const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::containsCaretOffset(*this, *layout, offset);
return m_lineBoxes.containsOffset(*this, offset, RenderTextLineBoxes::CaretOffset);
}
bool RenderText::hasRenderedText() const
{
if (auto* layout = simpleLineLayout())
return SimpleLineLayout::isTextRendered(*this, *layout);
return m_lineBoxes.hasRenderedText();
}
int RenderText::previousOffset(int current) const
{
if (m_isAllASCII || text().is8Bit())
return current - 1;
CachedTextBreakIterator iterator(text(), TextBreakIterator::Mode::Caret, nullAtom());
return iterator.preceding(current).value_or(current - 1);
}
int RenderText::previousOffsetForBackwardDeletion(int current) const
{
CachedTextBreakIterator iterator(text(), TextBreakIterator::Mode::Delete, nullAtom());
return iterator.preceding(current).value_or(0);
}
int RenderText::nextOffset(int current) const
{
if (m_isAllASCII || text().is8Bit())
return current + 1;
CachedTextBreakIterator iterator(text(), TextBreakIterator::Mode::Caret, nullAtom());
return iterator.following(current).value_or(current + 1);
}
bool RenderText::computeCanUseSimpleFontCodePath() const
{
if (m_isAllASCII || text().is8Bit())
return true;
return FontCascade::characterRangeCodePath(text().characters16(), length()) == FontCascade::Simple;
}
void RenderText::momentarilyRevealLastTypedCharacter(unsigned offsetAfterLastTypedCharacter)
{
if (style().textSecurity() == TSNONE)
return;
auto& secureTextTimer = secureTextTimers().add(this, nullptr).iterator->value;
if (!secureTextTimer)
secureTextTimer = std::make_unique<SecureTextTimer>(*this);
secureTextTimer->restart(offsetAfterLastTypedCharacter);
}
StringView RenderText::stringView(unsigned start, std::optional<unsigned> stop) const
{
unsigned destination = stop.value_or(text().length());
ASSERT(start <= length());
ASSERT(destination <= length());
ASSERT(start <= destination);
if (text().is8Bit())
return { text().characters8() + start, destination - start };
return { text().characters16() + start, destination - start };
}
RenderInline* RenderText::inlineWrapperForDisplayContents()
{
ASSERT(m_hasInlineWrapperForDisplayContents == inlineWrapperForDisplayContentsMap().contains(this));
if (!m_hasInlineWrapperForDisplayContents)
return nullptr;
return inlineWrapperForDisplayContentsMap().get(this).get();
}
void RenderText::setInlineWrapperForDisplayContents(RenderInline* wrapper)
{
ASSERT(m_hasInlineWrapperForDisplayContents == inlineWrapperForDisplayContentsMap().contains(this));
if (!wrapper) {
if (!m_hasInlineWrapperForDisplayContents)
return;
inlineWrapperForDisplayContentsMap().remove(this);
m_hasInlineWrapperForDisplayContents = false;
return;
}
inlineWrapperForDisplayContentsMap().add(this, makeWeakPtr(wrapper));
m_hasInlineWrapperForDisplayContents = true;
}
RenderText* RenderText::findByDisplayContentsInlineWrapperCandidate(RenderElement& renderer)
{
auto* firstChild = renderer.firstChild();
if (!is<RenderText>(firstChild))
return nullptr;
auto& textRenderer = downcast<RenderText>(*firstChild);
if (textRenderer.inlineWrapperForDisplayContents() != &renderer)
return nullptr;
ASSERT(textRenderer.textNode());
ASSERT(renderer.firstChild() == renderer.lastChild());
return &textRenderer;
}
} // namespace WebCore
| [
"jianbai.gbj@alibaba-inc.com"
] | jianbai.gbj@alibaba-inc.com |
ff00eb58bae7a07cda08b6d56ab4fa30d4d9e433 | e2edf4c5cbfd0010dd801d72a57ad598a070c5a7 | /SEMESTER 1 (C++)/CREATIVE PHONECASE(CODE).cpp | aa983d4dc070d6ca3793875cae550da34573f3ea | [] | no_license | aiiyinn/uni-days | ff45118cad15810804725ad4f5fd204dd24fb9c6 | 1c7d884c4e4759259ee3b8eceb79f74e13b11d8d | refs/heads/master | 2022-11-19T00:32:39.730652 | 2020-06-22T03:21:48 | 2020-06-22T03:21:48 | 268,451,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,654 | cpp | #include <iostream>
#include <iomanip>
#include <cstring>
#include <unistd.h> //wheader file using sleep() method
#include <Windows.h> //header file COLOR CODE
using namespace std;
//function prototype
//without return value
void displayHello();
void displayOffer();
void displayReminder();
void displayDesign();
void displayModel();
void displayPrinting();
void displayMaterial();
void displayDone();
void displayCongrats();
void displayError();
void displayLoading();
void displayReport(double, int, int , int ,int, int , int, int, int, int, char*, char*, char*, char*);
//with return value
double calcSelling(double);
//using reference parameter
void calcDiscount(double, double, double&);
//ARRAY
void designArray(char, char*);
void modelArray(char, char*);
void findHighPrints(int, int, int, int, char*);
void findLowPrints(int, int, int, int, char*);
void findHighMat(int, int, int, char*);
void findLowMat(int, int, int, char*);
void displayMember(char, char*);
int main ()
{
system ("COLOR 0F");
//Declaration
int count = 0, countCust = 0, countSP = 0, countEP = 0, countDP = 0, count3D = 0;
int countPL = 0, countTP = 0, countCF = 0;
int totCust, totSP, totEP, totDP, tot3D, totCase = 0;
int totPL, totTP, totCF;
double price, charges,off, discount, totalPrice, sellingPrice, discountPrice;
double totSales = 0, totPrice = 0;
char name[50], add[100], ic[20], phoNum[15],email[50], modCode, desCode, printCode[5], matCode[5], maxP[20], minP[20], maxM[20], minM[20],
response, desName[10], modName[10], disText[10];
//ARRAY DECLARATION
char tryDesign[100][50], tryModel[100][50];
int a=0, b=0;
//introduction of the store
displayHello();
//input
cout << "\n\nEnter name: ";
cin.getline(name,50);
for(int countCust=1;strcmp(name,"ADMIN")!=0;countCust++) //outer loop for daily report
{
//input
cout << "Enter IC Number: ";
cin >> ws;
cin.getline(ic,20);
cout << "Enter phone number: ";
cin >> ws;
cin.getline(phoNum, 15);
cout << "Enter your address: ";
cin >> ws;
cin.getline(add,100);
cout << "Enter your email address: ";
cin.getline(email,50);
//func call
displayOffer();
cout << "\n\nDo you have a membership here? < Y - YES / N - NO > ";
cin >> response;
while(response != 'Y' && response != 'N')
{
system ("COLOR C0");
displayError();
cout << "\n\n\nAre you a member? : ";
cin >> response;
system ("COLOR 0F");
}
//func call
displayMember(response,disText);
//func call
displayReminder();
//looping process
char sentinel = 'N' ;
char answer;
cout << "\n\nWould you like to START ORDERING? ";
cout << "\n\t< Y - YES> ";
cout << "\n\t< N - NO> ";
cin >> answer;
while(answer != 'Y' && answer != 'N')
{
system ("COLOR C0");
displayError();
cout << "\n\n\nWould you like to ORDER NOW? : ";
cin >> answer;
system ("COLOR 0F");
}
for(count = 0; answer != sentinel; count++) //inner loop for one customer
{
//func call
displayDesign();
cin.clear();
a++;
cout << "\n\nEnter design code: ";
cin >> desCode;
while(desCode != 'C' && desCode != 'O')
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter design code: ";
cin >> desCode;
system ("COLOR 0F");
}
//selection process
if (desCode == 'C' || desCode == 'O')
{
//func call
displayModel();
cin.clear();
b++;
cout << "\n\nEnter model code: ";
cin >> modCode;
while(modCode != 'S' && modCode != 'O' && modCode != 'V' && modCode != 'X' && modCode != 'I' && modCode != 'H' && modCode != 'L')
{
system ("COLOR C0");
displayError();
cout << "\n\nEnter model code: ";
cin >> modCode;
system ("COLOR 0F");
}
if (modCode == 'S'|| modCode == 'O'|| modCode == 'V'|| modCode == 'X'|| modCode == 'I'|| modCode == 'H'|| modCode == 'L')
{
//func call
displayPrinting();
cout << "\n\nEnter printing code: ";
cin >> printCode;
while( (strcmp(printCode, "SP")!= 0) && (strcmp(printCode, "EP")!=0) && (strcmp(printCode, "DP")!=0) && (strcmp(printCode, "3D")!=0) )
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter printing code: ";
cin >> printCode;
system ("COLOR 0F");
}
if (strcmp(printCode, "SP")==0)
{
//func call
displayMaterial();
cout << "\n\nEnter material code: ";
cin >> matCode;
while( (strcmp(matCode, "PL")!= 0) && (strcmp(matCode, "TP")!=0) && (strcmp(matCode, "CF")!=0) )
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter material code: ";
cin >> matCode;
system ("COLOR 0F");
}
if(strcmp(matCode, "PL")==0)
{
price = 10.00;
countPL++;
}
else if(strcmp(matCode, "TP")==0)
{
price = 20.00;
countTP++;
}
else if (strcmp(matCode, "CF")==0)
{
price = 15.00;
countCF++;
}
countSP++;
}
else if (strcmp(printCode, "EP")==0)
{
//func cal
displayMaterial();
cout << "\n\nEnter material code: ";
cin >> matCode;
while( (strcmp(matCode, "PL")!= 0) && (strcmp(matCode, "TP")!=0) && (strcmp(matCode, "CF")!=0) )
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter material code: ";
cin >> matCode;
system ("COLOR 0F");
}
if(strcmp(matCode, "PL")==0)
{
price = 15.00;
countPL++;
}
else if (strcmp(matCode, "TP")==0)
{
price = 23.00;
countTP++;
}
else if (strcmp(matCode, "CF")==0)
{
price = 18.00;
countCF++;
}
countEP++;
}
else if (strcmp(printCode, "DP")==0)
{
//func call
displayMaterial();
cout << "\n\nEnter material code: ";
cin >> matCode;
while( (strcmp(matCode, "PL")!= 0) && (strcmp(matCode, "TP")!=0) && (strcmp(matCode, "CF")!=0) )
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter material code: ";
cin >> matCode;
system ("COLOR 0F");
}
if (strcmp(matCode, "PL")==0)
{
price = 15.00;
countPL++;
}
else if (strcmp(matCode, "TP")==0)
{
price = 23.00;
countTP++;
}
else if (strcmp(matCode, "CF")==0)
{
price = 18.00;
countCF++;
}
countDP++;
}
else if (strcmp(printCode, "3D")==0)
{
//func call
displayMaterial();
cout << "\n\nEnter material code: ";
cin >> matCode;
while( (strcmp(matCode, "PL")!= 0) && (strcmp(matCode, "TP")!=0) && (strcmp(matCode, "CF")!=0) )
{
system ("COLOR C0");
displayError();
cout << "\n\n\nEnter material code: ";
cin >> matCode;
system ("COLOR 0F");
}
if (strcmp(matCode, "PL")==0)
{
price = 20.00;
countPL++;
}
else if (strcmp(matCode, "TP")==0)
{
price = 26.00;
countTP++;
}
else if (strcmp(matCode, "CF")==0)
{
price = 23.00;
countCF++;
}
count3D++;
}
}
}
//ARRRAY func call (DESIGN)
designArray(desCode, desName);
strcpy(tryDesign[a],desName);
//ARRAY func call (MODEL)
modelArray(modCode, modName);
strcpy(tryModel[b],modName);
//calculate per receipt
//discount for membership
if (response == 'Y')
{
off = 0.20;
}
else if (response == 'N')
{
off = 0.00;
}
//function call to CALCULATE TOTAL PRICE
sellingPrice = calcSelling(price); //initialize function call
totPrice = totPrice + sellingPrice;
calcDiscount(totPrice,off,discount);
totalPrice = totPrice - discount;
//func call
displayDone();
//looping process ends and begins
cout << "\n\nWould you like to ORDER MORE? ";
cout << "\n\t< Y - YES> ";
cout << "\n\t< N - NO> ";
cin >> answer;
while(answer != 'Y' && answer != 'N')
{
system ("COLOR C0");
displayError();
cout << "\n\n\nWould you like to make MORE OREDERS? : ";
cin >> answer;
system ("COLOR 0F");
}
}
//func call
displayCongrats();
//output (Receipt)
cout << setprecision(2) << fixed;
cout << "\n\n\t****************************************************************" << endl;
cout << "\t - CREATIVE PHONECASE OFFICIAL RECEIPT - " << endl;
cout << "\t****************************************************************" << endl;
cout << "\n\t BUYER'S PERSONAL INFORMATIONS " << endl;
cout << "\n\tName : " << name;
cout << "\n\n\tTotal phonecases bought : " << count;
cout << "\n\n\tIC Number : " << ic;
cout << "\n\n\tPhone Number : " << phoNum;
cout << "\n\n\tE-mail Address : " << email;
cout << "\n\n\tThe items will delivered to : " << add;
cout << "\n\n\n\t CHARGES AND ITEMS INFORMATIONS " << endl;
cout << "\n\n\tTax : FREE FROM TAX" ;
cout << "\n\n\tDesign choosen : ";
for(int a = 0; a < count; a++)
{
cout << tryDesign[a] << ",";
}
cout << "\n\n\tPhone model choosen : ";
for(int b = 0; b < count; b++)
{
cout << tryModel[b] << ",";
}
cout << "\n\n\tDiscount : " << disText;
cout << "\n\n\tCharges : RM 10.00";
cout << "\n\n\tTotal Price : RM " << totalPrice;
cout << "\n\n\n\t*****************************************************************" << endl;
cout << "\t THANK YOU FOR BUYING WITH US! " << endl;
cout << "\t*****************************************************************" << endl;
//calculate daily report
totSales = totSales + totalPrice;
totCase = totCase + count;
totCust = countCust;
//initialize value for max/min prints
totSP = countSP;
totEP = countEP;
totDP = countDP;
tot3D = count3D;
//initialize value for count material
totPL = countPL;
totTP = countTP;
totCF = countCF;
//PLEASE ENTER 'ADMIN' INSTEAD OF CUSTOMER'S NAME TO END A DAY'S TRANSACTIONS
cout << "\nEnter name: "; //if enter another cust name, will count next cust
cin >> ws;
cin.getline(name,50);
//reset to zero for next customer
totPrice = 0;
//func call (MIN MAX PRINTS)
findHighPrints(totSP, totEP, totDP, tot3D, maxP);
findLowPrints(totSP, totEP, totDP, tot3D, minP);
//func call (MIN MAX MATERIAL)
findHighMat(totPL, totTP, totCF, maxM);
findLowMat(totPL, totTP, totCF, minM);
}
//output (Daily report)
displayLoading();
displayReport( totSales, totCust, totCase, totSP, totEP,totDP, tot3D, totPL, totTP, totCF, maxP, minP, maxM, minM);
system ("pause");
return 0;
}
//display WELCOME
void displayHello()
{
cout << "\n********************************************************************************";
cout << "\nWelcome to CREATIVE PHONECASE. A place for you to shop for beautiful phonecases" << endl;
cout << "\n********************************************************************************" << endl << endl;
}
//display Discount = 20% for membership
void displayOffer()
{
cout << "\n\n -------------------- S P E C I A L O F F E R ---------------------- " << endl;
cout << "\n 20% OFF IS GIVEN TO THE MEMBERS OF CREATIVE PHONECASE " << endl;
cout << "\n ---------------------------------------------------------------------" << endl;
}
//display friendly instruction
void displayReminder()
{
cout << "\n\n\n -------------------------------------------------------------------------" << endl;
cout << "\n ~ Do remember that you must enter the letters in CAPITAL LETTERS ~ " << endl;
cout << "\n ------------------------------------------------------------------------- " << endl;
}
//display ORDER COMPLETE
void displayDone()
{
cout << "\n ===================================================================" << endl;
cout << "\n Your order is complete!! " << endl;
cout << "\n ===================================================================" << endl;
}
//display ORDER RECEIVED
void displayCongrats()
{
cout << "\n\n\t ++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "\n\t CONGRATULATIONS YOUR ORDERS HAS BEEN RECEIVED! " << endl;
cout << "\n\t ++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "\n\n\t +++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
cout << "\n\t PLEASE REFER THE RECEIPT BELOW FOR FURTHER DETAILS. " << endl;
cout << "\n\t +++++++++++++++++++++++++++++++++++++++++++++++++++++" << endl;
}
//display ERROR (USED SLEEP FOR 2 SECONDS)
void displayError()
{
for(int i=1;i<=1;i++) //2 time statement will blink
{
system ("COLOR C"); //wait for a second
cout << "\n\n\t\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl;
cout << "\n\t\t ERROR! YOU HAVE ENTERED INVALID CODE! " << endl;
cout << "\n\t\t!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << endl; //print this statement on screen.
sleep(1.5); //wait for a second
system ("COLOR 0F");
}
}
void displayLoading()
{
system("COLOR 0E" );
char d=177, c=219;
cout << "\n\n\n\t\t\t\tLoading...";
cout << "\n\n\n";
cout << "\t\t\t";
for (int i=0; i <=25; i++)
cout << d;
Sleep(150);
cout <<"\r";
cout <<"\t\t\t";
for (int i=0; i <= 25; i++)
{
cout <<c;
Sleep(200);
}
cout << "\n\n\n\n\n";
system ("COLOR 0F");
}
//menu table
void displayDesign()
{
cout << "\n\n\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | Letter | | Designs | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | C | | Customize | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | O | | Original | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
}
void displayModel()
{
cout << "\n\n\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | Letter | | Phone Model | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | S | | Samsung | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | O |-| Oppo | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | V |-| Vivo | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | X |-| Xiaomi | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | I |-| IPhone | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | H |-| Huawei | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | L |-| Lenovo | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
}
void displayPrinting()
{
cout << "\n\n\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | Letter | | Printing | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | SP | | Screen | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | EP |-| Embossing | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | DP |-| Debossing | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
cout << "\t\t\t| | 3D |-| 3D Sublimation | |" << endl;
cout << "\t\t\t|-|----------|-|-----------------|-|" << endl;
}
void displayMaterial()
{
cout << "\n\n\t\t\t|-|----------|-|------------------|-|" << endl;
cout << "\t\t\t| | Letter | | Material | |" << endl;
cout << "\t\t\t|-|----------|-|------------------|-|" << endl;
cout << "\t\t\t| | PL | | Plastic | |" << endl;
cout << "\t\t\t|-|----------|-|------------------|-|" << endl;
cout << "\t\t\t| | TP |-|Thermopolyurathane| |" << endl;
cout << "\t\t\t|-|----------|-|------------------|-|" << endl;
cout << "\t\t\t| | CF |-| Carbon Fiber | |" << endl;
cout << "\t\t\t|-|----------|-|------------------|-|" << endl;
}
//calculate and decide the highest printings
void findHighPrints(int totSP, int totEP, int totDP, int tot3D,char* maxP)
{
if (totSP > totEP && totSP > totDP && totSP > tot3D)
{
strcpy (maxP, "Screen Printing");
}
else if (totEP > totSP && totEP > totDP && totEP > tot3D)
{
strcpy (maxP, "Embossing Printing");
}
else if (totDP > totSP && totDP > totEP && totDP > tot3D)
{
strcpy (maxP, "Debossing Printing");
}
else if (tot3D > totSP && tot3D > totEP && tot3D > totDP )
{
strcpy (maxP, "3D Sublimation Printing");
}
}
//calculate and decide the lowest printings
void findLowPrints(int totSP, int totEP, int totDP, int tot3D,char* minP)
{
if (totSP < totEP && totSP < totDP && totSP < tot3D)
{
strcpy (minP, "Screen Printing");
}
else if (totEP < totSP && totEP < totDP && totEP < tot3D)
{
strcpy (minP, "Embossing Printing");
}
else if (totDP < totSP && totDP < totEP && totDP < tot3D)
{
strcpy (minP, "Debossing Printing");
}
else if (tot3D < totSP && tot3D < totEP && tot3D < totDP )
{
strcpy (minP, "3D Sublimation Printing");
}
}
//calculate and decide the highest material
void findHighMat(int totPL, int totTP, int totCF, char* maxM)
{
if (totPL > totTP && totPL > totCF)
{
strcpy (maxM, "Plastic");
}
else if (totTP > totPL && totTP > totCF)
{
strcpy (maxM, "Thermo-polyurathane");
}
else if (totCF > totPL && totCF > totTP)
{
strcpy (maxM, "Carbon Fiber");
}
}
//calculate and decide the lowest material
void findLowMat(int totPL, int totTP, int totCF, char* minM)
{
if (totPL < totTP && totPL < totCF)
{
strcpy (minM, "Plastic");
}
else if (totTP < totPL && totTP < totCF)
{
strcpy (minM, "Thermo-polyurathane");
}
else if (totCF < totPL && totCF < totTP)
{
strcpy (minM, "Carbon Fiber");
}
}
//calculate the total charges for one customer
double calcSelling(double price)
{
double charges,sellingPrice;
charges = 10.00;
sellingPrice = price + charges;
return sellingPrice;
}
//calculate the discount given (membership)
void calcDiscount(double totPrice, double off,double& discount)
{
discount = off * totPrice;
}
//display text of the discount (20% 0r 0%)
void displayMember(char response, char* disText)
{
if (response == 'Y')
{
strcpy (disText, "20% OFF");
}
else if (response == 'N')
{
strcpy (disText, "0% OFF");
}
}
//ARRAY
void designArray(char desCode, char*desName)
{
if(desCode == 'C')
{
strcpy(desName, "Customize");
}
else if (desCode == 'O')
{
strcpy(desName, "Original");
}
}
void modelArray(char modCode, char* modName)
{
if (modCode == 'S')
{
strcpy(modName, "Samsung");
}
else if (modCode == 'O')
{
strcpy(modName, "Oppo");
}
else if (modCode == 'V')
{
strcpy(modName, "Vivo");
}
else if (modCode == 'X')
{
strcpy(modName, "Xiomi");
}
else if (modCode == 'I')
{
strcpy(modName, "Iphone");
}
else if (modCode == 'H')
{
strcpy(modName, "Huawei");
}
else if (modCode == 'L')
{
strcpy(modName, "Lenovo");
}
}
//display DAILY REPORT
void displayReport(double totSales, int totCust, int totCase, int totSP,int totEP, int totDP, int tot3D, int totPL, int totTP, int totCF, char* maxP, char* minP, char* maxM, char* minM )
{
cout << "\n\n\t\tWelcome ADMIN! You have worked hard today.";
cout << "\n\t\tThis the report of the day!";
cout << setprecision << fixed;
cout << "\n\n\t****************************************************************" << endl;
cout << "\t - DAILY REPORT ON SALES - " << endl;
cout << "\t****************************************************************" << endl;
cout << "\n\tTotal Sales : RM " << totSales;
cout << "\n\n\tTotal customers : " << totCust;
cout << "\n\n\tTotal phonecases sold : " << totCase;
cout << "\n\n\n\tTotal Screen Printings : " << totSP;
cout << "\n\n\tTotal Embosssing Printings : " << totEP;
cout << "\n\n\tTotal Debossing Printings : " << totDP;
cout << "\n\n\tTotal 3D Sublimation Printings : " << tot3D;
cout << "\n\n\n\tTotal Plastic Material : " << totPL;
cout << "\n\n\tTotal Thermo-polyurathane Material : " << totTP;
cout << "\n\n\tTotal Carbon Fiber Material : " << totCF;
cout << "\n\n\n\tHighest Prints : " << maxP;
cout << "\n\n\tLowest Prints : " << minP;
cout << "\n\n\n\tHighest Material : " << maxM;
cout << "\n\n\tLowest Material : " << minM;
cout << "\n\n\n\t****************************************************************" << endl;
cout << "\t See you again! " << endl;
cout << "\t****************************************************************" << endl << endl;
}
| [
"noreply@github.com"
] | aiiyinn.noreply@github.com |
f7ceb8a9f9c9ea84968b0754ca461e10dbed8577 | ecdb37ca675fbf51dd1d8bbda6dfacbed30aee2b | /contests/tenka1-2018-beginner/C/main.cpp | fd3b3fe2091c915bbb1acff42e7edd9b8bb7cca6 | [
"MIT"
] | permissive | natsuki1996/atcoder-practice | 92de1423d297008c01f672e0e811d28d838ed039 | e6f2d1785f96553b822fc2677325614306f625f2 | refs/heads/master | 2022-12-08T15:52:36.140364 | 2020-09-20T04:29:16 | 2020-09-20T04:29:16 | 264,850,228 | 0 | 0 | null | 2020-07-22T06:12:39 | 2020-05-18T06:39:19 | C++ | UTF-8 | C++ | false | false | 686 | cpp | #include <bits/stdc++.h>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)
using namespace std;
using ll = long long;
using P = pair<int, int>;
int main() {
ll n;
cin >> n;
vector<int> a(n);
rep(i, n) cin >> a[i];
sort(a.begin(), a.end());
vector<int> c(n, 1);
for (int i = 1; i < n; i += 2) c[i] *= -1;
for (int i = 1; i < n - 1; i++) c[i] *= 2;
sort(c.begin(), c.end());
ll ans1 = 0;
rep(i, n) ans1 += a[i] * c[i];
vector<int> d(n, -1);
for (int i = 1; i < n; i += 2) d[i] *= -1;
for (int i = 1; i < n - 1; i++) d[i] *= 2;
sort(d.begin(), d.end());
ll ans2 = 0;
rep(i, n) ans2 += a[i] * d[i];
cout << max(ans1, ans2) << endl;
return 0;
}
| [
"natsu1580ki@gmail.com"
] | natsu1580ki@gmail.com |
c135cf32beb6ff1b21f07c1e198e6e0421006e0a | ece8ee6e04f74402e69d522ac48d6cd145b3d875 | /ThirdParty/LAStools/laszip.hpp | 038b63884a30a810e780f225a71a156ee19a1430 | [] | no_license | MAPSWorks/webAsmPlay-imgui-osm | f4cd3e60c9e79687c3a6c8ab85e0a62aa87c7c44 | 15775df8a914ff77efcfa5deda04ef7e49262f28 | refs/heads/master | 2020-07-10T17:33:03.440799 | 2019-12-01T09:43:44 | 2019-12-01T09:43:44 | 204,323,140 | 3 | 0 | null | 2019-12-01T09:43:45 | 2019-08-25T16:51:42 | C++ | UTF-8 | C++ | false | false | 5,907 | hpp | /*
===============================================================================
FILE: laszip.hpp
CONTENTS:
Contains LASitem and LASchunk structs as well as the IDs of the currently
supported entropy coding scheme
PROGRAMMERS:
martin.isenburg@rapidlasso.com - http://rapidlasso.com
COPYRIGHT:
(c) 2007-2017, martin isenburg, rapidlasso - fast tools to catch reality
This is free software; you can redistribute and/or modify it under the
terms of the GNU Lesser General Licence as published by the Free Software
Foundation. See the COPYING file for more information.
This software is distributed WITHOUT ANY WARRANTY and without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
CHANGE HISTORY:
23 August 2017 -- minor version increment for C++ stream-based read/write API
28 May 2017 -- support for "LAS 1.4 selective decompression" added into DLL API
8 April 2017 -- new check for whether point size and total size of items match
30 March 2017 -- support for "native LAS 1.4 extension" added into main branch
7 January 2017 -- set reserved VLR field from 0xAABB to 0x0 in DLL
7 January 2017 -- consistent compatibility mode scan angle quantization in DLL
7 January 2017 -- compatibility mode *decompression* fix for waveforms in DLL
25 February 2016 -- depreciating old libLAS laszipper/lasunzipper binding
29 July 2013 -- reorganized to create an easy-to-use LASzip DLL
5 December 2011 -- learns the chunk table if it is missing (e.g. truncated LAZ)
6 October 2011 -- large file support, ability to read with missing chunk table
23 June 2011 -- turned on LASzip version 2.0 compressor with chunking
8 May 2011 -- added an option for variable chunking via chunk()
23 April 2011 -- changed interface for simplicity and chunking support
20 March 2011 -- incrementing LASZIP_VERSION to 1.2 for improved compression
10 January 2011 -- licensing change for LGPL release and liblas integration
12 December 2010 -- refactored from lasdefinitions after movies with silke
===============================================================================
*/
#ifndef LASZIP_HPP
#define LASZIP_HPP
#if defined(_MSC_VER) && (_MSC_VER < 1300)
#define LZ_WIN32_VC6
typedef __int64 SIGNED_INT64;
#else
typedef long long SIGNED_INT64;
#endif
#if defined(_MSC_VER) && \
(_MSC_FULL_VER >= 150000000)
#define LASCopyString _strdup
#else
#define LASCopyString strdup
#endif
#define LASZIP_VERSION_MAJOR 3
#define LASZIP_VERSION_MINOR 1
#define LASZIP_VERSION_REVISION 0
#define LASZIP_VERSION_BUILD_DATE 170915
#define LASZIP_COMPRESSOR_NONE 0
#define LASZIP_COMPRESSOR_POINTWISE 1
#define LASZIP_COMPRESSOR_POINTWISE_CHUNKED 2
#define LASZIP_COMPRESSOR_LAYERED_CHUNKED 3
#define LASZIP_COMPRESSOR_TOTAL_NUMBER_OF 4
#define LASZIP_COMPRESSOR_CHUNKED LASZIP_COMPRESSOR_POINTWISE_CHUNKED
#define LASZIP_COMPRESSOR_NOT_CHUNKED LASZIP_COMPRESSOR_POINTWISE
#define LASZIP_COMPRESSOR_DEFAULT LASZIP_COMPRESSOR_CHUNKED
#define LASZIP_CODER_ARITHMETIC 0
#define LASZIP_CODER_TOTAL_NUMBER_OF 1
#define LASZIP_CHUNK_SIZE_DEFAULT 50000
class LASitem
{
public:
enum Type { BYTE = 0, SHORT, INT, LONG, FLOAT, DOUBLE, POINT10, GPSTIME11, RGB12, WAVEPACKET13, POINT14, RGB14, RGBNIR14, WAVEPACKET14, BYTE14 } type;
unsigned short size;
unsigned short version;
bool is_type(LASitem::Type t) const;
const char* get_name() const;
};
class LASzip
{
public:
// supported version control
bool check_compressor(const unsigned short compressor);
bool check_coder(const unsigned short coder);
bool check_item(const LASitem* item);
bool check_items(const unsigned short num_items, const LASitem* items, const unsigned short point_size=0);
bool check(const unsigned short point_size=0);
// go back and forth between item array and point type & size
bool setup(unsigned short* num_items, LASitem** items, const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_NONE);
bool is_standard(const unsigned short num_items, const LASitem* items, unsigned char* point_type=0, unsigned short* record_length=0);
bool is_standard(unsigned char* point_type=0, unsigned short* record_length=0);
// pack to and unpack from VLR
unsigned char* bytes;
bool unpack(const unsigned char* bytes, const int num);
bool pack(unsigned char*& bytes, int& num);
// setup
bool request_compatibility_mode(const unsigned short requested_compatibility_mode=0); // 0 = none, 1 = LAS 1.4 compatibility mode
bool setup(const unsigned char point_type, const unsigned short point_size, const unsigned short compressor=LASZIP_COMPRESSOR_DEFAULT);
bool setup(const unsigned short num_items, const LASitem* items, const unsigned short compressor);
bool set_chunk_size(const unsigned int chunk_size); /* for compressor only */
bool request_version(const unsigned short requested_version); /* for compressor only */
// in case a function returns false this string describes the problem
const char* get_error() const;
// stored in LASzip VLR data section
unsigned short compressor;
unsigned short coder;
unsigned char version_major;
unsigned char version_minor;
unsigned short version_revision;
unsigned int options;
unsigned int chunk_size;
SIGNED_INT64 number_of_special_evlrs; /* must be -1 if unused */
SIGNED_INT64 offset_to_special_evlrs; /* must be -1 if unused */
unsigned short num_items;
LASitem* items;
LASzip();
~LASzip();
private:
bool return_error(const char* err);
char* error_string;
};
#endif
| [
"trailcode@gmail.com"
] | trailcode@gmail.com |
e9178f11e39028d1ea708c9f3605cbd019ccc66d | 5de42c4e14a7ddbc284a742c66cb01b230ba43ce | /codeforces/681/E.cpp | d1a839c9b547910679d24caa65f013695b51ba1d | [] | no_license | NhatMinh0208/CP-Archive | 42d6cc9b1d2d6b8c85e637b8a88a6852a398cc23 | f95784d53708003e7ba74cbe4f2c7a888d29eac4 | refs/heads/master | 2023-05-09T15:50:34.344385 | 2021-05-04T14:25:00 | 2021-05-19T16:10:11 | 323,779,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,417 | cpp |
// Problem : D. Binary String To Subsequences
// Contest : Codeforces - Codeforces Round #661 (Div. 3)
// URL : https://codeforces.com/contest/1399/problem/D
// Memory Limit : 256 MB
// Time Limit : 2000 ms
// Powered by CP Editor (https://github.com/cpeditor/cpeditor)
/*
A Submission by $%U%$
at time: $%Y%$-$%M%$-$%D%$ $%h%$:$%m%$:$%s%$
*/
#include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define fef(i,a,b) for(ll i=a;i<=b;i++)
#define rer(i,a,b) for(ll i=b;i>=a;i--)
#define wew while(true)
#pragma comment(linker, "/stack:200000000")
#pragma GCC optimize("Ofast")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
#define FILE_IN "cseq.inp"
#define FILE_OUT "cseq.out"
#define ofile freopen(FILE_IN,"r",stdin);freopen(FILE_OUT,"w",stdout)
#define fio ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define nfio cin.tie(0);cout.tie(0)
#define max(x,y) (((x)>(y))?(x):(y))
#define min(x,y) (((x)<(y))?(x):(y))
#define ord(a,b,c) ((a>=b)and(b>=c))
#define MOD (ll(1000000007))
#define MAX 300001
#define mag 320
#define p1 first
#define p2 second.first
#define p3 second.second
#define fi first
#define se second
#define pow2(x) (ll(1)<<x)
#define pii pair<int,int>
#define piii pair<int,pii>
#define For(i,__,___) for(int i=__;i<=___;i++)
#define Rep(i,__,___) for(int i=__;i>=___;i--)
#define ordered_set tree<long long,null_type,less<long long>,rb_tree_tag,tree_order_statistics_node_update>
#define endl "\n"
#define bi BigInt
//---------END-------//
#undef M_PIl
#define LD double
#define EPSILON 1E-9
#define M_PIl pi
#define LL long long
const LD pi = std::acos(-1.0);
const LD pin2 = M_PIl * 2.0L;
int main()
{
fio;
LL x0, y0, r0, v, t, x, y, r;
cin >> x0 >> y0 >> v >> t;
r0 = v * t;
vector <pair <LD, LD> > res;
int n;
cin >> n;
for (; n; --n)
{
cin >> x >> y >> r;
LD dist((x - x0) * (x - x0) + (y - y0) * (y - y0));
if (dist < 1.0 * r * r + EPSILON)
{
cout << 1;
return 0;
}
dist = sqrt(dist);
if (dist - EPSILON > 1.0 * (r + r0))
continue;
LD easy_l(sqrt(dist * dist - 1.0 * r * r)), alpha(atan2((LD) (y - y0), (LD) (x - x0)));
double begin(alpha), end(alpha), delta;
if (easy_l < 1.0 * r0 + EPSILON)
delta = asin((1.0 * r) / dist);
else
delta = acos((1.0 * r0 * r0 + dist * dist - 1.0 * r * r) / (2.0 * r0 * dist));
begin -= delta;
end += delta;
if (end > pi)
{
res.push_back({ begin, pi });
res.push_back({ -pi, end - pin2 });
}
else if (begin < -pi)
{
res.push_back({ -pi, end });
res.push_back({ begin + pin2, pi });
}
else
res.push_back({ begin, end });
}
sort(res.begin(), res.end());
if (!res.size())
{
cout << 0;
return 0;
}
//res.push_back({ 2 * pin2, 2 * pin2 });
LD gl(0), prev(-pi);
for (int i(0); i < res.size(); ++i)
{
if (res[i].first > prev)
prev = res[i].first;
if (res[i].second <= prev)
continue;
gl += res[i].second - prev;
prev = res[i].second;
}
cout << setprecision(10) << (gl / pin2);
}
| [
"minhkhicon2468@gmail.com"
] | minhkhicon2468@gmail.com |
9d725a42eba910c6f98cc97509137e1bd2b54c8d | aa5385fb0fb6811a00fc25266cb59bcae5e8270e | /iphone/cardet/Source/Common.h | 7d31bab8df72fa6decc451831e17393d0fdb4f3f | [] | no_license | genesis32/cardet | 6c017d8d0c4b83fec499fe911fb79a73571d25f1 | 7fcf2a492bb4509084dbbbef809314aec9b5348e | refs/heads/master | 2021-01-20T04:11:35.819296 | 2017-04-28T01:19:53 | 2017-04-28T01:19:53 | 89,654,623 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 170 | h | #ifndef COMMON_H
#define COMMON_H
#include <assert.h>
#include <stdio.h>
#include <stdint.h>
#include "Util.h"
namespace cardet
{
extern int gCurrTimeMs;
}
#endif
| [
"ddmassey@gmail.com"
] | ddmassey@gmail.com |
36a2e265bea783ebd07f6628e415f3ab684ca766 | 8083aa52a558088e6762e1e74f4219d2f4494043 | /GreedyGenesLib/GreedyGenesLib/TwoPointInversion.h | 8dedf766357cf5b7f211e35cffcaa76178e4e3cd | [
"MIT"
] | permissive | s-ani/GreedyGenes | 78d1054b0697fe7dfbe2ab4a3f56b8117479c3b2 | 04c34edb09f087a9cfc3286b74e0aa17c3951882 | refs/heads/master | 2020-05-14T13:47:44.172868 | 2018-04-29T09:41:25 | 2018-04-29T09:41:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 283 | h | #pragma once
#include "InversionStrategy.h"
class TwoPointInversion : public InversionStrategy
{
public:
TwoPointInversion(double inversionRate)
: m_rate(inversionRate)
{}
void Inverse(Generation& gen) override;
private:
double m_rate;
};
| [
"Narek_Atayan@epam.com"
] | Narek_Atayan@epam.com |
12cc0b773d7f9fe310643a8da695f36516cb7e91 | de81b2510a358116d0a434b2e803d7aab814d101 | /src/Board.cpp | ad39ba2dbe76f7d72fd2026aefe5deaae21bc01e | [] | no_license | Davood96/MonopolyCMD | 978303c3ba15d2972d23edb0b566b6f3929506bb | 21ccd903611c3f9bf093def9fd6784bfeda7475f | refs/heads/master | 2021-01-17T19:51:56.577215 | 2016-08-06T08:29:25 | 2016-08-06T08:29:25 | 64,056,137 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,500 | cpp | /**
* This file contains the implementation of the following classes:
* - Board
**/
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include "../Headers/Board.h"
#include "../Headers/RandomCardImp.h"
#include "../Headers/PropertyChildren.h"
#include "../Headers/CardTypes.h"
#include "../Headers/Names.h"
void Board::shuffleDecks()
{
chanceDeck->shuffle();
communityDeck->shuffle();
//meow
}
void Board::createDecks()
{
chanceDeck = new RandomCardDeck();
communityDeck = new RandomCardDeck();
}
void Board::assignRandomCardPositions()
{
RandomSpace* chance = new RandomSpace(chanceDeck, "Chance");
elements[7] = chance;
elements[22] = chance;
elements[36] = chance;
RandomSpace* community = new RandomSpace(communityDeck, "Community Chest");
elements[17] = community;
elements[33] = community;
elements[2] = community;
}
void Board::readCities()
{
elements[0] = new GO("GO");
elements[4] = new IncomeTax("Income Tax");
elements[10] = new Jail();
elements[12] = new Service("Cellphone Service", 'f');
elements[20] = new FreeParking("Free Parking");
elements[28] = new Service("Internet Service", 'f');
elements[38] = new LuxuryTax("Luxury Tax");
fp = fopen(CITIES_LINK, "r");
if(fp == NULL)
{
printf("not found\n");
exit(1);
}
int i = 0;int index; float purchase;
for(i; i < 22; i++)
{
char* string = (char*) malloc(40*sizeof(char));
char c;int j = 0;
float* tmp = (float*) malloc(6 * sizeof(float));
while((c = fgetc(fp)) != '\t')
string[j++] = c;
string[j] = '\0';int code;
fscanf(fp, "%d", &code);
fscanf(fp, "%d%f%f%f%f%f%f%f\n", &index, tmp, tmp + 1, tmp + 2,
tmp + 3, tmp + 4, tmp + 5, &purchase);
City* city = new City(string, (char)code, tmp);
//std::cout << city->isOwned();
city->setPurchasePrice(purchase);
city->setRent(tmp[0]);
elements[index] = city;
}
fclose(fp);
}
void Board::readAirports()
{
fp = fopen(AIRPORT_LINK, "r");
if(fp == NULL)
{
printf("not found\n");
exit(1);
}
int i = 0;int index;
for(i; i < 4; i++)
{
char* string = (char*) malloc(40*sizeof(char));
char c;int j = 0;
while((c = fgetc(fp)) != '\t')
string[j++] = c;
string[j] = '\0';int code;
fscanf(fp, "%d\n", &code);
Airport* airport = new Airport(string, (char)code);
fscanf(fp, "%d\n", &index);
elements[index] = airport;
}
fclose(fp);
}
void Board::readChance()
{
fp = fopen(CHANCE_LINK, "r");
if(fp == NULL)
{
printf("not found\n");
exit(1);
}
int i = 0;int index;
for(i; i < 3; i++)
{
char* string = (char*) malloc(100*sizeof(char));
if(string == NULL)
exit(1);
char c;int j = 0;
while((c = fgetc(fp)) != '\t')
string[j++] = c;
string[j] = '\0';
fscanf(fp, "%d\n", &index);
RandomCard* card = new AdvanceCard (string, index);
chanceDeck->insert(card);
}
fclose(fp);
}
void Board::readCommunityChest()
{
fp = fopen(COMMUNITY_LINK, "r");
if(fp == NULL)
{
printf("not found\n");
exit(1);
}
int i = 0;int index;
for(i; i < 3; i++)
{
char* string = (char*) malloc(100*sizeof(char));
if(string == NULL)
exit(1);
char c;int j = 0;
while((c = fgetc(fp)) != '\t')
string[j++] = c;
string[j] = '\0';
fscanf(fp, "%d\n", &index);
RandomCard* card = new AdvanceCard (string, index);
communityDeck->insert(card);
}
fclose(fp);
}
void Board::readNearest()
{
char* string = "Advance to the nearest airport";
chanceDeck->insert(new NearestCard(string));
communityDeck->insert(new NearestCard(string));
}
| [
"david96@my.yorku.ca"
] | david96@my.yorku.ca |
0a7e4fe46eed3658626f2272c508cd2fe7669d91 | 16b142e8cd4a704c0488646c82141716409a698b | /Section6.5/checker.cpp | 09cba50882d74216157491da5bcdf8bfa7247457 | [] | no_license | BragCat/USACO | 3ba602c50210e60ebda3653263d27eb34996e31d | db22e56e5d42c462ea38cf656c4dfba619f79265 | refs/heads/master | 2018-11-22T08:42:46.196513 | 2018-10-30T13:46:07 | 2018-10-30T13:46:07 | 100,441,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | cpp | /*
ID: bragcat1
LANG: C++11
TASK: checker
*/
#include <cmath>
#include <fstream>
using namespace std;
int full, sum;
int a[14],n;
ifstream fin("checker.in");
ofstream fout("checker.out");
void dfs(int row, int ld, int rd, int deep) {
int pos, p;
if (row != full) {
pos = full & ~(row | ld | rd);
while (pos != 0) {
p = pos & -pos;
pos = pos - p;
if (sum < 3) {
a[deep] = p;
}
dfs(row + p, (ld + p) << 1, (rd + p) >> 1, deep + 1);
}
} else {
++sum;
if (sum <= 3) {
for (int i = 1;i <= n - 1; ++i) {
fout << static_cast<int>(log(a[i]) / log(2) + 1) << ' ';
}
fout << static_cast<int>(log(a[n]) / log(2) + 1) << endl;
}
}
}
int main() {
fin >> n;
fin.close();
full = (1 << n) - 1;
dfs(0, 0, 0, 1);
fout << sum << endl;
fout.close();
return 0;
}
| [
"bragcat.li@gmail.com"
] | bragcat.li@gmail.com |
6d4fae5b75586bd096b4a3eb01050c4f2e5b3b04 | 4d251c3f1dec4a9a1baf2b33fba09971dcbaf95e | /src/layouts/FixedLayout.cpp | 53c71e110eb53d988f6f1881b57d9699f69cf915 | [
"MIT"
] | permissive | tdp-libs/tp_maps_ui | fce7b3130def400d311257ca882663858a8dc79d | 31306f605246d44b219c47b33eba7c753d26160d | refs/heads/master | 2022-08-18T12:36:58.697394 | 2022-08-05T12:41:24 | 2022-08-05T12:41:24 | 156,202,095 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,867 | cpp | #include "tp_maps_ui/layouts/FixedLayout.h"
#include "tp_maps_ui/layers/UILayer.h"
#include "tp_maps_ui/Widget.h"
#include "tp_maps/Map.h"
#include "tp_utils/DebugUtils.h"
namespace tp_maps_ui
{
namespace
{
//##################################################################################################
class LayoutParams_lt : public LayoutParams
{
public:
Dim x;
Dim y;
Dim width;
Dim height;
LayoutParams_lt(const Dim& x_=Dim::zero(),
const Dim& y_=Dim::zero(),
const Dim& width_=Dim::full(),
const Dim& height_=Dim::full()):
x(x_),
y(y_),
width(width_),
height(height_)
{
}
};
}
//##################################################################################################
struct FixedLayout::Private
{
TP_REF_COUNT_OBJECTS("tp_maps_ui::FixedLayout::Private");
TP_NONCOPYABLE(Private);
Private() = default;
};
//##################################################################################################
FixedLayout::FixedLayout(Widget* parent):
Layout(parent),
d(new Private())
{
}
//##################################################################################################
FixedLayout::~FixedLayout()
{
delete d;
}
//##################################################################################################
void FixedLayout::updateLayout()
{
float parentW = parent()->width();
float parentH = parent()->height();
for(auto child : parent()->children())
{
auto params = child->layoutParams<LayoutParams_lt>();
float x=params->x .calc(parentW);
float y=params->y .calc(parentH);
float w=params->width .calc(parentW);
float h=params->height.calc(parentH);
child->setGeometry(x, y, w, h);
}
}
//##################################################################################################
void FixedLayout::addWidget(Widget* widget, Dim x, Dim y, Dim width, Dim height)
{
if(!parent())
{
tpWarning() << "FixedLayout::addWidget() Error! Add widgets to a layout after adding it to a widget!";
return;
}
widget->layoutParams<LayoutParams_lt>(x, y, width, height);
parent()->addWidget(widget);
}
//##################################################################################################
void FixedLayout::addLayout(Layout* layout, Dim x, Dim y, Dim width, Dim height)
{
auto widget = new Widget();
widget->setLayout(layout);
addWidget(widget, x, y, width, height);
}
//##################################################################################################
void FixedLayout::updateWidgetDims(Widget* widget, Dim x, Dim y, Dim width, Dim height)
{
auto dims = widget->layoutParams<LayoutParams_lt>(x, y, width, height);
dims->x = x;
dims->y = y;
dims->width = width;
dims->height = height;
updateLayout();
}
//##################################################################################################
void FixedLayout::getWidgetDims(Widget* widget, Dim& x, Dim& y, Dim& width, Dim& height)
{
auto params = widget->layoutParams<LayoutParams_lt>();
x = params->x;
y = params->y;
width = params->width;
height = params->height;
}
//##################################################################################################
std::function<bool(double)> FixedLayout::makeAnimationFunctor(tp_maps_ui::Widget* widget,
tp_maps_ui::Dim targetX,
tp_maps_ui::Dim targetY,
tp_maps_ui::Dim targetWidth,
tp_maps_ui::Dim targetHeight,
float speedR,
float speedP)
{
return [=, lastTimeMS=-1.0](double timeMS) mutable -> bool
{
auto delta = timeMS-lastTimeMS;
if(lastTimeMS<0.0)
{
lastTimeMS = timeMS;
return true;
}
if(delta<0.5)
return false;
auto sR = speedR * (float(delta)/1000.0f); //Speed for relative coords
auto sP = speedP * (float(delta)/1000.0f); //Speed for pixel coords
if(sR<0.000000000001f || sP<0.0000001f)
return false;
tp_maps_ui::Dim x;
tp_maps_ui::Dim y;
tp_maps_ui::Dim width;
tp_maps_ui::Dim height;
getWidgetDims(widget, x, y, width, height);
bool cont=false;
cont |= tp_maps_ui::calculateAnimationDim(targetX, x, sR, sP);
cont |= tp_maps_ui::calculateAnimationDim(targetY, y, sR, sP);
cont |= tp_maps_ui::calculateAnimationDim(targetWidth, width, sR, sP);
cont |= tp_maps_ui::calculateAnimationDim(targetHeight, height, sR, sP);
updateWidgetDims(widget, x, y, width, height);
return cont;
};
}
}
| [
"tompaynter@tdpe.co.uk"
] | tompaynter@tdpe.co.uk |
2f627f7d5c674550371b1dfc7c2f15cd95562a0a | 24169ed433d6fb46ee6c00d49a31ee834f517dce | /GFlowSim/src/visualization/raykdtree.cpp | 95f1922bf9afd5f99d4f0ecc037e63afde035d4c | [] | no_license | nrupprecht/GFlow | 0ae566e33305c31c1fead7834a0b89f611abb715 | 445bf3cbdbcdc68aa51b5737f60d96634009a731 | refs/heads/master | 2021-11-22T22:07:31.721612 | 2020-04-22T18:51:21 | 2020-04-22T18:51:21 | 60,136,842 | 2 | 2 | null | 2020-02-10T23:10:33 | 2016-06-01T01:49:26 | C++ | UTF-8 | C++ | false | false | 7,080 | cpp | #include "raykdtree.hpp"
// Other files
#include "../utility/vectormath.hpp"
namespace GFlowSimulation {
RayKDTreeNode::~RayKDTreeNode() {
if (lower) delete lower;
lower = nullptr;
if (higher) delete higher;
higher = nullptr;
}
void RayKDTreeNode::insert(Sphere *sphere) {
// If this is a leaf node, insert the sphere
if (lower==nullptr) {
sphere_list.push_back(sphere);
return;
}
// Else, check which children the sphere should be inserted into.
if (sphere->center[split_dim] - sphere->radius < split_value) lower->insert(sphere);
if (split_value < sphere->center[split_dim] + sphere->radius) higher->insert(sphere);
}
void RayKDTreeNode::empty() {
sphere_list.clear();
if (lower) lower->empty();
if (higher) higher->empty();
}
Sphere* RayKDTreeNode::traverse(const Ray& ray, float *point, float& distance_near, float& distance_far, float tmin, float tmax) const {
// If this is a terminal node, search through all spheres for an intersection.
if (lower==nullptr) {
float distance = 10000, d_far = 10000;
distance_near = distance_far = 10000;
float test_point[3];
Sphere *min_sphere = nullptr;
// Go through all spheres in this node.
for (const auto& sphere : sphere_list) {
if (sphere->intersect(ray, test_point, distance, d_far, tmin) && distance<distance_near) {
min_sphere = sphere;
distance_near = distance;
distance_far = d_far;
copyVec(test_point, point, 3);
}
}
// If we found nothing, this just returns nullptr.
return min_sphere;
}
// Else, march the ray through any child nodes that it intersects with.
float v = ray.orientation[split_dim];
if (v!=0) { // Make sure ray is not parallel to splitting plane
// Calculate the t value for which the ray intersects with the splitting plane.
float t_split = (split_value - ray.origin[split_dim])/v;
// In eiher case, we will need to know which child domain the ray enters first.
float X[3];
scalarMultVec(tmin, ray.orientation, X, 3);
plusEqVec(X, ray.origin, 3);
bool lower_first = (X[split_dim] < split_value);
// If t_split > tmax, the ray exits the bounding box before entering the other child domain.
// If t_split < tmin, the ray is going the wrong direction to go into one of the child domains.
// In either case, we only need to check with one child domain. We can test which one is relevant by seeing which child
// domain the entrance point is in.
if (t_split>tmax || t_split<tmin) {
// Check which side of the splitting coordinate X is on
if (lower_first) return lower->traverse(ray, point, distance_near, distance_far, tmin, tmax);
else return higher->traverse(ray, point, distance_near, distance_far, tmin, tmax);
}
// Otherwise, the ray intersects with both child domains. The only thing left to do is to figure out which domain comes first.
// We can do this by seeing which child domain the entrance point is in
Sphere *sphere = nullptr;
if (lower_first) {
sphere = lower->traverse(ray, point, distance_near, distance_far, tmin, tmax);
// If nothing was found in the first child, search the second child.
if (sphere==nullptr) return higher->traverse(ray, point, distance_near, distance_far, tmin, tmax);
// If something was found return it.
else return sphere;
}
else {
sphere = higher->traverse(ray, point, distance_near, distance_far, tmin, tmax);
// If nothing was found in the first child, search the second child.
if (sphere==nullptr) return lower->traverse(ray, point, distance_near, distance_far, tmin, tmax);
// If something was found return it.
else return sphere;
}
}
else {
// Only intersects the lower node
if (ray.origin[split_dim] < split_value) return lower->traverse(ray, point, distance_near, distance_far, tmin, tmax);
// Only intersects the higher node
else return higher->traverse(ray, point, distance_near, distance_far, tmin, tmax);
}
}
int RayKDTreeNode::getMaxDepth() const {
if (lower==nullptr) return 1;
return 1 + max(lower->getMaxDepth(), higher->getMaxDepth());
}
int RayKDTreeNode::getTotalSpheres() const {
if (lower==nullptr) return sphere_list.size();
return lower->getTotalSpheres() + higher->getTotalSpheres();
}
RayKDTree::~RayKDTree() {
clear();
}
void RayKDTree::insert(Sphere *sphere) {
if (head) head->insert(sphere);
}
Sphere* RayKDTree::traverse(const Ray& ray, float *point, float& distance_near, float& distance_far, bool& intersect, float& tmin, float& tmax) const {
// If the tree is empty, return nullptr.
if (head==nullptr) return nullptr;
// Find the tmin and tmax of the ray through the system bounding box.
tmin = 0; tmax = 0;
// If the ray does not intersect with the bounding box, set the flag and return.
if (!getRayIntersectionParameters(ray, tmin, tmax)) {
intersect = false;
return nullptr;
}
// The ray did intersect with the bounding box.
intersect = true;
// Traverse the data structure.
return head->traverse(ray, point, distance_near, distance_far, tmin, tmax);
}
bool RayKDTree::getRayIntersectionParameters(const Ray& ray, float& tmin, float& tmax) const {
float tmin_d[3], tmax_d[3];
// Find tmin, tmax for each dimension.
for (int i=0; i<3; ++i) {
if (ray.orientation[i]==0) {
// No intersection.
if (ray.origin[i]<=bounds.min[i] || bounds.max[i]<=ray.origin[i]) return false;
tmin_d[i] = 0;
tmax_d[i] = 10000; // Use as "infinity."
}
else if (ray.orientation[i]>0) {
tmin_d[i] = max(static_cast<float>((bounds.min[i] - ray.origin[i])/ray.orientation[i]), 0.f);
tmax_d[i] = max(static_cast<float>((bounds.max[i] - ray.origin[i])/ray.orientation[i]), 0.f);
}
else { // ray.orientation[i]<0
tmin_d[i] = max(static_cast<float>((bounds.max[i] - ray.origin[i])/ray.orientation[i]), 0.f);
tmax_d[i] = max(static_cast<float>((bounds.min[i] - ray.origin[i])/ray.orientation[i]), 0.f);
}
}
// Find actual tmin, tmax
tmin = max(tmin_d[0], tmin_d[1], tmin_d[2]);
tmax = min(tmax_d[0], tmax_d[1], tmax_d[2]);
// If the ray does not intersect with the bounding box, set the flag and return.
if (tmax<=tmin) return false;
// The ray did intersect with the bounding box.
return true;
}
void RayKDTree::clear() {
if (head) delete head;
head = nullptr;
}
void RayKDTree::empty() {
if (head) head->empty();
}
bool RayKDTree::isCreated() {
return head!=nullptr;
}
int RayKDTree::getMaxDepth() const {
if (head) return head->getMaxDepth();
else return 0;
}
int RayKDTree::getTotalSpheres() const {
if (head) return head->getTotalSpheres();
else return 0;
}
} | [
"nathaniel.rupprecht@gmail.com"
] | nathaniel.rupprecht@gmail.com |
d798a55e70c1945eb0752f9fa35e589cfd915f6f | 8194c153de598eaca637559443f71d13b729d4d2 | /ogsr_engine/xrGame/UIDialogHolder.h | 904fdc9fff7618e42835c72661733f3875a4cce2 | [
"Apache-2.0"
] | permissive | NikitaNikson/X-Ray_Renewal_Engine | 8bb464b3e15eeabdae53ba69bd3c4c37b814e33e | 38cfb4a047de85bb0ea6097439287c29718202d2 | refs/heads/dev | 2023-07-01T13:43:36.317546 | 2021-08-01T15:03:31 | 2021-08-01T15:03:31 | 391,685,134 | 4 | 4 | Apache-2.0 | 2021-08-01T16:52:09 | 2021-08-01T16:52:09 | null | UTF-8 | C++ | false | false | 1,420 | h | #pragma once
class CUIDialogWnd;
class CUIWindow;
class dlgItem{
public:
dlgItem (CUIWindow* pWnd);
CUIWindow* wnd;
bool enabled;
bool operator < (const dlgItem& itm) const;
};
class recvItem{
public:
enum{ eCrosshair = (1<<0),
eIndicators = (1<<1),};
recvItem (CUIDialogWnd*);
CUIDialogWnd* m_item;
Flags8 m_flags;
};
class CDialogHolder :public ISheduled,public pureFrame
{
//dialogs
xr_vector<recvItem> m_input_receivers;
xr_vector<dlgItem> m_dialogsToRender;
void StartMenu (CUIDialogWnd* pDialog, bool bDoHideIndicators);
void StopMenu (CUIDialogWnd* pDialog);
void SetMainInputReceiver (CUIDialogWnd* ir, bool _find_remove);
protected:
void DoRenderDialogs ();
void CleanInternals ();
public:
CDialogHolder ();
virtual ~CDialogHolder ();
virtual shared_str shedule_Name () const { return shared_str("CDialogHolder"); };
virtual void shedule_Update (u32 dt);
virtual float shedule_Scale ();
virtual bool shedule_Needed () {return true;};
//dialogs
CUIDialogWnd* MainInputReceiver ();
virtual void StartStopMenu (CUIDialogWnd* pDialog, bool bDoHideIndicators);
void AddDialogToRender (CUIWindow* pDialog);
void RemoveDialogToRender (CUIWindow* pDialog);
virtual void OnFrame ();
virtual bool UseIndicators () {return true;}
};
| [
"kdementev@gmail.com"
] | kdementev@gmail.com |
b8154f3bd47e4e8711ae3240d9c0a4934f5fba96 | 01c19b4b0f20c99c8e3f5a6c9ae32f7894357ed6 | /src/db/db_interface.cc | 005fa52842b4c092d26a3f98be145f707c1288de | [] | no_license | synxb/crypto_online_project | 555ab1206e0f55507b76751d47f72c45bcd292ec | 2c61362913a6c2f8098d934a074abc7d446174f7 | refs/heads/master | 2022-01-17T00:56:47.259922 | 2018-04-29T22:11:51 | 2018-04-29T22:11:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,087 | cc | /**
* File: db_interface.cc
* Created: 20/12/2017 19:45
* Finished:
*
* Description:
* @version 0.01
* Author: Jacob Powell
*/
#include "db_interface.h"
/**
* @brief This method gets given an id for a user and then searches through the DbUser table for the user with that id.
* If it finds a user with that id then it returns a Wt::Dbo::ptr<DbUser> object containing all the information
* on that user. If it does not find the user it does nothing.
*
* @param looking_for_id The id of the user we are looking for
* @return The user in db_user with id == looking for id
*/
Wt::Dbo::ptr<DbUser> db_interface::get_user(std::string looking_for_id) {
std::cerr << "Getting Information for User with ID(" << looking_for_id << ")" << std::endl;
Wt::Dbo::Transaction transaction(current_session);
std::cerr << "Getting all user data from the DbUser table" << std::endl;
Wt::Dbo::collection< Wt::Dbo::ptr<DbUser> > all_users = current_session.find<DbUser>();
if(!all_users.empty()){
std::cerr << "DbUser Table is not Empty" << std::endl;
for(const Wt::Dbo::ptr<DbUser>& current_user : all_users){
long long int id = current_user.id();
std::cout << "Identity: " << id << std::endl;
if(std::to_string(id) == looking_for_id)
return current_user;
else{
std::cout << "User not Found" << std::endl;
}
}
}
std::cout << "Leaving db_interface::db_user" << std::endl;
}
/**
* @brief When a user answers a question it stores their answer in the database
*/
void db_interface::add_answer_to_user(const std::string &answer, const int question_id) {
Wt::Dbo::Transaction transaction(current_session);
const Wt::Auth::User& u = current_session.login().user();
auto current_user = this->get_user(u.id());
std::cout << question_id << std::endl;
if(!this->does_answer_exist_user(question_id)){
std::cout << "Adding Question for the first time" << std::endl;
std::cout << question_id << std::endl;
std::unique_ptr<DbUserAnsweredQuestion> question_answer_1{new DbUserAnsweredQuestion()};
question_answer_1->question_id = question_id;
question_answer_1->answer_text = answer;
question_answer_1->user = current_user;
Wt::Dbo::ptr<DbUserAnsweredQuestion> userPtr = current_session.add(std::move(question_answer_1));
}else{
auto question = this->get_answer(question_id);
question.modify()->answer_text = answer;
}
}
/**
* @brief This method searches through the questions a user has saved and determines whether or not
* they have already answered said question.
*
* @param answer_id The id of the answer we are looking for
* @return True if the user has answered that question, False if the user has not.
*/
bool db_interface::does_answer_exist_user(const int &answer_id) {
Wt::Dbo::Transaction transaction(current_session);
const std::string ¤t_user_id = this->current_session.login().user().id();
auto current_user = this->get_user(current_user_id);
if(current_user->questions.empty()){
return false;
}else{
for(const Wt::Dbo::ptr<DbUserAnsweredQuestion>& question : current_user->questions){
std::cout << question->question_id << std::endl;
if(question->question_id == answer_id)
return true;
}
std::cout << "Question already exits" << std::endl;
return false;
}
}
/**
* @brief This method searches through the questions the user has answered and then returns an object
* containing the data on the question we are searching for.
*
* @param answer_id The answer_id of the question we are looking for
* @return An object containing the information on the question begin searched for
*/
Wt::Dbo::ptr<DbUserAnsweredQuestion> db_interface::get_answer(const int &answer_id){
std::cout << "GET ANSWER CALLED" << std::endl;
Wt::Dbo::Transaction transaction(current_session);
const std::string ¤t_user_id = this->current_session.login().user().id();
return this->current_session.find<DbUserAnsweredQuestion>().where("user_answered_question_id = ?").bind(answer_id)
.where("user_id = ?").bind(current_user_id);
}
/**
* @brief This method gets an answer and a question and then checks to see if the users answer is right
*
* @param answer The user answer
* @param question_id The id of the question being answered
* @return Whether or not the question is right
*/
bool db_interface::check_answer(const std::string &answer, int question_id) {
std::cout << "CHECK ANSWER CALLED" << std::endl;
Wt::Dbo::Transaction transaction(current_session);
const std::string& current_user_id = this->current_session.login().user().id();
std::cout << "Getting User Answered Questions" << std::endl;
Wt::Dbo::ptr<DbUserAnsweredQuestion> user_answer = this->current_session.find<DbUserAnsweredQuestion>()
.where("user_answered_question_id = ?").bind(question_id)
.where("user_id = ?").bind(current_user_id);
std::cout << "Getting Questions" << std::endl;
Wt::Dbo::ptr<DbQuestions> question = this->current_session.find<DbQuestions>()
.where("question_id = ?").bind(question_id);
std::cout << "Got Questions" << std::endl;
return (user_answer->answer_text == question->question_answer);
}
/**
* @brief This method works out how many questions the user has answered
* @return THe number of questions the user has attempted
*/
int db_interface::get_total_questions_answered() {
Wt::Dbo::Transaction transaction(current_session);
int number_of_questions = 0;
auto current_user_id = this->current_session.login().user().id();
auto current_user = this->get_user(current_user_id);
for(const Wt::Dbo::ptr<DbUserAnsweredQuestion> question : current_user->questions){
number_of_questions++;
}
return number_of_questions;
}
/**
* This method works out how many of the quesitons the user has answered correctly
* @return The number of correctly answered questions
*/
int db_interface::get_total_correct_question_answered() {
Wt::Dbo::Transaction transaction(current_session);
int number_of_correct_questions = 0;
auto current_user_id = this->current_session.login().user().id();
auto current_user = this->get_user(current_user_id);
for(const Wt::Dbo::ptr<DbUserAnsweredQuestion> question : current_user->questions){
if(question->is_correct)
number_of_correct_questions++;
}
return number_of_correct_questions;
}
/**
* @brief This method sets the is_correct flag in the user_answered_question table so I can easily work out whether or
* not the user got the question correct
*/
void db_interface::set_answer_check_flag(int question_id, bool check) {
Wt::Dbo::Transaction transaction(current_session);
auto question = this->get_answer(question_id);
question.modify()->is_correct = check;
}
| [
"jpwell3@gmail.com"
] | jpwell3@gmail.com |
1383496c769fd024a9ab3576238031927600b270 | 0cd19011318abe62f57ae5221cd82c142de18d31 | /矩形/矩形/squre.cpp | 569ef3050b223a983652f1c4c550b3da45af8f81 | [] | no_license | w7436/wen-CPP | 07c171d3f099475647480755af65ad1a0b419e0e | 4e70049186ea992154bc430cbffd3fed7b7f810e | refs/heads/master | 2022-03-31T10:53:54.074091 | 2019-12-10T15:18:48 | 2019-12-10T15:18:48 | 197,928,575 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 105 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include "squre.h"
void CRectangle::Move(int a,int b,int c,int d) {
} | [
"3239741254@qq.com"
] | 3239741254@qq.com |
c3075da49d25fd2e135217925cd00c4ed3ace064 | 9fad4848e43f4487730185e4f50e05a044f865ab | /src/content/common/gpu/media/v4l2_image_processor.cc | b7417b583b8cb989271b734ef9819eb017ed6a58 | [
"BSD-3-Clause"
] | permissive | dummas2008/chromium | d1b30da64f0630823cb97f58ec82825998dbb93e | 82d2e84ce3ed8a00dc26c948219192c3229dfdaa | refs/heads/master | 2020-12-31T07:18:45.026190 | 2016-04-14T03:17:45 | 2016-04-14T03:17:45 | 56,194,439 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,159 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <errno.h>
#include <fcntl.h>
#include <linux/videodev2.h>
#include <poll.h>
#include <string.h>
#include <sys/eventfd.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/numerics/safe_conversions.h"
#include "content/common/gpu/media/v4l2_image_processor.h"
#include "media/base/bind_to_current_loop.h"
#define NOTIFY_ERROR() \
do { \
LOG(ERROR) << "calling NotifyError()"; \
NotifyError(); \
} while (0)
#define IOCTL_OR_ERROR_RETURN_VALUE(type, arg, value, type_str) \
do { \
if (device_->Ioctl(type, arg) != 0) { \
PLOG(ERROR) << __func__ << "(): ioctl() failed: " << type_str; \
return value; \
} \
} while (0)
#define IOCTL_OR_ERROR_RETURN(type, arg) \
IOCTL_OR_ERROR_RETURN_VALUE(type, arg, ((void)0), #type)
#define IOCTL_OR_ERROR_RETURN_FALSE(type, arg) \
IOCTL_OR_ERROR_RETURN_VALUE(type, arg, false, #type)
#define IOCTL_OR_LOG_ERROR(type, arg) \
do { \
if (device_->Ioctl(type, arg) != 0) \
PLOG(ERROR) << __func__ << "(): ioctl() failed: " << #type; \
} while (0)
namespace content {
V4L2ImageProcessor::InputRecord::InputRecord() : at_device(false) {
}
V4L2ImageProcessor::InputRecord::~InputRecord() {
}
V4L2ImageProcessor::OutputRecord::OutputRecord() : at_device(false) {}
V4L2ImageProcessor::OutputRecord::~OutputRecord() {
}
V4L2ImageProcessor::JobRecord::JobRecord() : output_buffer_index(-1) {}
V4L2ImageProcessor::JobRecord::~JobRecord() {
}
V4L2ImageProcessor::V4L2ImageProcessor(const scoped_refptr<V4L2Device>& device)
: input_format_(media::PIXEL_FORMAT_UNKNOWN),
output_format_(media::PIXEL_FORMAT_UNKNOWN),
input_format_fourcc_(0),
output_format_fourcc_(0),
input_planes_count_(0),
output_planes_count_(0),
child_task_runner_(base::ThreadTaskRunnerHandle::Get()),
device_(device),
device_thread_("V4L2ImageProcessorThread"),
device_poll_thread_("V4L2ImageProcessorDevicePollThread"),
input_streamon_(false),
input_buffer_queued_count_(0),
output_streamon_(false),
output_buffer_queued_count_(0),
num_buffers_(0),
device_weak_factory_(this) {}
V4L2ImageProcessor::~V4L2ImageProcessor() {
DCHECK(child_task_runner_->BelongsToCurrentThread());
DCHECK(!device_thread_.IsRunning());
DCHECK(!device_poll_thread_.IsRunning());
DestroyInputBuffers();
DestroyOutputBuffers();
}
void V4L2ImageProcessor::NotifyError() {
if (!child_task_runner_->BelongsToCurrentThread())
child_task_runner_->PostTask(FROM_HERE, error_cb_);
else
error_cb_.Run();
}
bool V4L2ImageProcessor::Initialize(const base::Closure& error_cb,
media::VideoPixelFormat input_format,
media::VideoPixelFormat output_format,
int num_buffers,
gfx::Size input_visible_size,
gfx::Size output_visible_size,
gfx::Size* output_allocated_size) {
DCHECK(!error_cb.is_null());
error_cb_ = error_cb;
// TODO(posciak): Replace Exynos-specific format/parameter hardcoding in this
// class with proper capability enumeration.
DCHECK_EQ(input_format, media::PIXEL_FORMAT_I420);
DCHECK_EQ(output_format, media::PIXEL_FORMAT_NV12);
DCHECK_GT(num_buffers, 0);
input_format_ = input_format;
output_format_ = output_format;
input_format_fourcc_ = V4L2Device::VideoPixelFormatToV4L2PixFmt(input_format);
output_format_fourcc_ =
V4L2Device::VideoPixelFormatToV4L2PixFmt(output_format);
num_buffers_ = num_buffers;
if (!input_format_fourcc_ || !output_format_fourcc_) {
LOG(ERROR) << "Unrecognized format(s)";
return false;
}
input_visible_size_ = input_visible_size;
output_visible_size_ = output_visible_size;
output_allocated_size_ = *output_allocated_size;
input_planes_count_ = media::VideoFrame::NumPlanes(input_format);
DCHECK_LE(input_planes_count_, static_cast<size_t>(VIDEO_MAX_PLANES));
output_planes_count_ = media::VideoFrame::NumPlanes(output_format);
DCHECK_LE(output_planes_count_, static_cast<size_t>(VIDEO_MAX_PLANES));
// Capabilities check.
struct v4l2_capability caps;
memset(&caps, 0, sizeof(caps));
const __u32 kCapsRequired = V4L2_CAP_VIDEO_M2M_MPLANE | V4L2_CAP_STREAMING;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QUERYCAP, &caps);
if ((caps.capabilities & kCapsRequired) != kCapsRequired) {
LOG(ERROR) << "Initialize(): ioctl() failed: VIDIOC_QUERYCAP: "
"caps check failed: 0x" << std::hex << caps.capabilities;
return false;
}
if (!CreateInputBuffers() || !CreateOutputBuffers())
return false;
// CreateOutputBuffers may adjust |output_allocated_size_|.
*output_allocated_size = output_allocated_size_;
if (!device_thread_.Start()) {
LOG(ERROR) << "Initialize(): encoder thread failed to start";
return false;
}
// StartDevicePoll will NOTIFY_ERROR on failure, so IgnoreResult is fine here.
device_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(base::IgnoreResult(&V4L2ImageProcessor::StartDevicePoll),
base::Unretained(this)));
DVLOG(1) << "V4L2ImageProcessor initialized for "
<< " input_format:" << media::VideoPixelFormatToString(input_format)
<< ", output_format:"
<< media::VideoPixelFormatToString(output_format)
<< ", input_visible_size: " << input_visible_size.ToString()
<< ", input_allocated_size: " << input_allocated_size_.ToString()
<< ", output_visible_size: " << output_visible_size.ToString()
<< ", output_allocated_size: " << output_allocated_size_.ToString();
return true;
}
std::vector<base::ScopedFD> V4L2ImageProcessor::GetDmabufsForOutputBuffer(
int output_buffer_index) {
DCHECK_GE(output_buffer_index, 0);
DCHECK_LT(output_buffer_index, num_buffers_);
return device_->GetDmabufsForV4L2Buffer(output_buffer_index,
output_planes_count_,
V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE);
}
void V4L2ImageProcessor::Process(const scoped_refptr<media::VideoFrame>& frame,
int output_buffer_index,
const FrameReadyCB& cb) {
DVLOG(3) << __func__ << ": ts=" << frame->timestamp().InMilliseconds();
std::unique_ptr<JobRecord> job_record(new JobRecord());
job_record->frame = frame;
job_record->output_buffer_index = output_buffer_index;
job_record->ready_cb = cb;
device_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2ImageProcessor::ProcessTask,
base::Unretained(this),
base::Passed(&job_record)));
}
void V4L2ImageProcessor::ProcessTask(std::unique_ptr<JobRecord> job_record) {
int index = job_record->output_buffer_index;
DVLOG(3) << __func__ << ": Reusing output buffer, index=" << index;
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
EnqueueOutput(index);
input_queue_.push(make_linked_ptr(job_record.release()));
EnqueueInput();
}
void V4L2ImageProcessor::Destroy() {
DVLOG(3) << __func__;
DCHECK(child_task_runner_->BelongsToCurrentThread());
// If the device thread is running, destroy using posted task.
if (device_thread_.IsRunning()) {
device_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2ImageProcessor::DestroyTask, base::Unretained(this)));
// Wait for tasks to finish/early-exit.
device_thread_.Stop();
} else {
// Otherwise DestroyTask() is not needed.
DCHECK(!device_poll_thread_.IsRunning());
DCHECK(!device_weak_factory_.HasWeakPtrs());
}
delete this;
}
void V4L2ImageProcessor::DestroyTask() {
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
device_weak_factory_.InvalidateWeakPtrs();
// Stop streaming and the device_poll_thread_.
StopDevicePoll();
}
bool V4L2ImageProcessor::CreateInputBuffers() {
DVLOG(3) << __func__;
DCHECK(child_task_runner_->BelongsToCurrentThread());
DCHECK(!input_streamon_);
struct v4l2_control control;
memset(&control, 0, sizeof(control));
control.id = V4L2_CID_ROTATE;
control.value = 0;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CTRL, &control);
memset(&control, 0, sizeof(control));
control.id = V4L2_CID_HFLIP;
control.value = 0;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CTRL, &control);
memset(&control, 0, sizeof(control));
control.id = V4L2_CID_VFLIP;
control.value = 0;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CTRL, &control);
memset(&control, 0, sizeof(control));
control.id = V4L2_CID_ALPHA_COMPONENT;
control.value = 255;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CTRL, &control);
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
format.fmt.pix_mp.width = input_visible_size_.width();
format.fmt.pix_mp.height = input_visible_size_.height();
format.fmt.pix_mp.pixelformat = input_format_fourcc_;
format.fmt.pix_mp.num_planes = input_planes_count_;
for (size_t i = 0; i < input_planes_count_; ++i) {
format.fmt.pix_mp.plane_fmt[i].sizeimage =
media::VideoFrame::PlaneSize(input_format_, i, input_allocated_size_)
.GetArea();
format.fmt.pix_mp.plane_fmt[i].bytesperline =
base::checked_cast<__u32>(input_allocated_size_.width());
}
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
input_allocated_size_ = V4L2Device::CodedSizeFromV4L2Format(format);
DCHECK(gfx::Rect(input_allocated_size_).Contains(
gfx::Rect(input_visible_size_)));
struct v4l2_crop crop;
memset(&crop, 0, sizeof(crop));
crop.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
crop.c.left = 0;
crop.c.top = 0;
crop.c.width = base::checked_cast<__u32>(input_visible_size_.width());
crop.c.height = base::checked_cast<__u32>(input_visible_size_.height());
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CROP, &crop);
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.count = num_buffers_;
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = V4L2_MEMORY_USERPTR;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
if (reqbufs.count != num_buffers_) {
LOG(ERROR) << "Failed to allocate input buffers. reqbufs.count="
<< reqbufs.count << ", num_buffers=" << num_buffers_;
return false;
}
DCHECK(input_buffer_map_.empty());
input_buffer_map_.resize(reqbufs.count);
for (size_t i = 0; i < input_buffer_map_.size(); ++i)
free_input_buffers_.push_back(i);
return true;
}
bool V4L2ImageProcessor::CreateOutputBuffers() {
DVLOG(3) << __func__;
DCHECK(child_task_runner_->BelongsToCurrentThread());
DCHECK(!output_streamon_);
struct v4l2_format format;
memset(&format, 0, sizeof(format));
format.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
format.fmt.pix_mp.width = output_allocated_size_.width();
format.fmt.pix_mp.height = output_allocated_size_.height();
format.fmt.pix_mp.pixelformat = output_format_fourcc_;
format.fmt.pix_mp.num_planes = output_planes_count_;
for (size_t i = 0; i < output_planes_count_; ++i) {
format.fmt.pix_mp.plane_fmt[i].sizeimage =
media::VideoFrame::PlaneSize(output_format_, i, output_allocated_size_)
.GetArea();
format.fmt.pix_mp.plane_fmt[i].bytesperline =
base::checked_cast<__u32>(output_allocated_size_.width());
}
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_FMT, &format);
gfx::Size adjusted_allocated_size =
V4L2Device::CodedSizeFromV4L2Format(format);
DCHECK(gfx::Rect(adjusted_allocated_size).Contains(
gfx::Rect(output_allocated_size_)));
output_allocated_size_ = adjusted_allocated_size;
struct v4l2_crop crop;
memset(&crop, 0, sizeof(crop));
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
crop.c.left = 0;
crop.c.top = 0;
crop.c.width = base::checked_cast<__u32>(output_visible_size_.width());
crop.c.height = base::checked_cast<__u32>(output_visible_size_.height());
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_S_CROP, &crop);
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.count = num_buffers_;
reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
reqbufs.memory = V4L2_MEMORY_MMAP;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_REQBUFS, &reqbufs);
if (reqbufs.count != num_buffers_) {
LOG(ERROR) << "Failed to allocate output buffers. reqbufs.count="
<< reqbufs.count << ", num_buffers=" << num_buffers_;
return false;
}
DCHECK(output_buffer_map_.empty());
output_buffer_map_.resize(reqbufs.count);
return true;
}
void V4L2ImageProcessor::DestroyInputBuffers() {
DCHECK(child_task_runner_->BelongsToCurrentThread());
DCHECK(!input_streamon_);
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.count = 0;
reqbufs.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
reqbufs.memory = V4L2_MEMORY_USERPTR;
IOCTL_OR_LOG_ERROR(VIDIOC_REQBUFS, &reqbufs);
input_buffer_map_.clear();
free_input_buffers_.clear();
}
void V4L2ImageProcessor::DestroyOutputBuffers() {
DCHECK(child_task_runner_->BelongsToCurrentThread());
DCHECK(!output_streamon_);
struct v4l2_requestbuffers reqbufs;
memset(&reqbufs, 0, sizeof(reqbufs));
reqbufs.count = 0;
reqbufs.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
reqbufs.memory = V4L2_MEMORY_MMAP;
IOCTL_OR_LOG_ERROR(VIDIOC_REQBUFS, &reqbufs);
output_buffer_map_.clear();
}
void V4L2ImageProcessor::DevicePollTask(bool poll_device) {
DCHECK_EQ(device_poll_thread_.message_loop(), base::MessageLoop::current());
bool event_pending;
if (!device_->Poll(poll_device, &event_pending)) {
NOTIFY_ERROR();
return;
}
// All processing should happen on ServiceDeviceTask(), since we shouldn't
// touch encoder state from this thread.
device_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2ImageProcessor::ServiceDeviceTask,
base::Unretained(this)));
}
void V4L2ImageProcessor::ServiceDeviceTask() {
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
// ServiceDeviceTask() should only ever be scheduled from DevicePollTask(),
// so either:
// * device_poll_thread_ is running normally
// * device_poll_thread_ scheduled us, but then a DestroyTask() shut it down,
// in which case we should early-out.
if (!device_poll_thread_.message_loop())
return;
Dequeue();
EnqueueInput();
if (!device_->ClearDevicePollInterrupt())
return;
bool poll_device =
(input_buffer_queued_count_ > 0 && output_buffer_queued_count_ > 0);
device_poll_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(&V4L2ImageProcessor::DevicePollTask,
base::Unretained(this),
poll_device));
DVLOG(2) << __func__ << ": buffer counts: INPUT[" << input_queue_.size()
<< "] => DEVICE[" << free_input_buffers_.size() << "+"
<< input_buffer_queued_count_ << "/" << input_buffer_map_.size()
<< "->" << output_buffer_map_.size() - output_buffer_queued_count_
<< "+" << output_buffer_queued_count_ << "/"
<< output_buffer_map_.size() << "]";
}
void V4L2ImageProcessor::EnqueueInput() {
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
const int old_inputs_queued = input_buffer_queued_count_;
while (!input_queue_.empty() && !free_input_buffers_.empty()) {
if (!EnqueueInputRecord())
return;
}
if (old_inputs_queued == 0 && input_buffer_queued_count_ != 0) {
// We started up a previously empty queue.
// Queue state changed; signal interrupt.
if (!device_->SetDevicePollInterrupt())
return;
// VIDIOC_STREAMON if we haven't yet.
if (!input_streamon_) {
__u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
input_streamon_ = true;
}
}
}
void V4L2ImageProcessor::EnqueueOutput(int index) {
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
const int old_outputs_queued = output_buffer_queued_count_;
if (!EnqueueOutputRecord(index))
return;
if (old_outputs_queued == 0 && output_buffer_queued_count_ != 0) {
// We just started up a previously empty queue.
// Queue state changed; signal interrupt.
if (!device_->SetDevicePollInterrupt())
return;
// Start VIDIOC_STREAMON if we haven't yet.
if (!output_streamon_) {
__u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
IOCTL_OR_ERROR_RETURN(VIDIOC_STREAMON, &type);
output_streamon_ = true;
}
}
}
void V4L2ImageProcessor::Dequeue() {
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
// Dequeue completed input (VIDEO_OUTPUT) buffers,
// and recycle to the free list.
struct v4l2_buffer dqbuf;
struct v4l2_plane planes[VIDEO_MAX_PLANES];
while (input_buffer_queued_count_ > 0) {
DCHECK(input_streamon_);
memset(&dqbuf, 0, sizeof(dqbuf));
memset(&planes, 0, sizeof(planes));
dqbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
dqbuf.memory = V4L2_MEMORY_USERPTR;
dqbuf.m.planes = planes;
dqbuf.length = input_planes_count_;
if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
if (errno == EAGAIN) {
// EAGAIN if we're just out of buffers to dequeue.
break;
}
PLOG(ERROR) << "ioctl() failed: VIDIOC_DQBUF";
NOTIFY_ERROR();
return;
}
InputRecord& input_record = input_buffer_map_[dqbuf.index];
DCHECK(input_record.at_device);
input_record.at_device = false;
input_record.frame = NULL;
free_input_buffers_.push_back(dqbuf.index);
input_buffer_queued_count_--;
}
// Dequeue completed output (VIDEO_CAPTURE) buffers, recycle to the free list.
// Return the finished buffer to the client via the job ready callback.
while (output_buffer_queued_count_ > 0) {
DCHECK(output_streamon_);
memset(&dqbuf, 0, sizeof(dqbuf));
memset(&planes, 0, sizeof(planes));
dqbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
dqbuf.memory = V4L2_MEMORY_MMAP;
dqbuf.m.planes = planes;
dqbuf.length = output_planes_count_;
if (device_->Ioctl(VIDIOC_DQBUF, &dqbuf) != 0) {
if (errno == EAGAIN) {
// EAGAIN if we're just out of buffers to dequeue.
break;
}
PLOG(ERROR) << "ioctl() failed: VIDIOC_DQBUF";
NOTIFY_ERROR();
return;
}
OutputRecord& output_record = output_buffer_map_[dqbuf.index];
DCHECK(output_record.at_device);
output_record.at_device = false;
output_buffer_queued_count_--;
// Jobs are always processed in FIFO order.
DCHECK(!running_jobs_.empty());
linked_ptr<JobRecord> job_record = running_jobs_.front();
running_jobs_.pop();
DVLOG(3) << "Processing finished, returning frame, index=" << dqbuf.index;
child_task_runner_->PostTask(FROM_HERE,
base::Bind(job_record->ready_cb, dqbuf.index));
}
}
bool V4L2ImageProcessor::EnqueueInputRecord() {
DCHECK(!input_queue_.empty());
DCHECK(!free_input_buffers_.empty());
// Enqueue an input (VIDEO_OUTPUT) buffer for an input video frame.
linked_ptr<JobRecord> job_record = input_queue_.front();
input_queue_.pop();
const int index = free_input_buffers_.back();
InputRecord& input_record = input_buffer_map_[index];
DCHECK(!input_record.at_device);
input_record.frame = job_record->frame;
struct v4l2_buffer qbuf;
struct v4l2_plane qbuf_planes[VIDEO_MAX_PLANES];
memset(&qbuf, 0, sizeof(qbuf));
memset(qbuf_planes, 0, sizeof(qbuf_planes));
qbuf.index = index;
qbuf.type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
qbuf.memory = V4L2_MEMORY_USERPTR;
qbuf.m.planes = qbuf_planes;
qbuf.length = input_planes_count_;
for (size_t i = 0; i < input_planes_count_; ++i) {
qbuf.m.planes[i].bytesused = media::VideoFrame::PlaneSize(
input_record.frame->format(), i, input_allocated_size_).GetArea();
qbuf.m.planes[i].length = qbuf.m.planes[i].bytesused;
qbuf.m.planes[i].m.userptr =
reinterpret_cast<unsigned long>(input_record.frame->data(i));
}
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
input_record.at_device = true;
running_jobs_.push(job_record);
free_input_buffers_.pop_back();
input_buffer_queued_count_++;
DVLOG(3) << __func__ << ": enqueued frame ts="
<< job_record->frame->timestamp().InMilliseconds() << " to device.";
return true;
}
bool V4L2ImageProcessor::EnqueueOutputRecord(int index) {
DCHECK_GE(index, 0);
DCHECK_LT(index, output_buffer_map_.size());
// Enqueue an output (VIDEO_CAPTURE) buffer.
OutputRecord& output_record = output_buffer_map_[index];
DCHECK(!output_record.at_device);
struct v4l2_buffer qbuf;
struct v4l2_plane qbuf_planes[VIDEO_MAX_PLANES];
memset(&qbuf, 0, sizeof(qbuf));
memset(qbuf_planes, 0, sizeof(qbuf_planes));
qbuf.index = index;
qbuf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
qbuf.memory = V4L2_MEMORY_MMAP;
qbuf.m.planes = qbuf_planes;
qbuf.length = output_planes_count_;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_QBUF, &qbuf);
output_record.at_device = true;
output_buffer_queued_count_++;
return true;
}
bool V4L2ImageProcessor::StartDevicePoll() {
DVLOG(3) << __func__ << ": starting device poll";
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
DCHECK(!device_poll_thread_.IsRunning());
// Start up the device poll thread and schedule its first DevicePollTask().
if (!device_poll_thread_.Start()) {
LOG(ERROR) << "StartDevicePoll(): Device thread failed to start";
NOTIFY_ERROR();
return false;
}
// Enqueue a poll task with no devices to poll on - will wait only for the
// poll interrupt
device_poll_thread_.message_loop()->PostTask(
FROM_HERE,
base::Bind(
&V4L2ImageProcessor::DevicePollTask, base::Unretained(this), false));
return true;
}
bool V4L2ImageProcessor::StopDevicePoll() {
DVLOG(3) << __func__ << ": stopping device poll";
if (device_thread_.IsRunning())
DCHECK_EQ(device_thread_.message_loop(), base::MessageLoop::current());
// Signal the DevicePollTask() to stop, and stop the device poll thread.
if (!device_->SetDevicePollInterrupt())
return false;
device_poll_thread_.Stop();
// Clear the interrupt now, to be sure.
if (!device_->ClearDevicePollInterrupt())
return false;
if (input_streamon_) {
__u32 type = V4L2_BUF_TYPE_VIDEO_OUTPUT_MPLANE;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
}
input_streamon_ = false;
if (output_streamon_) {
__u32 type = V4L2_BUF_TYPE_VIDEO_CAPTURE_MPLANE;
IOCTL_OR_ERROR_RETURN_FALSE(VIDIOC_STREAMOFF, &type);
}
output_streamon_ = false;
// Reset all our accounting info.
while (!input_queue_.empty())
input_queue_.pop();
while (!running_jobs_.empty())
running_jobs_.pop();
free_input_buffers_.clear();
for (size_t i = 0; i < input_buffer_map_.size(); ++i) {
InputRecord& input_record = input_buffer_map_[i];
input_record.at_device = false;
input_record.frame = NULL;
free_input_buffers_.push_back(i);
}
input_buffer_queued_count_ = 0;
output_buffer_map_.clear();
output_buffer_map_.resize(num_buffers_);
output_buffer_queued_count_ = 0;
return true;
}
} // namespace content
| [
"dummas@163.com"
] | dummas@163.com |
2f72c5114c3d9d8bb5b195890644e0160bf9fee0 | 9c3a452da21455f64e1e86c1385d3d85c46070ee | /IfcPlusPlus/src/ifcpp/IFC4/lib/IfcText.cpp | 30883579be8d13b88d82f1368f3dbc54249e72ec | [
"MIT"
] | permissive | tao00720/ifcplusplus | a0e813757d79b505e36908894b031928389122c2 | 3d2e9aab5f74809a09832d041c20dec7323fd41d | refs/heads/master | 2021-07-02T04:51:25.421124 | 2017-04-11T15:53:48 | 2017-04-11T15:53:48 | 103,811,406 | 0 | 0 | null | 2017-09-17T07:35:36 | 2017-09-17T07:35:36 | null | UTF-8 | C++ | false | false | 1,338 | cpp | /* Code generated by IfcQuery EXPRESS generator, www.ifcquery.com */
#include <sstream>
#include <limits>
#include <map>
#include "ifcpp/reader/ReaderUtil.h"
#include "ifcpp/writer/WriterUtil.h"
#include "ifcpp/model/IfcPPBasicTypes.h"
#include "ifcpp/model/IfcPPException.h"
#include "ifcpp/IFC4/include/IfcSimpleValue.h"
#include "ifcpp/IFC4/include/IfcText.h"
// TYPE IfcText = STRING;
IfcText::IfcText() {}
IfcText::IfcText( std::wstring value ) { m_value = value; }
IfcText::~IfcText() {}
shared_ptr<IfcPPObject> IfcText::getDeepCopy( IfcPPCopyOptions& options )
{
shared_ptr<IfcText> copy_self( new IfcText() );
copy_self->m_value = m_value;
return copy_self;
}
void IfcText::getStepParameter( std::stringstream& stream, bool is_select_type ) const
{
if( is_select_type ) { stream << "IFCTEXT("; }
stream << "'" << encodeStepString( m_value ) << "'";
if( is_select_type ) { stream << ")"; }
}
shared_ptr<IfcText> IfcText::createObjectFromSTEP( const std::wstring& arg, const map_t<int,shared_ptr<IfcPPEntity> >& map )
{
// read TYPE
if( arg.compare( L"$" ) == 0 ) { return shared_ptr<IfcText>(); }
else if( arg.compare( L"*" ) == 0 ) { return shared_ptr<IfcText>(); }
shared_ptr<IfcText> type_object( new IfcText() );
readString( arg, type_object->m_value );
return type_object;
}
| [
"ifcquery@users.noreply.github.com"
] | ifcquery@users.noreply.github.com |
db56bcaa87d0dbc20a72203d8b05b813352eccc9 | 3f3c4602af10950d28c893c36e75879245d5faf7 | /A9/RadialForceField.cpp | 5404b3bf97dfae97390c424e3662837fa60598cd | [] | no_license | SuperVivian/computer_graphics_assignments | 7b164f12c6593463acd93eced6e478068a047b09 | b98cac60191ba51059601fb391fc536f082fc443 | refs/heads/master | 2021-02-04T10:14:02.310955 | 2020-02-28T01:53:32 | 2020-02-28T01:53:32 | 243,654,656 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 446 | cpp | #include "stdafx.h"
#include "RadialForceField.h"
RadialForceField::RadialForceField (float magnitude)
{
this->magnitude = magnitude;
}
Vec3f RadialForceField::getAcceleration (const Vec3f &position, float mass, float t)
{
//径向力场 加速度a=position*magnitude/m*(-1)
//将粒子拉向原点,力的大小和到原点的距离成正比
Vec3f force = position * magnitude;
force /= mass;
Vec3f a = force * -1.0f;
return a;
} | [
"1113679022@qq.com"
] | 1113679022@qq.com |
35d3a92f8adda057e8a9ebdb980da0d1531a9217 | 46c810a431d2a1616a09b55f5b5f202dc3907941 | /Plugins/StreetMap/Source/StreetMapImporting/OSMFile.h | f51adbd417baef92b6e415462251762778a557ee | [
"MIT",
"ODbL-1.0"
] | permissive | moenkhaus/UnrealLandscape | e06f83224522a1007857c430c4e3cda4d0f8a6be | 84b33921cf717ddb10cace5f62d5e7b36fc1823a | refs/heads/master | 2020-12-02T22:03:59.522633 | 2017-03-22T18:42:59 | 2017-03-22T18:42:59 | 231,140,085 | 0 | 0 | MIT | 2019-12-31T19:48:38 | 2019-12-31T19:48:37 | null | UTF-8 | C++ | false | false | 5,975 | h | // Copyright 2017 Mike Fricker. All Rights Reserved.
#pragma once
#include "FastXml.h"
/** OpenStreetMap file loader */
class FOSMFile : public IFastXmlCallback
{
public:
/** Default constructor for FOSMFile */
FOSMFile();
/** Destructor for FOSMFile */
virtual ~FOSMFile();
/** Loads the map from an OpenStreetMap XML file. Note that in the case of the file path containing the XML data, the string must be mutable for us to parse it quickly. */
bool LoadOpenStreetMapFile( FString& OSMFilePath, const bool bIsFilePathActuallyTextBuffer, class FFeedbackContext* FeedbackContext );
struct FOSMWayInfo;
/** Types of ways */
enum class EOSMWayType
{
///
/// ROADS
///
/** A restricted access major divided highway, normally with 2 or more running lanes plus emergency hard shoulder. Equivalent to the Freeway, Autobahn, etc. */
Motorway,
/** The link roads (sliproads/ramps) leading to/from a motorway from/to a motorway or lower class highway. Normally with the same motorway restrictions. */
Motorway_Link,
/** The most important roads in a country's system that aren't motorways. (Need not necessarily be a divided highway.) */
Trunk,
/** The link roads (sliproads/ramps) leading to/from a trunk road from/to a trunk road or lower class highway. */
Trunk_Link,
/** The next most important roads in a country's system. (Often link larger towns.) */
Primary,
/** The link roads (sliproads/ramps) leading to/from a primary road from/to a primary road or lower class highway. */
Primary_Link,
/** The next most important roads in a country's system. (Often link smaller towns and villages.) */
Secondary,
/** The link roads (sliproads/ramps) leading to/from a secondary road from/to a secondary road or lower class highway. */
Secondary_Link,
/** The next most important roads in a country's system. */
Tertiary,
/** The link roads (sliproads/ramps) leading to/from a tertiary road from/to a tertiary road or lower class highway. */
Tertiary_Link,
/** Roads which are primarily lined with and serve as an access to housing. */
Residential,
/** For access roads to, or within an industrial estate, camp site, business park, car park etc. */
Service,
/** The least most important through roads in a country's system, i.e. minor roads of a lower classification than tertiary, but which serve a purpose other than access to properties. */
Unclassified,
///
/// NON-ROADS
///
/** Residential streets where pedestrians have legal priority over cars, speeds are kept very low and where children are allowed to play on the street. */
Living_Street,
/** For roads used mainly/exclusively for pedestrians in shopping and some residential areas which may allow access by motorised vehicles only for very limited periods of the day. */
Pedestrian,
/** Roads for agricultural or forestry uses etc, often rough with unpaved/unsealed surfaces, that can be used only by off-road vehicles (4WD, tractors, ATVs, etc.) */
Track,
/** A busway where the vehicle guided by the way (though not a railway) and is not suitable for other traffic. */
Bus_Guideway,
/** A course or track for (motor) racing */
Raceway,
/** A road where the mapper is unable to ascertain the classification from the information available. */
Road,
///
/// PATHS
///
/** For designated footpaths; i.e., mainly/exclusively for pedestrians. This includes walking tracks and gravel paths. */
Footway,
/** For designated cycleways. */
Cycleway,
/** Paths normally used by horses */
Bridleway,
/** For flights of steps (stairs) on footways. */
Steps,
/** A non-specific path. */
Path,
///
/// LIFECYCLE
///
/** For planned roads, use with proposed=* and also proposed=* with a value of the proposed highway value. */
Proposed,
/** For roads under construction. */
Construction,
///
/// BUILDINGS
///
/** Default type of building. A general catch-all. */
Building,
///
/// UNSUPPORTED
///
/** Currently unrecognized type */
Other,
};
struct FOSMWayRef
{
// Way that we're referencing at this node
FOSMWayInfo* Way;
// Index of the node in the way's array of nodes
int32 NodeIndex;
};
struct FOSMNodeInfo
{
double Latitude;
double Longitude;
TArray<FOSMWayRef> WayRefs;
};
struct FOSMWayInfo
{
FString Name;
FString Ref;
TArray<FOSMNodeInfo*> Nodes;
EOSMWayType WayType;
double Height;
// If true, way is only traversable in the order the nodes are listed in the Nodes list
uint8 bIsOneWay : 1;
};
// Minimum latitude/longitude bounds
double MinLatitude = MAX_dbl;
double MinLongitude = MAX_dbl;
double MaxLatitude = -MAX_dbl;
double MaxLongitude = -MAX_dbl;
// Average Latitude (roughly the center of the map)
double AverageLatitude = 0.0;
double AverageLongitude = 0.0;
// All ways we've parsed
TArray<FOSMWayInfo*> Ways;
// Maps node IDs to info about each node
TMap<int64, FOSMNodeInfo*> NodeMap;
protected:
// IFastXmlCallback overrides
virtual bool ProcessXmlDeclaration( const TCHAR* ElementData, int32 XmlFileLineNumber ) override;
virtual bool ProcessComment( const TCHAR* Comment ) override;
virtual bool ProcessElement( const TCHAR* ElementName, const TCHAR* ElementData, int32 XmlFileLineNumber ) override;
virtual bool ProcessAttribute( const TCHAR* AttributeName, const TCHAR* AttributeValue ) override;
virtual bool ProcessClose( const TCHAR* Element ) override;
protected:
enum class ParsingState
{
Root,
Node,
Way,
Way_NodeRef,
Way_Tag
};
// Current state of parser
ParsingState ParsingState;
// ID of node that is currently being parsed
int64 CurrentNodeID;
// Node that is currently being parsed
FOSMNodeInfo* CurrentNodeInfo;
// Way that is currently being parsed
FOSMWayInfo* CurrentWayInfo;
// Current way's tag key string
const TCHAR* CurrentWayTagKey;
};
| [
"benjamin.neukom@gmail.com"
] | benjamin.neukom@gmail.com |
470762296581044b2e574447ac72a93f1a48ee93 | e60562720c8027ccfc07f6ab2c64dfe980daea53 | /src/CommandLineParser/CommandLineParser.cpp | 98fc7aec90e0597b98e40c6e084f546773c1f67c | [
"BSD-3-Clause"
] | permissive | sebastiandaberdaku/VoxMeshSurfOpenMP | 6a4696073be15ad41a1b4cd7c114bc08714473b5 | dc5c13a6b3cb3d1b47fa2a195635063b19bf73d7 | refs/heads/main | 2023-03-25T11:27:38.345119 | 2021-03-28T12:10:33 | 2021-03-28T12:10:33 | 352,317,124 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,228 | cpp | /*
* CommandLineParser.cpp
*
* Created on: Sep 6, 2014
* Author: sebastian
*/
#include "../utils/disclaimer.h"
#include "CommandLineParser.h"
#include "CustomValidators.h"
/**
* This method parses the input command line options.
* @param argc input argc reference, i.e. the first argument of the main method
* @param argv input argv reference, i.e. the second argument of the main method
*
* @return true if all arguments are parsed correctly, false otherwise.
*/
bool CommandLineParser::parseCommandLine(int const & argc,
char const * const argv[], float & solventRadius, float & resolution,
int & surface_type, string & inname, string & outname,
string & inname_radii, bool & hydrogen, bool & hetatm,
bool & normalize_pose, int & output_type, int & smoothing_iterations,
float & lambda, float & mu, bool & vertex_normals, bool & help,
bool & version, bool & license) {
//------------------------------- command line options --------------------------------------
stringstream ss;
ss << PROGRAM_NAME << " - version " << PROGRAM_VERSION << ". Usage";
options_description description(ss.str());
description.add_options()("help,h", "Display this help message.")
/*
* This token is used to specify the input filename. It is mandatory.
* The pqr command line token has no option name. The command line tokens which have
* no option name are called "positional options" in the program_options library.
*/
("pdb", value<input_PDB_filename>()->required(), "Input PDB or XYZR file.")
/*
* This token is used to specify the output filename.
*/
("output,o", value<filename>(), "Output filename. If not specified, the input filename (with no extension) will be used.")
/*
* This token is used to specify the input atom radii filename.
*/
("atom_radii", value<filename>(), "File containing the radius information of each atom. If not specified, the default CHARMM22 radius values will be used.")
/*
* This token is used to specify the output type.
*/
("output_type,t", value<out_type>()->default_value(6), "Output type (default is 6):\n1-Point Cloud Data file (*.pcd);\n2-OpenDX scalar data format (*.dx);\n3-Visualization Toolkit Structured Points (*.vtk);\n4-Visualization Toolkit PolyData (*.vtk);\n5-Surface mesh ASCII model (*.ply);\n6-Surface mesh binary model (*.ply).")
("surface_type,s", value<surf_type>()->default_value(3), "Surface type (default is 3):\n1-van der Waals;\n2-Solvent Accessible Surface;\n3-Solvent Excluded Surface.")
/*
* The -p (--probe_radius) flag is used to specify the probe radius. Default is 1.4. Optional.
*/
("probe_radius,p", value<probe_radius>()->default_value(1.4), "Solvent-probe radius (in Å), positive floating point number (default is 1.4).")
/*
* The -r (--resolution) flag is used to specify the resolution of the voxel grid. Default is 4. Optional.
*/
("resolution,r", value<resolution_param>()->default_value(2.0), "Resolution factor, positive floating point (default is 2.0). This value's cube determines the number of voxels per ų.")
("Laplacian_smoothing,L", value<num_iterations>()->default_value(5), "Number of Laplacian smoothing iterations on the output mesh (default is 1). If set to 0, no smoothing will be carried out on the surface mesh.")
("lambda", value<shrink_param>()->default_value(0.90), "lambda parameter in the Laplacian smoothing step (positive floating point, default is 0.90).")
("mu", value<inflate_param>()->default_value(-0.92), "mu parameter in the Laplacian smoothing step (negative floating point, default is -0.92).")
("no_vertex_normals", "Skip the vertex normals estimation step. The output mesh will not have smooth shading.")
/*
* The --hetatm flag is used to include HETATM records in the surface computation.
*/
("hetatm", "Include HETATM records in the surface computation (only for *.pdb input files, has no effect for *.xyzr files).")
/*
* The --hetatm flag is used to include HETATM records in the surface computation.
*/
("hydrogen", "Include hydrogen atoms in the surface computation (only for *.pdb input files, has no effect for *.xyzr files).\nNOTE: X-ray crystallography cannot resolve hydrogen atoms in most protein crystals, so in most PDB files, hydrogen atoms are absent. Sometimes hydrogens are added by modeling. Hydrogens are always present in PDB files resulting from NMR analysis, and are usually present in theoretical models.")
/*
* The --normalize_pose flag is used to run pose normalization on the molecule
* information.
*/
("no_pose_normalization", "By default, the three principal axes of the molecule are aligned with the three Cartesian axes in order to reduce the size of the voxel grid containing the molecule. If this option is set, no pose normalization will take place.")
/*
* The (--license) flag is used to view the program's license
* information.
*/
("license", "View license information.")
/*
* The -v (--version) flag is used to view the program's version
* information.
*/
("version,v", "Display the version number");
/*
* The input filename must be declared as positional.
*/
positional_options_description p;
p.add("pdb", 1);
variables_map vm;
try {
//--------------------------------parsing command line options------------------------------
/*
* And it is finally specified when parsing the command line.
*/
store(command_line_parser(argc, argv).options(description).positional(p).run(), vm);
if (vm.count("help")) {
cout << description;
help = true;
return true;
}
if (vm.count("version")) {
cout << "Program: " << argv[0] << ", version: " << PROGRAM_VERSION << "\n";
version = true;
return true;
}
if (vm.count("license")) {
DISCLAIMER
license = true;
return true;
}
if (vm.count("no_pose_normalization"))
normalize_pose = false;
else
normalize_pose = true;
if (vm.count("hetatm"))
hetatm = true;
else
hetatm = false;
if (vm.count("hydrogen"))
hydrogen = true;
else
hydrogen = false;
if (vm.count("no_vertex_normals"))
vertex_normals = false;
else
vertex_normals = true;
/*
* notify throws exceptions so we call it after the above checks
*/
notify(vm);
/* initializing variables */
inname = vm["pdb"].as<input_PDB_filename>().filename;
if (vm.count("output")) {
outname = vm["output"].as<filename>().fname;
} else {
int lastindex = inname.find_last_of(".");
outname = inname.substr(0, lastindex);
lastindex = outname.find_last_of("/");
outname = outname.substr(lastindex + 1);
}
if (vm.count("atom_radii")) {
inname_radii = vm["atom_radii"].as<filename>().fname;
} else {
inname_radii = "";
}
smoothing_iterations = vm["Laplacian_smoothing"].as<num_iterations>().iter;
lambda = vm["lambda"].as<shrink_param>().lambda;
mu = vm["mu"].as<inflate_param>().mu;
solventRadius = vm["probe_radius"].as<probe_radius>().p;
surface_type = vm["surface_type"].as<surf_type>().st;
resolution = vm["resolution"].as<resolution_param>().r;
output_type = vm["output_type"].as<out_type>().st;
} catch (error const & e) {
cerr << "error: " << e.what() << "\n";
cerr << description << "\n";
return false;
}
return true;
};
| [
"yye4468@infocert.it"
] | yye4468@infocert.it |
33fc6411b23e97fe527bb3766f2b9a1e729c2d80 | 3829c260c8a807da44309f60f9a76256ba15dd20 | /rgbled.cpp | 5d1711bcaecdcdd359861afc3cc74983aedafdd3 | [] | no_license | martinsv/arduino-rgbled | 9981eb9730f81639f8c0f3e6f2d0a4964327748a | 33cac49c863a106e8a69491fbb574bd6ce982ec6 | refs/heads/master | 2021-01-15T15:57:21.778271 | 2012-02-19T06:59:44 | 2012-02-19T06:59:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,879 | cpp | #if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include "rgbled.h"
static const uint16_t kDefaultDelay = 5; // milliseconds
RGBLED::RGBLED(const int red_pin, const int green_pin, const int blue_pin)
: red_pin_(red_pin),
green_pin_(green_pin),
blue_pin_(blue_pin),
red_value_(0),
green_value_(0),
blue_value_(0),
default_delay_(kDefaultDelay)
{
pinMode(red_pin, OUTPUT);
pinMode(green_pin, OUTPUT);
pinMode(blue_pin, OUTPUT);
}
RGBLED::Intensity RGBLED::channelIntensity(const Channel channel) const
{
switch (channel) {
case kBlue:
return blue_value_;
break;
case kGreen:
return green_value_;
break;
default:
case kRed:
return red_value_;
break;
}
}
void RGBLED::channelIntensityIs(const Channel channel, const Intensity value)
{
switch (channel) {
case kBlue:
analogWrite(blue_pin_, value);
blue_value_ = value;
break;
case kGreen:
analogWrite(green_pin_, value);
green_value_ = value;
break;
default:
case kRed:
analogWrite(red_pin_, value);
red_value_ = value;
break;
}
}
void RGBLED::colorIs(Intensity red, Intensity green, Intensity blue)
{
channelIntensityIs(kRed, red);
channelIntensityIs(kGreen, green);
channelIntensityIs(kBlue, blue);
}
void RGBLED::colorIs(uint32_t color)
{
Intensity red = (color & (0xFF0000)) >> 16;
Intensity green = (color & (0x00FF00)) >> 8;
Intensity blue = (color & (0x0000FF));
colorIs(red, green, blue);
}
void RGBLED::fadeChannel(const Channel channel,
const Intensity initial,
const Intensity final,
const uint16_t delay_ms)
{
uint8_t mask = channel;
fadeChannels(mask, initial, final, delay_ms);
}
void RGBLED::fadeChannels(const uint8_t channel_mask,
const Intensity initial,
const Intensity final,
uint16_t delay_ms)
{
delay_ms = (delay_ms == 0) ? defaultDelay() : delay_ms;
if (initial < final || initial == final) {
// Fade up.
for (Intensity i = initial; i < final; ++i) {
writeChannels(channel_mask, i);
delay(delay_ms);
}
} else {
// Fade down.
for (Intensity i = initial; i > final; --i) {
writeChannels(channel_mask, i);
delay(delay_ms);
}
}
// Support final = 255 or final = 0, where ++i/--i would have overflown.
delay(delay_ms);
writeChannels(channel_mask, final);
}
void RGBLED::writeChannels(const uint8_t channel_mask, const Intensity value)
{
if (channel_mask & kRed)
channelIntensityIs(kRed, value);
if (channel_mask & kGreen)
channelIntensityIs(kGreen, value);
if (channel_mask & kBlue)
channelIntensityIs(kBlue, value);
}
| [
"ms@quadpoint.org"
] | ms@quadpoint.org |
0b68a47a45741ddcf448927e99a6736d706ee966 | a93cf8f695c1d1d97b8d0b9ccec6932c5e499ff8 | /Beakjoon_pt1/Beakjoon_pt1/1546.cpp | d34f1486a1e9c38daeedf7b7fbe202eaf8ee2f7c | [] | no_license | tmdwns1101/AlgorithmStudy | 0abc108a7a73895934da2633998c7a90137d49ea | e8ca069e202f40e074b7311626fe8da8af057589 | refs/heads/master | 2021-07-22T11:32:30.817108 | 2020-05-20T16:28:27 | 2020-05-20T16:28:27 | 165,377,838 | 0 | 1 | null | 2020-02-07T07:56:16 | 2019-01-12T11:02:59 | C++ | UTF-8 | C++ | false | false | 452 | cpp | //#include<iostream>
//#include<vector>
//#pragma warning(disable : 4996)
//using namespace std;
//
//int main() {
//
// int n;
//
// cin >> n;
// vector<double> v(n);
//
//
// double max = 0;
// for (int i = 0; i < n; i++) {
// scanf("%lf", &v[i]);
// if (max < v[i]) max = v[i];
// }
// double ans = 0;
// double sum = 0;
// for (int i = 0; i < n; i++) {
// sum += ((v[i] / max) * 100);
// }
//
// ans = sum / n;
//
// cout << ans << endl;
//
//} | [
"tmdwns1101@naver.com"
] | tmdwns1101@naver.com |
48e5cc99c476bd1e233525d553967b989c8cdcf4 | 07d784d60aacc1872b19525e4de755378ba5fe9e | /EersteGraphicEngine/model/Road7.h | 9ac83b805295023ecf22fe6e1984d56e073d410b | [
"MIT"
] | permissive | fabsgc/EersteGraphicEngine | 0c9308a51d1b2b2e83f0f22da9950e75bdf5ee0b | 09d0da03dbe3a17a5da6651409f697a0db8634bd | refs/heads/master | 2021-04-29T15:47:30.391663 | 2018-09-24T14:13:48 | 2018-09-24T14:13:48 | 121,803,405 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | h | #pragma once
#include "PrerequisitesCore.h"
#include "Model.h"
namespace ege
{
class Road7 : public Model
{
public:
Road7();
~Road7();
void Initialise() override;
void Update();
};
} | [
"fabienbeaudimi@hotmail.fr"
] | fabienbeaudimi@hotmail.fr |
98ecb8076a3efb58139f0a1f751859e3914e5481 | b242a1f93c5324e23eafed5c4421f0f44ec8eaac | /FEM/element.cpp | aa3b30af770307370016c4222681055f1ad6c2e5 | [] | no_license | Czitels/FEM | ef7c75097f3b30a4c1951670d116005c4271ffa6 | f50a74185231ab14be63ffa5e1b3bb101cecb2c1 | refs/heads/master | 2020-04-07T05:37:15.765396 | 2019-03-05T14:41:31 | 2019-03-05T14:41:31 | 158,103,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,274 | cpp | #include <vector>
#include <cmath>
#include "element.h"
#include "universal_element.h"
Element::Element(std::array<unsigned int, 4> IDs) :ID(IDs) { H.resize(4); }
void Element::calculH(std::array<double,4> &cordsx, std::array<double,4> &cordsy)
{
Universal_element univ;
DbMtrx Jacobian;
std::vector<double> detJ;
DbMtrx JacMinusOne;
DbMtrx DerivX;
DbMtrx DerivY;
Jacobian.resize(4);
JacMinusOne.resize(4);
DerivX.resize(4);
DerivY.resize(4);
for (size_t i = 0; i < 4; i++)
{
double valueXEta = 0, valueYEta = 0;
double valueXKsi = 0, valueYKsi = 0;
for (size_t j = 0; j < 4; j++)
{
valueXEta += univ.DerivEta[j][i] * cordsx[j];
valueYEta += univ.DerivEta[j][i] * cordsy[j];
valueXKsi += univ.DerivKsi[j][i] * cordsx[j];
valueYKsi += univ.DerivKsi[j][i] * cordsy[j];
}
Jacobian[0].push_back(valueXEta);
Jacobian[1].push_back(valueYEta);
Jacobian[2].push_back(valueXKsi);
Jacobian[3].push_back(valueYKsi);
}
for (size_t i = 0; i < 4; i++)
{
double value = Jacobian[0][i] * Jacobian[3][i] - Jacobian[1][i] * Jacobian[2][i];
detJ.push_back(value);
}
calculC(detJ, univ);
calculHBC(cordsx, cordsy, univ);
for (size_t i = 0; i < 4; i++)
{
JacMinusOne[0].push_back(Jacobian[3][i] / detJ[i]);
JacMinusOne[1].push_back(-Jacobian[1][i] / detJ[i]);
JacMinusOne[2].push_back(-Jacobian[2][i] / detJ[i]);
JacMinusOne[3].push_back(Jacobian[0][i] / detJ[i]);
}
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
DerivX[i].push_back(JacMinusOne[0][i] * univ.DerivEta[j][i] + JacMinusOne[1][i] * univ.DerivKsi[j][i]);
DerivY[i].push_back(JacMinusOne[2][i] * univ.DerivEta[j][i] + JacMinusOne[3][i] * univ.DerivKsi[j][i]);
}
}
DbMtrx DerivXTransp1;
DbMtrx DerivXTransp2;
DbMtrx DerivXTransp3;
DbMtrx DerivXTransp4;
DbMtrx DerivYTransp1;
DbMtrx DerivYTransp2;
DbMtrx DerivYTransp3;
DbMtrx DerivYTransp4;
DerivXTransp1.resize(4);
DerivXTransp2.resize(4);
DerivXTransp3.resize(4);
DerivXTransp4.resize(4);
DerivYTransp1.resize(4);
DerivYTransp2.resize(4);
DerivYTransp3.resize(4);
DerivYTransp4.resize(4);
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
DerivXTransp1[i].push_back(DerivX[0][j] * DerivX[0][i]);
DerivXTransp2[i].push_back(DerivX[1][j] * DerivX[1][i]);
DerivXTransp3[i].push_back(DerivX[2][j] * DerivX[2][i]);
DerivXTransp4[i].push_back(DerivX[3][j] * DerivX[3][i]);
DerivYTransp1[i].push_back(DerivY[0][j] * DerivY[0][i]);
DerivYTransp2[i].push_back(DerivY[1][j] * DerivY[1][i]);
DerivYTransp3[i].push_back(DerivY[2][j] * DerivY[2][i]);
DerivYTransp4[i].push_back(DerivY[3][j] * DerivY[3][i]);
}
}
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
DerivXTransp1[i][j] *= detJ[0];
DerivXTransp2[i][j] *= detJ[1];
DerivXTransp3[i][j] *= detJ[2];
DerivXTransp4[i][j] *= detJ[3];
DerivYTransp1[i][j] *= detJ[0];
DerivYTransp2[i][j] *= detJ[1];
DerivYTransp3[i][j] *= detJ[2];
DerivYTransp4[i][j] *= detJ[3];
}
}
DbMtrx FinalP1;
DbMtrx FinalP2;
DbMtrx FinalP3;
DbMtrx FinalP4;
FinalP1.resize(4);
FinalP2.resize(4);
FinalP3.resize(4);
FinalP4.resize(4);
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
FinalP1[i].push_back(univ.k*(DerivXTransp1[i][j] + DerivYTransp1[i][j]));
FinalP2[i].push_back(univ.k*(DerivXTransp2[i][j] + DerivYTransp2[i][j]));
FinalP3[i].push_back(univ.k*(DerivXTransp3[i][j] + DerivYTransp3[i][j]));
FinalP4[i].push_back(univ.k*(DerivXTransp4[i][j] + DerivYTransp4[i][j]));
}
}
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
H[i].push_back(FinalP1[i][j] + FinalP2[i][j] + FinalP3[i][j] + FinalP4[i][j]+bcH[i][j]); // we sum points and add boundary conditions H
}
}
}
void Element::calculC(std::vector<double> &detJ, Universal_element &univ)
{
C.resize(4);
DbMtrx Point1;
DbMtrx Point2;
DbMtrx Point3;
DbMtrx Point4;
Point1.resize(4);
Point2.resize(4);
Point3.resize(4);
Point4.resize(4);
detJ = { 0.00027889,0.00027889,0.00027889,0.00027889 };
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
Point1[i].push_back(univ.Ni[j][0] * univ.Ni[i][0] * detJ[0] * univ.c * univ.ro);
Point2[i].push_back(univ.Ni[j][1] * univ.Ni[i][1] * detJ[1] * univ.c * univ.ro);
Point3[i].push_back(univ.Ni[j][2] * univ.Ni[i][2] * detJ[2] * univ.c * univ.ro);
Point4[i].push_back(univ.Ni[j][3] * univ.Ni[i][3] * detJ[3] * univ.c * univ.ro);
}
}
for (size_t i = 0; i < 4; i++)
{
for (size_t j = 0; j < 4; j++)
{
C[i].push_back(Point1[i][j] + Point2[i][j] + Point3[i][j] + Point4[i][j]);
}
}
}
void Element::calculHBC(std::array<double, 4> &cordsx, std::array<double, 4> &cordsy, Universal_element& univ)
{
P.resize(4);
bcH.resize(4);
for (size_t i = 0; i < 4; i++)
{
bcH[i].resize(4);
}
const double KSIPC1 = -1 / sqrt(3);
const double KSIPC2 = -KSIPC1;
double detJ, length;
std::vector<double> N1;
std::vector<double> N2;
N1.push_back(0.5 * (1.0 - KSIPC1));
N1.push_back(0.5 * (1.0 - KSIPC2));
N2.push_back(0.5 * (KSIPC1 + 1.0));
N2.push_back(0.5 * (KSIPC2 + 1.0));
DbMtrx sum;
DbMtrx boundP;
sum.resize(2);
sum[0].resize(2);
sum[1].resize(2);
boundP.resize(4);
for (auto &x:boundP)
{
x.resize(4);
}
for (size_t i = 0; i < 4; i++)
{
detJ = 0;
length = 0;
if (i != 3)
{
if (BC[i] == true && BC[i+1] == true)
{
double tmpx = cordsx[i + 1] - cordsx[i];
double tmpy = cordsy[i + 1] - cordsy[i];
length = sqrt(pow(tmpx,2) + pow(tmpy,2));
detJ = length / 2;
double pc1;
double pc2;
for (size_t j = 0; j < 2; j++)
{
for (size_t k = 0; k < 2; k++)
{
pc1 = N1[j] * N1[k] * univ.alfa;
pc2 = N2[j] * N2[k] * univ.alfa;
sum[j][k] = (pc1 + pc2)*detJ;
bcH[j + i][k + i] += sum[j][k];
}
}
P[i] += univ.tinf*(sum[0][0] + sum[1][0]);
P[i+1] += univ.tinf*(sum[0][1] + sum[1][1]);
}
}
else if(BC[i] == true && BC[0] == true)
{
double tmpx = cordsx[i] - cordsx[0];
double tmpy = cordsy[i] - cordsy[0];
length = sqrt(pow(tmpx, 2) + pow(tmpy, 2));
detJ = length / 2;
double pc1;
double pc2;
for (size_t j = 0; j < 2; j++)
{
for (size_t k = 0; k < 2; k++)
{
pc1 = N1[j] * N1[k] * univ.alfa;
pc2 = N2[j] * N2[k] * univ.alfa;
sum[j][k] = (pc1 + pc2)*detJ;
bcH[j * i][k * i] += sum[j][k]; // multiply, beacaouse we want to set corners of matrix
}
}
P[i] += univ.tinf*(sum[0][0] + sum[1][0]);
P[0] += univ.tinf*(sum[0][1] + sum[1][1]);
}
}
}
unsigned int Element::getID(unsigned int id)
{
return this->ID[id];
}
void Element::setBC(std::array<bool, 4> BC)
{
this->BC = BC;
}
std::vector<std::vector<double>>& Element::getMatrixH()
{
return H;
}
std::vector<std::vector<double>>& Element::getMatrixC()
{
return C;
}
std::vector<double>& Element::getvectorP()
{
return P;
}
std::array<unsigned int, 4>& Element::getArray()
{
return this->ID;
}
| [
"noreply@github.com"
] | Czitels.noreply@github.com |
7d68e03dbd59b9d3102ae74c68021e1761634f81 | 2fbf7b1459a51e92d728ab184a75575c6b50eee4 | /include/Popup.h | 22d9fd39075ea855de1500ebf52d1e51304ae566 | [] | no_license | swiftyjam/SpacePizza | 851a69a4064b5610846135b0073733f55b39dc3e | 67c2b34be51b57a50471f6d32fc7fe3953f7aba8 | refs/heads/master | 2022-01-17T08:14:09.470883 | 2019-05-22T08:11:49 | 2019-05-22T08:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 582 | h | #ifndef POPUP_H
#define POPUP_H
#include <iostream>
#include <vector>
#include <SFML/Graphics.hpp>
#include "SuperSprite.h"
class Popup
{
public:
Popup(string ruta, double life);
void setLife(double t);
SuperSprite* getSprite();
void setPosition(sf::Vector2f new_pos);
void drawPopup(sf::RenderWindow *w, double i);
void throwPopup();
virtual ~Popup();
protected:
private:
SuperSprite* popup;
sf::Clock popup_clock;
double popup_life;
bool alive;
sf::Vector2f pos;
};
#endif // POPUP_H
| [
"samjavaloyes96@gmail.com"
] | samjavaloyes96@gmail.com |
a5d429f4b067c25a62ee1ff247c777e57a5ba0bc | b33a9177edaaf6bf185ef20bf87d36eada719d4f | /qtbase/src/gui/math3d/qquaternion.cpp | 0e73f79ac0b43b3a557ba0573701264a7d16bc75 | [
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-commercial-license",
"LGPL-2.0-or-later",
"LGPL-2.1-only",
"GFDL-1.3-only",
"LicenseRef-scancode-qt-commercial-1.1",
"LGPL-3.0-only",
"LicenseRef-scancode-qt-company-exception-lgpl-2.1",
... | permissive | wgnet/wds_qt | ab8c093b8c6eead9adf4057d843e00f04915d987 | 8db722fd367d2d0744decf99ac7bafaba8b8a3d3 | refs/heads/master | 2021-04-02T11:07:10.181067 | 2020-06-02T10:29:03 | 2020-06-02T10:34:19 | 248,267,925 | 1 | 0 | Apache-2.0 | 2020-04-30T12:16:53 | 2020-03-18T15:20:38 | null | UTF-8 | C++ | false | false | 27,950 | cpp | /****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see http://www.qt.io/terms-conditions. For further
** information use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** As a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquaternion.h"
#include <QtCore/qdatastream.h>
#include <QtCore/qmath.h>
#include <QtCore/qvariant.h>
#include <QtCore/qdebug.h>
#include <cmath>
QT_BEGIN_NAMESPACE
#ifndef QT_NO_QUATERNION
/*!
\class QQuaternion
\brief The QQuaternion class represents a quaternion consisting of a vector and scalar.
\since 4.6
\ingroup painting-3D
\inmodule QtGui
Quaternions are used to represent rotations in 3D space, and
consist of a 3D rotation axis specified by the x, y, and z
coordinates, and a scalar representing the rotation angle.
*/
/*!
\fn QQuaternion::QQuaternion()
Constructs an identity quaternion (1, 0, 0, 0), i.e. with the vector (0, 0, 0)
and scalar 1.
*/
/*!
\fn QQuaternion::QQuaternion(Qt::Initialization)
\since 5.5
\internal
Constructs a quaternion without initializing the contents.
*/
/*!
\fn QQuaternion::QQuaternion(float scalar, float xpos, float ypos, float zpos)
Constructs a quaternion with the vector (\a xpos, \a ypos, \a zpos)
and \a scalar.
*/
#ifndef QT_NO_VECTOR3D
/*!
\fn QQuaternion::QQuaternion(float scalar, const QVector3D& vector)
Constructs a quaternion vector from the specified \a vector and
\a scalar.
\sa vector(), scalar()
*/
/*!
\fn QVector3D QQuaternion::vector() const
Returns the vector component of this quaternion.
\sa setVector(), scalar()
*/
/*!
\fn void QQuaternion::setVector(const QVector3D& vector)
Sets the vector component of this quaternion to \a vector.
\sa vector(), setScalar()
*/
#endif
/*!
\fn void QQuaternion::setVector(float x, float y, float z)
Sets the vector component of this quaternion to (\a x, \a y, \a z).
\sa vector(), setScalar()
*/
#ifndef QT_NO_VECTOR4D
/*!
\fn QQuaternion::QQuaternion(const QVector4D& vector)
Constructs a quaternion from the components of \a vector.
*/
/*!
\fn QVector4D QQuaternion::toVector4D() const
Returns this quaternion as a 4D vector.
*/
#endif
/*!
\fn bool QQuaternion::isNull() const
Returns \c true if the x, y, z, and scalar components of this
quaternion are set to 0.0; otherwise returns \c false.
*/
/*!
\fn bool QQuaternion::isIdentity() const
Returns \c true if the x, y, and z components of this
quaternion are set to 0.0, and the scalar component is set
to 1.0; otherwise returns \c false.
*/
/*!
\fn float QQuaternion::x() const
Returns the x coordinate of this quaternion's vector.
\sa setX(), y(), z(), scalar()
*/
/*!
\fn float QQuaternion::y() const
Returns the y coordinate of this quaternion's vector.
\sa setY(), x(), z(), scalar()
*/
/*!
\fn float QQuaternion::z() const
Returns the z coordinate of this quaternion's vector.
\sa setZ(), x(), y(), scalar()
*/
/*!
\fn float QQuaternion::scalar() const
Returns the scalar component of this quaternion.
\sa setScalar(), x(), y(), z()
*/
/*!
\fn void QQuaternion::setX(float x)
Sets the x coordinate of this quaternion's vector to the given
\a x coordinate.
\sa x(), setY(), setZ(), setScalar()
*/
/*!
\fn void QQuaternion::setY(float y)
Sets the y coordinate of this quaternion's vector to the given
\a y coordinate.
\sa y(), setX(), setZ(), setScalar()
*/
/*!
\fn void QQuaternion::setZ(float z)
Sets the z coordinate of this quaternion's vector to the given
\a z coordinate.
\sa z(), setX(), setY(), setScalar()
*/
/*!
\fn void QQuaternion::setScalar(float scalar)
Sets the scalar component of this quaternion to \a scalar.
\sa scalar(), setX(), setY(), setZ()
*/
/*!
\fn float QQuaternion::dotProduct(const QQuaternion &q1, const QQuaternion &q2)
\since 5.5
Returns the dot product of \a q1 and \a q2.
\sa length()
*/
/*!
Returns the length of the quaternion. This is also called the "norm".
\sa lengthSquared(), normalized(), dotProduct()
*/
float QQuaternion::length() const
{
return std::sqrt(xp * xp + yp * yp + zp * zp + wp * wp);
}
/*!
Returns the squared length of the quaternion.
\sa length(), dotProduct()
*/
float QQuaternion::lengthSquared() const
{
return xp * xp + yp * yp + zp * zp + wp * wp;
}
/*!
Returns the normalized unit form of this quaternion.
If this quaternion is null, then a null quaternion is returned.
If the length of the quaternion is very close to 1, then the quaternion
will be returned as-is. Otherwise the normalized form of the
quaternion of length 1 will be returned.
\sa normalize(), length(), dotProduct()
*/
QQuaternion QQuaternion::normalized() const
{
// Need some extra precision if the length is very small.
double len = double(xp) * double(xp) +
double(yp) * double(yp) +
double(zp) * double(zp) +
double(wp) * double(wp);
if (qFuzzyIsNull(len - 1.0f))
return *this;
else if (!qFuzzyIsNull(len))
return *this / std::sqrt(len);
else
return QQuaternion(0.0f, 0.0f, 0.0f, 0.0f);
}
/*!
Normalizes the current quaternion in place. Nothing happens if this
is a null quaternion or the length of the quaternion is very close to 1.
\sa length(), normalized()
*/
void QQuaternion::normalize()
{
// Need some extra precision if the length is very small.
double len = double(xp) * double(xp) +
double(yp) * double(yp) +
double(zp) * double(zp) +
double(wp) * double(wp);
if (qFuzzyIsNull(len - 1.0f) || qFuzzyIsNull(len))
return;
len = std::sqrt(len);
xp /= len;
yp /= len;
zp /= len;
wp /= len;
}
/*!
\fn QQuaternion QQuaternion::inverted() const
\since 5.5
Returns the inverse of this quaternion.
If this quaternion is null, then a null quaternion is returned.
\sa isNull(), length()
*/
/*!
\fn QQuaternion QQuaternion::conjugated() const
\since 5.5
Returns the conjugate of this quaternion, which is
(-x, -y, -z, scalar).
*/
/*!
\fn QQuaternion QQuaternion::conjugate() const
\obsolete
Use conjugated() instead.
*/
/*!
Rotates \a vector with this quaternion to produce a new vector
in 3D space. The following code:
\code
QVector3D result = q.rotatedVector(vector);
\endcode
is equivalent to the following:
\code
QVector3D result = (q * QQuaternion(0, vector) * q.conjugated()).vector();
\endcode
*/
QVector3D QQuaternion::rotatedVector(const QVector3D& vector) const
{
return (*this * QQuaternion(0, vector) * conjugated()).vector();
}
/*!
\fn QQuaternion &QQuaternion::operator+=(const QQuaternion &quaternion)
Adds the given \a quaternion to this quaternion and returns a reference to
this quaternion.
\sa operator-=()
*/
/*!
\fn QQuaternion &QQuaternion::operator-=(const QQuaternion &quaternion)
Subtracts the given \a quaternion from this quaternion and returns a
reference to this quaternion.
\sa operator+=()
*/
/*!
\fn QQuaternion &QQuaternion::operator*=(float factor)
Multiplies this quaternion's components by the given \a factor, and
returns a reference to this quaternion.
\sa operator/=()
*/
/*!
\fn QQuaternion &QQuaternion::operator*=(const QQuaternion &quaternion)
Multiplies this quaternion by \a quaternion and returns a reference
to this quaternion.
*/
/*!
\fn QQuaternion &QQuaternion::operator/=(float divisor)
Divides this quaternion's components by the given \a divisor, and
returns a reference to this quaternion.
\sa operator*=()
*/
#ifndef QT_NO_VECTOR3D
/*!
\fn void QQuaternion::getAxisAndAngle(QVector3D *axis, float *angle) const
\since 5.5
\overload
Extracts a 3D axis \a axis and a rotating angle \a angle (in degrees)
that corresponds to this quaternion.
\sa fromAxisAndAngle()
*/
/*!
Creates a normalized quaternion that corresponds to rotating through
\a angle degrees about the specified 3D \a axis.
\sa getAxisAndAngle()
*/
QQuaternion QQuaternion::fromAxisAndAngle(const QVector3D& axis, float angle)
{
// Algorithm from:
// http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q56
// We normalize the result just in case the values are close
// to zero, as suggested in the above FAQ.
float a = (angle / 2.0f) * M_PI / 180.0f;
float s = std::sin(a);
float c = std::cos(a);
QVector3D ax = axis.normalized();
return QQuaternion(c, ax.x() * s, ax.y() * s, ax.z() * s).normalized();
}
#endif
/*!
\since 5.5
Extracts a 3D axis (\a x, \a y, \a z) and a rotating angle \a angle (in degrees)
that corresponds to this quaternion.
\sa fromAxisAndAngle()
*/
void QQuaternion::getAxisAndAngle(float *x, float *y, float *z, float *angle) const
{
Q_ASSERT(x && y && z && angle);
// The quaternion representing the rotation is
// q = cos(A/2)+sin(A/2)*(x*i+y*j+z*k)
float length = xp * xp + yp * yp + zp * zp;
if (!qFuzzyIsNull(length)) {
*x = xp;
*y = yp;
*z = zp;
if (!qFuzzyIsNull(length - 1.0f)) {
length = std::sqrt(length);
*x /= length;
*y /= length;
*z /= length;
}
*angle = 2.0f * std::acos(wp);
} else {
// angle is 0 (mod 2*pi), so any axis will fit
*x = *y = *z = *angle = 0.0f;
}
*angle = qRadiansToDegrees(*angle);
}
/*!
Creates a normalized quaternion that corresponds to rotating through
\a angle degrees about the 3D axis (\a x, \a y, \a z).
\sa getAxisAndAngle()
*/
QQuaternion QQuaternion::fromAxisAndAngle
(float x, float y, float z, float angle)
{
float length = std::sqrt(x * x + y * y + z * z);
if (!qFuzzyIsNull(length - 1.0f) && !qFuzzyIsNull(length)) {
x /= length;
y /= length;
z /= length;
}
float a = (angle / 2.0f) * M_PI / 180.0f;
float s = std::sin(a);
float c = std::cos(a);
return QQuaternion(c, x * s, y * s, z * s).normalized();
}
#ifndef QT_NO_VECTOR3D
/*!
\fn QVector3D QQuaternion::toEulerAngles() const
\since 5.5
\overload
Calculates roll, pitch, and yaw Euler angles (in degrees)
that corresponds to this quaternion.
\sa fromEulerAngles()
*/
/*!
\fn QQuaternion QQuaternion::fromEulerAngles(const QVector3D &eulerAngles)
\since 5.5
\overload
Creates a quaternion that corresponds to a rotation of \a eulerAngles:
eulerAngles.z() degrees around the z axis, eulerAngles.x() degrees around the x axis,
and eulerAngles.y() degrees around the y axis (in that order).
\sa toEulerAngles()
*/
#endif // QT_NO_VECTOR3D
/*!
\since 5.5
Calculates \a roll, \a pitch, and \a yaw Euler angles (in degrees)
that corresponds to this quaternion.
\sa fromEulerAngles()
*/
void QQuaternion::getEulerAngles(float *pitch, float *yaw, float *roll) const
{
Q_ASSERT(pitch && yaw && roll);
// Algorithm from:
// http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q37
float xx = xp * xp;
float xy = xp * yp;
float xz = xp * zp;
float xw = xp * wp;
float yy = yp * yp;
float yz = yp * zp;
float yw = yp * wp;
float zz = zp * zp;
float zw = zp * wp;
const float lengthSquared = xx + yy + zz + wp * wp;
if (!qFuzzyIsNull(lengthSquared - 1.0f) && !qFuzzyIsNull(lengthSquared)) {
xx /= lengthSquared;
xy /= lengthSquared; // same as (xp / length) * (yp / length)
xz /= lengthSquared;
xw /= lengthSquared;
yy /= lengthSquared;
yz /= lengthSquared;
yw /= lengthSquared;
zz /= lengthSquared;
zw /= lengthSquared;
}
*pitch = std::asin(-2.0f * (yz - xw));
if (*pitch < M_PI_2) {
if (*pitch > -M_PI_2) {
*yaw = std::atan2(2.0f * (xz + yw), 1.0f - 2.0f * (xx + yy));
*roll = std::atan2(2.0f * (xy + zw), 1.0f - 2.0f * (xx + zz));
} else {
// not a unique solution
*roll = 0.0f;
*yaw = -std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz));
}
} else {
// not a unique solution
*roll = 0.0f;
*yaw = std::atan2(-2.0f * (xy - zw), 1.0f - 2.0f * (yy + zz));
}
*pitch = qRadiansToDegrees(*pitch);
*yaw = qRadiansToDegrees(*yaw);
*roll = qRadiansToDegrees(*roll);
}
/*!
\since 5.5
Creates a quaternion that corresponds to a rotation of
\a roll degrees around the z axis, \a pitch degrees around the x axis,
and \a yaw degrees around the y axis (in that order).
\sa getEulerAngles()
*/
QQuaternion QQuaternion::fromEulerAngles(float pitch, float yaw, float roll)
{
// Algorithm from:
// http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q60
pitch = qDegreesToRadians(pitch);
yaw = qDegreesToRadians(yaw);
roll = qDegreesToRadians(roll);
pitch *= 0.5f;
yaw *= 0.5f;
roll *= 0.5f;
const float c1 = std::cos(yaw);
const float s1 = std::sin(yaw);
const float c2 = std::cos(roll);
const float s2 = std::sin(roll);
const float c3 = std::cos(pitch);
const float s3 = std::sin(pitch);
const float c1c2 = c1 * c2;
const float s1s2 = s1 * s2;
const float w = c1c2 * c3 + s1s2 * s3;
const float x = c1c2 * s3 + s1s2 * c3;
const float y = s1 * c2 * c3 - c1 * s2 * s3;
const float z = c1 * s2 * c3 - s1 * c2 * s3;
return QQuaternion(w, x, y, z);
}
/*!
\since 5.5
Creates a rotation matrix that corresponds to this quaternion.
\note If this quaternion is not normalized,
the resulting rotation matrix will contain scaling information.
\sa fromRotationMatrix(), getAxes()
*/
QMatrix3x3 QQuaternion::toRotationMatrix() const
{
// Algorithm from:
// http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q54
QMatrix3x3 rot3x3(Qt::Uninitialized);
const float f2x = xp + xp;
const float f2y = yp + yp;
const float f2z = zp + zp;
const float f2xw = f2x * wp;
const float f2yw = f2y * wp;
const float f2zw = f2z * wp;
const float f2xx = f2x * xp;
const float f2xy = f2x * yp;
const float f2xz = f2x * zp;
const float f2yy = f2y * yp;
const float f2yz = f2y * zp;
const float f2zz = f2z * zp;
rot3x3(0, 0) = 1.0f - (f2yy + f2zz);
rot3x3(0, 1) = f2xy - f2zw;
rot3x3(0, 2) = f2xz + f2yw;
rot3x3(1, 0) = f2xy + f2zw;
rot3x3(1, 1) = 1.0f - (f2xx + f2zz);
rot3x3(1, 2) = f2yz - f2xw;
rot3x3(2, 0) = f2xz - f2yw;
rot3x3(2, 1) = f2yz + f2xw;
rot3x3(2, 2) = 1.0f - (f2xx + f2yy);
return rot3x3;
}
/*!
\since 5.5
Creates a quaternion that corresponds to a rotation matrix \a rot3x3.
\note If a given rotation matrix is not normalized,
the resulting quaternion will contain scaling information.
\sa toRotationMatrix(), fromAxes()
*/
QQuaternion QQuaternion::fromRotationMatrix(const QMatrix3x3 &rot3x3)
{
// Algorithm from:
// http://www.j3d.org/matrix_faq/matrfaq_latest.html#Q55
float scalar;
float axis[3];
const float trace = rot3x3(0, 0) + rot3x3(1, 1) + rot3x3(2, 2);
if (trace > 0.00000001f) {
const float s = 2.0f * std::sqrt(trace + 1.0f);
scalar = 0.25f * s;
axis[0] = (rot3x3(2, 1) - rot3x3(1, 2)) / s;
axis[1] = (rot3x3(0, 2) - rot3x3(2, 0)) / s;
axis[2] = (rot3x3(1, 0) - rot3x3(0, 1)) / s;
} else {
static int s_next[3] = { 1, 2, 0 };
int i = 0;
if (rot3x3(1, 1) > rot3x3(0, 0))
i = 1;
if (rot3x3(2, 2) > rot3x3(i, i))
i = 2;
int j = s_next[i];
int k = s_next[j];
const float s = 2.0f * std::sqrt(rot3x3(i, i) - rot3x3(j, j) - rot3x3(k, k) + 1.0f);
axis[i] = 0.25f * s;
scalar = (rot3x3(k, j) - rot3x3(j, k)) / s;
axis[j] = (rot3x3(j, i) + rot3x3(i, j)) / s;
axis[k] = (rot3x3(k, i) + rot3x3(i, k)) / s;
}
return QQuaternion(scalar, axis[0], axis[1], axis[2]);
}
#ifndef QT_NO_VECTOR3D
/*!
\since 5.5
Returns the 3 orthonormal axes (\a xAxis, \a yAxis, \a zAxis) defining the quaternion.
\sa fromAxes(), toRotationMatrix()
*/
void QQuaternion::getAxes(QVector3D *xAxis, QVector3D *yAxis, QVector3D *zAxis) const
{
Q_ASSERT(xAxis && yAxis && zAxis);
const QMatrix3x3 rot3x3(toRotationMatrix());
*xAxis = QVector3D(rot3x3(0, 0), rot3x3(1, 0), rot3x3(2, 0));
*yAxis = QVector3D(rot3x3(0, 1), rot3x3(1, 1), rot3x3(2, 1));
*zAxis = QVector3D(rot3x3(0, 2), rot3x3(1, 2), rot3x3(2, 2));
}
/*!
\since 5.5
Constructs the quaternion using 3 axes (\a xAxis, \a yAxis, \a zAxis).
\note The axes are assumed to be orthonormal.
\sa getAxes(), fromRotationMatrix()
*/
QQuaternion QQuaternion::fromAxes(const QVector3D &xAxis, const QVector3D &yAxis, const QVector3D &zAxis)
{
QMatrix3x3 rot3x3(Qt::Uninitialized);
rot3x3(0, 0) = xAxis.x();
rot3x3(1, 0) = xAxis.y();
rot3x3(2, 0) = xAxis.z();
rot3x3(0, 1) = yAxis.x();
rot3x3(1, 1) = yAxis.y();
rot3x3(2, 1) = yAxis.z();
rot3x3(0, 2) = zAxis.x();
rot3x3(1, 2) = zAxis.y();
rot3x3(2, 2) = zAxis.z();
return QQuaternion::fromRotationMatrix(rot3x3);
}
/*!
\since 5.5
Constructs the quaternion using specified forward direction \a direction
and upward direction \a up.
If the upward direction was not specified or the forward and upward
vectors are collinear, a new orthonormal upward direction will be generated.
\sa fromAxes(), rotationTo()
*/
QQuaternion QQuaternion::fromDirection(const QVector3D &direction, const QVector3D &up)
{
if (qFuzzyIsNull(direction.x()) && qFuzzyIsNull(direction.y()) && qFuzzyIsNull(direction.z()))
return QQuaternion();
const QVector3D zAxis(direction.normalized());
QVector3D xAxis(QVector3D::crossProduct(up, zAxis));
if (qFuzzyIsNull(xAxis.lengthSquared())) {
// collinear or invalid up vector; derive shortest arc to new direction
return QQuaternion::rotationTo(QVector3D(0.0f, 0.0f, 1.0f), zAxis);
}
xAxis.normalize();
const QVector3D yAxis(QVector3D::crossProduct(zAxis, xAxis));
return QQuaternion::fromAxes(xAxis, yAxis, zAxis);
}
/*!
\since 5.5
Returns the shortest arc quaternion to rotate from the direction described by the vector \a from
to the direction described by the vector \a to.
\sa fromDirection()
*/
QQuaternion QQuaternion::rotationTo(const QVector3D &from, const QVector3D &to)
{
// Based on Stan Melax's article in Game Programming Gems
const QVector3D v0(from.normalized());
const QVector3D v1(to.normalized());
float d = QVector3D::dotProduct(v0, v1) + 1.0f;
// if dest vector is close to the inverse of source vector, ANY axis of rotation is valid
if (qFuzzyIsNull(d)) {
QVector3D axis = QVector3D::crossProduct(QVector3D(1.0f, 0.0f, 0.0f), v0);
if (qFuzzyIsNull(axis.lengthSquared()))
axis = QVector3D::crossProduct(QVector3D(0.0f, 1.0f, 0.0f), v0);
axis.normalize();
// same as QQuaternion::fromAxisAndAngle(axis, 180.0f)
return QQuaternion(0.0f, axis.x(), axis.y(), axis.z());
}
d = std::sqrt(2.0f * d);
const QVector3D axis(QVector3D::crossProduct(v0, v1) / d);
return QQuaternion(d * 0.5f, axis).normalized();
}
#endif // QT_NO_VECTOR3D
/*!
\fn bool operator==(const QQuaternion &q1, const QQuaternion &q2)
\relates QQuaternion
Returns \c true if \a q1 is equal to \a q2; otherwise returns \c false.
This operator uses an exact floating-point comparison.
*/
/*!
\fn bool operator!=(const QQuaternion &q1, const QQuaternion &q2)
\relates QQuaternion
Returns \c true if \a q1 is not equal to \a q2; otherwise returns \c false.
This operator uses an exact floating-point comparison.
*/
/*!
\fn const QQuaternion operator+(const QQuaternion &q1, const QQuaternion &q2)
\relates QQuaternion
Returns a QQuaternion object that is the sum of the given quaternions,
\a q1 and \a q2; each component is added separately.
\sa QQuaternion::operator+=()
*/
/*!
\fn const QQuaternion operator-(const QQuaternion &q1, const QQuaternion &q2)
\relates QQuaternion
Returns a QQuaternion object that is formed by subtracting
\a q2 from \a q1; each component is subtracted separately.
\sa QQuaternion::operator-=()
*/
/*!
\fn const QQuaternion operator*(float factor, const QQuaternion &quaternion)
\relates QQuaternion
Returns a copy of the given \a quaternion, multiplied by the
given \a factor.
\sa QQuaternion::operator*=()
*/
/*!
\fn const QQuaternion operator*(const QQuaternion &quaternion, float factor)
\relates QQuaternion
Returns a copy of the given \a quaternion, multiplied by the
given \a factor.
\sa QQuaternion::operator*=()
*/
/*!
\fn const QQuaternion operator*(const QQuaternion &q1, const QQuaternion& q2)
\relates QQuaternion
Multiplies \a q1 and \a q2 using quaternion multiplication.
The result corresponds to applying both of the rotations specified
by \a q1 and \a q2.
\sa QQuaternion::operator*=()
*/
/*!
\fn const QQuaternion operator-(const QQuaternion &quaternion)
\relates QQuaternion
\overload
Returns a QQuaternion object that is formed by changing the sign of
all three components of the given \a quaternion.
Equivalent to \c {QQuaternion(0,0,0,0) - quaternion}.
*/
/*!
\fn const QQuaternion operator/(const QQuaternion &quaternion, float divisor)
\relates QQuaternion
Returns the QQuaternion object formed by dividing all components of
the given \a quaternion by the given \a divisor.
\sa QQuaternion::operator/=()
*/
#ifndef QT_NO_VECTOR3D
/*!
\fn QVector3D operator*(const QQuaternion &quaternion, const QVector3D &vec)
\since 5.5
\relates QQuaternion
Rotates a vector \a vec with a quaternion \a quaternion to produce a new vector in 3D space.
*/
#endif
/*!
\fn bool qFuzzyCompare(const QQuaternion& q1, const QQuaternion& q2)
\relates QQuaternion
Returns \c true if \a q1 and \a q2 are equal, allowing for a small
fuzziness factor for floating-point comparisons; false otherwise.
*/
/*!
Interpolates along the shortest spherical path between the
rotational positions \a q1 and \a q2. The value \a t should
be between 0 and 1, indicating the spherical distance to travel
between \a q1 and \a q2.
If \a t is less than or equal to 0, then \a q1 will be returned.
If \a t is greater than or equal to 1, then \a q2 will be returned.
\sa nlerp()
*/
QQuaternion QQuaternion::slerp
(const QQuaternion& q1, const QQuaternion& q2, float t)
{
// Handle the easy cases first.
if (t <= 0.0f)
return q1;
else if (t >= 1.0f)
return q2;
// Determine the angle between the two quaternions.
QQuaternion q2b(q2);
float dot = QQuaternion::dotProduct(q1, q2);
if (dot < 0.0f) {
q2b = -q2b;
dot = -dot;
}
// Get the scale factors. If they are too small,
// then revert to simple linear interpolation.
float factor1 = 1.0f - t;
float factor2 = t;
if ((1.0f - dot) > 0.0000001) {
float angle = std::acos(dot);
float sinOfAngle = std::sin(angle);
if (sinOfAngle > 0.0000001) {
factor1 = std::sin((1.0f - t) * angle) / sinOfAngle;
factor2 = std::sin(t * angle) / sinOfAngle;
}
}
// Construct the result quaternion.
return q1 * factor1 + q2b * factor2;
}
/*!
Interpolates along the shortest linear path between the rotational
positions \a q1 and \a q2. The value \a t should be between 0 and 1,
indicating the distance to travel between \a q1 and \a q2.
The result will be normalized().
If \a t is less than or equal to 0, then \a q1 will be returned.
If \a t is greater than or equal to 1, then \a q2 will be returned.
The nlerp() function is typically faster than slerp() and will
give approximate results to spherical interpolation that are
good enough for some applications.
\sa slerp()
*/
QQuaternion QQuaternion::nlerp
(const QQuaternion& q1, const QQuaternion& q2, float t)
{
// Handle the easy cases first.
if (t <= 0.0f)
return q1;
else if (t >= 1.0f)
return q2;
// Determine the angle between the two quaternions.
QQuaternion q2b(q2);
float dot = QQuaternion::dotProduct(q1, q2);
if (dot < 0.0f)
q2b = -q2b;
// Perform the linear interpolation.
return (q1 * (1.0f - t) + q2b * t).normalized();
}
/*!
Returns the quaternion as a QVariant.
*/
QQuaternion::operator QVariant() const
{
return QVariant(QVariant::Quaternion, this);
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QQuaternion &q)
{
QDebugStateSaver saver(dbg);
dbg.nospace() << "QQuaternion(scalar:" << q.scalar()
<< ", vector:(" << q.x() << ", "
<< q.y() << ", " << q.z() << "))";
return dbg;
}
#endif
#ifndef QT_NO_DATASTREAM
/*!
\fn QDataStream &operator<<(QDataStream &stream, const QQuaternion &quaternion)
\relates QQuaternion
Writes the given \a quaternion to the given \a stream and returns a
reference to the stream.
\sa {Serializing Qt Data Types}
*/
QDataStream &operator<<(QDataStream &stream, const QQuaternion &quaternion)
{
stream << quaternion.scalar() << quaternion.x()
<< quaternion.y() << quaternion.z();
return stream;
}
/*!
\fn QDataStream &operator>>(QDataStream &stream, QQuaternion &quaternion)
\relates QQuaternion
Reads a quaternion from the given \a stream into the given \a quaternion
and returns a reference to the stream.
\sa {Serializing Qt Data Types}
*/
QDataStream &operator>>(QDataStream &stream, QQuaternion &quaternion)
{
float scalar, x, y, z;
stream >> scalar;
stream >> x;
stream >> y;
stream >> z;
quaternion.setScalar(scalar);
quaternion.setX(x);
quaternion.setY(y);
quaternion.setZ(z);
return stream;
}
#endif // QT_NO_DATASTREAM
#endif
QT_END_NAMESPACE
| [
"p_pavlov@wargaming.net"
] | p_pavlov@wargaming.net |
a0ba93b6d154aeeed5004f1a67984007618d3026 | 7ea45377de05a91d447687c53e1a836cfaec4b11 | /forces_code/con276/a.cpp | 4a28b73066ff054a29e0670bac9811a3f122b9b1 | [] | no_license | saikrishna17394/Code | d2b71efe5e3e932824339149008c3ea33dff6acb | 1213f951233a502ae6ecf2df337f340d8d65d498 | refs/heads/master | 2020-05-19T14:16:49.037709 | 2017-01-26T17:17:13 | 2017-01-26T17:17:13 | 24,478,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | #include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <set>
#include <stack>
#include <vector>
#include <map>
#include <list>
#include <queue>
#define lli long long int
#define ii pair<int,int>
#define mod 1000000007
#define inf 999999999
#define lim 10000000
using namespace std;
lli len(lli n) {
lli ret=0;
while(n>0) {
ret++;
n/=2;
}
return ret;
}
lli solve(lli l,lli r) {
if(l==r)
return l;
if(l==0)
l++;
if(len(l)!=len(r)) {
lli ret=0;
lli val=len(r);
for(lli i=0;i<val;i++) {
ret*=2;
ret++;
}
if(ret==r)
return ret;
ret/=2;
return ret;
}
lli ret=1;
lli val=len(l);
for(lli i=1;i<val;i++)
ret*=2;
return ret+solve(l%ret,r%ret);
}
int main() {
lli n,l,r;
cin>>n;
while(n--) {
cin>>l>>r;
if(l==r) {
cout<<l<<endl;
continue;
}
if(l==0)
l++;
cout<<solve(l,r)<<endl;
}
return 0;
} | [
"saikrishna17394@gmail.com"
] | saikrishna17394@gmail.com |
ecf15a404143582ce437f0a19fd8e103565d5be0 | e51c1e02da0bd145308a8fb12ce372010afb7966 | /leetcode/21.合并两个有序链表.cpp | 12f67286c48082a55205e8e4e642331bbe0f7325 | [] | no_license | XU-zzy/zzy_win10 | 0ad945b29686049b0d3586b355a55134eab208d6 | 05d0cb1645562fe317592b90e11e88cab4f3923a | refs/heads/master | 2023-08-11T15:36:15.081440 | 2021-09-18T13:15:11 | 2021-09-18T13:15:11 | 369,444,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,543 | cpp | /*
* @lc app=leetcode.cn id=21 lang=cpp
*
* [21] 合并两个有序链表
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == nullptr) {
return l2;
} else if (l2 == nullptr) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
};
// class Solution {
// public:
// ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
// ListNode* preHead = new ListNode(-1);
// ListNode* prev = preHead;
// while (l1 != nullptr && l2 != nullptr) {
// if (l1->val < l2->val) {
// prev->next = l1;
// l1 = l1->next;
// } else {
// prev->next = l2;
// l2 = l2->next;
// }
// prev = prev->next;
// }
// // 合并后 l1 和 l2 最多只有一个还未被合并完,我们直接将链表末尾指向未合并完的链表即可
// prev->next = l1 == nullptr ? l2 : l1;
// return preHead->next;
// }
// };
// @lc code=end
| [
"1245215743@qq.com"
] | 1245215743@qq.com |
4076b134a165784f2f6f03167f6b8281cdbfe64f | 659d99d090479506b63b374831a049dba5d70fcf | /xray-svn-trunk/xr_3da/xrGame/EffectorFall.h | 5fbb62e1bb3f8a396fcf7c5a51ac247c4af67e72 | [] | no_license | ssijonson/Rengen_Luch | a9312fed06dd08c7de19f36e5fd5e476881beb85 | 9bd0ff54408a890d4bdac1c493d67ce26b964555 | refs/heads/main | 2023-05-03T13:09:58.983176 | 2021-05-19T10:04:47 | 2021-05-19T10:04:47 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 447 | h | #pragma once
#include "../Effector.h"
// приседание после падения
class CEffectorFall : public CEffectorCam
{
float fPower;
float fPhase;
public:
CEffectorFall (float power, float life_time=1);
virtual BOOL ProcessCam (SCamEffectorInfo& info);
};
class CEffectorDOF : public CEffectorCam
{
float m_fPhase;
public:
CEffectorDOF (const Fvector4& dof);
virtual BOOL ProcessCam (SCamEffectorInfo& info);
};
| [
"16670637+KRodinn@users.noreply.github.com"
] | 16670637+KRodinn@users.noreply.github.com |
ce1bb89a0db2cb94d5b3898006415f108ce33744 | 0fabf14823f3c0d963368e0672c64fc9aca2bead | /pro/Graduate/panels/panelnoise.cpp | 2a9155cc15d76d2908e2e71fc2698524de747481 | [] | no_license | zhoutl1106/graduate | f4272925693570e18b0e697ba8f9b5b14a2410f2 | 000d252385433d29ec02f966416ba725b835863d | refs/heads/master | 2016-09-09T19:26:00.136458 | 2014-06-14T06:15:07 | 2014-06-14T06:15:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,093 | cpp | #include "panelnoise.h"
#include "ui_panelnoise.h"
PanelNoise::PanelNoise(QWidget *parent) :
QWidget(parent),
ui(new Ui::PanelNoise)
{
ui->setupUi(this);
m_keyboardFreqLow = new Keyboard();
m_keyboardFreqLow->setWindowTitle("Keyboard of Freqency Low");
m_keyboardFreqHigh = new Keyboard();
m_keyboardFreqHigh->setWindowTitle("Keyboard of Freqency High");
m_keyboardAmp = new Keyboard();
m_keyboardAmp->setWindowTitle("Keyboard of Amplify");
m_keyboardN = new Keyboard();
m_keyboardN->setWindowTitle("Keyboard of Orders");
connect(m_keyboardFreqLow,SIGNAL(finishEdit(int)),ui->spinFreqLow,SLOT(setValue(int)));
connect(m_keyboardFreqHigh,SIGNAL(finishEdit(int)),ui->spinFreqHigh,SLOT(setValue(int)));
connect(m_keyboardAmp,SIGNAL(finishEdit(int)),ui->spinAmp,SLOT(setValue(int)));
connect(m_keyboardN,SIGNAL(finishEdit(int)),ui->spinN,SLOT(setValue(int)));
}
PanelNoise::~PanelNoise()
{
delete ui;
}
double PanelNoise::getAmp()
{
return ui->spinAmp->value();
}
double PanelNoise::getFreqLow()
{
return ui->spinFreqLow->value();
}
double PanelNoise::getFreqHigh()
{
return ui->spinFreqHigh->value();
}
int PanelNoise::getN()
{
return ui->spinN->value();
}
int PanelNoise::getWindow()
{
return ui->comboBoxWindow->currentIndex()+1;
}
void PanelNoise::on_toolButtonFreqLow_clicked()
{
m_keyboardFreqLow->show();
}
void PanelNoise::on_toolButtonFreqHigh_clicked()
{
m_keyboardFreqHigh->show();
}
void PanelNoise::on_toolButtonAmp_clicked()
{
m_keyboardAmp->show();
}
void PanelNoise::on_toolButtonN_clicked()
{
m_keyboardN->show();
}
void PanelNoise::on_spinFreqLow_valueChanged(int arg1)
{
emit parametersChanged();
}
void PanelNoise::on_spinFreqHigh_valueChanged(int arg1)
{
emit parametersChanged();
}
void PanelNoise::on_spinAmp_valueChanged(int arg1)
{
emit parametersChanged();
}
void PanelNoise::on_spinN_valueChanged(int arg1)
{
emit parametersChanged();
}
void PanelNoise::on_comboBoxWindow_currentIndexChanged(int index)
{
emit parametersChanged();
}
| [
"arm2440@arm2440-VirtualBox.(none)"
] | arm2440@arm2440-VirtualBox.(none) |
54a2fcdb20a6bf1b23c976604f8129a1397776f4 | 043226adf84531a160bb816f0926382f3e3f4a5c | /PizzaAbstractFactory/chicago_pizza_ingredient_factory.cc | d0a6e787a6c297c2c8108feb12db6eff6ec6c2f6 | [] | no_license | Akhil-Dalwadi/CPP | 14ddba738bc39e771523a5d498be712d034db592 | 1f8030a39b6e7d9ed3038aee91d16be33c1af971 | refs/heads/master | 2022-02-16T10:56:40.302269 | 2018-10-19T16:40:23 | 2018-10-19T16:40:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cc | #include "chicago_pizza_ingredient_factory.h"
#include "black_olives.h"
#include "egg_plant.h"
#include "frozen_clams.h"
#include "spinach.h"
#include "sliced_pepperoni.h"
#include "thick_crust_dough.h"
#include "plum_tomato_sauce.h"
#include "mozzarella_cheese.h"
std::unique_ptr<Dough>
ChicagoPizzaIngredientFactory::CreateDough() {
return std::make_unique<ThickCrustDough>();
}
std::unique_ptr<Sauce>
ChicagoPizzaIngredientFactory::CreateSauce() {
return std::make_unique<PlumTomatoSauce>();
}
std::unique_ptr<Cheese>
ChicagoPizzaIngredientFactory::CreateCheese() {
return std::make_unique<MozzarellaCheese>();
}
std::unique_ptr<std::vector<std::unique_ptr<Veggies>>>
ChicagoPizzaIngredientFactory::CreateVeggies() {
std::unique_ptr<std::vector<std::unique_ptr<Veggies>>> veggies =
std::make_unique<std::vector<std::unique_ptr<Veggies>>>();
veggies->push_back(std::make_unique<BlackOlives>());
veggies->push_back(std::make_unique<Spinach>());
veggies->push_back(std::make_unique<EggPlant>());
return veggies;
}
std::unique_ptr<Pepperoni>
ChicagoPizzaIngredientFactory::CreatePepperoni() {
return std::make_unique<SlicedPepperoni>();
}
std::unique_ptr<Clams>
ChicagoPizzaIngredientFactory::CreateClam() {
return std::make_unique<FrozenClams>();
} | [
"nguyen_bn@hotmail.com"
] | nguyen_bn@hotmail.com |
38f9013d8d02dad05977fd8c0a08c56cf27d928d | 35b432d3a4254c3c206c92097d7cb86b02270448 | /VirtualConstructorsAndFactories/WhendoesAnObjectgetItstype2.cpp | 0a1218663302947b3ab8e7d9eea54943f6bd06e4 | [] | no_license | AlexWuDDD/DesignModel | d14859d13c5c77ed765351568f97c25f3e753882 | a12a376885c68c9ac0eb1dd88ec148c300211284 | refs/heads/master | 2020-11-26T17:34:55.337536 | 2020-01-23T14:28:46 | 2020-01-23T14:28:46 | 229,159,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 649 | cpp | //
// Created by Wu Alex on 2020/1/6.
//
#include <iostream>
class A{
public:
A(){ whoami();};
virtual ~A(){ whoami();}
virtual void whoami() const{
std::cout << "A::whoami" << std::endl;
}
};
class B : public A{
public:
B(){ whoami();};
~B(){ whoami();}
virtual void whoami() const{
std::cout << "B::whoami" << std::endl;
}
};
class C : public B{
public:
C(){ whoami();};
~C(){ whoami();}
virtual void whoami() const{
std::cout << "C::whoami" << std::endl;
}
};
int main(){
// C c;
// c.whoami();
// return 0;
C* c = new C;
c->whoami();
delete c;
} | [
"wkjworking@outlook.com"
] | wkjworking@outlook.com |
9cc18efac82c675538e801d6cfbf775cd310e147 | 2a0fee7a6f566843c6d533bc1f7b621c7e3b3400 | /third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.cc | c0228aafc028fd19f5d3e5e016be1ebd296f9d3b | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"MIT",
"Apache-2.0"
] | permissive | amitsadaphule/chromium | f53b022c12d196281c55e41e44d46ff9eadf0e56 | 074114ff0d3f24fc078684526b2682f03aba0b93 | refs/heads/master | 2022-11-22T22:10:09.177669 | 2019-06-16T12:14:29 | 2019-06-16T12:14:29 | 282,966,085 | 0 | 0 | BSD-3-Clause | 2020-07-27T17:19:52 | 2020-07-27T17:19:51 | null | UTF-8 | C++ | false | false | 9,845 | cc | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_text_track_list_element.h"
#include "third_party/blink/renderer/core/dom/events/event.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/html/forms/html_input_element.h"
#include "third_party/blink/renderer/core/html/forms/html_label_element.h"
#include "third_party/blink/renderer/core/html/html_span_element.h"
#include "third_party/blink/renderer/core/html/media/html_media_element.h"
#include "third_party/blink/renderer/core/html/track/text_track.h"
#include "third_party/blink/renderer/core/html/track/text_track_list.h"
#include "third_party/blink/renderer/core/input_type_names.h"
#include "third_party/blink/renderer/modules/media_controls/elements/media_control_toggle_closed_captions_button_element.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_impl.h"
#include "third_party/blink/renderer/modules/media_controls/media_controls_text_track_manager.h"
#include "third_party/blink/renderer/platform/heap/heap.h"
#include "third_party/blink/renderer/platform/text/platform_locale.h"
namespace blink {
namespace {
// When specified as trackIndex, disable text tracks.
constexpr int kTrackIndexOffValue = -1;
const QualifiedName& TrackIndexAttrName() {
// Save the track index in an attribute to avoid holding a pointer to the text
// track.
DEFINE_STATIC_LOCAL(QualifiedName, track_index_attr,
(g_null_atom, "data-track-index", g_null_atom));
return track_index_attr;
}
bool HasDuplicateLabel(TextTrack* current_track) {
DCHECK(current_track);
TextTrackList* track_list = current_track->TrackList();
// The runtime of this method is quadratic but since there are usually very
// few text tracks it won't affect the performance much.
String current_track_label = current_track->label();
for (unsigned i = 0; i < track_list->length(); i++) {
TextTrack* track = track_list->AnonymousIndexedGetter(i);
if (current_track != track && current_track_label == track->label())
return true;
}
return false;
}
} // anonymous namespace
MediaControlTextTrackListElement::MediaControlTextTrackListElement(
MediaControlsImpl& media_controls)
: MediaControlPopupMenuElement(media_controls) {
setAttribute(html_names::kRoleAttr, "menu");
setAttribute(html_names::kAriaLabelAttr,
WTF::AtomicString(GetLocale().QueryString(
WebLocalizedString::kOverflowMenuCaptionsSubmenuTitle)));
SetShadowPseudoId(AtomicString("-internal-media-controls-text-track-list"));
}
bool MediaControlTextTrackListElement::WillRespondToMouseClickEvents() {
return true;
}
void MediaControlTextTrackListElement::SetIsWanted(bool wanted) {
if (wanted)
RefreshTextTrackListMenu();
if (!wanted && !GetMediaControls().OverflowMenuIsWanted())
GetMediaControls().CloseOverflowMenu();
MediaControlPopupMenuElement::SetIsWanted(wanted);
}
void MediaControlTextTrackListElement::DefaultEventHandler(Event& event) {
if (event.type() == event_type_names::kClick) {
// This handles the back button click. Clicking on a menu item triggers the
// change event instead.
GetMediaControls().ToggleOverflowMenu();
event.SetDefaultHandled();
} else if (event.type() == event_type_names::kChange) {
// Identify which input element was selected and set track to showing
Node* target = event.target()->ToNode();
if (!target || !target->IsElementNode())
return;
GetMediaControls().GetTextTrackManager().DisableShowingTextTracks();
int track_index =
ToElement(target)->GetIntegralAttribute(TrackIndexAttrName());
if (track_index != kTrackIndexOffValue) {
DCHECK_GE(track_index, 0);
GetMediaControls().GetTextTrackManager().ShowTextTrackAtIndex(
track_index);
MediaElement().DisableAutomaticTextTrackSelection();
}
// Close the text track list,
// since we don't support selecting multiple tracks
SetIsWanted(false);
event.SetDefaultHandled();
}
MediaControlPopupMenuElement::DefaultEventHandler(event);
}
// TextTrack parameter when passed in as a nullptr, creates the "Off" list item
// in the track list.
Element* MediaControlTextTrackListElement::CreateTextTrackListItem(
TextTrack* track) {
int track_index = track ? track->TrackIndex() : kTrackIndexOffValue;
auto* track_item = MakeGarbageCollected<HTMLLabelElement>(GetDocument());
track_item->SetShadowPseudoId(
AtomicString("-internal-media-controls-text-track-list-item"));
auto* track_item_input = MakeGarbageCollected<HTMLInputElement>(
GetDocument(), CreateElementFlags());
track_item_input->SetShadowPseudoId(
AtomicString("-internal-media-controls-text-track-list-item-input"));
track_item_input->setAttribute(html_names::kAriaHiddenAttr, "true");
track_item_input->setType(input_type_names::kCheckbox);
track_item_input->SetIntegralAttribute(TrackIndexAttrName(), track_index);
if (!MediaElement().TextTracksVisible()) {
if (!track) {
track_item_input->setChecked(true);
track_item->setAttribute(html_names::kAriaCheckedAttr, "true");
}
} else {
// If there are multiple text tracks set to showing, they must all have
// checkmarks displayed.
if (track && track->mode() == TextTrack::ShowingKeyword()) {
track_item_input->setChecked(true);
track_item->setAttribute(html_names::kAriaCheckedAttr, "true");
} else {
track_item->setAttribute(html_names::kAriaCheckedAttr, "false");
}
}
// Allows to focus the list entry instead of the button.
track_item->setTabIndex(0);
track_item_input->setTabIndex(-1);
// Set track label into an aria-hidden span so that aria will not repeat the
// contents twice.
String track_label =
GetMediaControls().GetTextTrackManager().GetTextTrackLabel(track);
auto* track_label_span = MakeGarbageCollected<HTMLSpanElement>(GetDocument());
track_label_span->setInnerText(track_label, ASSERT_NO_EXCEPTION);
track_label_span->setAttribute(html_names::kAriaHiddenAttr, "true");
track_item->setAttribute(html_names::kAriaLabelAttr,
WTF::AtomicString(track_label));
track_item->ParserAppendChild(track_label_span);
track_item->ParserAppendChild(track_item_input);
// Add a track kind marker icon if there are multiple tracks with the same
// label or if the track has no label.
if (track && (track->label().IsEmpty() || HasDuplicateLabel(track))) {
auto* track_kind_marker =
MakeGarbageCollected<HTMLSpanElement>(GetDocument());
if (track->kind() == track->CaptionsKeyword()) {
track_kind_marker->SetShadowPseudoId(AtomicString(
"-internal-media-controls-text-track-list-kind-captions"));
} else {
DCHECK_EQ(track->kind(), track->SubtitlesKeyword());
track_kind_marker->SetShadowPseudoId(AtomicString(
"-internal-media-controls-text-track-list-kind-subtitles"));
}
track_item->ParserAppendChild(track_kind_marker);
}
return track_item;
}
Element* MediaControlTextTrackListElement::CreateTextTrackHeaderItem() {
auto* header_item = MakeGarbageCollected<HTMLLabelElement>(GetDocument());
header_item->SetShadowPseudoId(
"-internal-media-controls-text-track-list-header");
header_item->ParserAppendChild(
Text::Create(GetDocument(),
GetLocale().QueryString(
WebLocalizedString::kOverflowMenuCaptionsSubmenuTitle)));
header_item->setAttribute(html_names::kRoleAttr, "button");
header_item->setAttribute(
html_names::kAriaLabelAttr,
AtomicString(GetLocale().QueryString(
WebLocalizedString::kAXMediaHideClosedCaptionsMenuButton)));
header_item->setTabIndex(0);
return header_item;
}
void MediaControlTextTrackListElement::RefreshTextTrackListMenu() {
if (!MediaElement().HasClosedCaptions() ||
!MediaElement().TextTracksAreReady()) {
return;
}
EventDispatchForbiddenScope::AllowUserAgentEvents allow_events;
RemoveChildren(kOmitSubtreeModifiedEvent);
ParserAppendChild(CreateTextTrackHeaderItem());
TextTrackList* track_list = MediaElement().textTracks();
// Construct a menu for subtitles and captions. Pass in a nullptr to
// createTextTrackListItem to create the "Off" track item.
auto* off_track = CreateTextTrackListItem(nullptr);
off_track->setAttribute(html_names::kAriaSetsizeAttr,
WTF::AtomicString::Number(track_list->length() + 1));
off_track->setAttribute(html_names::kAriaPosinsetAttr,
WTF::AtomicString::Number(1));
off_track->setAttribute(html_names::kRoleAttr, "menuitemcheckbox");
ParserAppendChild(off_track);
for (unsigned i = 0; i < track_list->length(); i++) {
TextTrack* track = track_list->AnonymousIndexedGetter(i);
if (!track->CanBeRendered())
continue;
auto* track_item = CreateTextTrackListItem(track);
track_item->setAttribute(
html_names::kAriaSetsizeAttr,
WTF::AtomicString::Number(track_list->length() + 1));
// We set the position with an offset of 2 because we want to start the
// count at 1 (versus 0), and the "Off" track item holds the first position
// and isnt included in this loop.
track_item->setAttribute(html_names::kAriaPosinsetAttr,
WTF::AtomicString::Number(i + 2));
track_item->setAttribute(html_names::kRoleAttr, "menuitemcheckbox");
ParserAppendChild(track_item);
}
}
} // namespace blink
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
df9fffb27bc9935913c75d579080544b0247ec01 | 042dd77f1c0adad08117a507aaa9b0f39ad72d6b | /案例55-长方体图像纹理映射算法/Face.h | 1ecd2f4f07211af9f52cc35c6a9a296e6e14cbac | [] | no_license | daoxiaochuan/Computer_graphics | c3af8b3cb28fd0c22a2a73fd0488525e9f36f73d | 70a04d7c528dd681691424521fc528622e64aa41 | refs/heads/master | 2023-08-05T09:07:02.361578 | 2019-09-11T02:31:20 | 2019-09-11T02:31:20 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 769 | h | // Face.h: interface for the CFace class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_FACE_H__82BF93AE_A82E_407D_AF42_6E6608253C1C__INCLUDED_)
#define AFX_FACE_H__82BF93AE_A82E_407D_AF42_6E6608253C1C__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "T2.h"
#include "Vector.h"
class CFace
{
public:
CFace();
virtual ~CFace();
void SetNum(int);//设置小面的顶点数
void SetFaceNormal(CP3,CP3,CP3);//设置小面法矢量
public:
int vN; //小面的顶点数
int *vI; //小面的顶点索引
CVector fNormal; //小面的法矢量
CT2 *t; //纹理顶点动态数组
};
#endif // !defined(AFX_FACE_H__82BF93AE_A82E_407D_AF42_6E6608253C1C__INCLUDED_)
| [
"2907805535@qq.com"
] | 2907805535@qq.com |
9d0e8917faaa2a25b00e4e942ab36044cf3be9a3 | 70615fa8f43c903f59b81337386e9e73c4a0c3cd | /chrome/browser/apps/app_service/extension_apps.h | 8ff0acaeb3c601340961cc25f9d9b6a371d05006 | [
"BSD-3-Clause"
] | permissive | MinghuiGao/chromium | 28e05be8cafe828da6b2a4b74d46d2fbb357d25b | 7c79100d7f3124e2702a4d4586442912e161df7e | refs/heads/master | 2023-03-03T00:47:05.735666 | 2019-12-03T15:35:35 | 2019-12-03T15:35:35 | 225,664,287 | 1 | 0 | BSD-3-Clause | 2019-12-03T16:18:56 | 2019-12-03T16:18:55 | null | UTF-8 | C++ | false | false | 10,261 | h | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_APPS_APP_SERVICE_EXTENSION_APPS_H_
#define CHROME_BROWSER_APPS_APP_SERVICE_EXTENSION_APPS_H_
#include <string>
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/scoped_observer.h"
#include "chrome/browser/apps/app_service/app_icon_factory.h"
#include "chrome/browser/apps/app_service/icon_key_util.h"
#include "chrome/browser/ui/app_list/arc/arc_app_list_prefs.h"
#include "chrome/services/app_service/public/cpp/instance.h"
#include "chrome/services/app_service/public/cpp/instance_registry.h"
#include "chrome/services/app_service/public/mojom/app_service.mojom.h"
#include "components/content_settings/core/browser/content_settings_observer.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/prefs/pref_change_registrar.h"
#include "extensions/browser/app_window/app_window_registry.h"
#include "extensions/browser/extension_prefs.h"
#include "extensions/browser/extension_prefs_observer.h"
#include "extensions/browser/extension_registry.h"
#include "extensions/browser/extension_registry_observer.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "mojo/public/cpp/bindings/remote_set.h"
class Profile;
namespace extensions {
class AppWindow;
class ExtensionSet;
}
namespace apps {
class ExtensionAppsEnableFlow;
// An app publisher (in the App Service sense) of extension-backed apps,
// including Chrome Apps (platform apps and legacy packaged apps) and hosted
// apps (including desktop PWAs).
//
// In the future, desktop PWAs will be migrated to a new system.
//
// See chrome/services/app_service/README.md.
class ExtensionApps : public apps::mojom::Publisher,
public extensions::AppWindowRegistry::Observer,
public extensions::ExtensionPrefsObserver,
public extensions::ExtensionRegistryObserver,
public content_settings::Observer,
public ArcAppListPrefs::Observer {
public:
// Record uninstall dialog action for Web apps and Chrome apps.
static void RecordUninstallCanceledAction(Profile* profile,
const std::string& app_id);
static bool ShowPauseAppDialog(const std::string& app_id);
ExtensionApps(const mojo::Remote<apps::mojom::AppService>& app_service,
Profile* profile,
apps::mojom::AppType app_type,
apps::InstanceRegistry* instance_registry);
~ExtensionApps() override;
void FlushMojoCallsForTesting();
void Shutdown();
void ObserveArc();
private:
void Initialize(const mojo::Remote<apps::mojom::AppService>& app_service);
// Determines whether the given extension should be treated as type app_type_,
// and should therefore by handled by this publisher.
bool Accepts(const extensions::Extension* extension);
// apps::mojom::Publisher overrides.
void Connect(mojo::PendingRemote<apps::mojom::Subscriber> subscriber_remote,
apps::mojom::ConnectOptionsPtr opts) override;
void LoadIcon(const std::string& app_id,
apps::mojom::IconKeyPtr icon_key,
apps::mojom::IconCompression icon_compression,
int32_t size_hint_in_dip,
bool allow_placeholder_icon,
LoadIconCallback callback) override;
void Launch(const std::string& app_id,
int32_t event_flags,
apps::mojom::LaunchSource launch_source,
int64_t display_id) override;
void LaunchAppWithIntent(const std::string& app_id,
apps::mojom::IntentPtr intent,
apps::mojom::LaunchSource launch_source,
int64_t display_id) override;
void SetPermission(const std::string& app_id,
apps::mojom::PermissionPtr permission) override;
void PromptUninstall(const std::string& app_id) override;
void Uninstall(const std::string& app_id,
bool clear_site_data,
bool report_abuse) override;
void PauseApp(const std::string& app_id) override;
void UnpauseApps(const std::string& app_id) override;
void OpenNativeSettings(const std::string& app_id) override;
void OnPreferredAppSet(const std::string& app_id,
apps::mojom::IntentFilterPtr intent_filter,
apps::mojom::IntentPtr intent) override;
// content_settings::Observer overrides.
void OnContentSettingChanged(const ContentSettingsPattern& primary_pattern,
const ContentSettingsPattern& secondary_pattern,
ContentSettingsType content_type,
const std::string& resource_identifier) override;
// Overridden from AppWindowRegistry::Observer:
void OnAppWindowAdded(extensions::AppWindow* app_window) override;
void OnAppWindowShown(extensions::AppWindow* app_window,
bool was_hidden) override;
// extensions::ExtensionPrefsObserver overrides.
void OnExtensionLastLaunchTimeChanged(
const std::string& app_id,
const base::Time& last_launch_time) override;
void OnExtensionPrefsWillBeDestroyed(
extensions::ExtensionPrefs* prefs) override;
// extensions::ExtensionRegistryObserver overrides.
void OnExtensionLoaded(content::BrowserContext* browser_context,
const extensions::Extension* extension) override;
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UnloadedExtensionReason reason) override;
void OnExtensionInstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
bool is_update) override;
void OnExtensionUninstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UninstallReason reason) override;
// ArcAppListPrefs::Observer overrides.
void OnPackageInstalled(
const arc::mojom::ArcPackageInfo& package_info) override;
void OnPackageRemoved(const std::string& package_name,
bool uninstalled) override;
void OnPackageListInitialRefreshed() override;
void OnArcAppListPrefsDestroyed() override;
void Publish(apps::mojom::AppPtr app);
// Checks if extension is disabled and if enable flow should be started.
// Returns true if extension enable flow is started or there is already one
// running.
bool RunExtensionEnableFlow(const std::string& app_id,
int32_t event_flags,
apps::mojom::LaunchSource launch_source,
int64_t display_id);
static bool IsBlacklisted(const std::string& app_id);
static void SetShowInFields(apps::mojom::AppPtr& app,
const extensions::Extension* extension,
Profile* profile);
static bool ShouldShow(const extensions::Extension* extension,
Profile* profile);
// Handles profile prefs kHideWebStoreIcon changes.
void OnHideWebStoreIconPrefChanged();
// Update the show_in_xxx fields for the App structure.
void UpdateShowInFields(const std::string& app_id);
void PopulatePermissions(const extensions::Extension* extension,
std::vector<mojom::PermissionPtr>* target);
void PopulateIntentFilters(const base::Optional<GURL>& app_scope,
std::vector<mojom::IntentFilterPtr>* target);
apps::mojom::AppPtr Convert(const extensions::Extension* extension,
apps::mojom::Readiness readiness);
void ConvertVector(const extensions::ExtensionSet& extensions,
apps::mojom::Readiness readiness,
std::vector<apps::mojom::AppPtr>* apps_out);
// Calculate the icon effects for the extension.
IconEffects GetIconEffects(const extensions::Extension* extension);
// Get the equivalent Chrome app from |arc_package_name| and set the Chrome
// app badge on the icon effects for the equivalent Chrome apps. If the
// equivalent ARC app is installed, add the Chrome app badge, otherwise,
// remove the Chrome app badge.
void ApplyChromeBadge(const std::string& arc_package_name);
void SetIconEffect(const std::string& app_id);
void RegisterInstance(extensions::AppWindow* app_window, InstanceState state);
mojo::Receiver<apps::mojom::Publisher> receiver_{this};
mojo::RemoteSet<apps::mojom::Subscriber> subscribers_;
Profile* profile_;
ScopedObserver<extensions::ExtensionPrefs, extensions::ExtensionPrefsObserver>
prefs_observer_{this};
ScopedObserver<extensions::ExtensionRegistry,
extensions::ExtensionRegistryObserver>
registry_observer_{this};
ScopedObserver<HostContentSettingsMap, content_settings::Observer>
content_settings_observer_{this};
apps_util::IncrementingIconKeyFactory icon_key_factory_;
apps::mojom::AppType app_type_;
apps::InstanceRegistry* instance_registry_;
ScopedObserver<extensions::AppWindowRegistry,
extensions::AppWindowRegistry::Observer>
app_window_registry_{this};
using EnableFlowPtr = std::unique_ptr<ExtensionAppsEnableFlow>;
std::map<std::string, EnableFlowPtr> enable_flow_map_;
std::set<std::string> paused_apps_;
ArcAppListPrefs* arc_prefs_ = nullptr;
// app_service_ is owned by the object that owns this object.
apps::mojom::AppService* app_service_;
// Registrar used to monitor the profile prefs.
PrefChangeRegistrar profile_pref_change_registrar_;
base::WeakPtrFactory<ExtensionApps> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(ExtensionApps);
};
} // namespace apps
#endif // CHROME_BROWSER_APPS_APP_SERVICE_EXTENSION_APPS_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
3de788052829ef71ece4c8004c70de690abcec5c | 501bd46a5aa0ffebdeb55392351328b646cf4276 | /TextureSynthesis/Tiler.cpp | da561585a3d5c2b2099e75f4fedd203c34e5ed4f | [] | no_license | ialhashim/extend-mesh | f5a68d257ed5d6356a10cb8728b7910395725f37 | 2d4a0ba14332116b2c67dc7b59ce4cebd62fd076 | refs/heads/master | 2021-01-10T20:22:48.908517 | 2015-03-13T18:32:03 | 2015-03-13T18:32:03 | 32,124,922 | 9 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,308 | cpp | #include "Tiler.h"
Tiler::Tiler(const MatrixXf & src, int bandSize, int tileCount)
{
src_img = src;
band_size = Min(bandSize, src.cols() - 1);
tile_count = Max(1, tileCount); // at least one
is_done = false;
}
MatrixXi Tiler::tileAsPos()
{
MatrixXf square_diff, weighted_square_diff;
MatrixXf weight = LeftWeight(src_img.rows(), band_size);
MatrixXf L = src_img;
MatrixXi Li = NumberedMatrix(src_img.rows(), src_img.cols());
// Final result for tiles as positions
Vector<MatrixXi> texture;
texture.reserve(tile_count);
// last tile result
MatrixXi result;
for(int i = 0; i < tile_count; i++)
{
int l_rows = L.rows(), l_cols = L.cols();
int bandStart = l_cols - band_size;
square_diff = (fromRight(L, band_size) - fromLeft(src_img, band_size)).array().square();
//weighted_square_diff = square_diff;
weighted_square_diff = square_diff.array() * weight.array();
//float total_cost = (weighted_square_diff).sum();
MatrixXi mask = cut_mask(weighted_square_diff);
// Identity = all zeros
result = MatrixXi::Zero(l_rows, l_cols + (src_img.cols() - band_size));
// Copy positions to result
for(int y = 0; y < result.rows(); y++){
int mask_x = 0;
for(int x = 0; x < result.cols(); x++){
if(x < bandStart)
{
result.coeffRef(y,x) = Li.coeffRef(y,x);
}
else
{
if(mask_x < mask.cols() && !mask(y, mask_x++))
result.coeffRef(y,x) = Li.coeffRef(y, x);
else
result.coeffRef(y,x) = Li.coeffRef(y, (x - (l_cols -band_size)) % l_cols);
}
}
}
// Split into two parts, Texture part:
texture.push_back(result.topLeftCorner(l_rows, l_cols - band_size));
// New input part
Li = result.topRightCorner(l_rows, l_cols);
L = FromPositionMatrix(src_img, Li);
}
// Last part
texture.push_back(result.topRightCorner( src_img.rows(), src_img.cols()));
int rows = src_img.rows();
int cols = texture[0].cols();
// compute actual target column count
int target_cols = 0;
for(size_t i = 0; i < texture.size(); i++) target_cols += texture[i].cols();
// Create target pos matrix
MatrixXi target = MatrixXi::Ones(rows, target_cols);
for(size_t i = 0; i < texture.size(); i++)
target.block(0, i * cols, rows, texture[i].cols()) = texture[i];
return target;
}
MatrixXi Tiler::stitchAsPos(const MatrixXi & left_img, const MatrixXi & right_img, const MatrixXi & mask)
{
MatrixXi invMask = InverseMask(mask);
MatrixXi leftImg = left_img;
MatrixXi rightImg = right_img;
leftImg.topRightCorner(leftImg.rows(), mask.cols()) = leftImg.topRightCorner( leftImg.rows(), invMask.cols()).array() * invMask.array();
rightImg.block(0,0, rightImg.rows(), mask.cols()) = rightImg.topLeftCorner(rightImg.rows(), mask.cols()).array() * mask.array();
MatrixXi result = MatrixXi::Zero(left_img.rows(), left_img.cols() + (right_img.cols() - mask.cols()));
result.block(0,0,leftImg.rows(), leftImg.cols()) = leftImg;
result.block(0,leftImg.cols() - mask.cols(), leftImg.rows(), rightImg.cols()) += rightImg;
return result;
}
MatrixXi Tiler::cut_mask(const MatrixXf & costMatrix)
{
Graph<int, float> g;
StdMap<Point, int> node;
StdMap<int, Point> point;
int rows = costMatrix.rows();
int cols = costMatrix.cols();
// Register nodes
for(int y = 0; y < rows; y++){
for(int x = 0; x < cols; x++){
point[node.size()] = Point(x,y);
node[Point(x,y)] = node.size();
}
}
// Connect with costs
for(int y = 0; y < rows; y++){
for(int x = 0; x < cols; x++){
Point p1 = Point( x , y );
Point p2 = Point( x + 1 , y );
Point p3 = Point( x , y + 1 );
if(node.find(p2) != node.end()){
float cost = costMatrix(p1.y, p1.x) + costMatrix(p2.y, p2.x);
g.AddEdge(node[p1], node[p2], cost);
}
if(node.find(p3) != node.end()){
float cost = costMatrix(p1.y, p1.x) + costMatrix(p3.y, p3.x);
g.AddEdge(node[p1], node[p3], cost);
}
}
}
int start = node.size();
int end = start + 1;
// Connect start and end nodes to graph
for(int i = 0; i < cols; i++)
{
g.AddEdge(start, node[Point(i, 0)], 0);
g.AddEdge(end, node[Point(i, rows - 1)], 0);
}
// Get shortest path
std::list<int> path = g.DijkstraShortestPath(start, end);
// Create full mask and set path nodes to zero
MatrixXi mask = MatrixXi::Ones(rows, cols);
for(std::list<int>::iterator i = path.begin(); i != path.end(); i++)
{
Point p = point[*i];
mask.coeffRef(p.y, p.x) = 0;
}
// fill in the rest of the mask, row by row
for(int i = 0; i < rows; i++)
{
fillMask(0, i, mask); // vertical (left)
}
/*for(int i = 0; i < cols; i++)
{
fillMask(i, 0, mask); // horiz (top)
fillMask(i, rows - 1, mask); // horiz (bottom)
}*/
return mask;
}
void Tiler::fillMask(int x, int y, MatrixXi & m)
{
if(x >= 0 && x < m.cols() && y >= 0 && y < m.rows() && m(y,x) == 1)
{
m.coeffRef(y,x) = 0;
fillMask(x + 1, y, m);
fillMask(x - 1, y, m);
fillMask(x, y + 1, m);
fillMask(x, y - 1, m);
}
}
MatrixXf Tiler::getTarget()
{
return target_img;
}
MatrixXf Tiler::getSource()
{
return src_img;
}
bool Tiler::isDone()
{
return is_done;
}
| [
"ennetws@49f7b1b1-d3fc-9bea-4e79-022a69d0483f"
] | ennetws@49f7b1b1-d3fc-9bea-4e79-022a69d0483f |
fb865a3f346f09432db77a1ad0ef75e899641fda | 875b7e7fe1aac12b927c5f7177862d29d945ef25 | /SPlisHSPlasH/Viscosity/Viscosity_Weiler2018.h | 05e61786c714e1749db3dee01a70fe25417ddd99 | [
"MIT"
] | permissive | horizon-research/SPlisHSPlasH_with_time | ea8bceb100a10596b45c6bec517a0f13bb644dc5 | 147ada04d35e354f9cb01675834c1bd80e1b1d23 | refs/heads/master | 2023-04-24T09:14:21.936180 | 2021-05-10T22:31:29 | 2021-05-10T22:31:29 | 366,188,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,314 | h | #ifndef __Viscosity_Weiler2018_h__
#define __Viscosity_Weiler2018_h__
#include "SPlisHSPlasH/Common.h"
#include "SPlisHSPlasH/FluidModel.h"
#include "ViscosityBase.h"
#include "SPlisHSPlasH/Utilities/MatrixFreeSolver.h"
#define USE_BLOCKDIAGONAL_PRECONDITIONER
namespace SPH
{
/** \brief This class implements the implicit Laplace viscosity method introduced
* by Weiler et al. 2018 [WKBB18].
*
* References:
* - [WKBB18] Marcel Weiler, Dan Koschier, Magnus Brand, and Jan Bender. A physically consistent implicit viscosity solver for SPH fluids. Computer Graphics Forum (Eurographics), 2018. URL: https://doi.org/10.1111/cgf.13349
*/
class Viscosity_Weiler2018 : public ViscosityBase
{
protected:
Real m_boundaryViscosity;
unsigned int m_maxIter;
Real m_maxError;
unsigned int m_iterations;
std::vector<Vector3r> m_vDiff;
Real m_tangentialDistanceFactor;
#ifdef USE_BLOCKDIAGONAL_PRECONDITIONER
typedef Eigen::ConjugateGradient<MatrixReplacement, Eigen::Lower | Eigen::Upper, BlockJacobiPreconditioner3D> Solver;
FORCE_INLINE static void diagonalMatrixElement(const unsigned int row, Matrix3r &result, void *userData);
#else
typedef Eigen::ConjugateGradient<MatrixReplacement, Eigen::Lower | Eigen::Upper, JacobiPreconditioner3D> Solver;
FORCE_INLINE static void diagonalMatrixElement(const unsigned int row, Vector3r &result, void *userData);
#endif
Solver m_solver;
virtual void initParameters();
public:
static int ITERATIONS;
static int MAX_ITERATIONS;
static int MAX_ERROR;
static int VISCOSITY_COEFFICIENT_BOUNDARY;
Viscosity_Weiler2018(FluidModel *model);
virtual ~Viscosity_Weiler2018(void);
static NonPressureForceBase* creator(FluidModel* model) { return new Viscosity_Weiler2018(model); }
virtual void step();
virtual void reset();
virtual void performNeighborhoodSearchSort();
static void matrixVecProd(const Real* vec, Real *result, void *userData);
FORCE_INLINE const Vector3r& getVDiff(const unsigned int i) const
{
return m_vDiff[i];
}
FORCE_INLINE Vector3r& getVDiff(const unsigned int i)
{
return m_vDiff[i];
}
FORCE_INLINE void setVDiff(const unsigned int i, const Vector3r& val)
{
m_vDiff[i] = val;
}
};
}
#endif
| [
"hanlinGao@outlook.com"
] | hanlinGao@outlook.com |
5a1328bb701071e260cb70dd0565064c7ee32b3b | 856ecf9a67596438b827a375554af0e135ab888b | /Tron/Tron/Src/Draw/DrawerBase.h | 443b385aa900e79a15a0ae3f31287e679a0404c9 | [] | no_license | Huku1225/MyProjects | 96b8f11a0236605c1ba370169c32ed5596cc2c7a | d4c1fee7a1d036caa7b99c236c694638f7437997 | refs/heads/master | 2023-01-22T16:16:39.795575 | 2020-11-25T03:17:51 | 2020-11-25T03:17:51 | 315,815,595 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,036 | h | #ifndef DRAWER_BASE_H_
#define DRAWER_BASE_H_
/**
* @file DrawerBase.h
* @brief DrawerBaseクラスのヘッダ
*/
#include "../Definition.h"
#include <string>
/**
* @class DrawerBase
* @brief Drawerクラスの基底クラス
*/
class DrawerBase {
public:
DrawerBase();
virtual ~DrawerBase();
/**
* @brief 描画関数
*/
void Draw();
/**
* @brief 描画情報のクリア関数
* 描画に使用した
*/
void Clear();
//! 描画用バッファのセット関数
virtual void SetDrawBuffer(Vec2 pos_, char* string_) = 0;
/**
* @brief リザルト情報をセットする関数
* @param result_ 出力する結果の文字列
*/
void SetResultString(std::string result_);
protected:
//! 描画バッファのクリア
virtual void BufferClear() = 0;
//! 描画バッファを連結して1つの文字列へ変換する関数
virtual void LinkDrawBuffer() = 0;
protected:
//! 描画用文字列
std::string m_draw_string;
//! リザルト描画用文字列
std::string m_result_string;
};
#endif
| [
"fksoccer1225@icloud.com"
] | fksoccer1225@icloud.com |
f5252765c4946439da78e639af28b9ac6c039c29 | 175ac9db7cf96b04fb902d0505b2f325ca88a522 | /Lib/Src/Expression/SNodeReduce.cpp | f9ee6ddf5cb102edebd841283f7429c86b27b549 | [] | no_license | dancingpenguins/Big-Numbers | f1f1f0f57134ea836c1be86f27eaadcc76e5caaa | c35403347f5a565ed41edb08638b7c0973d655a8 | refs/heads/master | 2022-12-11T12:30:39.427811 | 2020-09-06T03:46:34 | 2020-09-06T03:46:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 39,797 | cpp | #include "pch.h"
#include <Math/PrimeFactors.h>
#include <Math/Expression/ParserTree.h>
#include <Math/Expression/ExpressionNode.h>
#include <Math/Expression/SNodeReduceDbgStack.h>
namespace Expr {
SNode SNode::beautify(SNode n) { // static
if(n.isEmpty()) return n;
Expression e(n.node());
ParserTree *srcTree = &n.getTree();
ParserTree *tmpTree = e.getTree();
ExpressionNode *result = tmpTree->reduce().getRoot()->clone(srcTree);
n.getTree().addNonRootNode(result);
return SNode(result);
}
SNode SNode::reduce() {
ENTERMETHOD();
if(isReduced()) RETURNTHIS;
switch(getNodeType()) {
case NT_STMTLIST :
RETURNNODE(reduceStmtList());
case NT_ASSIGN :
RETURNNODE(reduceAssign());
default :
switch(getReturnType()) {
case EXPR_RETURN_FLOAT:
RETURNNODE(reduceRealExp());
case EXPR_RETURN_BOOL :
RETURNNODE(reduceBoolExp());
}
throwUnknownReturnTypeException(__TFUNCTION__);
}
throwUnknownNodeTypeException(__TFUNCTION__);
return NULL;
}
SNode SNode::reduceStmtList() {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_STMTLIST);
if(isReduced()) RETURNTHIS;
const SNodeArray &childArray = getChildArray();
const size_t childCount = childArray.size();
const size_t stmtCount = childCount - 1;
StmtList newStmtList(getTree(), childCount);
for(size_t i = 0; i < stmtCount; i++) {
newStmtList.add(childArray[i].reduceAssign());
}
SNode last = childArray.last();
switch(last.getReturnType()) {
case EXPR_RETURN_FLOAT:
newStmtList.add(last.reduceRealExp());
break;
case EXPR_RETURN_BOOL :
newStmtList.add(last.reduceBoolExp());
break;
default :
last.UNKNOWNSYMBOL();
}
newStmtList.removeUnusedAssignments();
if(newStmtList.isSameNodes(childArray)) {
setReduced();
RETURNTHIS;
}
RETURNNODE(stmtList(newStmtList));
}
SNode SNode::reduceAssign() const {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_ASSIGN);
if(isReduced()) RETURNTHIS;
SNode Rr = right().reduceRealExp();
if(Rr.isSameNode(right())) {
right().setReduced();
setReduced();
RETURNTHIS;
}
RETURNNODE(assignStmt(left(), Rr));
}
SNode SNode::reduceBoolExp() {
ENTERMETHOD();
CHECKNODERETURNTYPE(*this,EXPR_RETURN_BOOL);
if(isReduced()) RETURNTHIS;
if(isConstant()) {
RETURNNODE(SNV(evaluateBool()));
} else {
switch(getSymbol()) {
case AND:
case OR : RETURNNODE(reduceAndOr());
case NOT: RETURNNODE(reduceNot());
case EQ:
case NE:
case LT:
case LE:
case GT:
case GE:
{ SNode Rl = left().reduceRealExp(), Rr = right().reduceRealExp();
if(Rl.isSameNode(left()) && Rr.isSameNode(right())) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE(boolExp(getSymbol(), Rl, Rr));
}
}
default:
UNKNOWNSYMBOL();
RETURNNULL;
}
}
}
SNode SNode::reduceRealExp() {
ENTERMETHOD();
CHECKNODERETURNTYPE(*this, EXPR_RETURN_FLOAT);
if(isReduced()) RETURNTHIS;
switch(getSymbol()) {
case NUMBER :
case NAME :
setReduced();
RETURNTHIS;
case UNARYMINUS : RETURNNODE( -left().reduceRealExp() );
case SUM : RETURNNODE( reduceSum() );
case PRODUCT : RETURNNODE( reduceProduct() );
case POW : RETURNNODE( reducePower() );
case MOD : RETURNNODE( reduceModulus() );
case LN : RETURNNODE( reduceLn() );
case LOG10 : RETURNNODE( reduceLog10() );
case LOG2 : RETURNNODE( reduceLog2() );
case ASIN :
case ASINH :
case ATAN :
case ATANH :
case COT :
case ERF :
case INVERF :
case SIGN :
case SIN :
case SINH :
case TAN :
case TANH : RETURNNODE( reduceAsymmetricFunction() );
case ABS :
case COS :
case COSH :
case GAUSS : RETURNNODE( reduceSymmetricFunction() );
case POLY : RETURNNODE( reducePoly() );
case ACOS :
case ACOT :
case ATAN2 :
case ACOSH :
case ACSC :
case ASEC :
case BINOMIAL :
case CHI2DENS :
case CHI2DIST :
case LINCGAMMA :
case CEIL :
case FAC :
case FLOOR :
case GAMMA :
case MAX :
case MIN :
case HYPOT :
case NORM :
case PROBIT : RETURNNODE( reduceTreeNode() );
case INDEXEDSUM :
case INDEXEDPRODUCT : RETURNNODE( reduceIndexedExpr() );
case IIF : RETURNNODE( reduceCondExp() );
default :
UNKNOWNSYMBOL();
RETURNNULL;
}
}
SNode SNode::reduceIndexedExpr() {
ENTERMETHOD();
if(isReduced()) RETURNTHIS;
SNode assign = child(0);
SNode end = child(1);
SNode exp = child(2);
SNode Rassign = assign.reduceAssign();
SNode Rend = end.reduceRealExp();
SNode Rexp = exp.reduceRealExp();
if(Rassign.isSameNode(assign) && Rend.isSameNode(end) && Rexp.isSameNode(exp)) {
setReduced();
RETURNTHIS;
}
RETURNNODE( indexedExp(getSymbol(), Rassign, Rend, Rexp) );
}
//------------------------------------ reduceSum ----------------------------------------
// symbol == SUM
SNode SNode::reduceSum() const {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_SUM);
if(isReduced()) RETURNTHIS;
static const ExpressionSymbolSet logFunctionSet( LN,LOG10,LOG2,EOI);
static const ExpressionSymbolSet sinCosFunctionSet(SIN,COS, EOI);
bool hasTrigonometricFunctions = false, hasLogarithmicFunctions = false;
AddentArray a(getTree());
getAddents(a);
AddentArray reduced(a.getTree());
for(size_t i = 0; i < a.size(); i++) {
SNode e = a[i], n = e.left();
SNode Rn = n.reduceRealExp();
if(!hasTrigonometricFunctions) hasTrigonometricFunctions = Rn.getNodeCount(sinCosFunctionSet) > 0;
if(!hasLogarithmicFunctions ) hasLogarithmicFunctions = Rn.getNodeCount(logFunctionSet ) > 0;
if(Rn.isSameNode(n)) {
reduced.add(e);
} else {
reduced.add(addentExp(Rn, e.isPositive()));
}
}
if(reduced.size() <= 1) {
if(reduced.isSameNodes(a)) {
setReduced();
RETURNTHIS;
}
SNode result = sumExp(reduced);
result.setReduced();
RETURNNODE( result );
}
BitSet done(reduced.size());
do {
AddentArray tmp = reduced;
reduced.clear();
done.setCapacity(tmp.size()).clear();
SNode sqrSinOrCos;
for(size_t i1 = 1; i1 < tmp.size(); i1++) {
SNode e1 = tmp[i1];
for(size_t i2 = 0; i2 < i1; i2++) {
if(done.contains(i1)) break;
if(done.contains(i2)) continue;
SNode e2 = tmp[i2];
if(e1.left().equal(e2.left())) {
done.add(i1).add(i2);
int factor = (e1.isPositive() == e2.isPositive()) ? 2 : 0;
for(size_t i3 = i2+1; i3 < tmp.size(); i3++) { // check if there are more copies
if(done.contains(i3)) continue;
SNode e3 = tmp[i3];
if(e1.left().equal(e3.left())) {
done.add(i3);
factor += (e3.isPositive() == e1.isPositive()) ? 1 : -1;
}
}
switch(factor) {
case 0:
break; // all copies cancels
case -1:
reduced.add(addentExp(e1.left(), !e1.isPositive()));
break;
case 1:
reduced.add(e1);
break;
case 2:
case -2:
reduced.add(addentExp(_2() * e1.left(), (factor>0) == e1.isPositive()));
break;
default:
if(factor < 0) {
reduced.add(addentExp(SNV(-factor) * e1.left(), !e1.isPositive()));
} else {
reduced.add(addentExp(SNV( factor) * e1.left(), e1.isPositive()));
}
}
} else if(hasTrigonometricFunctions && canUseIdiotRule(e1.left(), e2.left()) && (e1.isPositive() == e2.isPositive())) {
reduced.add(addentExp(_1(), e1.isPositive()));
done.add(i1).add(i2);
} else if(hasTrigonometricFunctions && canUseReverseIdiotRule(e1, e2, sqrSinOrCos)) {
reduced.add(sqrSinOrCos);
done.add(i1).add(i2);
} else if(hasLogarithmicFunctions && e1.left().sameLogarithm(e2.left())) {
reduced.add(mergeLogarithms(e1, e2));
done.add(i1).add(i2);
} else {
SNode cf = (getTree().getState() == PS_MAINREDUCTION1) ? getCommonFactor(e1, e2) : NULL;
if(!cf.isEmpty()) {
if(cf.left().getSymbol() != SUM) {
reduced.add(cf);
} else {
if(cf.isPositive()) {
reduced += cf.left().getAddentArray();
} else {
reduced -= cf.left().getAddentArray();
}
}
done.add(i1).add(i2);
}
}
}
}
reduced += tmp.selectNodes(compl(done)); // now add the untouched
} while(!done.isEmpty() && reduced.size() > 1);
AddentArray tmp = reduced;
reduced.clear();
for(size_t i = 0; i < tmp.size(); i++) {
SNode e = tmp[i], n = e.left();
SNode n1 = changeFirstNegativeFactor();
if(!n1.isEmpty()) {
reduced.add(addentExp(n1, !e.isPositive()));
} else {
reduced.add(e);
}
}
tmp = reduced;
reduced.clear();
Rational rationalAcc = 0;
BitSet rationalAddentSet(tmp.size());
// then replace all rational constants, added together in rationalAcc
// if only 1 rational exist, then reuse it
for(size_t i = 0; i < tmp.size(); i++) {
SNode e = tmp[i], c = e.left();
Rational r;
if(c.isRational()) {
rationalAddentSet.add(i);
r = c.getRational();
} else if(!c.reducesToRational(&r)) {
reduced.add(e);
continue;
}
if(e.isPositive()) {
rationalAcc += r;
} else {
rationalAcc -= r;
}
}
if(rationalAddentSet.size() == 1) {
reduced.add(tmp[rationalAddentSet.select()]); // put the one found back again, to keep array the same (if not changed already)
} else if(rationalAcc != 0) {
reduced += rationalAcc;
}
reduced.sort();
if(reduced.isSameNodes(a)) {
setReduced();
RETURNTHIS;
}
RETURNNODE( sumExp( reduced) );
}
/*
* n1,n2 expression in a sum
* return true if n1 = cos^2(expression) and n2 = sin^2(expression) or vice versa
*/
bool SNode::canUseIdiotRule(SNode n1, SNode n2) const {
ENTERMETHOD2(n1, n2);
if(n1.getSymbol() == POW && n2.getSymbol() == POW) {
if(n1.right().isConstant() && n2.right().isConstant()) {
const Real e1 = n1.right().evaluateReal();
const Real e2 = n2.right().evaluateReal();
if((e1 == 2) && (e2 == 2)) {
const ExpressionInputSymbol f1 = n1.left().getSymbol();
const ExpressionInputSymbol f2 = n2.left().getSymbol();
RETURNBOOL( ((f1 == SIN && f2 == COS) || (f1 == COS && f2 == SIN)) && n1.left().left().equal(n2.left().left()));
}
}
}
RETURNBOOL( false );
}
static ExpressionInputSymbol getDualTrigonometricFunction(ExpressionInputSymbol symbol) {
switch(symbol) {
case SIN: return COS;
case COS: return SIN;
default : throwInvalidArgumentException(__TFUNCTION__, _T("symbol=%s"), SNode::getSymbolName(symbol).cstr());
return EOI;
}
}
static bool isSinOrCos(SNode n) {
switch(n.getSymbol()) {
case SIN:
case COS:
return true;
default:
return false;
}
}
bool SNode::isSquareOfSinOrCos() const {
ENTERMETHOD();
switch(getSymbol()) {
case POW:
RETURNBOOL( isSinOrCos(left()) && right().isConstant() && (right().evaluateReal() == 2) );
default :
RETURNBOOL( false );
}
}
bool SNode::canUseReverseIdiotRule(SNode e1, SNode e2, SNode &result) const {
ENTERMETHOD2(e1, e2);
for(int i = 0; i < 2; i++) {
Rational r1;
if(e1.left().reducesToRational(&r1)) {
if(!e1.isPositive()) r1 = -r1;
if((fabs(r1) == 1) && e2.left().isSquareOfSinOrCos() && (r1 == 1) != (e2.isPositive())) {
SNode sinOrCos = e2.left().left();
SNode n = pow(unaryExp(getDualTrigonometricFunction(sinOrCos.getSymbol()), sinOrCos.left()), _2());
result = addentExp(n, r1 == 1);
RETURNBOOL( true );
}
}
std::swap(e1, e2);
}
RETURNBOOL( false );
}
bool SNode::sameLogarithm(SNode n) const {
ENTERMETHOD2(*this, n);
RETURNBOOL( ((getSymbol() == LN ) && (n.getSymbol() == LN ))
|| ((getSymbol() == LOG10) && (n.getSymbol() == LOG10))
|| ((getSymbol() == LOG2 ) && (n.getSymbol() == LOG2 ))
);
}
/*
* e1 assumes e1->getNode.getSymbol = LN,LOG10 or LOG2
* e2 assumes e2->getNode.getSymbol = e1.getNode.getSymbol
* return log(a*b) = log(a) + log(b),
* -log(a*b) = -log(a) - log(b),
* log(a/b) = log(a) - log(b)
* log(b/a) = -log(a) + log(b) where log = LN or LOG10
*/
SNode SNode::mergeLogarithms(SNode e1, SNode e2) const {
ENTERMETHOD2(e1, e2);
CHECKSYMBOL(e1,e2.getSymbol());
SNode arg1 = e1.left().left();
SNode arg2 = e2.left().left();
const ExpressionInputSymbol logFunction = e1.left().getSymbol();
SNode result;
if(e1.isPositive() == e2.isPositive()) { // log(arg1) + log(arg2) = log(arg1*arg2)
result = addentExp(unaryExp(logFunction, (arg1 * arg2).reduceRealExp()), e1.isPositive());
} else if(e1.isPositive()) { // log(arg1) - log(arg2) = log(arg1/arg2)
result = addentExp(unaryExp(logFunction, (arg1 / arg2).reduceRealExp()),true);
} else { // log(arg2) - log(arg1) = log(arg2/arg1)
result = addentExp(unaryExp(logFunction, (arg2 / arg1).reduceRealExp()),true);
}
RETURNNODE(result);
}
/*
* e1, e2 both type NT_ADDENT
* return If(e1 == a*b and e2 == a*c)
* then return a*(b+c). Distributive low for * and +/-
* If(e1 == p1 * a^c1 and e2 == p2 * a^c2)
* then, assuming c1 < c2, return a^c1 * (p1 + p2 * a^(c2-c1))
* and symmetric if c1 > c2 (taking care of signs of e1 and e2 too)
* return NULL If no common factors found
*/
SNode SNode::getCommonFactor(SNode e1, SNode e2) const {
ENTERMETHOD2(e1, e2);
CHECKNODETYPE(e1,NT_ADDENT);
CHECKNODETYPE(e1,NT_ADDENT);
FactorArray fl1(getTree()), fl2(getTree());
e1.left().getFactors(fl1);
e2.left().getFactors(fl2);
FactorArray commonFactors(getTree());
int signShiftCount = 0;
StartSearch:
for(size_t i1 = 0; i1 < fl1.size(); i1++) {
SNode factor1 = fl1[i1];
for(size_t i2 = 0; i2 < fl2.size(); i2++) {
SNode factor2 = fl2[i2];
if(factor1.equal(factor2)) {
fl1.remove(i1);
fl2.remove(i2);
commonFactors *= factor1;
goto StartSearch;
} else if((factor1.base().equal(factor2.base()))
&& (factor1.exponent().isNumber() && factor2.exponent().isNumber())) { // exponents are different
fl1.remove(i1);
fl2.remove(i2);
SNode base = factor1.base(); // == factor2->base()
const Number &c1 = factor1.exponent().getNumber();
const Number &c2 = factor2.exponent().getNumber();
const Number *minExponent , *maxExponent;
FactorArray *flEMin , *flEMax;
if(c1 < c2) {
minExponent = &c1 ; maxExponent = &c2;
flEMin = &fl1; flEMax = &fl2;
} else {
minExponent = &c2 ; maxExponent = &c1;
flEMin = &fl2; flEMax = &fl1;
}
commonFactors *= powerExp(base, SNV(*minExponent));
*flEMax *= powerExp(base, SNV(*maxExponent - *minExponent));
goto StartSearch;
} else {
Rational eR1,eR2;
if((factor1.exponent().reducesToRational(&eR1) && factor2.exponent().reducesToRational(&eR2))
&& factor1.base().equalMinus(factor2.base())) {
if(isAsymmetricExponent(eR1) && isAsymmetricExponent(eR2)) {
signShiftCount++;
} else if(isSymmetricExponent(eR1) && isSymmetricExponent(eR2)) {
// do nothing
} else {
continue;
}
fl1.remove(i1);
fl2.remove(i2);
SNode base = factor1.base(); // == -factor2->base()
const Rational *minExponent , *maxExponent;
FactorArray *flEMin , *flEMax;
if(eR1 == eR2) {
commonFactors *= factor1;
} else {
if(eR1 < eR2) {
minExponent = &eR1; maxExponent = &eR2;
flEMin = &fl1; flEMax = &fl2;
} else { // e1 > e2
minExponent = &eR2; maxExponent = &eR1;
flEMin = &fl2; flEMax = &fl1;
}
commonFactors *= powerExp(base, *minExponent);
*flEMax *= powerExp(base, *maxExponent - *minExponent);
}
goto StartSearch;
}
}
}
}
if(commonFactors.size() == 0) {
RETURNNULL;
}
SNode a = productExp(commonFactors);
bool positive = true;
const bool e2positive = (e2.isPositive() == ::isEven(signShiftCount));
SNode bc;
if(e1.isPositive() == e2positive) {
bc = productExp(fl1) + productExp(fl2);
positive = e1.isPositive();
} else if(e1.isPositive()) { // a2 negative
bc = productExp(fl1) - productExp(fl2);
} else { // e1 negative and e2 positive
bc = productExp(fl2) - productExp(fl1);
}
SNode result = addentExp(a * bc, positive);
RETURNNODE( result );
}
// Assume symbol = SUM. nested SUM-nodes will all be put on the same level, (in result), by recursive calls
bool SNode::getAddents(AddentArray &result, bool positive) const {
ENTERMETHOD();
CHECKNODETYPE(*this, NT_SUM);
const AddentArray &a = getAddentArray();
const size_t n = a.size();
bool changed = false;
for(size_t i = 0; i < n; i++) {
SNode e = a[i], child = e.left();
if(child.getSymbol() == SUM) {
child.getAddents(result, e.isPositive() == positive);
changed = true;
} else if(positive) {
result.add(e);
} else {
result.add(addentExp(child,!e.isPositive()));
changed = true;
}
}
RETURNBOOL( changed );
}
SNode SNode::changeFirstNegativeFactor() const {
ENTERMETHOD();
switch(getSymbol()) {
case NUMBER :
if(isNegativeNumber()) {
RETURNNODE( SNV(-getNumber()) );
}
break;
case PRODUCT:
{ const FactorArray &factorArray = getFactorArray();
if(factorArray.size() == 0) RETURNNULL;
FactorArray newFactorArray(getTree());
SNode f0 = factorArray[0];
if(f0.base().isNegativeNumber() && f0.exponent().isOdd()) {
newFactorArray *= powerExp(-f0.base(), f0.exponent());
for(size_t i = 1; i < factorArray.size(); i++) {
newFactorArray *= factorArray[i];
}
RETURNNODE( productExp(newFactorArray) );
}
}
break;
case POW :
if(left().isNegativeNumber() && right().isOdd()) {
RETURNNODE( pow(SNV(-left().getNumber()), right()) );
}
break;
}
RETURNNULL;
}
//------------------------------------ reduceProduct ----------------------------------------
// Symbol = PRODUCT
SNode SNode::reduceProduct() {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_PRODUCT);
FactorArray unreducedFactors(getTree()), nonConstantFactors(getTree()), constantFactors(getTree());
getFactors(unreducedFactors);
for(size_t i = 0; i < unreducedFactors.size(); i++) { // first remove all number factors, multiplied together in constantFactor
SNode f = unreducedFactors[i];
Number v;
if(!f.isConstant(&v)) {
nonConstantFactors *= f; // contains non-constant factors
} else if(f.isReduced()) {
constantFactors *= f;
} else if(!v.isRational()) {
constantFactors *= f;
} else {
const Rational r = (Rational)v;
if(r == 0) { // the whole product is 0
RETURNNODE( _0() );
} else if(r != 1) { // No need to add 1 as a factor
constantFactors *= r;
constantFactors.last().setReduced();
}
}
}
// nonConstantFactors contains no constant factors
FactorArray reduced = nonConstantFactors;
if(reduced.size() > 1) {
BitSet done(reduced.size());
do {
FactorArray tmp = reduced;
reduced.clear();
done.setCapacity(tmp.size()).clear();
for(size_t i1 = 1; i1 < tmp.size(); i1++) {
SNode f1 = tmp[i1];
for(size_t i2 = 0; i2 < i1; i2++) {
if(done.contains(i1)) break;
if(done.contains(i2)) continue;
SNode f2 = tmp[i2];
if(f1.base().equal(f2.base())) { // Common base
SNode newExponent = (f1.exponent() + f2.exponent()).reduceRealExp();
if(!newExponent.isZero()) {
reduced *= powerExp(f1.base(), newExponent);
}
done.add(i1).add(i2);
} else {
SNode f = reduceTrigonometricFactors(f1, f2);
if(!f.isEmpty()) {
done.add(i1).add(i2);
Number v;
if(!f.isConstant(&v)) {
reduced *= f;
} else if(!v.isRational()) {
constantFactors *= f;
} else {
const Rational r = (Rational)v;
if(r == 0) { // No need to go further. The product is 0
RETURNNODE( _0() );
} else if(r != 1) { // No need to add 1 as a factor
constantFactors *= r;
}
}
}
}
}
}
for(size_t i = 0; i < tmp.size(); i++) {
if(!done.contains(i)) {
reduced *= tmp[i];
}
}
} while(!done.isEmpty() && reduced.size() > 1);
}
SNode constantFactor = reduceConstantFactors(constantFactors);
if(!constantFactor.isOne()) {
reduced *= constantFactor;
}
reduced.sort();
if(getFactorArray().isSameNodes(reduced)) {
setReduced();
RETURNTHIS;
}
RETURNNODE( productExp(reduced) );
}
FactorArray &SNode::getFactors(FactorArray &result) {
return getFactors(result, _1());
}
FactorArray &SNode::getFactors(FactorArray &result, SNode exponent) {
ENTERMETHOD2(*this, exponent);
switch(getSymbol()) {
case NUMBER:
if(!isOne()) { // 1 should not be added
const Number &v = getNumber();
if(v.isRational()) {
const Rational r = (Rational)v;
if(::abs(r.getNumerator()) == 1) {
result *= powerExp(SNV(sign(r.getNumerator()) * r.getDenominator()), (-exponent).reduceRealExp());
break;
}
}
result *= powerExp(*this, exponent);
}
break;
case PRODUCT:
{ FactorArray &a = getFactorArray();
for(size_t i = 0; i < a.size(); i++) {
a[i].getFactors(result, exponent);
}
}
break;
case POW :
getFactorsInPower(result, exponent);
break;
default:
result *= powerExp(reduceRealExp(), exponent);
break;
}
RETURNSHOWSTR( result );
}
/*
* symbol = POW
* exponent is the outer exponent of this. value = pow(pow(left,right),exponent)
* return this split into as many separate factors as possible
*/
FactorArray &SNode::getFactorsInPower(FactorArray &result, SNode exponent) {
ENTERMETHOD2(*this, exponent);
CHECKSYMBOL(*this,POW);
FactorArray tmp1(getTree()), tmp2(getTree());
SNode base = left();
switch(base.getSymbol()) {
case POW :
multiplyExponents(tmp2, base.left().reduceRealExp().getFactors(tmp1, base.right().reduceRealExp()), right().reduceRealExp());
break;
default :
base.reduceRealExp().getFactors(tmp2, right().reduceRealExp());
break;
}
multiplyExponents(result, tmp2, exponent);
RETURNSHOWSTR( result );
}
// symbol = POW
SNode SNode::reducePower() {
ENTERMETHOD();
CHECKSYMBOL(*this,POW);
SNode base = left();
SNode expo = right();
SNode rBase = base.reduceRealExp();
SNode rExpo = expo.reduceRealExp();
SNode result;
if(rBase.getSymbol() == POW) {
result = pow(rBase.left(), multiplyExponents(rBase.right(), rExpo));
} else if(rBase.isSameNode(base) && rExpo.isSameNode(expo)) { // nothing changed
Rational r;
if(rExpo.reducesToRational(&r)) {
if((r == 1) && !rExpo.isOne()) {
result = abs(rBase);
} else if((r == -1) && !rExpo.isMinusOne()) {
result = reciprocal(abs(rBase));
} else {
result = *this;
}
} else {
result = *this;
}
} else {
result = pow(rBase, rExpo);
}
Rational tmp;
if(result.reducesToRational(&tmp)) {
result = SNV(tmp);
}
RETURNNODE( result );
}
/* factors list of ExpressionFactor
* factor factor to multiply with
* return list of expressionFactors, result[i] = fetchFactorNode(factors[i].base,factors[i].exponent * factor)
*/
FactorArray &SNode::multiplyExponents(FactorArray &result, FactorArray &factors, SNode exponent) {
ENTERMETHOD2(factors, exponent);
if(exponent.isOne()) {
result *= factors;
RETURNSHOWSTR( result );
} else if(exponent.isZero()) {
RETURNSHOWSTR( result ); // the empty list has value 1
}
Rational erat;
if(exponent.reducesToRational(&erat)) {
SNode er = SNode(getTree(), erat);
for(size_t i = 0; i < factors.size(); i++) {
SNode f = factors[i];
result *= powerExp(f.base(), multiplyExponents(f.exponent(), er));
}
} else { // exponent is not rational. so no need to use multiplyExponents
for(size_t i = 0; i < factors.size(); i++) {
SNode f = factors[i];
result *= powerExp(f.base(), f.exponent() * exponent);
}
}
RETURNSHOWSTR( result );
}
SNode SNode::multiplyExponents(SNode e1, SNode e2) const {
return getTree().multiplyExponents(e1.node(), e2.node());
}
SNode SNode::divideExponents(SNode e1, SNode e2) const {
return getTree().divideExponents(e1.node(), e2.node());
}
SNode SNode::multiplySumSum(SNode n1, SNode n2) const {
ENTERMETHOD2(n1,n2);
CHECKNODETYPE(n1,NT_SUM);
CHECKNODETYPE(n2,NT_SUM);
const AddentArray &aa1 = n1.getAddentArray();
const AddentArray &aa2 = n2.getAddentArray();
ParserTree &tree = n1.getTree();
AddentArray newAddentArray(tree, aa1.size() * aa2.size());
for(size_t i = 0; i < aa1.size(); i++) {
SNode e1 = aa1[i], s1 = e1.left();
for(size_t j = 0; j < aa2.size(); j++) {
SNode e2 = aa2[j], s2 = e2.left();
newAddentArray.add(addentExp(s1 * s2, e1.isPositive() == e2.isPositive()));
}
}
SNode result = sumExp(newAddentArray);
RETURNNODE( result );
}
SNode SNode::reduceTrigonometricFactors(SNode f1, SNode f2) {
ENTERMETHOD2(f1,f2);
if(!f1.base().isTrigonomtricFunction() || !f2.base().isTrigonomtricFunction()) {
RETURNNULL;
}
SNode arg = f1.base().left();
if(!arg.equal(f2.base().left())) {
RETURNNULL;
}
if(!f1.exponent().isNumber() || !f2.exponent().isNumber()) {
RETURNNULL;
}
const Real e1 = f1.exponent().getReal();
const Real e2 = f2.exponent().getReal();
switch(f1.base().getSymbol()) {
case SIN:
switch(f2.base().getSymbol()) {
case COS:
if(e1 == -e2) RETURNNODE(powerExp(tan(arg), f1.exponent()));
break;
case TAN:
if(e1 == -e2) RETURNNODE(powerExp(cos(arg), f1.exponent()));
break;
}
break;
case COS:
switch(f2.base().getSymbol()) {
case SIN:
if(e1 == -e2) RETURNNODE(powerExp(tan(arg), f2.exponent()));
break;
case TAN:
if(e1 == e2) RETURNNODE(powerExp(tan(arg), f1.exponent()));
break;
}
break;
case TAN:
switch(f2.base().getSymbol()) {
case SIN:
if(e1 == -e2) RETURNNODE(powerExp(cos(arg),f2.exponent()));
break;
case COS:
if(e1 == e2) RETURNNODE(powerExp(sin(arg),f1.exponent()));
break;
}
break;
}
RETURNNULL;
}
SNode SNode::reduceConstantFactors(FactorArray &factorArray) {
ENTERMETHOD1(factorArray);
if(factorArray.size() == 0) {
RETURNNODE( _1() );
}
FactorArray reduced = factorArray;
for(int startSize = (int)reduced.size(); startSize > 0; startSize = (int)reduced.size()) {
const FactorArray tmp = reduced;
reduced.clear();
BitSet done(tmp.size());
for(size_t i1 = 1; i1 < tmp.size(); i1++) {
if(done.contains(i1)) continue;
SNode f1 = tmp[i1];
SNode base1 = f1.base();
SNode expo1 = f1.exponent();
Rational B1R, E1R;
const bool b1IsRationalConstant = base1.reducesToRational(&B1R);
const bool e1IsRationalConstant = expo1.reducesToRational(&E1R);
SNode reducedBase1 = b1IsRationalConstant ? SNV(B1R) : base1;
for(size_t i2 = 0; i2 < i1; i2++) {
if(done.contains(i1)) break;
if(done.contains(i2)) continue;
SNode f2 = tmp[i2];
SNode base2 = f2.base();
SNode expo2 = f2.exponent();
Rational B2R, E2R;
const bool b2IsRationalConstant = base2.reducesToRational(&B2R);
const bool e2IsRationalConstant = expo2.reducesToRational(&E2R);
SNode reducedBase2 = b2IsRationalConstant ? SNV(B2R) : base2;
if(e1IsRationalConstant && e2IsRationalConstant) {
if(E1R == E2R) {
reduced *= powerExp(reducedBase1 * reducedBase2, E1R);
done.add(i1).add(i2);
} else if(E1R == -E2R) {
if(E1R > 0) {
reduced *= powerExp(reducedBase1 / reducedBase2, E1R);
} else {
reduced *= powerExp(reducedBase2 / reducedBase1, E2R);
}
done.add(i1).add(i2);
} else if(base1.equal(base2)) {
reduced *= powerExp(reducedBase1, E2R + E1R);
done.add(i1).add(i2);
}
} else if(expo1.equal(expo2)) {
reduced *= powerExp(reducedBase1 * reducedBase2, expo1);
done.add(i1).add(i2);
}
}
}
reduced *= tmp.selectFactors(compl(done));
if(reduced.size() == startSize) {
break;
}
}
Rational rationalPart = 1;
FactorArray fa(getTree());
for(size_t i = 0; i < reduced.size(); i++) {
SNode f = reduced[i];
Rational r;
if(f.reducesToRational(&r)) {
if(r == 0) {
RETURNNODE( _0() );
} else if(r == 1) {
continue;
} else {
rationalPart *= r;
}
} else {
SNode base = f.base();
SNode expo = f.exponent();
Rational baseR, expoR;
if(base.reducesToRational(&baseR)) {
if(expo.reducesToRational(&expoR)) {
fa *= reduceRationalPower(baseR, expoR);
} else { // base is rational. expo is irrational
fa *= powerExp(SNV(baseR), expo);
}
} else {
fa *= f;
}
}
}
if(rationalPart != 1) {
const INT64 &num = rationalPart.getNumerator();
const INT64 &den = rationalPart.getDenominator();
fa *= num;
fa /= den;
}
RETURNNODE( productExp(fa) );
}
SNode SNode::reduceRationalPower(const Rational &base, const Rational &exponent) {
ENTERMETHOD2NUM(base, exponent);
if(exponent.isInteger()) {
RETURNNODE( SNV(pow(base, (int)exponent)) );
} else {
const INT64 &ed = exponent.getDenominator();
const INT64 &bn = base.getNumerator();
const INT64 &bd = base.getDenominator();
PrimeFactorArray bnPrimeFactors(bn);
PrimeFactorArray bdPrimeFactors(bd);
PrimeFactorSet bnRootFactors = bnPrimeFactors.findFactorsWithMultiplicityAtLeast((UINT)ed);
PrimeFactorSet bdRootFactors = bdPrimeFactors.findFactorsWithMultiplicityAtLeast((UINT)ed);
Rational niceRootFactor = 1;
__int64 bnR = 1, bdR = 1;
if((::abs(bn) == 1 || !bnRootFactors.isEmpty()) && (bd == 1 || !bdRootFactors.isEmpty())) {
for(Iterator<size_t> it1 = bnRootFactors.getIterator(); it1.hasNext();) {
PrimeFactor &pf = bnPrimeFactors[it1.next()];
do {
bnR *= pf.m_prime;
pf.m_multiplicity -= (UINT)ed;
} while(pf.m_multiplicity >= (UINT)ed);
}
for(Iterator<size_t> it2 = bdRootFactors.getIterator(); it2.hasNext();) {
PrimeFactor &pf = bdPrimeFactors[it2.next()];
do {
bdR *= pf.m_prime;
pf.m_multiplicity -= (UINT)ed;
} while(pf.m_multiplicity >= (UINT)ed);
}
}
if(bnPrimeFactors.isPositive()) {
niceRootFactor = Rational(bnR, bdR);
} else if(isAsymmetricExponent(exponent)) {
niceRootFactor = Rational(-bnR, bdR);
bnPrimeFactors.setPositive();
} else {
throwInvalidArgumentException(__TFUNCTION__, _T("Base:%s, exponent:%s"), ::toString(base).cstr(), ::toString(exponent).cstr());
}
FactorArray fa(getTree());
if(niceRootFactor != 1) {
fa *= powerExp(SNV(niceRootFactor), exponent.getNumerator());
}
const Rational nonRootFactor = pow(Rational(bnPrimeFactors.getProduct(), bdPrimeFactors.getProduct()), (int)exponent.getNumerator());
if(nonRootFactor != 1) {
if(nonRootFactor.getNumerator() == 1) {
fa *= powerExp(SNV(nonRootFactor.getDenominator()), Rational(-1,ed));
} else {
fa *= powerExp(SNV(nonRootFactor), Rational(1,ed));
}
}
RETURNNODE( productExp(fa) );
}
}
SNode SNode::reduceModulus() const {
ENTERMETHOD();
CHECKSYMBOL(*this,MOD);
if(isReduced()) RETURNTHIS;
SNode l = left();
SNode r = right();
SNode Rl = l.reduceRealExp();
SNode Rr = r.reduceRealExp();
if(Rr.isNegativeNumber() || Rr.isUnaryMinus()) Rr = -Rr;
if(Rl.isSameNode(l) && Rr.isSameNode(r)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( Rl % Rr );
}
}
/*
* symbol = LN
* return if argument is an integer power p of e then p else LN(reduce(leftChild))
*/
SNode SNode::reduceLn() {
ENTERMETHOD();
CHECKSYMBOL(*this,LN);
if(isReduced()) RETURNTHIS;
SNode arg = left();
SNode Rarg = arg.reduceRealExp();
SNode p = Rarg.getPowerOfE();
if(!p.isEmpty()) {
RETURNNODE( p );
}
if(Rarg.getSymbol() == POW) { // ln(a^b) = b * ln(a)
RETURNNODE( Rarg.right() * ln( Rarg.left()) );
}
if(Rarg.isSameNode(arg)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE(ln( Rarg) );
}
}
SNode SNode::getPowerOfE() {
ENTERMETHOD();
if(isEulersConstant()) {
RETURNNODE( _1() );
} else if(isOne()) {
RETURNNODE( _0() );
} else if((getSymbol() == POW) && left().isEulersConstant()) {
RETURNNODE( right() );
}
RETURNNULL;
}
/*
* symbol = LOG10
* return if argument is an integer power p of 10 then p else LOG10(reduce(leftChild))
*/
SNode SNode::reduceLog10() {
ENTERMETHOD();
CHECKSYMBOL(*this,LOG10);
if(isReduced()) RETURNTHIS;
SNode arg = left();
SNode Rarg = arg.reduceRealExp();
SNode p = Rarg.getPowerOf10();
if(!p.isEmpty()) {
RETURNNODE( p );
}
if(Rarg.getSymbol() == POW) {
RETURNNODE( Rarg.right() * log10( Rarg.left()) );
}
if(Rarg.isSameNode(arg)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( log10( Rarg) );
}
}
SNode SNode::getPowerOf10() {
ENTERMETHOD();
if(isTen()) {
RETURNNODE( _1() );
} else if(isOne()) {
RETURNNODE( _0() );
} else if((getSymbol() == POW) && left().isTen()) {
RETURNNODE( right() );
}
RETURNNULL;
}
/*
* symbol = LOG2
* return if argument is an integer power p of 2 then p else LOG2(reduce(leftChild))
*/
SNode SNode::reduceLog2() {
ENTERMETHOD();
CHECKSYMBOL(*this,LOG2);
if(isReduced()) RETURNTHIS;
SNode arg = left();
SNode Rarg = arg.reduceRealExp();
SNode p = Rarg.getPowerOf2();
if(!p.isEmpty()) {
RETURNNODE( p );
}
if(Rarg.getSymbol() == POW) {
RETURNNODE( Rarg.right() * log2( Rarg.left()) );
}
if(Rarg.isSameNode(arg)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( log2( Rarg) );
}
}
SNode SNode::getPowerOf2() {
ENTERMETHOD();
if(isTwo()) {
RETURNNODE( _1() );
} else if(isOne()) {
RETURNNODE( _0() );
} else if((getSymbol() == POW) && left().isTwo()) {
RETURNNODE( right() );
}
RETURNNULL;
}
SNode SNode::reduceAsymmetricFunction() {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_TREE);
if(isReduced()) RETURNTHIS;
SNode arg = left();
if(getInverseFunction() == arg.getSymbol()) {
RETURNNODE(arg.left());
}
const SNode Rarg = arg.reduceRealExp();
if(Rarg.isUnaryMinus()) { // f(-exp) = -f(exp)
RETURNNODE(-unaryExp(getSymbol(), Rarg.left()));
} else if(Rarg.isSameNode(arg)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE(unaryExp(getSymbol(), Rarg));
}
}
SNode SNode::reduceSymmetricFunction() {
ENTERMETHOD();
CHECKNODETYPE(*this,NT_TREE);
if(isReduced()) RETURNTHIS;
SNode arg = left();
if(getInverseFunction() == arg.getSymbol()) {
RETURNNODE(arg.left());
}
const SNode Rarg = arg.reduceRealExp();
if(Rarg.isUnaryMinus()) { // f(-exp) = f(exp)
RETURNNODE( unaryExp(getSymbol(), Rarg.left()));
} else if(Rarg.isSameNode(arg)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE(unaryExp(getSymbol(), Rarg));
}
}
/*
* symbol = POLY
* return no leading zeroes, all constant coefficients evaluated
*/
SNode SNode::reducePoly() {
ENTERMETHOD();
CHECKSYMBOL(*this,POLY);
if(isReduced()) RETURNTHIS;
CoefArray &coefArray = getCoefArray();
SNode arg = getArgument(); // arg is the parameter to the polynomial ex. poly[a,b,c,d](arg)
CoefArray newCoefArray(coefArray.getTree());
bool leadingCoef = true;
for(size_t i = 0; i < coefArray.size(); i++) {
SNode coef = coefArray[i];
Number cv;
if(!coef.isConstant(&cv)) { // coef not constant
newCoefArray.add(coef.reduceRealExp());
} else if(coef.isNumber()) { // coef is constant
if(coef.isZero() && leadingCoef) continue;
newCoefArray.add(coef);
} else { // coef is consant and !NUMBER
if((cv == 0) && leadingCoef) continue;
newCoefArray.add(SNV(cv));
}
leadingCoef = false;
}
switch(newCoefArray.size()) {
case 0 : RETURNNODE( _0() ); // 0 polynomial == 0
case 1 : RETURNNODE( newCoefArray[0] ); // Independent of arg
default:
{ const SNode newArg = arg.reduceRealExp();
if((newCoefArray.isSameNodes(coefArray)) && (newArg.isSameNode(arg))) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( polyExp(newCoefArray, newArg) );
}
}
}
}
SNode SNode::reduceCondExp() {
ENTERMETHOD();
CHECKSYMBOL(*this, IIF);
if(isReduced()) RETURNTHIS;
SNode cond = child(0);
SNode trueExp = child(1);
SNode falseExp = child(2);
SNode RtrueExp = trueExp.reduceRealExp();
SNode RfalseExp = falseExp.reduceRealExp();
if(RtrueExp.equal(RfalseExp)) {
RETURNNODE( RtrueExp );
}
SNode Rcond = cond.reduceBoolExp();
if(Rcond.isTrue() ) RETURNNODE( RtrueExp );
if(Rcond.isFalse()) RETURNNODE( RfalseExp );
if(Rcond.isSameNode(cond) && RtrueExp.isSameNode(trueExp) && RfalseExp.isSameNode(falseExp)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( condExp(Rcond, RtrueExp, RfalseExp ) );
}
}
SNode SNode::reduceTreeNode() {
ENTERMETHOD();
CHECKNODETYPE(*this, NT_TREE);
if(isReduced()) RETURNTHIS;
if(getInverseFunction() == left().getSymbol()) {
RETURNNODE( left().left() );
}
SNodeArray &a = getChildArray();
const size_t sz = a.size();
SNodeArray newChildArray(a.getTree(),sz);
for(size_t i = 0; i < sz; i++) {
newChildArray.add(a[i].reduceRealExp());
}
if(newChildArray.isSameNodes(a)) {
setReduced();
RETURNTHIS;
} else {
RETURNNODE( treeExp(getSymbol(), newChildArray) );
}
}
}; // namespace Expr
| [
"jesper.gr.mikkelsen@gmail.com"
] | jesper.gr.mikkelsen@gmail.com |
9068bc7d71f03b6814b8d5918dfffba24495bf4f | 332f69ccfcb5cc957666272fed764d35da6660f1 | /Source/dx.cpp | 3ca0befdf660cff3d3a80616eb88803352735c12 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | neokdev/devilution | d6e8c43b26432335be07892f47a0b43b73f9255d | ee5675108eb0b8e169b5f154ccc4dee8a11d4abe | refs/heads/master | 2020-03-28T12:49:08.618399 | 2018-09-10T23:12:12 | 2018-09-10T23:12:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,838 | cpp | //HEADER_GOES_HERE
#include "../types.h"
void *sgpBackBuf;
int dx_cpp_init_value; // weak
IDirectDraw *lpDDInterface;
IDirectDrawPalette *lpDDPalette; // idb
int sgdwLockCount;
Screen *gpBuffer;
IDirectDrawSurface *lpDDSBackBuf;
IDirectDrawSurface *lpDDSPrimary;
static CRITICAL_SECTION sgMemCrit;
char gbBackBuf; // weak
char gbEmulate; // weak
HMODULE ghDiabMod; // idb
int dx_inf = 0x7F800000; // weak
struct dx_cpp_init_1
{
dx_cpp_init_1()
{
dx_cpp_init_value = dx_inf;
}
} _dx_cpp_init_1;
// 47A464: using guessed type int dx_inf;
// 52A514: using guessed type int dx_cpp_init_value;
struct dx_cpp_init_2
{
dx_cpp_init_2()
{
dx_init_mutex();
dx_cleanup_mutex_atexit();
}
} _dx_cpp_init_2;
void __cdecl dx_init_mutex()
{
InitializeCriticalSection(&sgMemCrit);
}
void __cdecl dx_cleanup_mutex_atexit()
{
atexit(dx_cleanup_mutex);
}
void __cdecl dx_cleanup_mutex()
{
DeleteCriticalSection(&sgMemCrit);
}
void __fastcall dx_init(HWND hWnd)
{
HWND v1; // esi
GUID *v2; // ecx
int v3; // eax
int v4; // eax
//int v5; // ecx
int v6; // edi
int v7; // eax
int v8; // eax
HWND hWnda; // [esp+1Ch] [ebp-4h]
v1 = hWnd;
hWnda = hWnd;
SetFocus(hWnd);
ShowWindow(v1, SW_SHOWNORMAL);
v2 = NULL;
if ( gbEmulate )
v2 = (GUID *)DDCREATE_EMULATIONONLY;
v3 = dx_DirectDrawCreate(v2, &lpDDInterface, NULL);
if ( v3 )
ErrDlg(IDD_DIALOG1, v3, "C:\\Src\\Diablo\\Source\\dx.cpp", 149);
fullscreen = 1;
v4 = lpDDInterface->SetCooperativeLevel(v1, DDSCL_EXCLUSIVE|DDSCL_ALLOWREBOOT|DDSCL_FULLSCREEN);
if ( v4 == DDERR_EXCLUSIVEMODEALREADYSET )
{
MI_Dummy(0); // v5
}
else if ( v4 )
{
ErrDlg(IDD_DIALOG1, v4, "C:\\Src\\Diablo\\Source\\dx.cpp", 170);
}
if ( lpDDInterface->SetDisplayMode(640, 480, 8) )
{
v6 = GetSystemMetrics(SM_CXSCREEN);
v7 = GetSystemMetrics(SM_CYSCREEN);
v8 = lpDDInterface->SetDisplayMode(v6, v7, 8);
if ( v8 )
ErrDlg(IDD_DIALOG1, v8, "C:\\Src\\Diablo\\Source\\dx.cpp", 183);
}
dx_create_primary_surface();
palette_init();
GdiSetBatchLimit(1);
dx_create_back_buffer();
SDrawManualInitialize(hWnda, lpDDInterface, lpDDSPrimary, 0, 0, lpDDSBackBuf, lpDDPalette, 0);
}
// 484364: using guessed type int fullscreen;
// 52A549: using guessed type char gbEmulate;
void __cdecl dx_create_back_buffer()
{
int v0; // eax
int v1; // eax
int v2; // eax
int v3; // eax
DDSURFACEDESC v4; // [esp+Ch] [ebp-70h]
DDSCAPS v5; // [esp+78h] [ebp-4h]
v0 = lpDDSPrimary->GetCaps(&v5);
if ( v0 )
DDErrMsg(v0, 59, "C:\\Src\\Diablo\\Source\\dx.cpp");
if ( !gbBackBuf )
{
v4.dwSize = 108;
v1 = lpDDSPrimary->Lock(NULL, &v4, DDLOCK_WRITEONLY|DDLOCK_WAIT, NULL);
if ( !v1 )
{
lpDDSPrimary->Unlock(NULL);
sgpBackBuf = DiabloAllocPtr(0x7B000);
return;
}
if ( v1 != DDERR_CANTLOCKSURFACE )
ErrDlg(IDD_DIALOG1, v1, "C:\\Src\\Diablo\\Source\\dx.cpp", 81);
}
memset(&v4, 0, 0x6Cu);
v4.dwWidth = 768;
v4.lPitch = 768;
v4.dwSize = 108;
v4.dwFlags = DDSD_PIXELFORMAT|DDSD_PITCH|DDSD_WIDTH|DDSD_HEIGHT|DDSD_CAPS;
v4.ddsCaps.dwCaps = DDSCAPS_SYSTEMMEMORY|DDSCAPS_OFFSCREENPLAIN;
v4.dwHeight = 656;
v4.ddpfPixelFormat.dwSize = 32;
v2 = lpDDSPrimary->GetPixelFormat(&v4.ddpfPixelFormat);
if ( v2 )
ErrDlg(IDD_DIALOG1, v2, "C:\\Src\\Diablo\\Source\\dx.cpp", 94);
v3 = lpDDInterface->CreateSurface(&v4, &lpDDSBackBuf, NULL);
if ( v3 )
ErrDlg(IDD_DIALOG1, v3, "C:\\Src\\Diablo\\Source\\dx.cpp", 96);
}
// 52A548: using guessed type char gbBackBuf;
void __cdecl dx_create_primary_surface()
{
int v0; // eax
DDSURFACEDESC v1; // [esp+0h] [ebp-6Ch]
memset(&v1, 0, 0x6Cu);
v1.dwSize = 108;
v1.dwFlags = DDSD_CAPS;
v1.ddsCaps.dwCaps = DDSCAPS_PRIMARYSURFACE;
v0 = lpDDInterface->CreateSurface(&v1, &lpDDSPrimary, NULL);
if ( v0 )
ErrDlg(IDD_DIALOG1, v0, "C:\\Src\\Diablo\\Source\\dx.cpp", 109);
}
HRESULT __fastcall dx_DirectDrawCreate(GUID *guid, IDirectDraw **DD, void *unknown)
{
IDirectDraw **v3; // ebp
int v4; // eax
FARPROC v5; // ebx
int v6; // eax
GUID *v8; // [esp+10h] [ebp-4h]
v3 = DD;
v8 = guid;
if ( !ghDiabMod )
{
ghDiabMod = LoadLibraryA("ddraw.dll");
if ( !ghDiabMod )
{
v4 = GetLastError();
ErrDlg(IDD_DIALOG4, v4, "C:\\Src\\Diablo\\Source\\dx.cpp", 122);
}
}
v5 = GetProcAddress(ghDiabMod, "DirectDrawCreate");
if ( !v5 )
{
v6 = GetLastError();
ErrDlg(IDD_DIALOG4, v6, "C:\\Src\\Diablo\\Source\\dx.cpp", 127);
}
return ((int (__stdcall *)(GUID *, IDirectDraw **, void *))v5)(v8, v3, unknown);
}
void __cdecl lock_buf_priv()
{
Screen *v0; // eax
int v1; // eax
DDSURFACEDESC v2; // [esp+0h] [ebp-6Ch]
EnterCriticalSection(&sgMemCrit);
v0 = (Screen *)sgpBackBuf;
if ( sgpBackBuf )
goto LABEL_8;
if ( lpDDSBackBuf )
{
if ( sgdwLockCount )
goto LABEL_9;
v2.dwSize = 108;
v1 = lpDDSBackBuf->Lock(NULL, &v2, DDLOCK_WAIT, NULL);
if ( v1 )
DDErrMsg(v1, 235, "C:\\Src\\Diablo\\Source\\dx.cpp");
v0 = (Screen *)v2.lpSurface;
gpBufEnd += (unsigned int)v2.lpSurface;
LABEL_8:
gpBuffer = v0;
goto LABEL_9;
}
Sleep(20000);
TermMsg("lock_buf_priv");
LABEL_9:
++sgdwLockCount;
}
// 69CF0C: using guessed type int gpBufEnd;
void __cdecl unlock_buf_priv()
{
Screen *v0; // eax
int v1; // eax
if ( !sgdwLockCount )
TermMsg("draw main unlock error");
if ( !gpBuffer )
TermMsg("draw consistency error");
if ( !--sgdwLockCount )
{
v0 = gpBuffer;
gpBuffer = 0;
gpBufEnd -= (signed int)v0;
if ( !sgpBackBuf )
{
v1 = lpDDSBackBuf->Unlock(NULL);
if ( v1 )
DDErrMsg(v1, 273, "C:\\Src\\Diablo\\Source\\dx.cpp");
}
}
LeaveCriticalSection(&sgMemCrit);
}
// 69CF0C: using guessed type int gpBufEnd;
void __cdecl dx_cleanup()
{
void *v0; // ecx
if ( ghMainWnd )
ShowWindow(ghMainWnd, SW_HIDE);
SDrawDestroy();
EnterCriticalSection(&sgMemCrit);
if ( sgpBackBuf )
{
v0 = sgpBackBuf;
sgpBackBuf = 0;
mem_free_dbg(v0);
}
else if ( lpDDSBackBuf )
{
lpDDSBackBuf->Release();
lpDDSBackBuf = 0;
}
sgdwLockCount = 0;
gpBuffer = 0;
LeaveCriticalSection(&sgMemCrit);
if ( lpDDSPrimary )
{
lpDDSPrimary->Release();
lpDDSPrimary = 0;
}
if ( lpDDPalette )
{
lpDDPalette->Release();
lpDDPalette = 0;
}
if ( lpDDInterface )
{
lpDDInterface->Release();
lpDDInterface = 0;
}
}
void __cdecl dx_reinit()
{
int v0; // esi
EnterCriticalSection(&sgMemCrit);
ClearCursor();
v0 = sgdwLockCount;
while ( sgdwLockCount )
unlock_buf_priv();
dx_cleanup();
drawpanflag = 255;
dx_init(ghMainWnd);
for ( ; v0; --v0 )
lock_buf_priv();
LeaveCriticalSection(&sgMemCrit);
}
// 52571C: using guessed type int drawpanflag;
| [
"noreply@github.com"
] | neokdev.noreply@github.com |
0603b329a93eae90b51eb3b608228cb8d2aebf66 | 67d19bd09fe300fd54ac654c5cac486605c151d5 | /Source/ProjectParasite/Utilities/StateMachine/States/Player/Player_State_Idle.h | 51f91f93eb5a0c1e3c395cd15a0207edc4010771 | [] | no_license | EliasWickander/ProjectParasite | 589ed1260d6be5997ea48edc86a0a9de1d63727c | 97224ee2c74f17d60eb2ae2bb04899e78f587594 | refs/heads/main | 2023-07-16T17:54:34.846673 | 2021-08-09T09:51:29 | 2021-08-09T09:51:29 | 371,028,965 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 455 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "../State.h"
#include "Player_State_Idle.generated.h"
class APawnParasite;
UCLASS()
class PROJECTPARASITE_API UPlayer_State_Idle : public UState
{
GENERATED_BODY()
protected:
virtual void Start() override;
virtual void Update() override;
virtual void Exit() override;
private:
APawnParasite* playerRef = nullptr;
};
| [
"elias.wt@hotmail.com"
] | elias.wt@hotmail.com |
61387db86b5a60e90e71b15bba46f4b0cebde6d4 | 74d6b6d8d03208020da46df94d301a23b3ba6225 | /src/MuONeUserEventInformation.cc | d206e6ba963c06fdd49f66276a169608fd4595ac | [] | no_license | stroili/MuOneSim | b35259437ef2db4b27ee6b7a35ef56012a92e3c8 | 907aff54ddfc7f0da6d367005273c7e21b54580a | refs/heads/master | 2021-07-24T17:19:07.651072 | 2017-11-03T09:29:40 | 2017-11-03T09:29:40 | 109,375,495 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,441 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
#include "MuONeUserEventInformation.hh"
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
MuONeUserEventInformation::MuONeUserEventInformation()
: _hitCount ( 0 ), _photonCount_Scint ( 0 ), _photonCount_Ceren ( 0 ), _absorptionCount ( 0 ),
_boundaryAbsorptionCount ( 0 ), _muonExitMom(G4ThreeVector()), _eProdMom(G4ThreeVector()),
_eExitMom(G4ThreeVector()), _muE(0.), _eE(0.), _eZprod(0.), _gammaEnergy(0.), _othersEnergy(0.),
_gammas(0), _others(0), _totE ( 0. ), _eWeightPos ( 0. ), _reconPos ( 0. ),
_convPos ( 0. ), _convPosSet ( false ), _posMax ( 0. ), _pmtsAboveThreshold ( 0 )
{
}
//_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_-_
MuONeUserEventInformation::~MuONeUserEventInformation()
{
}
| [
"roberto.stroili@desy.de"
] | roberto.stroili@desy.de |
9b91ebd7b63c426e9bb8ae9416466dddcfe0e303 | 7ba53ecbb5f2180c65b9b0ea935307938d91ac0b | /oldversion/compute_event_dihed-v2.cpp | 508e4804736f41ad6fb383eb8e1bbace689ddf02 | [] | no_license | lcwatkins/USER-LAURA | f08a800ec59ca70c8fe55864b9bc876bddf1c4b5 | b7c5f35f2bef45cebfee5cf9c4017a1ff732cbc0 | refs/heads/master | 2021-07-04T03:38:52.328534 | 2017-09-26T15:12:48 | 2017-09-26T15:12:48 | 104,902,435 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,768 | cpp | /* ----------------------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#include <math.h>
#include <string.h>
#include "compute_event_dihed.h"
#include "atom.h"
#include "atom_vec.h"
#include "molecule.h"
#include "update.h"
#include "domain.h"
#include "force.h"
#include "dihedral.h"
#include "math_const.h"
#include "memory.h"
#include "error.h"
#include "fix_event.h"
#include "modify.h"
#include "universe.h"
#include "group.h"
using namespace LAMMPS_NS;
using namespace MathConst;
#define DELTA 10000
#define SMALL 0.001
#define INVOKED_SCALAR 1
/* ---------------------------------------------------------------------- */
ComputeEventDihedral::ComputeEventDihedral(LAMMPS *lmp, int narg, char **arg) :
Compute(lmp, narg, arg), id_event(NULL), fix_event(NULL), group2(NULL)
{
if (narg < 4) error->all(FLERR,"Illegal compute event/dihedral command");
if (atom->avec->dihedrals_allow == 0)
error->all(FLERR,
"Compute event/dihedral used when dihedrals are not allowed");
local_flag = 1;
nvalues = narg - 3;
// do I want to keep this?
if (nvalues == 1) size_local_cols = 0;
else size_local_cols = nvalues;
pflag = -1;
nvalues = 0;
// get rid of this argument?
/*
for (int iarg = 3; iarg < narg; iarg++) {
if (strcmp(arg[iarg],"phi") == 0) pflag = nvalues++;
else error->all(FLERR,"Invalid keyword in compute event/dihedral command");
}
*/
scalar_flag = 1;
extscalar = 0;
// Get other group for 2nd dihedral to compute
int n = strlen(arg[3]) + 1;
group2 = new char[n];
strcpy(group2,arg[3]);
jgroup = group->find(group2);
if (jgroup == -1)
error->all(FLERR,"Compute event/dihedral group ID does not exist");
jgroupbit = group->bitmask[jgroup];
// fix event ID will be set later by accelerated dynamics method
id_event = NULL;
}
/* ---------------------------------------------------------------------- */
ComputeEventDihedral::~ComputeEventDihedral()
{
delete [] id_event;
delete [] group2;
}
/* ---------------------------------------------------------------------- */
void ComputeEventDihedral::init()
{
if (force->dihedral == NULL)
error->all(FLERR,"No dihedral style is defined for compute event/dihedral");
// if id_event is not set, this compute is not active
// if set by PRD, then find fix which stores original atom coords
// check if it is correct style
if (id_event != NULL) {
int ifix = modify->find_fix(id_event);
if (ifix < 0) error->all(FLERR,
"Could not find compute event/dihedral fix ID");
fix_event = (FixEvent*) modify->fix[ifix];
if (strcmp(fix_event->style,"EVENT/PRD") != 0 &&
strcmp(fix_event->style,"EVENT/TAD") != 0 &&
strcmp(fix_event->style,"EVENT/HYPER") != 0)
error->all(FLERR,"Compute event/dihedral has invalid fix event assigned");
}
// Why necessary? Recheck that group 2 has not been deleted
jgroup = group->find(group2);
if (jgroup == -1)
error->all(FLERR,"Compute group/group group ID does not exist");
jgroupbit = group->bitmask[jgroup];
}
/* ----------------------------------------------------------------------
count dihedrals on this proc
only count if 2nd atom is the one storing the dihedral
all atoms in interaction must be in group
all atoms in interaction must be known to proc
if flag is set, compute requested info about dihedral
------------------------------------------------------------------------- */
double ComputeEventDihedral::compute_scalar()
{
invoked_scalar = update->ntimestep;
if (id_event == NULL) return 0.0;
// default no event
double event = 0.0;
double **xevent = fix_event->array_atom;
int i,nd,atom1,atom2,atom3,atom4,imol,iatom;
tagint tagprev;
// This is to keep track of if dihed. is in group 1, group 2, or both...
// for now, should be either phi or psi
// hard-coding that group1 == phi and group2 == psi atom definitions
int grpflag, jgrpflag;
int dihedcount = 0;
double dih, dihev, jdih, jdihev;
int region, regionev;
// I think don't need following line
double **x = atom->x;
tagint *tag = atom->tag;
int *num_dihedral = atom->num_dihedral;
tagint **dihedral_atom1 = atom->dihedral_atom1;
tagint **dihedral_atom2 = atom->dihedral_atom2;
tagint **dihedral_atom3 = atom->dihedral_atom3;
tagint **dihedral_atom4 = atom->dihedral_atom4;
int *mask = atom->mask;
int *molindex = atom->molindex;
int *molatom = atom->molatom;
Molecule **onemols = atom->avec->onemols;
int nlocal = atom->nlocal;
int molecular = atom->molecular;
/*
int numj;
numj = group->count(jgroup);
fprintf(universe->uscreen,"num atoms in group2: %d\n",numj);
int testatom;
for (testatom = 0; testatom < nlocal; testatom++) {
if (mask[testatom] & groupbit) {
fprintf(universe->uscreen,"atom %d in group2\n",testatom);
}
}
*/
for (atom2 = 0; atom2 < nlocal; atom2++) {
grpflag = jgrpflag = 0;
if (!(mask[atom2] & groupbit || mask[atom2] & jgroupbit)) continue;
if (mask[atom2] & groupbit) grpflag = 1;
if (mask[atom2] & jgroupbit) jgrpflag = 1;
if (molecular == 1) nd = num_dihedral[atom2];
else {
if (molindex[atom2] < 0) continue;
imol = molindex[atom2];
iatom = molatom[atom2];
nd = onemols[imol]->num_dihedral[iatom];
}
for (i = 0; i < nd; i++) {
if (molecular == 1) {
if (tag[atom2] != dihedral_atom2[atom2][i]) continue;
atom1 = atom->map(dihedral_atom1[atom2][i]);
atom3 = atom->map(dihedral_atom3[atom2][i]);
atom4 = atom->map(dihedral_atom4[atom2][i]);
} else {
if (tag[atom2] != onemols[imol]->dihedral_atom2[atom2][i]) continue;
tagprev = tag[atom2] - iatom - 1;
atom1 = atom->map(onemols[imol]->dihedral_atom1[atom2][i]+tagprev);
atom3 = atom->map(onemols[imol]->dihedral_atom3[atom2][i]+tagprev);
atom4 = atom->map(onemols[imol]->dihedral_atom4[atom2][i]+tagprev);
}
if (!(atom1 < 0 || atom3 < 0 || atom4 < 0)) {
if (grpflag) {
if ((mask[atom1] & groupbit) && (mask[atom3] & groupbit) && (mask[atom4] & groupbit)) {
dih = compute_dihedral(atom1, atom2, atom3, atom4, 0);
dihev = compute_dihedral(atom1, atom2, atom3, atom4, 1);
// fprintf(universe->uscreen,"atoms: %d, %d, %d, %d in grp1\n", atom1, atom2, atom3, atom4);
// fprintf(universe->uscreen,"no fxn dih: %f\n", dih);
dihedcount += 1;
}
}
if (jgrpflag) {
if ((mask[atom1] & jgroupbit) && (mask[atom3] & jgroupbit) && (mask[atom4] & jgroupbit)) {
jdih = compute_dihedral(atom1, atom2, atom3, atom4, 0);
jdihev = compute_dihedral(atom1, atom2, atom3, atom4, 1);
// fprintf(universe->uscreen,"atoms: %d, %d, %d, %d in grp2\n", atom1, atom2, atom3, atom4);
dihedcount += 1;
}
}
}
if (dihedcount == 2) break;
}
}
region = find_region(dih, jdih);
regionev = find_region(dihev, jdihev);
if (region == 0 | regionev == 0) error->all(FLERR,"Region not defined");
fprintf(universe->uscreen,"phi: %f, psi: %f\n", dih, jdih);
fprintf(universe->uscreen,"evphi: %f, evpsi: %f\n", dihev, jdihev);
fprintf(universe->uscreen,"prev region: %d, current: %d\n", regionev, region);
if (region != regionev) {
event = 1.0;
}
MPI_Allreduce(&event,&scalar,1,MPI_DOUBLE,MPI_SUM,world);
return scalar;
}
/* ----------------------------------------------------------------------
determine region of Ramachandran plot from two angles
------------------------------------------------------------------------- */
int ComputeEventDihedral::find_region(double phi, double psi)
{
int region = 0;
if ((0.0 <= phi) && (phi < 150.0)) {
if ((0.0 <= psi) && (psi < 130.0)) region = 5;
else region = 1;
} else {
if ((-120.0 <= psi) && (psi < 0.0)) region = 2;
else if ((0.0 <= psi) && (psi < 120.0)) region = 4;
else region = 3;
}
return region;
}
/* ----------------------------------------------------------------------
actual dihedral computation from dihedral style harmonic
------------------------------------------------------------------------- */
double ComputeEventDihedral::compute_dihedral(int atom1, int atom2, int atom3, int atom4, int eventflag)
{
double vb1x,vb1y,vb1z,vb2x,vb2y,vb2z,vb3x,vb3y,vb3z,vb2xm,vb2ym,vb2zm;
double ax,ay,az,bx,by,bz,rasq,rbsq,rgsq,rg,ra2inv,rb2inv,rabinv;
double s,c, dih;
double **x = NULL ;
if (eventflag) {
x = fix_event->array_atom ;
} else {
x = atom->x ;
}
vb1x = x[atom1][0] - x[atom2][0];
vb1y = x[atom1][1] - x[atom2][1];
vb1z = x[atom1][2] - x[atom2][2];
domain->minimum_image(vb1x,vb1y,vb1z);
vb2x = x[atom3][0] - x[atom2][0];
vb2y = x[atom3][1] - x[atom2][1];
vb2z = x[atom3][2] - x[atom2][2];
domain->minimum_image(vb2x,vb2y,vb2z);
vb2xm = -vb2x;
vb2ym = -vb2y;
vb2zm = -vb2z;
domain->minimum_image(vb2xm,vb2ym,vb2zm);
vb3x = x[atom4][0] - x[atom3][0];
vb3y = x[atom4][1] - x[atom3][1];
vb3z = x[atom4][2] - x[atom3][2];
domain->minimum_image(vb3x,vb3y,vb3z);
ax = vb1y*vb2zm - vb1z*vb2ym;
ay = vb1z*vb2xm - vb1x*vb2zm;
az = vb1x*vb2ym - vb1y*vb2xm;
bx = vb3y*vb2zm - vb3z*vb2ym;
by = vb3z*vb2xm - vb3x*vb2zm;
bz = vb3x*vb2ym - vb3y*vb2xm;
rasq = ax*ax + ay*ay + az*az;
rbsq = bx*bx + by*by + bz*bz;
rgsq = vb2xm*vb2xm + vb2ym*vb2ym + vb2zm*vb2zm;
rg = sqrt(rgsq);
ra2inv = rb2inv = 0.0;
if (rasq > 0) ra2inv = 1.0/rasq;
if (rbsq > 0) rb2inv = 1.0/rbsq;
rabinv = sqrt(ra2inv*rb2inv);
c = (ax*bx + ay*by + az*bz)*rabinv;
s = rg*rabinv*(ax*vb3x + ay*vb3y + az*vb3z);
if (c > 1.0) c = 1.0;
if (c < -1.0) c = -1.0;
dih = 180.0*atan2(s,c)/MY_PI;
// fprintf(universe->uscreen,"in fxn dih: %f\n",dih);
return dih;
}
/* ---------------------------------------------------------------------- */
void ComputeEventDihedral::reset_extra_compute_fix(const char *id_new)
{
delete [] id_event;
id_event = NULL;
if (id_new == NULL) return;
int n = strlen(id_new) + 1;
id_event = new char[n];
strcpy(id_event,id_new);
}
| [
"lcwatkins@uchicago.edu"
] | lcwatkins@uchicago.edu |
90e837bed906776e377542977574ea2ad4dcbf54 | bdfca7d4bd6e1baf2c43e593de66fcba80afadeb | /prog-verf/assignment1/sketch-1.7.5/sketch-frontend/test/sk/seq/miniTestb491_test.cpp | ec2341e83480dd6768a75e713944a7fc71dc5d99 | [] | no_license | wanghanxiao123/Semester4 | efa82fc435542809d6c1fbed46ed5fea1540787e | c37ecda8b471685b0b6350070b939d01122f5e7f | refs/heads/master | 2023-03-22T06:47:16.823584 | 2021-03-15T10:46:53 | 2021-03-15T10:46:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include "vops.h"
#include "miniTestb491.h"
using namespace std;
void main__Wrapper_ANONYMOUSTest(Parameters& _p_) {
for(int _test_=0;_test_< _p_.niters ;_test_++) {
int n;
n=abs(rand()) % 32;
if(_p_.verbosity > 2){
cout<<"n="<<n<<endl;
}
if(n==0){ continue; }
int* a= new int [n];
for(int _i_=0;_i_<n;_i_++) {
a[_i_]=abs(rand()) % 32;
}
if(_p_.verbosity > 2){
cout<<"a=[";
for(int _i_=0;_i_<n;_i_++) {
cout<<a[_i_]<<", ";
}
cout<<"]"<<endl;
}
try{
ANONYMOUS::main__WrapperNospec(n,a);
ANONYMOUS::main__Wrapper(n,a);
}catch(AssumptionFailedException& afe){ }
delete[] a;
}
}
int main(int argc, char** argv) {
Parameters p(argc, argv);
srand(time(0));
main__Wrapper_ANONYMOUSTest(p);
printf("Automated testing passed for miniTestb491\n");
return 0;
}
| [
"akshatgoyalak23@gmail.com"
] | akshatgoyalak23@gmail.com |
59d6b6709c2bde1ca17654f596d8a98ac902686e | 26ad4f11ee9900ae33ba1257ba36e85817204249 | /cpp/cpp_basic/Cpp_OOP_Basics/The_Circle_Class/TestCircle.cpp | 76900c139fcddeabc2c43d6d9b179a278f4b0601 | [] | no_license | phamvubinh/working_space | 9a45187b8855c901ff6c653d9d40d23511df575b | 7939bae93d1c9809a95e4acf41abdb31a28093fa | refs/heads/master | 2022-11-26T12:24:44.358256 | 2022-11-06T07:19:22 | 2022-11-06T07:19:22 | 181,434,939 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include <iostream>
#include "Circle.h"
int main()
{
Circle c1(1.2, "red");
c1.printInfo();
Circle c2(c1);
c2.printInfo();
c2.setColor("blue");
c2.printInfo();
return 0;
} | [
"phamvubinh91@gmail.com"
] | phamvubinh91@gmail.com |
ab6b2db9ec39fc6bbaafc14b9f9fb800c6289c84 | 571c39f625479a10f2543ed033133705ef6c0d56 | /src/ThirdParty/xerces/mac/xerces-c-3.1.1/src/xercesc/internal/ValidationContextImpl.cpp | cc547ce2d6c2495c4c006e9a4edec8391e3e2a9b | [
"Apache-2.0"
] | permissive | k8w/pixi-animate-extension | 4578879da61e7f8ed8aec373903defdafdbaf816 | e9a15d42db1d0a2a1e228f58bf2aa50346ca3ef4 | refs/heads/master | 2021-05-06T11:16:31.477555 | 2018-01-24T04:25:53 | 2018-01-24T04:25:53 | 114,258,145 | 1 | 0 | null | 2017-12-14T14:10:19 | 2017-12-14T14:10:18 | null | UTF-8 | C++ | false | false | 6,080 | cpp | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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.
*/
/*
* $Id: ValidationContextImpl.cpp 903149 2010-01-26 09:58:40Z borisk $
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/internal/ValidationContextImpl.hpp>
#include <xercesc/framework/XMLRefInfo.hpp>
#include <xercesc/validators/DTD/DTDEntityDecl.hpp>
#include <xercesc/validators/datatype/InvalidDatatypeValueException.hpp>
#include <xercesc/validators/schema/NamespaceScope.hpp>
#include <xercesc/internal/ElemStack.hpp>
#include <xercesc/internal/XMLScanner.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Constructor and Destructor
// ---------------------------------------------------------------------------
ValidationContextImpl::~ValidationContextImpl()
{
if (fIdRefList)
delete fIdRefList;
}
ValidationContextImpl::ValidationContextImpl(MemoryManager* const manager)
:ValidationContext(manager)
,fIdRefList(0)
,fEntityDeclPool(0)
,fToCheckIdRefList(true)
,fValidatingMemberType(0)
,fElemStack(0)
,fScanner(0)
,fNamespaceScope(0)
{
fIdRefList = new (fMemoryManager) RefHashTableOf<XMLRefInfo>(109, fMemoryManager);
}
/**
* IdRefList
*
*/
RefHashTableOf<XMLRefInfo>* ValidationContextImpl::getIdRefList() const
{
return fIdRefList;
}
void ValidationContextImpl::setIdRefList(RefHashTableOf<XMLRefInfo>* const newIdRefList)
{
if (fIdRefList)
delete fIdRefList;
fIdRefList = newIdRefList;
}
void ValidationContextImpl::clearIdRefList()
{
if (fIdRefList)
fIdRefList->removeAll();
}
void ValidationContextImpl::addId(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (idEntry)
{
if (idEntry->getDeclared())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ID_Not_Unique
, content
, fMemoryManager);
}
}
else
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it declared
//
idEntry->setDeclared(true);
}
void ValidationContextImpl::addIdRef(const XMLCh * const content)
{
if (!fIdRefList || !fToCheckIdRefList)
return;
XMLRefInfo* idEntry = fIdRefList->get(content);
if (!idEntry)
{
idEntry = new (fMemoryManager) XMLRefInfo(content, false, false, fMemoryManager);
fIdRefList->put((void*)idEntry->getRefName(), idEntry);
}
//
// Mark it used
//
idEntry->setUsed(true);
}
void ValidationContextImpl::toCheckIdRefList(bool toCheck)
{
fToCheckIdRefList = toCheck;
}
/**
* EntityDeclPool
*
*/
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::getEntityDeclPool() const
{
return fEntityDeclPool;
}
const NameIdPool<DTDEntityDecl>* ValidationContextImpl::setEntityDeclPool(const NameIdPool<DTDEntityDecl>* const newEntityDeclPool)
{
// we don't own it so we return the existing one for the owner to delete
const NameIdPool<DTDEntityDecl>* tempPool = fEntityDeclPool;
fEntityDeclPool = newEntityDeclPool;
return tempPool;
}
void ValidationContextImpl::checkEntity(const XMLCh * const content) const
{
if (fEntityDeclPool)
{
const DTDEntityDecl* decl = fEntityDeclPool->getByKey(content);
if (!decl || !decl->isUnparsed())
{
ThrowXMLwithMemMgr1(InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager);
}
}
else
{
ThrowXMLwithMemMgr1
(
InvalidDatatypeValueException
, XMLExcepts::VALUE_ENTITY_Invalid
, content
, fMemoryManager
);
}
}
/* QName
*/
bool ValidationContextImpl::isPrefixUnknown(XMLCh* prefix) {
bool unknown = false;
if (XMLString::equals(prefix, XMLUni::fgXMLNSString)) {
return true;
}
else if (!XMLString::equals(prefix, XMLUni::fgXMLString)) {
if(fElemStack && !fElemStack->isEmpty())
fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
unknown = (fNamespaceScope->getNamespaceForPrefix(prefix)==fNamespaceScope->getEmptyNamespaceId());
}
return unknown;
}
const XMLCh* ValidationContextImpl::getURIForPrefix(XMLCh* prefix) {
bool unknown = false;
unsigned int uriId = 0;
if(fElemStack)
uriId = fElemStack->mapPrefixToURI(prefix, unknown);
else if(fNamespaceScope)
{
uriId = fNamespaceScope->getNamespaceForPrefix(prefix);
unknown = uriId == fNamespaceScope->getEmptyNamespaceId();
}
if (!unknown)
return fScanner->getURIText(uriId);
return XMLUni::fgZeroLenString;
}
XERCES_CPP_NAMESPACE_END
| [
"mbittarelli@Matts-MacBook-Pro.local"
] | mbittarelli@Matts-MacBook-Pro.local |
8d4b583cc7867dca627d596f7caca2e2a24f01eb | 75a574cc626abb6106d749cc55c7acd28e672594 | /Test/FiniteAutomation.cpp | c3a9f9210ba8b6d888318022745c79e498522e2e | [] | no_license | PeterGH/temp | 6b247e0f95ac3984d61459e0648421253d11bdc3 | 0427b6614880e8c596cca0350a02fda08fb28176 | refs/heads/master | 2020-03-31T16:10:30.114748 | 2018-11-19T03:48:53 | 2018-11-19T03:48:53 | 152,365,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,695 | cpp | #include "FiniteAutomation.h"
namespace Test {
FiniteAutomation::FiniteAutomation(char * pattern, int length)
{
if (pattern == nullptr) throw invalid_argument("pattern is nullptr");
if (pattern[0] == '\0') throw invalid_argument("pattern is empty");
if (length <= 0) throw invalid_argument(String::Format("length %d <= 0", length));
this->ComputeTransition(pattern, length);
}
FiniteAutomation::~FiniteAutomation(void)
{
for_each(this->transition.begin(), this->transition.end(), [](pair<int, map<char, int>*> it)->void {
if (it.second != nullptr) {
delete it.second;
it.second = nullptr;
}
});
}
int FiniteAutomation::PatternLength(void)
{
return this->transition.size() - 1;
}
void FiniteAutomation::Print(void)
{
for_each(this->transition.begin(), this->transition.end(), [](pair<int, map<char, int>*> it)->void {
printf_s("State %d\n", it.first);
for_each(it.second->begin(), it.second->end(), [](pair<char, int> iit)->void {
printf_s("\t%c -> %d\n", iit.first, iit.second);
});
});
}
vector<int> FiniteAutomation::SearchString(char * input, int length)
{
vector<int> indices;
if (input == nullptr || input[0] == '\0' || length <= 0) return indices;
int state = -1;
for (int i = 0; i < length; i++) {
map<int, map<char, int>*>::iterator itState = this->transition.find(state);
if (itState == this->transition.end()) {
state = -1;
continue;
}
map<char, int>::iterator itChar = itState->second->find(input[i]);
if (itChar == itState->second->end()) {
// input[i] is invalid
state = -1;
} else {
state = itChar->second;
if (state == this->transition.size() - 2) {
// It is the final state
indices.push_back(i - state);
}
}
}
return indices;
}
void FiniteAutomation::ComputeTransition(char * pattern, int length)
{
// Construct state transition given pattern
// Valid states are -1, 0, 1, ..., (length-1)
unique_ptr<char[]> uniquechars(new char[length+1]);
memcpy(uniquechars.get(), pattern, length*sizeof(char));
uniquechars.get()[length] = '\0';
int count = String::RemoveDuplicateChars(uniquechars.get(), length);
// Initialize starting state -1
map<char, int>* initState = new map<char, int>();
initState->insert(pair<char, int>(pattern[0], 0));
this->transition.insert(pair<int, map<char, int>*>(-1, initState));
unique_ptr<char[]> buffer(new char[length + 2]);
for (int state = 0; state < length; state ++) {
buffer[state] = pattern[state];
map<char, int>* nextState = new map<char, int>();
// Build nextState given each unique char
for (int i = 0; i < count; i ++) {
char c = uniquechars[i];
buffer[state+1] = c;
buffer[state+2] = '\0';
int index = Suffix(pattern, buffer.get());
if (index != -1) {
nextState->insert(pair<char, int>(c, index));
}
}
this->transition.insert(pair<int, map<char, int>*>(state, nextState));
}
}
// Find the longest prefix substring of pattern that is also a suffix of input
int FiniteAutomation::Suffix(char* pattern, char* input)
{
if (pattern == nullptr) return -1;
if (input == nullptr) return -1;
int m = (int)strlen(pattern);
if (m <= 0) return -1;
int n = (int)strlen(input);
if (n <= 0) return -1;
for (int i = min(m-1, n-1); i >= 0; i --) {
// Start from pattern[i], move backward to pattern[0]
int j = 0;
while (pattern[i-j] == input[n-1-j] && j <= i) {
j ++;
}
if (j == i+1) {
// pattern[0..i] == input[(n-1-i)..(n-1)]
return i;
}
}
return -1;
}
} | [
"peteryzufl@gmail.com"
] | peteryzufl@gmail.com |
65c85c6cde554b348393df52be2c029e9bdae114 | 4423987b3cb13ad3321479d11de9f0250575df75 | /Codeforces/Ascendants/TWO/Round410/bb.cpp | cffa85363d563b663e80354dca0b9cef1bc52768 | [] | no_license | samplex63/Competitive-Programming | 5ebc3a933eed1a5921bea8e91b798c96225007bf | 546aecd109dbdedef5b9b2afaddb1fa5ff69bbde | refs/heads/master | 2022-12-04T16:51:57.648719 | 2020-08-24T13:37:47 | 2020-08-24T13:37:47 | 282,802,436 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | cpp | #include <bits/stdc++.h>
using namespace std;
#define fi first
#define se second
#define sz(x) static_cast<int>((x).size())
#define all(x) (x).begin(), (x).end()
using ll = long long;
using ld = long double;
using vi = vector<int>;
using pii = pair<int, int>;
template<class T> bool cmn(T &a, T b) { return a > b ? (a = b, true) : false; }
template<class T> bool cmx(T &a, T b) { return a < b ? (a = b, true) : false; }
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
vector<string> vec(n);
for(int i = 0; i < n; ++i) cin >> vec[i];
if(n == 1) {
cout << 0 << '\n';
return 0;
}
int ans = INT_MAX;
for(int i = 0; i < n; ++i) {
vector<int> req;
for(int j = 0; j < n; ++j) {
if(i == j) continue;
string cpy = vec[j];
int cnt = 0;
while(cnt < sz(vec[j]) && vec[i] != cpy) {
cpy = cpy.substr(1) + cpy[0];
cnt++;
}
req.push_back(cnt);
}
int mxi = *max_element(all(req));
if(mxi == sz(vec[i])) {
ans = -1;
break;
}
// for(int j = 0; j < sz(req); ++j) {
// cerr << req[j] << ' ';
// }
// cerr << '\n';
int tot = accumulate(all(req), 0);
cmn(ans, tot);
}
cout << ans << '\n';
return 0;
} | [
"42390214+samplex63@users.noreply.github.com"
] | 42390214+samplex63@users.noreply.github.com |
9c8dff2edaef1cb8221d4ef665f2f6f4eaffcba6 | 24653c0a8be19e46eb95451de1d961ffbcc01341 | /software/src/8.0/src/backend/rslang.cpp | c19b715a7b75034c9e1590362159bf33087a63cf | [
"BSD-3-Clause"
] | permissive | VisionAerie/vision | 150e5bfa7eb16116b1e5b4bdb1bb8cee888fbfe5 | e40c39e3abc49b0e2c9623204c54b900c4333f29 | refs/heads/master | 2021-01-19T09:23:34.429209 | 2019-01-30T17:10:59 | 2019-01-30T17:10:59 | 82,104,368 | 2 | 1 | BSD-3-Clause | 2019-01-30T17:11:00 | 2017-02-15T20:41:27 | C++ | UTF-8 | C++ | false | false | 122,926 | cpp | /***** Research System Language Compiler *****/
/***************************
***** Facility Name *****
***************************/
#define FacilityName RSLANG
/******************************************
***** Header and Declaration Files *****
******************************************/
/***** System *****/
#include "Vk.h"
/***** Facility *****/
#include "m.h"
#include "selector.h"
#include "vdsc.h"
#include "venvir.h"
#include "verr.h"
#include "vfac.h"
#include "vmagic.h"
#include "vstdio.h"
#include "viobj.h"
#include "vutil.h"
#include "VByteCodeScanner.h"
#include "VSelector.h"
#include "RTblock.h"
#include "RTdictionary.h"
#include "RTdsc.h"
#include "RTstring.h"
/***** Self *****/
#include "rslang.h"
/****************************
***** Common Strings *****
****************************/
PrivateVarDef char const
*StringSpaceAvailabilityMessage = "Checking String Storage availability\n",
*StringSpaceParametersMessage = "\t\tSpace = %08X, Ptr = %08X, Size = %u",
*StringSpaceUsedMessage = " Used = %u\n",
*StringSpaceAdjustmentMessage = " Adjustment = %d\n",
*StringSpaceAddMessage = "... Adding Storage\n",
*StringSpaceReallocateMessage = "Reallocated Space\n",
*BufferAllocationMessage = "Buffer alloc. Buffer = %08X, Size = %u, used = %u\n",
*OneParameterBCTraceMessage = "\t%u ",
*TagBCTraceMessage = "\tVMACHINE_BC_Tag %c\n",
*StringSpaceTraceMessage = "%u(%s)\n",
*StringSpaceTraceMessage2 = "%u(%s) %u\n",
*StackAllocationMessage = "Stack alloc. Stack = %08X, Size = %d\n",
*StackPushMessage = "RSLANG[DCStack_Push]: n:%d ByteCode:%u String:%.*s SP:%d\n",
*StackPopMessage = "RSLANG[DCStack_Pop]: SP:%d\n";
/***********************************
***** Parse Tree Node Types *****
***********************************/
enum TokenTypes {
_Error,
_Identifier,
_IntensionalIdentifier,
_ConcatOp,
_IntensionalConcatOp,
_Keyword,
_IntensionalKeyword,
_LeftAssignment,
_IntensionalLeftAssignment,
_RightAssignment,
_IntensionalRightAssignment,
_LessThanP,
_IntensionalLessThanP,
_LessThanOrEqualP,
_IntensionalLessThanOrEqualP,
_GreaterThanOrEqualP,
_IntensionalGreaterThanOrEqualP,
_GreaterThanP,
_IntensionalGreaterThanP,
_EqualP,
_IntensionalEqualP,
_IdenticalP,
_IntensionalIdenticalP,
_NotEqualP,
_IntensionalNotEqualP,
_NotIdenticalP,
_IntensionalNotIdenticalP,
_Or,
_IntensionalOr,
_And,
_IntensionalAnd,
_Plus,
_IntensionalPlus,
_Minus,
_IntensionalMinus,
_Times,
_IntensionalTimes,
_Divide,
_IntensionalDivide,
_Integer,
_NegInteger,
_HexInteger,
_NegHexInteger,
_Real,
_NegReal,
_String,
_OpenKeywordExpression,
_ClosedKeywordExpression,
_UnaryExpression,
_BinaryExpression,
_Root,
_EmptyExpression,
_SimpleBlock,
_HeadedBlock,
_Magic,
_LocalId,
_UnarySelector,
_BinarySelector,
_KeywordSelector,
_UnaryMessageTemplate,
_BinaryMessageTemplate,
_KeywordMessageTemplate,
_ParametricMessageTemplate
};
/******************************
***** Parser Utilities *****
******************************/
#define DoNothing
/***** Parse Tree Node List Terminator *****/
/*---------------------------------------------------------------------------
* The parse tree node list terminator is passed as the last argument of
* routines that expect a variable list of parse tree nodes.
*---------------------------------------------------------------------------
*/
#define pTreeNLT -1
/****************************************
***** Parse Tree Node Structures *****
****************************************/
struct ParseTreeNode {
unsigned is_a_terminal_node : 1;
unsigned parenthesized : 1;
unsigned precedingSemi_colon : 1;
unsigned trailingPeriod : 1;
unsigned node_type : 28;
int threading_cell;
union node_info_t {
struct terminal_info_t {
int line_number,
origin,
length;
} terminal_info;
struct non_terminal_info_t {
int subtree_head,
subtree_tail;
} non_terminal_info;
} node_info;
};
#define InitialTreeSize 256
#define TreeSizeIncrement 256
#define NULL_NODE -1
struct TreeTemplate {
unsigned int NodeCount;
ParseTreeNode NodeArray[InitialTreeSize];
};
PrivateVarDef TreeTemplate *ParseTree;
PrivateVarDef int FreeList = NULL_NODE, rsROOT;
PrivateVarDef char const* rsSOURCE;
PrivateVarDef char const* sourceBASE;
/*---------------------------------------------------------------------------
* Debugger Trace Switches
*---------------------------------------------------------------------------
*/
PrivateVarDef bool
retainingBlockForBrowsing = false,
tracingCompile = false,
tracingCodeGeneration = false,
tracingDecompile = false,
tracingStackOps = false,
tracingStringSpaceOps = false,
tracingNodeTypeChange = false,
tracingNodeAppend = false,
tracingNodeAlloc = false,
tracingTerminalCreation = false,
tracingNonTerminalCreation = false;
PrivateVarDef IOBJ_IObject blockIObj;
/***************************
***** Access Macros *****
***************************/
#define nodeCount ParseTree->NodeCount
#define nodeArray(i) &(ParseTree->NodeArray[i])
#define Is_a_terminal_node(node)\
((nodeArray (node))->is_a_terminal_node)
#define Parenthesized(node)\
((nodeArray (node))->parenthesized)
#define PrecedingSemi_Colon(node)\
((nodeArray (node))->precedingSemi_colon)
#define TrailingPeriod(node)\
((nodeArray (node))->trailingPeriod)
#define NodeType(node)\
((nodeArray (node))->node_type)
#define NodeThreadingCell(node)\
((nodeArray (node))->threading_cell)
#define LineNumber(node)\
(((nodeArray (node))->node_info).terminal_info.line_number)
#define TerminalNode_Origin(node)\
(((nodeArray (node))->node_info).terminal_info.origin)
#define TerminalNode_Length(node)\
(((nodeArray (node))->node_info).terminal_info.length)
#define NonTerminal_SubtreeHead(node)\
(((nodeArray (node))->node_info).non_terminal_info.subtree_head)
#define NonTerminal_SubtreeTail(node)\
(((nodeArray (node))->node_info).non_terminal_info.subtree_tail)
/*******************************
***** Functional Macros *****
*******************************/
#define Thread_ParseNode(head, tail)\
NodeThreadingCell (head) = (tail)
#define Free_Node(node)\
Thread_ParseNode (node, FreeList);\
FreeList = (node)
PrivateFnDef void Expand_NodeStorage () {
int oldFree = FreeList;
ParseTree = (TreeTemplate *)UTIL_Realloc (
ParseTree,
sizeof (int) + (nodeCount += TreeSizeIncrement) * sizeof(ParseTreeNode)
);
for (unsigned int i = nodeCount - TreeSizeIncrement; i < nodeCount; i++) {
Free_Node (i);
}
if (tracingNodeAlloc) IO_printf (
"...RSLANG[Extend_NodeStorage] PT:%0p NC: %d FL:%d OFL:%d\n",
ParseTree, nodeCount, FreeList, oldFree
);
return;
}
PrivateFnDef void Alloc_ParseTree_Node (int* node_ptr) {
if (FreeList == NULL_NODE)
Expand_NodeStorage ();
*node_ptr = FreeList;
FreeList = NodeThreadingCell (FreeList);
return;
}
PrivateFnDef void Initialize_ParseTree_Nodes () {
FreeList = NULL_NODE;
if (IsNil (ParseTree)) {
ParseTree = (TreeTemplate *)UTIL_Malloc (sizeof (TreeTemplate));
nodeCount = InitialTreeSize;
}
for (unsigned int i = 0; i < nodeCount; i++) {
Free_Node (i);
}
if (tracingNodeAlloc) IO_printf (
"...RSLANG[Initialize_ParseTree_Nodes] PT:%0p NC: %d FL:%d\n",
ParseTree, nodeCount, FreeList
);
}
/***********************************************
***** Parse Tree Node Creation Routines *****
***********************************************/
/*---------------------------------------------------------------------------
***** Routine to create and return a new terminal symbol parse tree node.
*
* Arguments:
* nodeType - the logical type of the node being created.
* origin - the index of the start of the symbol in the
* input stream.
* extent - the length of the input symbol.
* lineNumber - the line number in the source at the end of
* this Terminal Symbol.
* Returns:
* An integer representing the index of the parse tree node created.
*
*****/
PrivateFnDef int pTreeTerminal (
int nodeType,
int origin,
int extent,
int lineNumber
)
{
int node;
Alloc_ParseTree_Node (&node);
Is_a_terminal_node (node) = true;
Parenthesized (node) = false;
PrecedingSemi_Colon (node) = false;
TrailingPeriod (node) = false;
NodeType (node) = nodeType;
NodeThreadingCell (node) = NULL_NODE;
LineNumber (node) = lineNumber;
TerminalNode_Origin (node) = origin;
TerminalNode_Length (node) = extent;
if (tracingTerminalCreation) IO_printf (
"T:%d, o:%d, e:%d, node:%d, ln:%d\n",
(int)NodeType (node), origin, extent, node, lineNumber
);
return node;
}
/*---------------------------------------------------------------------------
***** Routine to create and return a new non-terminal symbol parse tree node.
*
* Arguments:
* nodeType - the logical type of the node to be created.
* subTree1, ... - the indices of the parse tree nodes which are
* to become the initial subtrees of this node.
* pTreeNLT - the constant 'pTreeNLT'. This constant is
* guaranteed to be an invalid parse tree node
* index; its presence terminates the list.
*
* Returns:
* The index of the parse tree node created.
*
*****/
PrivateFnDef int __cdecl pTreeNonTerminal (int nodeType, ...) {
int node,
subnode,
first_node,
previous_node,
node_num;
Alloc_ParseTree_Node (&node);
Is_a_terminal_node (node) = false;
Parenthesized (node) = false;
PrecedingSemi_Colon (node) = false;
TrailingPeriod (node) = false;
NodeThreadingCell (node) = NULL_NODE;
NodeType (node) = nodeType;
V_VARGLIST (iArgList, nodeType);
previous_node = pTreeNLT;
for (node_num = 0; (subnode = (iArgList.arg<int>())) != pTreeNLT; node_num++) {
if (node_num == 0)
first_node = subnode;
else
Thread_ParseNode (previous_node, subnode);
previous_node = subnode;
}
NonTerminal_SubtreeHead (node) = first_node;
NonTerminal_SubtreeTail (node) = previous_node;
if (tracingNonTerminalCreation) IO_printf (
"NT:%d, H:%d, T:%d, node:%d\n",
(int)NodeType (node), first_node, previous_node, node
);
return node;
}
/***************************************************
***** Parse Tree Node Modification Routines *****
***************************************************/
/*---------------------------------------------------------------------------
***** Routine to append a collection of subtrees to a non-terminal node.
*
* Arguments:
* node - the index of a Non Terminal parse tree node
* to which the subtrees are to be appended.
* subTree1, ... - the indices of the parse tree nodes of the
* roots of the subtrees to be appended.
* pTreeNLT - the constant 'pTreeNLT'. This constant is
* guaranteed to be an invalid parse tree node
* index; its presence terminates the list.
*
* Returns:
* 'node'
*
* Errors Signalled:
* This routine will signal 'ERR_InvalidParseTreeNodeForOperation' if
* 'node' is not a terminal node.
*
*****/
PrivateFnDef int __cdecl pTreeAppendSubTrees (int node, ...) {
int previous, subnode;
if (tracingNodeAppend) IO_printf ("Type %u:Append", (int)NodeType (node));
if (Is_a_terminal_node (node))
return node; /* ERR_InvalidParseTreeNodeForOperation; */
V_VARGLIST (iArgList, node);
for (previous = NonTerminal_SubtreeTail (node); ((subnode = iArgList.arg<int>())) != pTreeNLT; previous = subnode) {
Thread_ParseNode (previous, subnode);
if (tracingNodeAppend) IO_printf ("\t%d to %d\n", subnode, previous);
}
NonTerminal_SubtreeTail (node) = previous;
return node;
}
/*---------------------------------------------------------------------------
***** Routine to change the logical type of a parse tree node.
*
* Arguments:
* node - the index of the parse tree node whose
* logical type is to be changed.
* newType - the new logical type of the node.
*
* Returns:
* 'node'
*
*****/
PrivateFnDef int pTreeChangeNodeType (
int node,
int newType
)
{
if (tracingNodeTypeChange) IO_printf (
"Node:%d Type change from %d to %d\n",node,(int)NodeType(node),newType
);
NodeType (node) = newType;
return node;
}
/*******************************************************************
***** Lexical and Syntactic Analysis Global State Variables *****
*******************************************************************/
extern int rslanglineno; /***** Must be declared 'extern' *****
***** to deal with VAX C 'extern' *****
***** brain damage. *****/
class ScanPointer {
// Construction
public:
ScanPointer () : m_xScan (0), m_xDisplay (0) {
}
// Access
public:
operator int () const {
return m_xScan;
}
int displayOffset () const {
return m_xDisplay;
}
// Update
public:
void reset () {
m_xDisplay = m_xScan = 0;
}
int operator++ () { // Prefix
int result = ++m_xScan;
m_xDisplay = m_xScan;
return result;
}
int operator-- () { // Prefix
int result = --m_xScan;
m_xDisplay = m_xScan;
return result;
}
int operator++ (int) { // Postfix
int result = m_xScan++;
m_xDisplay = m_xScan;
return result;
}
int operator-- (int) { // Postfix
int result = m_xScan--;
m_xDisplay = m_xScan;
return result;
}
void setDisplayOffsetTo (int xDisplay) {
m_xDisplay = xDisplay;
}
// State
protected:
int m_xScan;
int m_xDisplay;
};
PrivateVarDef ScanPointer CurrentScanPointer;
PrivateVarDef int IntensionalOp;
/*************************
***** Yacc Macros *****
*************************/
/***** Parse Tree Node Generating Macros *****/
#define Percolate(r, ntype, sub)\
r = pTreeNonTerminal ((int)ntype, sub, pTreeNLT)
#define Extend(r, a, b)\
r = pTreeAppendSubTrees (a, b, pTreeNLT);
#define Empty(r)\
r = pTreeTerminal ((int)_EmptyExpression, 0, 0, rslanglineno)
#define Root(r, exp)\
r = pTreeNonTerminal ((int)_Root, exp, pTreeNLT)
#define HeadedBlock(r, head, body)\
r = pTreeNonTerminal ((int)_HeadedBlock, head, body, pTreeNLT)
#define UnaryOp(r, a, op)\
r = pTreeNonTerminal ((int)_UnaryExpression, a, op, pTreeNLT)
#define BinaryOp(r, a, op, b)\
r = pTreeNonTerminal ((int)_BinaryExpression, a, op, b, pTreeNLT)
#define BinaryMessage(r, a, b)\
r = pTreeNonTerminal ((int)_BinaryMessageTemplate, a, b, pTreeNLT)
#define KeywordTerm(r, a, keyword, b)\
if (NodeType (a) == (int)_OpenKeywordExpression)\
r = pTreeAppendSubTrees (a, keyword, b, pTreeNLT);\
else\
r = pTreeNonTerminal ((int)_OpenKeywordExpression,\
a, keyword, b, pTreeNLT)
#define ClosingKeywordTerm(r, a, keyword, b)\
{\
if (NodeType (a) == (int)_OpenKeywordExpression)\
{\
pTreeAppendSubTrees (a, keyword, b, pTreeNLT);\
r = pTreeChangeNodeType (a, (int)_ClosedKeywordExpression);\
}\
else\
r = pTreeNonTerminal\
((int)_ClosedKeywordExpression, a, keyword, b, pTreeNLT);\
TrailingPeriod (r) = true;\
}
#define CloseParens(r, exp) {\
if (NodeType (exp) == (int)_OpenKeywordExpression)\
r = pTreeChangeNodeType ((exp), (int)_ClosedKeywordExpression);\
else\
r = exp;\
Parenthesized (r) = true;\
}
#define SetPrecedingSemi_Colon(exp) {\
PrecedingSemi_Colon (exp) = true;\
}
/***** Error Handler *****/
PrivateVarDef char *MessageBuffer;
PrivateVarDef int
MessageBufferMax,
*ErrorLine,
*ErrorCharacter;
#if defined(_AIX) && defined(__cplusplus) && !defined(_CPP_IOSTREAMS)
extern "C"
#endif
void rslangerror (char const *s) {
/***** Just fill the error message buffer if one was supplied, ... *****/
if (IsntNil (MessageBuffer)) {
sprintf (MessageBuffer, "%.*s", MessageBufferMax - 1, s);
*ErrorLine = rslanglineno + 1;
*ErrorCharacter = CurrentScanPointer.displayOffset ();
return;
}
/***** Otherwise, create a pointer to the current scan position in the input, ... *****/
char const* scanPointer = rsSOURCE + CurrentScanPointer.displayOffset () - 1;
if (scanPointer < rsSOURCE)
scanPointer = rsSOURCE;
/***** ... locate the beginning of the area to be displayed, ... *****/
char const* displayBase = rsSOURCE;
char const* newDisplayBase = strchr (displayBase, '\n');
while (newDisplayBase && newDisplayBase < scanPointer - 200) {
displayBase = newDisplayBase + 1;
newDisplayBase = strchr (displayBase, '\n');
}
/***** ... and print a description of the error, ... *****/
IO_printf (
">>> '%s' near source line %d, character %d <<<\n",
s, rslanglineno + 1, CurrentScanPointer.displayOffset ()
);
/***** ... along with some context: *****/
char const* displayLimit = displayBase + strlen (displayBase);
if (scanPointer + 100 < displayLimit)
displayLimit = scanPointer + 100;
do {
newDisplayBase = strchr (displayBase, '\n');
if (IsNil (newDisplayBase))
newDisplayBase = displayBase + strlen (displayBase);
IO_printf (" %.*s\n", newDisplayBase - displayBase, displayBase);
if (scanPointer >= displayBase && scanPointer <= newDisplayBase
) IO_printf (
"*%-*.*s^\n",
scanPointer - displayBase,
scanPointer - displayBase,
"*"
);
displayBase = newDisplayBase + 1;
} while (displayBase < displayLimit);
if (scanPointer >= displayBase) IO_printf (
"\n*%-*.*s^\n",
scanPointer - displayBase,
scanPointer - displayBase,
"*"
);
}
/**********************************
***** The Lexical Analyzer *****
**********************************/
/***** Token Generating Macros *****/
#define ReturnNode(nodeType, tokenType)\
rslanglval = pTreeTerminal (nodeType,\
CurrentScanPointer - (rslangleng),\
rslangleng, rslanglineno);\
return tokenType
#define ReturnSelector(nType, intensionalNType, tType, intensionalTType)\
if (IntensionalOp) {\
IntensionalOp = false;\
ReturnNode (intensionalNType, intensionalTType);\
}\
ReturnNode (nType, tType)
/***** I/O and Wrap-up Routines *****/
#ifdef __cplusplus
extern "C" {
#endif
extern int rslangwrap () {
return 1;
}
extern int rslanglex ();
#ifdef __cplusplus
}
#endif
/***** 'yacc' Output *****/
#include "rslang.yo"
/***** 'lex' Output *****/
#include "rslang.lo"
/**************************************************************
**************************************************************
***** Code Generator Routines *****
**************************************************************
**************************************************************/
/**************************************
***** Internal Data Structures *****
**************************************/
typedef struct bufferType {
int size;
pointer_t allocated_area,
current_ptr;
} stringSpaceType;
struct PLVectorType {
int size;
M_CPD** allocated_area;
unsigned short index;
} ;
struct ELEVectorType {
int size;
int * allocated_area;
unsigned short index;
} ;
/***************************
***** Access Macros *****
***************************/
#define Storage(x)\
((x)->allocated_area)
#define Size(x)\
((x)->size)
#define Ptr(x)\
((x)->current_ptr)
#define Index(x)\
((x)->index)
#define stringSpaceIndex(x)\
(Ptr (x) - Storage (x))
#define bufferIndex(x) (unsigned int)stringSpaceIndex(x)
/*******************************
***** Functional Macros *****
*******************************/
#define AlignShort(bufferPtr)\
(bufferPtr) += *(bufferPtr) = (unsigned char)(1 - ((pointer_size_t)(bufferPtr) & 1))
#define AlignInt(bufferPtr)\
(bufferPtr) += *(bufferPtr) = (unsigned char)(3 - ((pointer_size_t)(bufferPtr) & 3))
#define bCodePtr(cpd)\
rtBLOCK_CPD_PC(cpd)
/***********************
***** Constants *****
***********************/
#define MAX_BYTE_SIZE 255
#define INITIAL_BUFFER_SIZE 128
#define INITIAL_STRING_SPACE 1024
#define INITIAL_PLVECTOR_SIZE 16
#define INITIAL_ELEVECTOR_SIZE 16
#define bufferINCREMENT 128
#define stringSpaceINCREMENT 512
#define BCVectorINCREMENT 512
#define PLVectorINCREMENT 8
#define ELEVectorINCREMENT 8
#define MAX_BYTES_TO_ADD 32
#define PUSHNewLine 1
PrivateFnDef VByteCodeDescriptor::ByteCode getBinaryByteCode (
TokenTypes nodetype, int *intensional
) {
*intensional = false;
switch (nodetype) {
case _IntensionalLeftAssignment:
*intensional = true;
case _LeftAssignment:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_LAssign\n");
return (VByteCodeDescriptor::ByteCode_LAssign);
case _IntensionalRightAssignment:
*intensional = true;
case _RightAssignment:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_RAssign\n");
return (VByteCodeDescriptor::ByteCode_RAssign);
case _IntensionalConcatOp:
*intensional = true;
case _ConcatOp:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Concat\n");
return (VByteCodeDescriptor::ByteCode_Concat);
case _IntensionalLessThanP:
*intensional = true;
case _LessThanP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_LT\n");
return (VByteCodeDescriptor::ByteCode_LT);
case _IntensionalLessThanOrEqualP:
*intensional = true;
case _LessThanOrEqualP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_LE\n");
return (VByteCodeDescriptor::ByteCode_LE);
case _IntensionalGreaterThanOrEqualP:
*intensional = true;
case _GreaterThanOrEqualP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_GE\n");
return (VByteCodeDescriptor::ByteCode_GE);
case _IntensionalGreaterThanP:
*intensional = true;
case _GreaterThanP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_GT\n");
return (VByteCodeDescriptor::ByteCode_GT);
case _IntensionalEqualP:
*intensional = true;
case _EqualP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Equal\n");
return (VByteCodeDescriptor::ByteCode_Equal);
case _IntensionalIdenticalP:
*intensional = true;
case _IdenticalP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Equivalent\n");
return (VByteCodeDescriptor::ByteCode_Equivalent);
case _IntensionalNotEqualP:
*intensional = true;
case _NotEqualP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_NEqual\n");
return (VByteCodeDescriptor::ByteCode_NEqual);
case _IntensionalNotIdenticalP:
*intensional = true;
case _NotIdenticalP:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_NEquivalent\n");
return (VByteCodeDescriptor::ByteCode_NEquivalent);
case _IntensionalOr:
*intensional = true;
case _Or:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Or\n");
return (VByteCodeDescriptor::ByteCode_Or);
case _IntensionalAnd:
*intensional = true;
case _And:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_And\n");
return (VByteCodeDescriptor::ByteCode_And);
case _IntensionalPlus:
*intensional = true;
case _Plus:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Add\n");
return (VByteCodeDescriptor::ByteCode_Add);
case _IntensionalMinus:
*intensional = true;
case _Minus:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Subtract\n");
return (VByteCodeDescriptor::ByteCode_Subtract);
case _IntensionalTimes:
*intensional = true;
case _Times:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Multiply\n");
return (VByteCodeDescriptor::ByteCode_Multiply);
case _IntensionalDivide:
*intensional = true;
case _Divide:
if (tracingCodeGeneration) IO_printf ("\tVMACHINE_BC_Divide\n");
return (VByteCodeDescriptor::ByteCode_Divide);
default:
break;
}
return VByteCodeDescriptor::ByteCode_Pad0;
}
/********************************************
***** Symbol Table State and Utility *****
********************************************/
PrivateVarDef unsigned short stringIndex;
PrivateVarDef pointer_t stringSpaceBase;
/*---------------------------------------------------------------------------
***** Function passed to the HP_Unix provided twalk routine.
***** See documentation for tsearch(3C) in HP_Unix manual.
*****/
PrivateFnDef void findIndex (treenode *node, STD_VISIT order, int level) {
if (level == 0 && (order == STD_preorder || order == STD_leaf))
stringIndex = (unsigned short)((char *)STD_tdata (node) - stringSpaceBase);
}
PrivateVarDef pointer_diff_t ptrAdjustment;
/*---------------------------------------------------------------------------
***** Function passed to the HP_Unix provided twalk routine.
***** See documentation for tsearch(3C) in HP_Unix manual.
*****/
PrivateFnDef void adjustTableValues (treenode *node, STD_VISIT order, int Unused(level)) {
if (order == STD_preorder || order == STD_leaf)
*((char **)&STD_tdata (node)) += ptrAdjustment;
}
PrivateVarDef M_CPD *LocalMDCPD = NilOf (M_CPD*);
/*---------------------------------------------------------------------------
***** Function passed to the HP_Unix provided twalk routine.
***** See documentation for tsearch(3C) in HP_Unix manual.
*****/
PrivateFnDef void InsertMethodDEntries (treenode *node, STD_VISIT order, int Unused(level)) {
switch (order) {
case STD_preorder:
case STD_leaf: {
static M_KOT *g_pPropertySpecificationKOT = NilOf (M_KOT*);
static DSC_Descriptor *g_pPropertySpecification = NilOf (DSC_Descriptor*);
M_KOT *pMDKOT = LocalMDCPD->KOT ();
if (g_pPropertySpecificationKOT != pMDKOT) {
g_pPropertySpecificationKOT = NilOf (M_KOT*);
if (g_pPropertySpecification)
g_pPropertySpecification->clear ();
else {
static DSC_Descriptor g_iPropertySpecification;
g_pPropertySpecification = &g_iPropertySpecification;
}
rtDSC_Unpack (pMDKOT->TheDefaultProperty, g_pPropertySpecification);
g_pPropertySpecificationKOT = pMDKOT;
}
VSelectorGenerale selector((char const*)STD_tdata (node));
rtDICTIONARY_Define (LocalMDCPD, &selector, g_pPropertySpecification);
}
break;
default:
break;
}
}
/*******************************************
**** String Space Management Macros ****
*******************************************/
PrivateFnDef void InitializeStringSpace (
stringSpaceType *stringSpace
)
{
Ptr (stringSpace) =
Storage (stringSpace) = (char*)UTIL_Malloc (INITIAL_STRING_SPACE);
Size (stringSpace) = INITIAL_STRING_SPACE;
if (tracingStringSpaceOps) IO_printf (
"StringSpace alloc. StringSpace = %08X, Size = %u, used = %u\n",
Ptr (stringSpace), Size (stringSpace),
stringSpaceIndex (stringSpace)
);
}
#define WalkTable(table)\
if (IsntNil (table)) STD_twalk (*(table), adjustTableValues)
#define ConditionalGrow(stringSpace,stringLength,walkIdTable,walkEnvTable)\
{\
pointer_t oldSpace;\
\
if (tracingStringSpaceOps)\
{\
IO_printf (StringSpaceAvailabilityMessage);\
IO_printf (\
StringSpaceParametersMessage,\
Storage (stringSpace), Ptr (stringSpace), Size (stringSpace)\
);\
IO_printf (StringSpaceUsedMessage, stringSpaceIndex (stringSpace));\
}\
int spaceNeeded = stringSpaceIndex (stringSpace) + (stringLength) + 1;\
if (spaceNeeded > Size (stringSpace)) {\
if (tracingStringSpaceOps)\
IO_printf (StringSpaceAddMessage);\
oldSpace = Storage (stringSpace);\
Storage (stringSpace) = (char*)UTIL_Realloc (\
Storage (stringSpace), Size (stringSpace) += V_Max (spaceNeeded, stringSpaceINCREMENT)\
);\
ptrAdjustment = (pointer_size_t)Storage (stringSpace) - (pointer_size_t)oldSpace;\
Ptr (stringSpace) += ptrAdjustment;\
walkIdTable;\
walkEnvTable;\
if (tracingStringSpaceOps) {\
IO_printf (StringSpaceReallocateMessage);\
IO_printf (\
StringSpaceParametersMessage,\
Storage (stringSpace), Ptr (stringSpace), Size (stringSpace)\
);\
IO_printf (StringSpaceAdjustmentMessage, ptrAdjustment);\
}\
}\
}
/****************************************************
***** String Space Management Routines *****
****************************************************/
/*---------------------------------------------------------------------------
**** Internal Routine to check whether a string is currently in stringSpace
**** and add it if it isnt there. In either case, set the variable
**** stringIndex to the string's offset in stringSpace.
*
* Arguments:
* stringSpace - the string space being checked (and added to?).
* idTable - the root of the current symbol table.
* envTable - the root of the current environment table.
* stringOrigin - the address of the string to be found or added.
* stringLength - the length of the string to be found or added.
* removeBackslash - Boolean which when true indicates that backslash
* characters should be removed before adding to string
* space.
*
* Returns:
* 0 if successful; -1 if failed (stringSpace too big)
*
****/
PrivateFnDef int addToStringSpace (
stringSpaceType *stringSpace,
void **idTable,
void **envTable,
char const* stringOrigin,
int stringLength,
int removeBackslash
)
{
char
*SSptr,
*tNodeLocation;
int
x;
ConditionalGrow (
stringSpace, stringLength, WalkTable (idTable), WalkTable (envTable)
);
if (tracingStringSpaceOps)
IO_printf ("Inserting String in String Space\n");
if (removeBackslash)
{
SSptr = Ptr (stringSpace);
for (x = 0; x < stringLength; x++)
{
if (*stringOrigin == '\\' && x != stringLength - 1)
{
stringOrigin++;
stringLength--;
}
*SSptr++ = *stringOrigin++;
}
*SSptr = '\0';
}
else
{
memcpy (Ptr (stringSpace), stringOrigin, stringLength);
Ptr (stringSpace) [stringLength] = '\0';
}
if (tracingStringSpaceOps)
{
IO_printf ("Inserting String '%s' in Idtable\n", Ptr (stringSpace));
}
if (IsNil (tNodeLocation = (char *)STD_tfind (Ptr (stringSpace), idTable, (VkComparator)strcmp))) {
if (tracingStringSpaceOps)
IO_printf ("Not Present, so Insert ...");
(void)STD_tsearch (Ptr (stringSpace), idTable, (VkComparator)strcmp);
if (tracingStringSpaceOps)
IO_printf ("Adjust StringSpace pointer\n");
if (stringSpaceIndex (stringSpace) > USHRT_MAX) {
rslangerror (
UTIL_FormatMessage (
"String space index of %u for string '%.*s%s' exceeds %u maximum",
stringSpaceIndex (stringSpace),
V_Min (128, stringLength),
Ptr (stringSpace),
stringLength > 128 ? "..." : "",
USHRT_MAX
)
);
return -1;
}
stringIndex = (unsigned short)(stringSpaceIndex (stringSpace));
Ptr (stringSpace) += (stringLength + 1);
}
else
{
stringSpaceBase = Storage (stringSpace);
STD_twalk (tNodeLocation, findIndex);
}
return 0;
}
/***************************************************
**** Temporary Buffer Management Macros ****
***************************************************/
PrivateFnDef void InitializeBuffer (
bufferType *buffer
)
{
if (IsNil (Storage (buffer)))
{
Storage (buffer) = (char*)UTIL_Malloc (INITIAL_BUFFER_SIZE);
Size (buffer) = INITIAL_BUFFER_SIZE;
if (tracingStringSpaceOps)
IO_printf (
BufferAllocationMessage, Ptr (buffer), Size (buffer), bufferIndex (buffer)
);
}
Ptr (buffer) = Storage (buffer);
}
PrivateFnDef void ConditionalGrowBuffer (
bufferType *buffer,
int stringLength
)
{
char *oldStorage;
if (tracingStringSpaceOps)
{
IO_printf (StringSpaceAvailabilityMessage);
IO_printf (
StringSpaceParametersMessage,
Storage (buffer), Ptr (buffer), Size (buffer)
);
IO_printf (StringSpaceUsedMessage, bufferIndex (buffer));
}
while ((int)bufferIndex (buffer) + stringLength + 1 > Size (buffer))
{
if (tracingStringSpaceOps) IO_printf (StringSpaceAddMessage);
oldStorage = Storage (buffer);
Storage (buffer) = (char*)UTIL_Realloc (
Storage (buffer), Size (buffer) += bufferINCREMENT
);
ptrAdjustment = (pointer_size_t)Storage (buffer) - (pointer_size_t)oldStorage;
Ptr (buffer) += ptrAdjustment;
if (tracingStringSpaceOps)
{
IO_printf (StringSpaceReallocateMessage);
IO_printf (
StringSpaceParametersMessage,
Storage (buffer), Ptr (buffer), Size (buffer)
);
IO_printf (StringSpaceAdjustmentMessage, ptrAdjustment);
}
}
}
PrivateFnDef void WriteToBuffer (
bufferType* buffer, char const*source, int sourceLength
)
{
ConditionalGrowBuffer (buffer, sourceLength);
memcpy (Ptr (buffer), source, sourceLength);
Ptr (buffer) += sourceLength;
*(Ptr (buffer)) = '\0';
}
/***** Define Dynamic Holding Buffers *****/
PrivateVarDef bufferType
selector,
parameter,
tagbuffer,
asciiNumber;
/***** Byte Code Output Macros *****/
PrivateFnDef void output1ParamByteCode (
unsigned char **PC,
unsigned char shortCode,
unsigned char byteCode,
stringSpaceType *stringSpace
)
{
if (stringIndex > MAX_BYTE_SIZE)
{
AlignShort (*PC);
*(*PC)++ = shortCode;
if (tracingCodeGeneration) IO_printf (
OneParameterBCTraceMessage, shortCode
);
*(unsigned short *)(*PC) = stringIndex;
(*PC) += sizeof (short);
}
else
{
*(*PC)++ = byteCode;
if (tracingCodeGeneration) IO_printf (
OneParameterBCTraceMessage, byteCode
);
*(*PC)++ = (unsigned char)stringIndex;
}
if (tracingCodeGeneration) IO_printf (
StringSpaceTraceMessage,
stringIndex,
&Storage (stringSpace)[stringIndex]
);
}
PrivateFnDef void output2ParamByteCode (
unsigned char **PC,
unsigned char shortCode,
unsigned char byteCode,
unsigned char param2,
stringSpaceType *stringSpace
)
{
if (stringIndex > MAX_BYTE_SIZE)
{
AlignShort (*PC);
*(*PC)++ = shortCode;
if (tracingCodeGeneration) IO_printf (
OneParameterBCTraceMessage, shortCode
);
*(unsigned short *)(*PC) = stringIndex;
(*PC) += sizeof (short);
}
else
{
*(*PC)++ = byteCode;
if (tracingCodeGeneration) IO_printf (
OneParameterBCTraceMessage, byteCode
);
*(*PC)++ = (unsigned char)stringIndex;
}
*(*PC)++ = param2;
if (tracingCodeGeneration) IO_printf (
StringSpaceTraceMessage2,
stringIndex, &Storage (stringSpace)[stringIndex], param2
);
}
PrivateFnDef void outputTag (
unsigned char **PC,
unsigned char val
)
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_Tag;
*(*PC)++ = val;
if (tracingCodeGeneration) IO_printf (TagBCTraceMessage, val);
}
PrivateFnDef void conditionallyTagNewline (
unsigned char **PC,
int subTree
)
{
if (Is_a_terminal_node (subTree))
{
if (LineNumber (subTree) != rslanglineno)
{
outputTag (PC, '\n');
rslanglineno = LineNumber (subTree);
}
CurrentScanPointer.setDisplayOffsetTo (
TerminalNode_Origin (subTree) + TerminalNode_Length(subTree)
);
}
}
/***************************************
***** Selector Binding Routine *****
***************************************/
/*---------------------------------------------------------------------------
***** Inserts selector binding into block
*
* Arguments:
* cpd - the address of the CPD for the block into which
* the selector is being inserted.
* stringSpace - the string space being added to.
* idTable - the root of the current symbol table.
* envTable - the root of the current environment table.
* selectorPtr - pointer to the location of the selector name.
*
* Returns:
* 0 if successful; -1 if failed;
*
*****/
PrivateFnDef int insertSelectorBinding (
M_CPD *cpd,
stringSpaceType *stringSpace,
void **idTable,
void **envTable,
pointer_t selectorPtr
)
{
int index = SELECTOR_StringToKSI (selectorPtr);
rtBLOCK_BlockType* blockPtr = rtBLOCK_CPDBase (cpd);
if (index < 0) { /** is not known **/
/** put selector in string space and initialize pointer to it **
** addToStringSpace puts pointer in static variable 'stringIndex' **/
if (-1 == addToStringSpace (
stringSpace, idTable, envTable,
selectorPtr, strlen (selectorPtr), true
)) return -1;
rtBLOCK_SelectorType (blockPtr) = rtBLOCK_C_DefinedSelector;
rtBLOCK_SelectorIndex (blockPtr) = stringIndex;
}
else { /** is a known selector **/
rtBLOCK_SelectorType (blockPtr) = rtBLOCK_C_KnownSelector;
rtBLOCK_SelectorIndex (blockPtr) = (short)index;
}
return 0;
}
PrivateFnDef void extractSelector (
int node,
bufferType *selector,
int *intension,
unsigned char *valence
)
{
int subnode;
for (subnode = NonTerminal_SubtreeHead (node);;
subnode = NodeThreadingCell (subnode))
{
switch (NodeType (subnode))
{
case _IntensionalKeyword:
*intension = true;
case _Keyword:
(*valence)++;
WriteToBuffer (
selector, &sourceBASE [TerminalNode_Origin (subnode)],
TerminalNode_Length (subnode)
);
break;
default:
break;
}
if (subnode == NonTerminal_SubtreeTail (node))
break;
}
}
/*---------------------------------------------------------------------------
***** 'buildProgram' forward declaration
*---------------------------------------------------------------------------
*/
PrivateFnDef M_CPD *buildProgram (
M_ASD *pContainerSpace, int root, M_CPD *pDictionary, int Header
);
/*---------------------------------------------------------------------------
***** Routine inserts parameters into the block in reverse order *****
*
* Arguments:
* subTree - the root node of the subtree to be walked
* for this phase of code generation.
* PC - position in Byte Code vector.
* stringSpace - an area, which may be enlarged, containing
* strings, identifiers and selectors. The
* position of identifiers and selectors is
* kept in the idTable.
* envTable - the table used to temporarily store
* variables until they are inserted into the
* local environment.
* idTable - the symbol table to be used for lookup and
* to be added to if necessary.
* nextSubTree - next parse tree node in chain.
* programCPD - CPD of the block being built.
* skipSelector - true if no selector, false to skip over
* selectors in parse tree node chain.
*
* Returns:
* 0 if successful; -1 if failed
*****/
PrivateFnDef int acquireParameterLoop (
int subTree,
unsigned char **PC,
stringSpaceType *stringSpace,
void **envTable,
void **idTable,
int nextSubTree,
M_CPD *programCPD,
int skipSelector
) {
if (skipSelector)
nextSubTree = NodeThreadingCell (nextSubTree);
if (nextSubTree != NonTerminal_SubtreeTail (subTree)) {
if ( -1 == acquireParameterLoop (
subTree, PC, stringSpace, envTable, idTable,
NodeThreadingCell (nextSubTree), programCPD, skipSelector
)) return -1;
}
conditionallyTagNewline (PC, nextSubTree);
InitializeBuffer (¶meter);
WriteToBuffer (¶meter, &sourceBASE [TerminalNode_Origin (nextSubTree)],
TerminalNode_Length (nextSubTree));
/**** If it is a known parameter ... ****/
int messageIndex = SELECTOR_StringToKSI (Storage (¶meter));
if (messageIndex >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_AcquireKnownParameter;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_AcquireKnownParameter %u(%s) 0\n",
messageIndex, Storage (¶meter)
);
/***** although it may appear logical to use parameter instead of
KS__ToString, the program will bomb if you do
because parameter is stored on the stack and tsearch puts
that address in the envTable instead of the string.
Consequently when tsearch (in buildProgram) tries to access
the stack address, only garbage will be there. The same
is true in the tsearch code below. *****/
(void)STD_tsearch (KS__ToString (messageIndex), envTable, (VkComparator)strcmp);
}
/***** otherwise it must be a user defined parameter *****/
else {
if (-1 == addToStringSpace (
stringSpace, idTable, envTable,
&sourceBASE [TerminalNode_Origin (nextSubTree)],
TerminalNode_Length (nextSubTree), true)
) return -1;
(void)STD_tsearch (&Storage (stringSpace)[stringIndex], envTable, (VkComparator)strcmp);
output1ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_AcquireParameterS,
VByteCodeDescriptor::ByteCode_AcquireParameter,
stringSpace);
}
/***** Check to ensure that there is enough space for a set *****
***** of byte codes. If not, call GrowContainer *****/
if ((size_t) (
(*PC) - M_CPD_ContainerBaseAsType (programCPD, unsigned char)
) + MAX_BYTES_TO_ADD > M_CPD_Size (programCPD)
)
{
if (tracingCompile) IO_printf (
"Increasing Program Size by %d\n", BCVectorINCREMENT
);
programCPD->GrowContainer (BCVectorINCREMENT);
rtBLOCK_CPDEnd (programCPD) += BCVectorINCREMENT;
}
return 0;
}
/*---------------------------------------------------------------------------
***** routine takes selector and parameters and inserts them into the *****
***** block.
*
* Arguments:
* subTree - the root node of the subtree to be walked
* for this phase of code generation.
* programCPD - the block being built.
* idTable - the symbol table to be used for lookup and
* to be added to if necessary.
* envTable - the table used to temporarily store
* variables until they are inserted into the
* local environment.
* stringSpace - an area, which may be enlarged, containing
* strings, identifiers and selectors. The
* position of identifiers and selectors is
* kept in the idTable.
* Returns:
* 0 if successful, -1 if failed.
*
*****/
PrivateFnDef int acquireParameters (
int subTree,
M_CPD *programCPD,
void **idTable,
void **envTable,
stringSpaceType *stringSpace
)
{
unsigned char
**PC = (unsigned char **)(&(M_CPD_Pointers (programCPD) [rtBLOCK_CPx_PC])),
valence;
int
Intensional,
xOperator,
nextSubTree;
if (tracingCompile)
{
IO_printf ("Entered acquireParameters.");
IO_printf ("subTree = %08X, NodeType = %d\n",
subTree, NodeType (subTree));
}
/***** initialize selector variable. *****/
/***** selector placed here before being inserted into the block ****/
InitializeBuffer (&selector);
switch (NodeType (subTree))
{
case _UnaryMessageTemplate:
subTree = NonTerminal_SubtreeHead (subTree);
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
break;
case _BinaryMessageTemplate:
outputTag (PC, '|');
xOperator = NonTerminal_SubtreeHead (subTree);
nextSubTree = NonTerminal_SubtreeTail (subTree);
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (xOperator)],
TerminalNode_Length (xOperator));
if ( -1 == acquireParameterLoop (
subTree, PC, stringSpace, envTable,
idTable, nextSubTree, programCPD, false)
) return -1;
outputTag (PC, '|');
break;
case _KeywordMessageTemplate:
outputTag (PC, '|');
extractSelector (subTree, &selector, &Intensional, &valence);
nextSubTree = NonTerminal_SubtreeHead (subTree);
if ( -1 == acquireParameterLoop (
subTree, PC, stringSpace, envTable,
idTable, nextSubTree, programCPD, true)
) return -1;
outputTag (PC, '|');
break;
case _ParametricMessageTemplate:
outputTag (PC, '|');
nextSubTree = NonTerminal_SubtreeHead (subTree);
if ( -1 == acquireParameterLoop (
subTree, PC, stringSpace, envTable,
idTable, nextSubTree, programCPD, false)
) return -1;
outputTag (PC, '|');
break;
default:
/***** Error or do nothing *****/
break;
}
/***** insert selector into the block *****/
return Ptr (&selector) != Storage (&selector) && -1 == insertSelectorBinding (
programCPD, stringSpace, idTable, envTable, Storage (&selector)
) ? -1 : 0;
}
/************************************
**** Magic Word Helper Macros ****
************************************/
typedef unsigned char PostMagicWord_t;
PrivateVarDef PostMagicWord_t PostMagicWord = 0200;
PrivateVarDef PostMagicWord_t PostMagicWordMask = 0177;
#define MarkTagAsPostMagicWord(tag)\
((tag) |= PostMagicWord)
#define TagIsPostMagicWord(tag)\
((tag) & PostMagicWord)
#define ConvertPostMagicWordTag(target, source)\
((target) = (PostMagicWord_t)((source) & PostMagicWordMask))
/*---------------------------------------------------------------------------
***** Internal Routine to control the building of the program. It calls
***** itself recursively as it 'walks' the parse tree.
*
* Arguments:
* subTree - the root node of the subtree to be walked
* for this phase of code generation.
* programCPD - the block being built.
* idTable - the symbol table to be used for lookup and
* to be added to if necessary.
* envTable - the table used to temporarily store
* variables until they are inserted into the
* local environment.
* stringSpace - an area, which may be enlarged, containing
* strings, identifiers and selectors. The
* position of identifiers and selectors is
* kept in the idTable.
* physicalLiteralVector - an area which may also be enlarged that
* contains POP's for the blocks immediately
* nested in the one passed to this routine.
* evaledLiteralVector - an area which again may be enlarged that
* contains (will contain) entry points for
* evaled Literals in this block's bytecode
* stream.
*
* Returns:
* 0 if successful; -1 if failed
*****/
PrivateFnDef int GenerateCode (
M_ASD *pContainerSpace,
int subTree,
M_CPD *programCPD,
void **idTable,
void **envTable,
stringSpaceType *stringSpace,
PLVectorType *physicalLiteralVector,
ELEVectorType *evaledLiteralVector
) {
#define wrapUpCase\
justStoredMagicWord = false;\
break
VByteCodeDescriptor::ByteCode xByteCode;
int
messageIndex;
unsigned char
**PC = (unsigned char **)(&(M_CPD_Pointers (programCPD)
[rtBLOCK_CPx_PC])),
paren = false,
period = false,
valence,
magicWord;
PrivateVarDef int
justStoredMagicWord = false;
int
x,
length = 0,
Intensional,
result,
integer_val,
header = NULL_NODE,
xOperator,
receiver,
nextSubTree;
double
real_val;
M_CPD
*newProgram,
*newEnvCPD;
InitializeBuffer (&selector);
InitializeBuffer (&tagbuffer);
InitializeBuffer (&asciiNumber);
if (Parenthesized (subTree))
paren = true;
if (PrecedingSemi_Colon (subTree))
outputTag (PC, ';');
if (TrailingPeriod (subTree))
period = true;
if (tracingCompile) IO_printf (
"Entered GenerateCode. subTree = %08X, NodeType = %d\n",
subTree, NodeType (subTree)
);
/***** Check to ensure that there is enough space for a set of byte codes.
if not, call GrowContainer
*****/
if ((size_t) (
(*PC) - M_CPD_ContainerBaseAsType (programCPD, unsigned char)
) + MAX_BYTES_TO_ADD > M_CPD_Size (programCPD)
)
/*
if ((unsigned int) ((*PC)
- (unsigned char *)M_CPD_ContainerBase (programCPD)
+ MAX_BYTES_TO_ADD)
> M_CPD_Size (programCPD))
*/
{
if (tracingCompile) IO_printf (
"Increasing Program Size by %d\n", BCVectorINCREMENT
);
programCPD->GrowContainer (BCVectorINCREMENT);
rtBLOCK_CPDEnd (programCPD) += BCVectorINCREMENT;
}
conditionallyTagNewline (PC, subTree);
if (paren)
outputTag (PC, '(');
switch (NodeType (subTree)) {
case _Identifier:
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
if (justStoredMagicWord) {
for (x = -2;; x -= 2)
if ((*PC) [x] != VByteCodeDescriptor::ByteCode_Tag) break;
else MarkTagAsPostMagicWord ((*PC) [x+1]);
(*PC) += x;
magicWord = (*PC) [1];
length = (-2) - x;
WriteToBuffer (&tagbuffer, (char *)(*PC + 2), length);
}
else magicWord = (unsigned char)VMagicWord_Current;
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_KnownUnaryValue;
*(*PC)++ = (unsigned char)messageIndex;
*(*PC)++ = magicWord;
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_KnownUnaryValue %u(%s) 0\n",
messageIndex, Storage (&selector)
);
}
else {
/**** check Identifier Table. If Not present, append to string
space and add to Id table. Else, get string space index.
****/
if ( -1 == addToStringSpace (
stringSpace, idTable, envTable,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree), true)
) return -1;
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_UnaryValueS,
VByteCodeDescriptor::ByteCode_UnaryValue,
magicWord,
stringSpace);
}
if (length != 0)
{
memcpy (*PC, Storage (&tagbuffer), length);
*PC += length;
}
wrapUpCase;
case _IntensionalIdentifier:
WriteToBuffer (
&selector,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
if (justStoredMagicWord)
{
for (x = -2;; x -= 2)
if ((*PC) [x] != VByteCodeDescriptor::ByteCode_Tag) break;
else MarkTagAsPostMagicWord ((*PC) [x+1]);
(*PC) += x;
magicWord = (*PC) [1];
length = (-2) - x;
WriteToBuffer (&tagbuffer, (char *)(*PC + 2), length);
}
else magicWord = (unsigned char)VMagicWord_Current;
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_KnownUnaryIntension;
*(*PC)++ = (unsigned char)messageIndex;
*(*PC)++ = magicWord;
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_KnownUnaryIntension %u(%s) 0\n",
messageIndex,
Storage (&selector)
);
}
else {
/**** check Identifier Table. If Not present, append to string
space and add to Id table. Else, get string space index.
****/
if ( -1 == addToStringSpace (
stringSpace, idTable, envTable,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree), true)
) return -1;
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_UnaryIntensionS,
VByteCodeDescriptor::ByteCode_UnaryIntension,
magicWord,
stringSpace);
}
if (length != 0)
{
memcpy (*PC, Storage (&tagbuffer), length);
*PC += length;
}
wrapUpCase;
case _Integer:
/**** Grab value at SourceString offset and convert it to an
integer.
****/
WriteToBuffer (
&asciiNumber,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
real_val = atof (Storage (&asciiNumber));
integer_val = (int)real_val;
AlignInt ((*PC));
if (real_val != integer_val)
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreDouble;
*(double *)(*PC) = real_val;
(*PC) += sizeof (double);
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_StoreDouble %g\n", real_val
);
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreInteger;
*(int *)(*PC) = integer_val;
(*PC) += sizeof (int);
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_StoreInteger %d\n", integer_val
);
}
wrapUpCase;
case _NegInteger:
/**** Grab value at SourceString offset and convert it to an
integer.
****/
WriteToBuffer (
&asciiNumber,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
real_val = -atof (Storage (&asciiNumber));
integer_val = (int)real_val;
AlignInt ((*PC));
if (real_val != integer_val)
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreDouble;
*(double *)(*PC) = real_val;
(*PC) += sizeof (double);
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_StoreDouble %g\n", real_val
);
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreInteger;
*(int *)(*PC) = integer_val;
(*PC) += sizeof (int);
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_StoreInteger %d\n", integer_val
);
}
wrapUpCase;
case _HexInteger:
/**** Grab value at SourceString offset and convert it to an
integer.
****/
WriteToBuffer (
&asciiNumber,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
STD_sscanf (Storage (&asciiNumber), "0x%x", &integer_val);
AlignInt ((*PC));
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreInteger;
*(int *)(*PC) = integer_val;
(*PC) += sizeof (int);
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreInteger %d\n", integer_val);
wrapUpCase;
case _NegHexInteger:
/**** Grab value at SourceString offset and convert it to an
integer.
****/
WriteToBuffer (
&asciiNumber,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
STD_sscanf (Storage (&asciiNumber), "0x%x", &integer_val);
AlignInt ((*PC));
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreInteger;
*(int *)(*PC) = -integer_val;
(*PC) += sizeof (int);
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreInteger %d\n", integer_val);
wrapUpCase;
case _Real:
/**** Grab value at SourceString offset and convert it to a
double.
****/
WriteToBuffer (
&asciiNumber,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree)
);
real_val = atof (Storage (&asciiNumber));
AlignInt ((*PC));
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreDouble;
*(double *)(*PC) = real_val;
(*PC) += sizeof (double);
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreDouble %g\n", real_val);
wrapUpCase;
case _NegReal:
/**** Grab value at SourceString offset and convert it to a
double.
****/
WriteToBuffer (&asciiNumber, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
real_val = -atof (Storage (&asciiNumber));
AlignInt ((*PC));
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreDouble;
*(double *)(*PC) = real_val;
(*PC) += sizeof (double);
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreDouble %g\n", real_val);
wrapUpCase;
case _String:
/**** Copy string from SourceString offset to the end of
StringSpace, first removing any backslashes preceding
quotes.
****/
if ( -1 == addToStringSpace (
stringSpace, idTable, envTable,
&sourceBASE [TerminalNode_Origin (subTree) + 1],
TerminalNode_Length (subTree) - 2, true)
) return -1;
output1ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_StoreStringS,
VByteCodeDescriptor::ByteCode_StoreString,
stringSpace);
wrapUpCase;
case _BinaryExpression:
/**** Get BinaryOperator and look up known message index. Determine
whether this is an Intensional or a value message.
****/
nextSubTree = subTree = NonTerminal_SubtreeHead (subTree);
while (!Is_a_terminal_node (nextSubTree))
nextSubTree = NonTerminal_SubtreeTail (nextSubTree);
if (LineNumber (NodeThreadingCell (subTree))
!= LineNumber (nextSubTree))
outputTag (PC, PUSHNewLine);
nextSubTree = NodeThreadingCell (subTree);
xByteCode = getBinaryByteCode ((TokenTypes)NodeType (nextSubTree), &Intensional);
*(*PC)++ = (unsigned char)(unsigned int)xByteCode;
/**** Eval recipient ****/
if (result = GenerateCode (
pContainerSpace, subTree, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
subTree = NodeThreadingCell (nextSubTree);
/**** Dispatch ****/
if (justStoredMagicWord) {
if (Intensional) outputTag (PC, ':');
for (x = -2;; x -= 2)
if ((*PC) [x] != VByteCodeDescriptor::ByteCode_Tag) break;
else MarkTagAsPostMagicWord ((*PC) [x+1]);
(*PC) [x] = VByteCodeDescriptor::ByteCode_DispatchMagic;
if (tracingCodeGeneration) IO_printf (
"\tVMACHINE_BC_DispatchMagic\n"
);
justStoredMagicWord = false;
}
else
{
if (Intensional) outputTag (PC, ':');
*(*PC)++ = VByteCodeDescriptor::ByteCode_Dispatch;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Dispatch\n");
}
/**** Evaluate Parameter ****/
if (result = GenerateCode (
pContainerSpace, subTree, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
if (paren)
{
outputTag (PC, ')');
paren = false;
}
*(*PC)++ = VByteCodeDescriptor::ByteCode_NextMessageParameter;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_NextMessageParameter\n");
/**** Evaluate Binary Expression ****/
if (Intensional)
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_Intension;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Intension\n");
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_Value;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Value\n");
}
wrapUpCase;
case _OpenKeywordExpression:
case _ClosedKeywordExpression:
/**** Determine Selector and if Intensional ****/
valence = '\0';
Intensional = false;
extractSelector (subTree, &selector, &Intensional, &valence);
nextSubTree = subTree = NonTerminal_SubtreeHead (subTree);
while (!Is_a_terminal_node (nextSubTree))
nextSubTree = NonTerminal_SubtreeTail (nextSubTree);
if (LineNumber (NodeThreadingCell (subTree))
!= LineNumber (nextSubTree))
outputTag (PC, PUSHNewLine);
/**** If it is a known selector ... ****/
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_KnownMessage;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_KnownMessage %d(%s)\n",
messageIndex, Storage (&selector));
}
/**** ... Otherwise, Append to stringSpace and ****/
else {
if ( -1 == addToStringSpace (stringSpace, idTable, envTable,
Storage (&selector),
strlen (Storage (&selector)), true)
) return -1;
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_KeywordMessageS,
VByteCodeDescriptor::ByteCode_KeywordMessage,
valence,
stringSpace);
}
/**** Evaluate Recipient ****/
if (result = GenerateCode (
pContainerSpace, subTree, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
/**** Dispatch ****/
if (justStoredMagicWord) {
if (Intensional) outputTag (PC, ':');
for (x = -2;; x -= 2)
if ((*PC) [x] != VByteCodeDescriptor::ByteCode_Tag) break;
else MarkTagAsPostMagicWord ((*PC) [x+1]);
(*PC) [x] = VByteCodeDescriptor::ByteCode_DispatchMagic;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_DispatchMagic\n");
}
else
{
if (Intensional) outputTag (PC, ':');
*(*PC)++ = VByteCodeDescriptor::ByteCode_Dispatch;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Dispatch\n");
}
for (x = 0; x < (int) valence; x++)
{
justStoredMagicWord = false;
/**** Get Parameter (skipping selector) ****/
subTree = NodeThreadingCell (subTree);
rslanglineno = LineNumber (subTree);
CurrentScanPointer.setDisplayOffsetTo (
TerminalNode_Origin (subTree) + TerminalNode_Length(subTree)
);
subTree = NodeThreadingCell (subTree);
/**** Evaluate Parameter ****/
if (result = GenerateCode (
pContainerSpace, subTree, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
if (period && x + 1 == valence)
{
outputTag (PC, '.');
period = false;
}
if (paren && x + 1 == valence)
{
outputTag (PC, ')');
paren = false;
}
*(*PC)++ = VByteCodeDescriptor::ByteCode_NextMessageParameter;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_NextMessageParameter\n");
}
/**** Evaluate Keyword Expression ****/
if (Intensional)
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_Intension;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Intension\n");
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_Value;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Value\n");
}
wrapUpCase;
case _UnaryExpression:
/**** Determine selector, if it is known, and if it is
intensional.
****/
receiver = NonTerminal_SubtreeHead (subTree);
xOperator = NonTerminal_SubtreeTail (subTree);
if ((TokenTypes)NodeType (receiver) == _Magic)
{
if (result = GenerateCode (
pContainerSpace, receiver, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
if (result = GenerateCode (
pContainerSpace, xOperator, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
wrapUpCase;
}
Intensional =
(TokenTypes)NodeType (xOperator) == _IntensionalIdentifier;
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (xOperator)],
TerminalNode_Length (xOperator));
nextSubTree = receiver;
while (!Is_a_terminal_node (nextSubTree))
nextSubTree = NonTerminal_SubtreeTail (nextSubTree);
if (LineNumber (xOperator)
!= LineNumber (nextSubTree))
outputTag (PC, PUSHNewLine);
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_KnownMessage;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_KnownMessage %d(%s)\n",
messageIndex, Storage (&selector));
}
else {
/**** Append Selector to StringSpace ****/
if ( -1 == addToStringSpace (stringSpace, idTable, envTable,
Storage (&selector),
strlen (Storage (&selector)), true)
) return -1;
output1ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_UnaryMessageS,
VByteCodeDescriptor::ByteCode_UnaryMessage,
stringSpace);
}
/**** Evaluate Recipient ****/
if (result = GenerateCode (
pContainerSpace, receiver, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
if (Intensional)
{
outputTag (PC, ':');
*(*PC)++ = VByteCodeDescriptor::ByteCode_WrapupUnaryIntension;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_WrapupUnaryIntension\n");
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_WrapupUnaryValue;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_WrapupUnaryValue\n");
}
wrapUpCase;
case _EmptyExpression:
/**** Output NOP bytecode ****/
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreNoValue;
wrapUpCase;
case _Root:
/**** Loop through children, generating code for each expression
****/
for (nextSubTree = NonTerminal_SubtreeHead (subTree);
nextSubTree != NonTerminal_SubtreeTail (subTree);
nextSubTree = NodeThreadingCell (nextSubTree))
{
if (result = GenerateCode (
pContainerSpace, nextSubTree, programCPD, idTable, envTable,
stringSpace, physicalLiteralVector, evaledLiteralVector
)
) return result;
justStoredMagicWord = false;
}
if (result = GenerateCode (
pContainerSpace, nextSubTree, programCPD, idTable, envTable, stringSpace,
physicalLiteralVector, evaledLiteralVector
)
) return result;
wrapUpCase;
case _HeadedBlock:
header = NonTerminal_SubtreeHead (subTree);
case _SimpleBlock:
/**** Create an 'empty' environment and link to the current
environment.
****/
newEnvCPD = rtDICTIONARY_New (pContainerSpace);
/**** Arrange to get a new program built for this block ****/
justStoredMagicWord = false;
newProgram = buildProgram (
pContainerSpace, NonTerminal_SubtreeTail (subTree), newEnvCPD, header
);
/**** Cleanup newEnvCPD ****/
rtDICTIONARY_AlignAll (newEnvCPD, true);
newEnvCPD->release ();
if (IsNil (newProgram))
return -1;
/**** Insert in Physical Literal Table ****/
Storage (physicalLiteralVector)[Index (physicalLiteralVector)] =
newProgram;
/**** Output Code ****/
if (Index (physicalLiteralVector) > MAX_BYTE_SIZE)
{
AlignShort ((*PC));
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreLexBindingS;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreLexBindingS ");
*(unsigned short *)(*PC) =
Index (physicalLiteralVector)++;
(*PC) += 2;
}
else
{
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreLexBinding;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreLexBinding ");
*(*PC)++ = (unsigned char)Index (physicalLiteralVector)++;
}
if (tracingCodeGeneration)
IO_printf ("%u\n", Index (physicalLiteralVector) - 1);
/**** Determine if the PLVector is still big enough ****/
if ((int) Index (physicalLiteralVector) >= Size (physicalLiteralVector))
Storage (physicalLiteralVector) = (M_CPD **)UTIL_Realloc (
Storage (physicalLiteralVector), (
Size (physicalLiteralVector) += PLVectorINCREMENT
) * sizeof (M_CPD*)
);
wrapUpCase;
case _Magic:
/**** Get the magic word index ****/
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
if ((result = MAGIC_StringToMWI (Storage (&selector))) < 0) {
/**** error ****/
rslangerror (
UTIL_FormatMessage ("Unrecognized magic word '%s'", Storage (&selector))
);
return -1;
}
/**** Output Code ****/
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreMagic;
*(*PC)++ = (unsigned char)result;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreMagic %d(%s)\n", result, Storage (&selector));
justStoredMagicWord = true;
break;
case _LocalId:
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
outputTag (PC, '!');
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
/***** Add to the environment table *****/
(void)STD_tsearch (KS__ToString (messageIndex), envTable, (VkComparator)strcmp);
/**** Process as an intension. ****/
*(*PC)++ = VByteCodeDescriptor::ByteCode_KnownUnaryIntension;
*(*PC)++ = (unsigned char)messageIndex;
*(*PC)++ = (unsigned char) VMagicWord_Current;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_KnownUnaryIntension %u(%s) 0\n",
messageIndex,
Storage (&selector));
}
else {
/**** Add to the Id table and to the environment Table.
****/
if ( -1 == addToStringSpace (stringSpace, idTable, envTable,
&sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree), true)
) return -1;
(void)STD_tsearch (&Storage (stringSpace)[stringIndex], envTable,(VkComparator)strcmp);
/**** Process as an intension. ****/
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_UnaryIntensionS,
VByteCodeDescriptor::ByteCode_UnaryIntension,
(unsigned char) VMagicWord_Current,
stringSpace);
}
wrapUpCase;
case _UnarySelector:
subTree = NonTerminal_SubtreeHead (subTree);
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
conditionallyTagNewline (PC, subTree);
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreKnownSelector;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreKnownSelector %u(%s)\n", messageIndex,
Storage (&selector));
}
else {
/**** Append Selector to StringSpace ****/
if ( -1 == addToStringSpace (stringSpace, idTable, envTable,
Storage (&selector),
strlen (Storage (&selector)), true)
) return -1;
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_StoreSelectorS,
VByteCodeDescriptor::ByteCode_StoreSelector,
0,
stringSpace);
}
wrapUpCase;
case _BinarySelector:
/**** Binaries are all known ****/
subTree = NonTerminal_SubtreeHead (subTree);
WriteToBuffer (&selector, &sourceBASE [TerminalNode_Origin (subTree)],
TerminalNode_Length (subTree));
conditionallyTagNewline (PC, subTree);
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreKnownSelector;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreKnownSelector %u(%s)\n", messageIndex,
Storage (&selector));
}
else
/**** Error ****/;
wrapUpCase;
case _KeywordSelector:
/**** Determine Selector ****/
valence = '\0';
extractSelector (subTree, &selector, &Intensional, &valence);
/**** If it is a known selector ... ****/
if ((messageIndex = SELECTOR_StringToKSI (Storage (&selector))) >= 0) {
*(*PC)++ = VByteCodeDescriptor::ByteCode_StoreKnownSelector;
*(*PC)++ = (unsigned char)messageIndex;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_StoreKnownSelector %u(%s)\n", messageIndex,
Storage (&selector));
}
/**** ... Otherwise, Append to stringSpace and ****/
else {
if (-1 == addToStringSpace (stringSpace, idTable, envTable,
Storage (&selector),
strlen (Storage (&selector)), true)
) return -1;
output2ParamByteCode (PC,
VByteCodeDescriptor::ByteCode_StoreSelectorS,
VByteCodeDescriptor::ByteCode_StoreSelector,
valence,
stringSpace);
}
wrapUpCase;
default:
/**** Error ****/
rslangerror (
UTIL_FormatMessage ("Unknown Node Type: %u", NodeType (subTree))
);
return -1;
}
if (period)
outputTag (PC, '.');
if (paren)
outputTag (PC, ')');
/***** Check to ensure that there is enough space for a set of byte codes.
if not, call GrowContainer. This check at the end is for the space
that will be needed when it returns from one level of recursion and
finishes up by emitting the rest of the byte code.
*****/
if ((size_t) (
(*PC) - M_CPD_ContainerBaseAsType (programCPD, unsigned char)
) + MAX_BYTES_TO_ADD > M_CPD_Size (programCPD)
)
/*
if ((unsigned int) ((*PC)
- (unsigned char *)M_CPD_ContainerBase (programCPD)
+ MAX_BYTES_TO_ADD)
> M_CPD_Size (programCPD))
*/
{
if (tracingCompile)
IO_printf ("Increasing Program Size by %d\n", BCVectorINCREMENT);
programCPD->GrowContainer (BCVectorINCREMENT);
rtBLOCK_CPDEnd (programCPD) += BCVectorINCREMENT;
}
/***** Completed Successfully *****/
return 0;
}
/*---------------------------------------------------------------------------
***** Internal Routine to actually build an instance of a block
*
* Arguments:
* pContainerSpace - the address of the ASD for the object space
* in which to create the block's container.
* root - the block's parse tree root node index.
* pDictionary - the address of the block's dictionary.
* Header - the Header for the block (Nil) if it
* is a simple block.
* Returns:
* The CPD pointer for the block or an error description
*
*****/
PrivateFnDef M_CPD *buildProgram (
M_ASD *pContainerSpace, int root, M_CPD *pDictionary, int Header
) {
int
x;
stringSpaceType
stringSpace;
PLVectorType
plVector;
ELEVectorType
eleVector;
void
*envirTable = NilOf (void *),
*symbolTable = NilOf (void *);
if (tracingCompile)
IO_printf ("Entered buildProgram. root = %08X, Header = %08X\n", root, Header);
if (tracingCodeGeneration)
IO_printf ("[\n");
InitializeStringSpace (&stringSpace);
/**** Initialize plVector ****/
Storage (&plVector) = (M_CPD **)UTIL_Malloc (INITIAL_PLVECTOR_SIZE * sizeof (M_CPD *));
Size (&plVector) = INITIAL_PLVECTOR_SIZE;
Index (&plVector) = 0;
/**** Initialize eleVector ****/
Storage (&eleVector) = (int *)UTIL_Malloc (INITIAL_ELEVECTOR_SIZE * sizeof (int));
Size (&eleVector) = INITIAL_ELEVECTOR_SIZE;
Index (&eleVector) = 0;
/***** Create an rtBLOCK instance *****/
if (tracingCompile)
IO_printf ("Calling rtBLOCK_New\n");
M_CPD *programCPD = rtBLOCK_New (pContainerSpace);
/***** Store dictionary reference in block *****/
if (tracingCompile)
IO_printf ("Inserting Environment\n");
programCPD->StoreReference (rtBLOCK_CPx_LocalEnv, pDictionary);
/***** Aquire Parameters *****/
if (NULL_NODE != Header) {
if (tracingCompile) IO_printf ("Acquiring Parameters\n");
if (-1 == acquireParameters (
Header, programCPD, &symbolTable, &envirTable, &stringSpace))
{
UTIL_Free (Storage (&stringSpace));
UTIL_Free (Storage (&plVector));
UTIL_Free (Storage (&eleVector));
programCPD->release ();
return NilOf (M_CPD*);
}
}
if (tracingCompile)
IO_printf ("Root Code Generation\n");
if (-1 == GenerateCode (
pContainerSpace, root, programCPD, &symbolTable, &envirTable,
&stringSpace, &plVector, &eleVector
)
) {
for (x = 0; x < (int) Index (&plVector); x++)
(Storage (&plVector) [x])->release ();
UTIL_Free (Storage (&stringSpace));
UTIL_Free (Storage (&plVector));
UTIL_Free (Storage (&eleVector));
programCPD->release ();
return NilOf (M_CPD*);
}
*(bCodePtr (programCPD))++ = VByteCodeDescriptor::ByteCode_Exit;
if (tracingCodeGeneration)
IO_printf ("\tVMACHINE_BC_Exit\n");
/***** Remove 'air' from Block *****/
programCPD->ShiftContainerTail (
rtBLOCK_CPx_End,
0,
M_CPD_PointerToByte (programCPD, rtBLOCK_CPx_PC) -
M_CPD_PointerToByte (programCPD, rtBLOCK_CPx_End),
true
);
if (tracingCompile)
IO_printf ("Updating local environment.\n");
/***** Update local environment with local Variables *****/
LocalMDCPD = pDictionary;
if (tracingCompile)
IO_printf ("preparing to walk tree.\n");
STD_twalk (envirTable, InsertMethodDEntries);
if (tracingCompile)
IO_printf ("Appending Components\n");
/***** Append stringSpace to Program *****/
rtBLOCK_AppendStringSpace (programCPD, Storage (&stringSpace),
stringSpaceIndex (&stringSpace));
/***** Append plVector to Program *****/
rtBLOCK_AppendPLVector (programCPD, Storage (&plVector), Index (&plVector));
/***** Append eleVector to Program *****/
rtBLOCK_AppendELEVector (programCPD,
Storage (&eleVector), Index (&eleVector));
/***** Initialize CPD pointers *****/
rtBLOCK_InitStdCPD (programCPD);
for (x = 0; x < (int) Index (&plVector); x++)
(Storage (&plVector) [x])->release ();
UTIL_Free (Storage (&stringSpace));
UTIL_Free (Storage (&plVector));
UTIL_Free (Storage (&eleVector));
if (retainingBlockForBrowsing)
blockIObj = RTYPE_QRegister (programCPD->GetCPD ());
if (tracingCodeGeneration)
IO_printf ("]\n");
return programCPD;
}
/**************************
***** The Compiler *****
**************************/
/*---------------------------------------------------------------------------
***** Routine to compile a source string into an executable program.
*
* Argument:
* source - the address of the string to compile.
* dictionary - a CPD for the dictionary in which new top
* level local variables will be created.
* pMessageBuffer - the address of a buffer which will be
* initialized with the text of any error
* messages associated with the compilation.
* If 'nil', the compiler will print an
* error message to standard output.
* sMessageBuffer - the maximum size of the supplied message
* buffer.
* errorLine - the address of an integer variable which
* will be set to the line number of the first
* compilation error encountered.
* errorCharacter - the address of an integer variable which
* will be set to the character position of the
* first compilation error encountered.
*
* Returns:
* The address of a CPD for:
* the created program if the parse was successful
* OR:
* Nil if the parse was unsuccessful.
*
* Notes:
* This program should not display any explicit error messages; rather,
* it should quietly return a CPD for an object describing in some
* structured way what it finds objectionable in the input it was asked
* to compile.
*****/
PublicFnDef M_CPD *RSLANG_Compile (
M_ASD *pContainerSpace,
char const *source,
M_CPD *dictionary,
char *pMessageBuffer,
unsigned int sMessageBuffer,
int *errorLine,
int *errorCharacter
) {
if (tracingCompile)
IO_printf ("Starting ... ");
rslanglineno = 0;
CurrentScanPointer.reset ();
IntensionalOp = false;
sourceBASE =
rsSOURCE = source;
MessageBuffer = pMessageBuffer;
MessageBufferMax = sMessageBuffer;
ErrorLine = errorLine;
ErrorCharacter = errorCharacter;
if (tracingCompile)
IO_printf ("Parsing ... ");
Initialize_ParseTree_Nodes ();
if (rslangparse ())
return NilOf (M_CPD*);
rslanglineno = 0;
if (tracingCompile)
IO_printf ("GO!!!\n");
return buildProgram (pContainerSpace, rsROOT, dictionary, NULL_NODE);
}
/*****************************
***** The De-Compiler *****
*****************************/
/*---------------------------------------------------------------------------
* The De_Compiler runs as a stack machine. A block's byte code vector is read
* and various push, pop and output operations are performed based on the byte
* code's defined decompile operation and the values of the byte code's
* parameters. Some provision is made to output the decompiled program in
* properly indented, easily read style.
*---------------------------------------------------------------------------
*/
/********************************************
***** Decompiler Stack Declarations *****
********************************************/
struct RSLangDC_StackFrameType {
VByteCodeDescriptor::ByteCode
byteCode;
char const
*stringVal;
int
valLength;
unsigned int
m_iOutputOffset;
unsigned char
newline,
colon,
m_iMoreParameters,
nextpOutput;
};
/**** The Stack ****/
struct RSLandDC_StackType {
int
size;
RSLangDC_StackFrameType
*stack;
};
PrivateVarDef RSLandDC_StackType RSLangDC_Stack;
/**** The Stack Pointer (actually an index to the next free stack frame) ****/
PrivateVarDef int SP;
/***** Access Macros *****/
#define rslangSFNewLine(frame)\
RSLangDC_Stack.stack [frame].newline
#define rslangSFIntensional(frame)\
RSLangDC_Stack.stack [frame].colon
#define rslangSFMorep(frame)\
RSLangDC_Stack.stack [frame].m_iMoreParameters
#define rslangSFNextp(frame)\
RSLangDC_Stack.stack [frame].nextpOutput
#define rslangSFByteCode(frame)\
RSLangDC_Stack.stack [frame].byteCode
#define rslangSFStringVal(frame)\
RSLangDC_Stack.stack [frame].stringVal
#define rslangSFValLength(frame)\
RSLangDC_Stack.stack [frame].valLength
#define rslangSFOutputOffset(frame)\
RSLangDC_Stack.stack [frame].m_iOutputOffset
#define topOfStackVal (SP > 0 ? rslangSFStringVal (SP - 1) : NilOf (char *))
#define topOfStack (SP > 0 ? rslangSFByteCode (SP - 1) : 0)
/***** Constants *****/
#define InitialStackSize 128
#define StackIncrement 32
/***********************************************
**** Output Operations and Structures ****
***********************************************/
/**** Pretty Printer Variables ****/
PrivateVarDef unsigned int IndentationIndex = 0;
PrivateVarDef char const *headMark = "|";
PrivateVarDef char const *blockClose = "]";
PrivateVarDef char const *blockOpen = "[";
PrivateVarDef char const *magic = "^";
PrivateVarDef char const *evaledLit = "$";
PrivateVarDef char const *selMark = "\'";
PrivateVarDef char const *colon = ":";
PrivateVarDef char const *quote = "\"";
PrivateVarDef char const *backslash = "\\";
PrivateVarDef char const *newline = "\n";
PrivateVarDef char const *tab = " ";
PrivateVarDef stringSpaceType decompiledProgram;
/***** Utilities to copy outputVal to the string space holding the decompiled
***** program being produced.
*
* Argument:
* outputVal - a pointer to a null terminated string to be appended
* to the decompiled program.
*
*****/
PrivateFnDef void DoBasicOutput (char const *outputVal, int len) {
if (0 == len)
return;
ConditionalGrow (&decompiledProgram, len, DoNothing, DoNothing);
memcpy (Ptr (&decompiledProgram), outputVal, len);
if (tracingDecompile) IO_printf (
"RSLANG[DoBasicOutput]:%.*s o:%u co:%d\n",
len, Ptr (&decompiledProgram),
bufferIndex (&decompiledProgram),
SP > 0 ? rslangSFOutputOffset (SP - 1) : UINT_MAX
);
Ptr (&decompiledProgram) += len;
}
#define DoBlank DoBasicOutput (tab, 1)
#define Output(outputVal, len, doBlank) {\
DoBasicOutput (outputVal, len);\
doBlank;\
}
/********************************************
***** Internal Stack Handling Macros *****
********************************************/
PrivateFnDef void outputStkVal (
void
)
{
if (SP > 0)
{
if (rslangSFNewLine (SP - 1))
{
unsigned int x;
Output (newline, 1, DoNothing);
for (x = 1; x <= IndentationIndex; x++) Output (tab, 4, DoNothing);
rslangSFNewLine (SP - 1) = false;
}
if (rslangSFIntensional (SP - 1))
{
Output (colon, 1, DoNothing);
rslangSFIntensional (SP - 1) = false;
}
if (IsntNil (topOfStackVal))
{
if (tracingStackOps) IO_printf (
"...RSLANG[outputStkVal]: SP:[%d]\n", SP
);
Output (
rslangSFStringVal (SP - 1), rslangSFValLength (SP - 1), DoBlank
);
rslangSFStringVal (SP - 1) = NilOf (char *);
}
}
}
PrivateFnDef void Grow_DCStack (
void
)
{
if (SP >= Size (&RSLangDC_Stack))
{
if (tracingStackOps) IO_printf ("... Growing DC Stack\n");
RSLangDC_Stack.stack = (RSLangDC_StackFrameType *)UTIL_Realloc (
RSLangDC_Stack.stack,
(Size (&RSLangDC_Stack) += StackIncrement)
* sizeof (RSLangDC_StackFrameType)
);
if (tracingStackOps) IO_printf (
"Reallocated Stack\n\t\tStack = %08X, Size = %u",
RSLangDC_Stack.stack,
Size (&RSLangDC_Stack)
);
}
}
PrivateFnDef void DCStack_Initialize () {
RSLangDC_Stack.stack = (RSLangDC_StackFrameType *)UTIL_Malloc (
InitialStackSize * sizeof (RSLangDC_StackFrameType)
);
Size (&RSLangDC_Stack) = InitialStackSize;
SP = 0;
if (tracingStackOps) IO_printf (
StackAllocationMessage,
RSLangDC_Stack.stack, Size (&RSLangDC_Stack)
);
}
PrivateFnDef void DCStack_Push (VByteCodeDescriptor::ByteCode byteCode, char const *string, unsigned int length) {
Grow_DCStack ();
if (tracingStackOps) IO_printf (
StackPushMessage, length, byteCode, length, string, SP
);
rslangSFNewLine (SP) = false;
rslangSFIntensional (SP) = false;
rslangSFMorep (SP) = false;
rslangSFNextp (SP) = false;
rslangSFValLength (SP) = length;
rslangSFByteCode (SP) = byteCode;
rslangSFStringVal (SP) = string;
rslangSFOutputOffset(SP) = bufferIndex (&decompiledProgram);
SP++;
}
PrivateFnDef void DCStack_Push (VByteCodeDescriptor::ByteCode byteCode, char const *string) {
DCStack_Push (byteCode, string, strlen (string));
}
PrivateFnDef void DCStack_Pop () {
if (tracingStackOps)
IO_printf (StackPopMessage, SP);
--SP;
}
/************************************
***** Selector Decomposition *****
************************************/
/*---------------------------------------------------------------------------
***** routine to pull the index'th keyword out of a selector.
*
* Arguments:
* cpd - The cpd for a block containing a selector.
* keyword - The address of a character pointer which will be set
* to the desired keyword.
* index - which keyword to get from the selector.
*
* Returns:
* Length of keyword.
*
*****/
PrivateFnDef int getSelector (M_CPD *cpd, char const **keyword, int index) {
if (rtBLOCK_CPD_SelectorIsKnown (cpd)) {
*keyword = KS__ToString (rtBLOCK_CPD_SelectorIndex (cpd));
if (1 == SELECTOR_KSValence (rtBLOCK_CPD_SelectorIndex (cpd))) {
if (tracingDecompile)
IO_printf ("Known Selector: %s(%d)\n", *keyword, strlen (*keyword));
return strlen (*keyword);
}
}
else
*keyword = rtBLOCK_CPD_SelectorName (cpd);
int x;
for (x = 0; x < index;)
if (*(*keyword)++ == ':') x++;
for (x = 0; (*keyword)[x] && (*keyword)[x] != ':'; x++);
if (tracingDecompile)
IO_printf ("User Selector: %*s(%d)\n", (*keyword)[x] ? x + 1 : x,
*keyword, (*keyword)[x] ? x + 1 : x);
return (*keyword)[x]
? x + 1
: x;
}
/*******************************
***** Decompiler Kernel *****
*******************************/
/*---------------------------------------------------------------------------
***** Routine to convert a compiled program into a string.
*
* Argument:
* pBlockCPD - the address of a CPD which identifies a
* block for the program to be de-compiled.
*
* Returns:
* Nothing
*
* Note:
* No pointer index is passed. This is assumed to be the CPD wanted.
*
*****/
PrivateFnDef void reproduceSource (
M_CPD *pBlockCPD, M_CPD *pReferenceCPD, unsigned int *pDecompiledPCOffset
) {
M_CPD *nestedBlockCPD;
unsigned int x;
bool parametersInStack = false, finished = false, needToGetSelector = false;
int length, pcount, sindex;
bool pushNewLine = false;
char const *selectorPtr, *tptr;
char
tagString [2],
outputString [128];
tagString [1] = '\0';
if (!(rtBLOCK_CPD_NoSelector (pBlockCPD))) {
needToGetSelector = true;
if (rtBLOCK_CPD_SelectorIsKnown (pBlockCPD)) {
if (0 == SELECTOR_KSValence (rtBLOCK_CPD_SelectorIndex (pBlockCPD)))
{
Output (headMark, 1, DoNothing);
length = strlen (KS__ToString
(rtBLOCK_CPD_SelectorIndex (pBlockCPD)));
Output (
KS__ToString (rtBLOCK_CPD_SelectorIndex (pBlockCPD)),
length,
DoNothing
);
Output (headMark, 1, DoNothing);
}
}
else {
if (IsNil (strchr (rtBLOCK_CPD_SelectorName (pBlockCPD), ':'))) {
Output (headMark, 1, DoNothing);
length = strlen (rtBLOCK_CPD_SelectorName (pBlockCPD));
Output (
rtBLOCK_CPD_SelectorName (pBlockCPD), length, DoNothing
);
Output (headMark, 1, DoNothing);
}
}
}
VByteCodeScanner iByteCodeScanner (pBlockCPD);
if (pReferenceCPD) {
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
if (tracingDecompile)
IO_printf ("Reference PC: %d\n", rtBLOCK_CPD_PC (pReferenceCPD));
}
do {
/***** Fetch the next instruction... *****/
iByteCodeScanner.fetchInstruction (true);
if (tracingDecompile) IO_printf (
"Instruction[%d]:%s \n",
iByteCodeScanner.bcAddress (),
iByteCodeScanner.fetchedByteCodeName ()
);
VByteCodeDescriptor::ByteCode xByteCode = iByteCodeScanner.fetchedByteCode ();
switch (xByteCode) {
default:
case VByteCodeDescriptor::ByteCode_Pad0:
case VByteCodeDescriptor::ByteCode_Pad1:
case VByteCodeDescriptor::ByteCode_Pad2:
case VByteCodeDescriptor::ByteCode_Value:
case VByteCodeDescriptor::ByteCode_Intension:
case VByteCodeDescriptor::ByteCode_Comment:
case VByteCodeDescriptor::ByteCode_CommentS:
break;
case VByteCodeDescriptor::ByteCode_Tag:
if (iByteCodeScanner.fetchedLiteral () == PUSHNewLine) {
pushNewLine = true;
break;
}
switch (outputString [0] = (char)iByteCodeScanner.fetchedLiteral ()) {
case '\n':
Output (outputString, 1, DoNothing);
for (x = 0; x < IndentationIndex; x++)
Output (tab, 4, DoNothing);
break;
case '|':
if (!parametersInStack) {
parametersInStack = true;
pcount = 0;
}
else {
for (sindex = 0; sindex < pcount; sindex++) {
if (needToGetSelector) {
length = getSelector (pBlockCPD, &selectorPtr, sindex);
Output (selectorPtr, length, DoBlank);
}
else
Output (colon, 1, DoNothing);
outputStkVal ();
DCStack_Pop ();
}
parametersInStack = false;
}
case ';':
case ')':
if (Ptr (&decompiledProgram) > Storage(&decompiledProgram) && *(Ptr (&decompiledProgram) - 1) == ' ') {
Ptr (&decompiledProgram)--;
if (pReferenceCPD && *pDecompiledPCOffset > bufferIndex (&decompiledProgram))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
}
Output (outputString, 1, DoBlank);
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD) && ';' == outputString[0])
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
break;
case ':':
if (SP > 0)
rslangSFIntensional (SP - 1) = true;
break;
case '.':
case '(':
case '!':
Output (outputString, 1, DoNothing);
break;
default:
break;
}
break;
case VByteCodeDescriptor::ByteCode_AcquireParameter:
case VByteCodeDescriptor::ByteCode_AcquireParameterS:
DCStack_Push (
xByteCode, iByteCodeScanner.fetchedSelectorName ()
);
pcount++;
break;
case VByteCodeDescriptor::ByteCode_AcquireKnownParameter:
DCStack_Push (
xByteCode, KS__ToString (iByteCodeScanner.fetchedSelectorIndex ())
);
pcount++;
break;
case VByteCodeDescriptor::ByteCode_UnaryMessage:
case VByteCodeDescriptor::ByteCode_UnaryMessageS:
DCStack_Push (
xByteCode, iByteCodeScanner.fetchedSelectorName ()
);
if (pushNewLine)
{
pushNewLine = false;
rslangSFNewLine (SP - 1) = true;
}
break;
case VByteCodeDescriptor::ByteCode_KeywordMessage:
case VByteCodeDescriptor::ByteCode_KeywordMessageS:
{
unsigned int valence = iByteCodeScanner.fetchedSelectorValence ();
selectorPtr = iByteCodeScanner.fetchedSelectorName ();
if (tracingDecompile)
IO_printf ("Selector -- '%s'\n", selectorPtr);
tptr = selectorPtr + strlen (selectorPtr) - 1;
for (x = 0; x < valence; x++)
{
length = 1;
while (*--tptr != ':' && tptr != selectorPtr) length++;
length += tptr == selectorPtr ? 1 : 0;
if (tracingDecompile) IO_printf (
"Keyword(%d) -- '%.*s'\n",
x,
length,
tptr == selectorPtr ? tptr : tptr + 1
);
DCStack_Push (
xByteCode, tptr == selectorPtr ? tptr : tptr + 1, length
);
rslangSFMorep (SP - 1) = x > 0;
if (x + 1 < valence)
rslangSFNextp (SP - 1) = true;
if (pushNewLine)
{
pushNewLine = false;
rslangSFNewLine (SP - 1) = true;
}
}
}
break;
case VByteCodeDescriptor::ByteCode_KnownMessage:
{
unsigned int ksi = iByteCodeScanner.fetchedSelectorIndex ();
unsigned int valence = SELECTOR_KSValence (ksi);
selectorPtr = KS__ToString (ksi);
if (tracingDecompile)
IO_printf ("Selector -- '%s'\n", selectorPtr);
length = strlen (selectorPtr);
tptr = selectorPtr + length - 1;
if (valence == 0)
{
if (tracingDecompile)
IO_printf ("Keyword(%d) -- '%.*s'\n", 0, length, selectorPtr);
DCStack_Push (xByteCode, selectorPtr, length);
if (pushNewLine)
{
pushNewLine = false;
rslangSFNewLine (SP - 1) = true;
}
}
else for (x = 0; x < valence; x++)
{
length = 1;
while (*--tptr != ':' && tptr != selectorPtr) length++;
length += tptr == selectorPtr ? 1 : 0;
if (tracingDecompile)
IO_printf ("Keyword(%d) -- '%.*s'\n", x, length,
tptr == selectorPtr ? tptr : tptr + 1);
DCStack_Push (
xByteCode, tptr == selectorPtr ? tptr : tptr + 1, length
);
rslangSFMorep (SP - 1) = x > 0;
if (x + 1 < valence)
rslangSFNextp (SP - 1) = true;
if (pushNewLine)
{
pushNewLine = false;
rslangSFNewLine (SP - 1) = true;
}
}
}
break;
case VByteCodeDescriptor::ByteCode_LAssign:
case VByteCodeDescriptor::ByteCode_RAssign:
case VByteCodeDescriptor::ByteCode_Concat:
case VByteCodeDescriptor::ByteCode_LT:
case VByteCodeDescriptor::ByteCode_LE:
case VByteCodeDescriptor::ByteCode_GE:
case VByteCodeDescriptor::ByteCode_GT:
case VByteCodeDescriptor::ByteCode_Equal:
case VByteCodeDescriptor::ByteCode_Equivalent:
case VByteCodeDescriptor::ByteCode_NEqual:
case VByteCodeDescriptor::ByteCode_NEquivalent:
case VByteCodeDescriptor::ByteCode_Or:
case VByteCodeDescriptor::ByteCode_And:
case VByteCodeDescriptor::ByteCode_Add:
case VByteCodeDescriptor::ByteCode_Subtract:
case VByteCodeDescriptor::ByteCode_Multiply:
case VByteCodeDescriptor::ByteCode_Divide:
DCStack_Push (
xByteCode, KS__ToString (
iByteCodeScanner.fetchedAssociatedKSI ()
)
);
break;
case VByteCodeDescriptor::ByteCode_Dispatch:
// Selector Tracking
rslangSFOutputOffset (SP - 1) = bufferIndex (&decompiledProgram);
outputStkVal ();
break;
case VByteCodeDescriptor::ByteCode_DispatchMagic:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
if (tracingDecompile)
IO_printf ("'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
for (
x = 0;
iByteCodeScanner.getUByte (x++) == VByteCodeDescriptor::ByteCode_Tag;
x++
) if (TagIsPostMagicWord (iByteCodeScanner.getUByte (x)))
{
ConvertPostMagicWordTag (tagString [0], iByteCodeScanner.getUByte (x));
Output (tagString, 1, DoBlank);
}
// Selector Tracking
rslangSFOutputOffset (SP - 1) = bufferIndex (&decompiledProgram);
outputStkVal ();
}
break;
case VByteCodeDescriptor::ByteCode_NextMessageParameter: {
unsigned int iMoreParameters = rslangSFMorep (SP - 1);
unsigned int iSelectorOffset = rslangSFOutputOffset (SP - 1);
DCStack_Pop ();
if (iMoreParameters)
rslangSFOutputOffset (SP - 1) = iSelectorOffset;
if (SP > 0 && rslangSFNextp (SP - 1))
outputStkVal ();
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = iSelectorOffset;
}
break;
case VByteCodeDescriptor::ByteCode_KnownUnaryValue:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
unsigned int ksi = iByteCodeScanner.fetchedSelectorIndex ();
if (tracingDecompile)
IO_printf ("[magic]'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
if (mwi != (unsigned)VMagicWord_Current || (
iByteCodeScanner.getUByte (0) == VByteCodeDescriptor::ByteCode_Tag &&
TagIsPostMagicWord (iByteCodeScanner.getUByte (1))
)
)
{
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
}
for (
x = 0;
iByteCodeScanner.getUByte (x++) == VByteCodeDescriptor::ByteCode_Tag;
x++
) if (TagIsPostMagicWord (iByteCodeScanner.getUByte (x)))
{
ConvertPostMagicWordTag (tagString [0], iByteCodeScanner.getUByte (x));
Output (tagString, 1, DoBlank);
}
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
length = strlen (KS__ToString (ksi));
Output (KS__ToString (ksi), length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_KnownUnaryIntension:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
unsigned int ksi = iByteCodeScanner.fetchedSelectorIndex ();
if (tracingDecompile)
IO_printf ("[magic]'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
if (mwi != (unsigned)VMagicWord_Current || (
iByteCodeScanner.getUByte (0) == VByteCodeDescriptor::ByteCode_Tag &&
TagIsPostMagicWord (iByteCodeScanner.getUByte (1))
)
)
{
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
}
for (
x = 0;
iByteCodeScanner.getUByte (x++) == VByteCodeDescriptor::ByteCode_Tag;
x++
) if (TagIsPostMagicWord (iByteCodeScanner.getUByte (x)))
{
ConvertPostMagicWordTag (tagString [0], iByteCodeScanner.getUByte (x));
Output (tagString, 1, DoBlank);
}
if (Ptr (&decompiledProgram) == Storage (&decompiledProgram) ||
*(Ptr (&decompiledProgram) - 1) != '!'
) Output (colon, 1, DoNothing);
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
length = strlen (KS__ToString (ksi));
Output (KS__ToString (ksi), length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_UnaryValue:
case VByteCodeDescriptor::ByteCode_UnaryValueS:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
if (tracingDecompile)
IO_printf ("[magic]'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
if (mwi != (unsigned)VMagicWord_Current || (
iByteCodeScanner.getUByte (0) == VByteCodeDescriptor::ByteCode_Tag &&
TagIsPostMagicWord (iByteCodeScanner.getUByte (1))
)
)
{
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
}
for (
x = 0;
iByteCodeScanner.getUByte (x++) == VByteCodeDescriptor::ByteCode_Tag;
x++
) if (TagIsPostMagicWord (iByteCodeScanner.getUByte (x)))
{
ConvertPostMagicWordTag (tagString [0], iByteCodeScanner.getUByte (x));
Output (tagString, 1, DoBlank);
}
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
selectorPtr = iByteCodeScanner.fetchedSelectorName ();
length = strlen (selectorPtr);
Output (selectorPtr, length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_UnaryIntension:
case VByteCodeDescriptor::ByteCode_UnaryIntensionS:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
if (tracingDecompile)
IO_printf ("[magic]'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
if (mwi != (unsigned)VMagicWord_Current || (
iByteCodeScanner.getUByte (0) == VByteCodeDescriptor::ByteCode_Tag &&
TagIsPostMagicWord (iByteCodeScanner.getUByte (1))
)
)
{
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
}
for (
x = 0;
iByteCodeScanner.getUByte (x++) == VByteCodeDescriptor::ByteCode_Tag;
x++
) if (TagIsPostMagicWord (iByteCodeScanner.getUByte (x)))
{
ConvertPostMagicWordTag (tagString [0], iByteCodeScanner.getUByte (x));
Output (tagString, 1, DoBlank);
}
if (Ptr (&decompiledProgram) == Storage (&decompiledProgram) ||
*(Ptr (&decompiledProgram) - 1) != '!'
) Output (colon, 1, DoNothing);
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
selectorPtr = iByteCodeScanner.fetchedSelectorName ();
length = strlen (selectorPtr);
Output (selectorPtr, length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_WrapupUnaryIntension:
case VByteCodeDescriptor::ByteCode_WrapupUnaryValue:
// Selector Tracking
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
outputStkVal ();
DCStack_Pop ();
break;
case VByteCodeDescriptor::ByteCode_StoreMagic:
{
unsigned int mwi = iByteCodeScanner.fetchedLiteral ();
if (tracingDecompile)
IO_printf ("[magic]'%s' (%d)\n", MAGIC_MWIToString (mwi), mwi);
Output (magic, 1, DoNothing);
length = strlen (MAGIC_MWIToString (mwi));
Output (MAGIC_MWIToString (mwi), length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_StoreLexBinding:
case VByteCodeDescriptor::ByteCode_StoreLexBindingS:
DCStack_Push (xByteCode, NilOf (char *), 0);
Output (blockOpen, 1, DoNothing);
IndentationIndex++;
/**** produce code for nested block (uses nestedBlockCPD) ****/
nestedBlockCPD = iByteCodeScanner.fetchedBlockCPD ();
reproduceSource (nestedBlockCPD, 0, 0);
nestedBlockCPD->release ();
Output (blockClose, 1, DoNothing);
break;
case VByteCodeDescriptor::ByteCode_StoreInteger:
STD_sprintf (outputString, "%d", iByteCodeScanner.fetchedInteger ());
length = strlen (outputString);
Output (outputString, length, DoBlank);
break;
case VByteCodeDescriptor::ByteCode_StoreDouble:
{
double dp = iByteCodeScanner.fetchedDouble ();
if (fabs (dp) > 1e20 || (fabs (dp) < 1e-20 && dp != 0.0))
STD_sprintf (outputString, "%.20g", dp);
else
STD_sprintf (outputString, "%f", dp);
length = strlen (outputString);
Output (outputString, length, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_StoreString:
case VByteCodeDescriptor::ByteCode_StoreStringS:
Output (quote, 1, DoNothing);
tptr = iByteCodeScanner.fetchedStringText ();
while (IsntNil (selectorPtr = strchr (tptr, '\"')))
{
Output (tptr, selectorPtr - tptr, DoNothing);
Output (backslash, 1, DoNothing);
Output (quote, 1, DoNothing);
tptr = selectorPtr + 1;
}
length = strlen (tptr);
Output (tptr, length, DoNothing);
Output (quote, 1, DoBlank);
break;
case VByteCodeDescriptor::ByteCode_StoreSelector:
case VByteCodeDescriptor::ByteCode_StoreSelectorS:
Output (selMark, 1, DoNothing);
selectorPtr = iByteCodeScanner.fetchedSelectorName ();
length = strlen (selectorPtr);
Output (selectorPtr, length, DoNothing);
Output (selMark, 1, DoBlank);
break;
case VByteCodeDescriptor::ByteCode_StoreKnownSelector: {
unsigned int ksi = iByteCodeScanner.fetchedSelectorIndex ();
Output (selMark, 1, DoNothing);
length = strlen (KS__ToString (ksi));
Output (KS__ToString (ksi), length, DoNothing);
Output (selMark, 1, DoBlank);
}
break;
case VByteCodeDescriptor::ByteCode_StoreNoValue:
/**** Output Nothing ****/
break;
case VByteCodeDescriptor::ByteCode_Exit:
if (topOfStack == VByteCodeDescriptor::ByteCode_StoreLexBinding ||
topOfStack == VByteCodeDescriptor::ByteCode_StoreLexBindingS
)
{
outputStkVal ();
DCStack_Pop ();
IndentationIndex--;
}
if (pReferenceCPD && iByteCodeScanner.bcAddress () <= rtBLOCK_CPD_PC (pReferenceCPD))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
finished = true;
break;
}
if (tracingDecompile && pReferenceCPD)
IO_printf (" DecompiledPCOffset = %d\n", *pDecompiledPCOffset);
} while (!finished);
/***** Remove trailing space if there is one *****/
if (Ptr (&decompiledProgram) > Storage(&decompiledProgram) && *(Ptr (&decompiledProgram) - 1) == ' ')
Ptr (&decompiledProgram)--;
if (pReferenceCPD && *pDecompiledPCOffset > bufferIndex (&decompiledProgram))
*pDecompiledPCOffset = bufferIndex (&decompiledProgram);
}
/*---------------------------------------------------------------------------
***** Routine to convert a compiled program into a string.
*
* Arguments:
* pBlockCPD - a CPD for the block to decompile.
* pDecompiledPCOffset - the optional address of an 'unsigned int'
* which will be set to the character offset
* of the program counter of 'pBlockCPD' in
* its decompiled representation.
* xPCOffset - the optional (UINT_MAX if absent) program
* counter to be used in the computation of
* *pDecompiledPCOffset
*
* Returns:
* A CPD for a text string representing the de-compiled version of
* the program.
*
*****/
PublicFnDef void RSLANG_Decompile (
VString &rSourceReturn,
M_CPD *pBlockCPD,
unsigned int *pDecompiledPCOffset,
unsigned int xPCOffset
) {
M_CPD *pReferenceCPD;
if (IsNil (pDecompiledPCOffset))
pReferenceCPD = 0;
else if (UINT_MAX == xPCOffset)
pReferenceCPD = pBlockCPD;
else {
pReferenceCPD = pBlockCPD->GetCPD (-1, (RTYPE_Type)M_CPD_RType (pBlockCPD));
rtBLOCK_CPD_PC (pReferenceCPD) = rtBLOCK_CPD_ByteCodeVector (pReferenceCPD) + xPCOffset;
}
pBlockCPD = pBlockCPD->GetCPD (-1, (RTYPE_Type)M_CPD_RType (pBlockCPD));
/***** Initialize the string space, ... *****/
InitializeStringSpace (&decompiledProgram);
/***** Initialize the decompiler stack, ... *****/
DCStack_Initialize ();
/***** Interpret the byte codes, ... *****/
reproduceSource (pBlockCPD, pReferenceCPD, pDecompiledPCOffset);
*Ptr (&decompiledProgram) = '\0';
rSourceReturn.setTo (Storage (&decompiledProgram));
/***** Cleanup the string space, ... *****/
UTIL_Free (Storage (&decompiledProgram));
/***** Cleanup the decompiler stack, ... *****/
UTIL_Free (RSLangDC_Stack.stack);
/***** Release the block and reference CPDs if copies were made, ... *****/
pBlockCPD->release ();
if (pReferenceCPD && UINT_MAX > xPCOffset)
pReferenceCPD->release ();
}
/**************************************************
***** Facility I-Object Method Definitions *****
**************************************************/
/*********************************
* Trace Switch Access Methods *
*********************************/
IOBJ_DefineUnaryMethod (TracesOn) {
tracingNodeAlloc =
tracingNodeTypeChange =
tracingNodeAppend =
tracingNonTerminalCreation =
tracingTerminalCreation = true;
return self;
}
IOBJ_DefineUnaryMethod (TracesOff) {
tracingNodeAlloc =
tracingNodeTypeChange =
tracingNodeAppend =
tracingNonTerminalCreation =
tracingTerminalCreation = false;
return self;
}
IOBJ_DefineNilaryMethod (NodeChangeTrace) {
return IOBJ_SwitchIObject (&tracingNodeTypeChange);
}
IOBJ_DefineNilaryMethod (NodeAllocTrace) {
return IOBJ_SwitchIObject (&tracingNodeAlloc);
}
IOBJ_DefineNilaryMethod (AppendTrace) {
return IOBJ_SwitchIObject (&tracingNodeAppend);
}
IOBJ_DefineNilaryMethod (NonTerminalTrace) {
return IOBJ_SwitchIObject (&tracingNonTerminalCreation);
}
IOBJ_DefineNilaryMethod (TerminalTrace) {
return IOBJ_SwitchIObject (&tracingTerminalCreation);
}
IOBJ_DefineUnaryMethod (CompilerTracesOn) {
tracingCompile =
tracingStringSpaceOps =
tracingCodeGeneration = true;
return self;
}
IOBJ_DefineUnaryMethod (CompilerTracesOff) {
tracingCompile =
tracingStringSpaceOps =
tracingCodeGeneration = false;
return self;
}
IOBJ_DefineNilaryMethod (CompileTrace) {
return IOBJ_SwitchIObject (&tracingCompile);
}
IOBJ_DefineNilaryMethod (StringSpaceTrace) {
return IOBJ_SwitchIObject (&tracingStringSpaceOps);
}
IOBJ_DefineNilaryMethod (CodeGenerationTrace) {
return IOBJ_SwitchIObject (&tracingCodeGeneration);
}
IOBJ_DefineNilaryMethod (SaveBlock) {
return IOBJ_SwitchIObject (&retainingBlockForBrowsing);
}
IOBJ_DefineNilaryMethod (DCStackTrace) {
return IOBJ_SwitchIObject (&tracingStackOps);
}
IOBJ_DefineNilaryMethod (DecompileTrace) {
return IOBJ_SwitchIObject (&tracingDecompile);
}
IOBJ_DefineNilaryMethod (GetBlock) {
return blockIObj;
}
IOBJ_DefineUnaryMethod (OneStepRecursivePrint) {
RTYPE_RPrint (RTYPE_QRegisterCPD (blockIObj), -1);
return self;
}
IOBJ_DefineUnaryMethod (OneStepPrint) {
RTYPE_Print (RTYPE_QRegisterCPD (blockIObj), -1);
return self;
}
IOBJ_DefineNilaryMethod (Decompile) {
VString iSource;
RSLANG_Decompile (iSource, RTYPE_QRegisterCPD (blockIObj));
return RTYPE_QRegister (rtSTRING_New (iSource));
}
IOBJ_DefineNewaryMethod (GetSource) {
VString iSource;
RSLANG_Decompile (iSource, RTYPE_QRegisterCPD (parameterArray [0]));
return RTYPE_QRegister (rtSTRING_New (iSource));
}
/*********************************
***** Facility Definition *****
*********************************/
FAC_DefineFacility {
IOBJ_BeginMD (methodDictionary)
IOBJ_MDE ("qprint" , FAC_DisplayFacilityIObject)
IOBJ_MDE ("print" , FAC_DisplayFacilityIObject)
IOBJ_MDE ("parseTracesOn" , TracesOn)
IOBJ_MDE ("parseTracesOff" , TracesOff)
IOBJ_MDE ("nodeChangeTrace" , NodeChangeTrace)
IOBJ_MDE ("nodeAllocTrace" , NodeAllocTrace)
IOBJ_MDE ("appendTrace" , AppendTrace)
IOBJ_MDE ("nonTerminalTrace" , NonTerminalTrace)
IOBJ_MDE ("terminalTrace" , TerminalTrace)
IOBJ_MDE ("compilerTracesOn" , CompilerTracesOn)
IOBJ_MDE ("compilerTracesOff" , CompilerTracesOff)
IOBJ_MDE ("compileTrace" , CompileTrace)
IOBJ_MDE ("stringSpaceTrace" , StringSpaceTrace)
IOBJ_MDE ("codeGenerationTrace" , CodeGenerationTrace)
IOBJ_MDE ("saveBlock" , SaveBlock)
IOBJ_MDE ("dcStackTrace" , DCStackTrace)
IOBJ_MDE ("decompileTrace" , DecompileTrace)
IOBJ_MDE ("getBlock" , GetBlock)
IOBJ_MDE ("P" , OneStepPrint)
IOBJ_MDE ("R" , OneStepRecursivePrint)
IOBJ_MDE ("getSource:" , GetSource)
IOBJ_MDE ("decompile" , Decompile)
IOBJ_EndMD;
switch (FAC_RequestTypeField)
{
FAC_FDFCase_FacilityIdAsString (RSLANG);
FAC_FDFCase_FacilityDescription ("The Compiler/Decompiler");
FAC_FDFCase_FacilitySccsId ("%W%:%G%:%H%:%T%");
case FAC_ReturnFacilityMD:
FAC_MDResultField = methodDictionary;
FAC_CompletionCodeField = FAC_RequestSucceeded;
break;
case FAC_DoStartupInitialization:
blockIObj = IOBJ_TheNilIObject;
rslangout = stderr;
FAC_CompletionCodeField = FAC_RequestSucceeded;
break;
default:
break;
}
}
/************************** SOURCE FILE HISTORY: ************************/
/************************************************************************
rslang.c 1 replace /users/mjc/system
860226 16:26:59 mjc create
************************************************************************/
/************************************************************************
rslang.c 2 replace /users/mjc/system
860317 18:12:38 mjc Replace parser to allow release of new lex/yacc make rules
************************************************************************/
/************************************************************************
rslang.c 3 replace /users/jck
860318 13:04:15 jck Yacc and lex names beginning with 'yy' changed to begin with 'rslang'
************************************************************************/
/************************************************************************
rslang.c 4 replace /users/mjc/system
860324 12:51:38 mjc Returned parser to library for jck\'s use
************************************************************************/
/************************************************************************
rslang.c 6 replace /users/jck/source
860418 00:03:14 jck Code Generator version release
************************************************************************/
/************************************************************************
rslang.c 7 replace /users/jck/system
860418 11:27:40 jck Bug with Binary operations fixed
************************************************************************/
/************************************************************************
rslang.c 8 replace /users/jck/system
860424 11:11:59 jck Miscellaneous bugs fixed
************************************************************************/
/************************************************************************
rslang.c 11 replace /users/jck/system
860429 10:28:22 jck Decompiler completed except for 'pretty printing'
************************************************************************/
/************************************************************************
rslang.c 12 replace /users/jck/system
860430 17:42:12 jck Problems with parse tree allocation fixed
************************************************************************/
/************************************************************************
rslang.c 13 replace /users/jad/system
860509 15:11:56 jad fixed the recursive bug
************************************************************************/
/************************************************************************
rslang.c 14 replace /users/jck/system
860522 12:09:26 jck Incorporated Method Dictionaries
************************************************************************/
/************************************************************************
rslang.c 15 replace /users/jck/system
860523 15:12:41 jck Use of rtVECTOR_USVD_Type parameter revised
************************************************************************/
/************************************************************************
rslang.c 16 replace /users/mjc/system
860527 18:00:08 mjc Changed 'rtBLOCK_CPD_PCCounter' to 'rtBLOCK_CPD_PC'
************************************************************************/
/************************************************************************
rslang.c 17 replace /users/mjc/system
860531 10:42:57 mjc Changed 'RSLANG_Compile' to pick up its method dictionary from 'envir'
************************************************************************/
/************************************************************************
rslang.c 18 replace /users/mjc/system
860531 17:57:15 mjc Release new known CPD names
************************************************************************/
/************************************************************************
rslang.c 19 replace /users/spe/system
860612 16:19:26 spe Implemented NOP bytecode in GenerateCode and reproduceSource.
************************************************************************/
/************************************************************************
rslang.c 20 replace /users/spe/system
860613 09:33:37 spe Corrected _EmptyExpression case in generateSource.
************************************************************************/
/************************************************************************
rslang.c 21 replace /users/spe/system
860613 11:35:01 spe Added SetPrecedingSemi_Colon macro and replaced trailingSemi_Colon bit with precedingSemi_Colon bit in parse tree node.
************************************************************************/
/************************************************************************
rslang.c 23 replace /users/spe/system
860624 16:57:59 spe Modified buildProgram so selector is installed into the block.
************************************************************************/
/************************************************************************
rslang.c 24 replace /users/spe/system
860703 11:37:40 spe Modified acquire parameter bytecode operations and removed all UNWIND_LongJumpTrap calls.
************************************************************************/
/************************************************************************
rslang.c 25 replace /users/mjc/maketest
860708 12:46:16 mjc Deleted references to 'RTselb'
************************************************************************/
/************************************************************************
rslang.c 26 replace /users/mjc/rsystem
860717 21:05:07 mjc Make 'ENVIR_KCPD_TheDefaultProp' the default property
************************************************************************/
/************************************************************************
rslang.c 27 replace /users/jck/system
860804 16:42:54 jck Constant 'MAX_BYTE_SIZE' changed from 256 to 255.
bug fixed in handling of environment table
************************************************************************/
/************************************************************************
rslang.c 28 replace /users/jck/system
860805 16:43:45 jck Fixed bug related to magic word optimizations
Fixed bug in decompiler related to known unary messages
************************************************************************/
/************************************************************************
rslang.c 29 replace /users/jck/system
860806 13:53:35 jck Corrected some decompiler problems
************************************************************************/
/************************************************************************
rslang.c 30 replace /users/jck/system
860807 16:52:02 jck Fixed bug in code generated when magic word
was recipient of keyword or binary message
************************************************************************/
/************************************************************************
rslang.c 31 replace /users/jck/system
860811 11:51:04 jck Changed _EmptyExpression to be a terminal node
in the parse tree
************************************************************************/
/************************************************************************
rslang.c 32 replace /users/jck/system
860812 07:40:00 jck Fixed bug occurring when magic word was the
parameter of a keyword message
************************************************************************/
/************************************************************************
rslang.c 33 replace /users/mjc/system
861002 19:15:42 mjc Release of changes in support of list architecture
************************************************************************/
/************************************************************************
rslang.c 34 replace /usr/rs/versions/5
861107 17:23:12 mjc Fixed bug caused by randomly initialized value of 'IntensionalOp' flag
************************************************************************/
/************************************************************************
rslang.c 35 replace /users/jck/system
861110 12:19:08 jck Added some error recognition to GenerateCode and
fixed 'localId generation' to take advantage of Known selectors
************************************************************************/
/************************************************************************
rslang.c 36 replace /users/mjc/system
861203 13:11:13 mjc Implemented a more reasonable error reporting mechanism
************************************************************************/
/************************************************************************
rslang.c 37 replace /users/mjc/system
861224 11:28:47 mjc Add form feed to whitespace set, add escaped characters to selectors
************************************************************************/
/************************************************************************
rslang.c 38 replace /users/mjc/translation
870524 09:41:03 mjc Shortened all identifiers to <= 31 characters
************************************************************************/
/************************************************************************
rslang.c 39 replace /users/mjc/system
870527 12:51:18 mjc Moved initialization of lex 'output' file to module initialization (VAX portability)
************************************************************************/
/************************************************************************
rslang.c 40 replace /users/mjc/system
870607 03:14:41 mjc Begin conversion to 'stdoss' utilities
************************************************************************/
/************************************************************************
rslang.c 41 replace /users/mjc/system
870607 13:11:14 mjc Changed definition of 'rslanglineno' from 'PublicVarDef int' to 'int' to deal with VAX C 'extern' brain damage
************************************************************************/
/************************************************************************
rslang.c 42 replace /users/mjc/system
870607 22:07:54 mjc Corrected improper correction of 'rslang.c' declaration of 'rslanglineno'
************************************************************************/
/************************************************************************
rslang.c 43 replace /users/mjc/system
870614 20:15:23 mjc Altered 'twalk' action routines to access node contents indirectly
************************************************************************/
/************************************************************************
rslang.c 44 replace /users/jck/system
880114 16:06:17 jck Replaced calls to strncat with calls to memcpy
************************************************************************/
/************************************************************************
rslang.c 45 replace /users/mjc/Workbench/system
880210 15:12:50 mjc Moved recognition of negative numbers from lexical to syntactic analysis
************************************************************************/
/************************************************************************
rslang.c 46 replace /users/jck/system
880328 10:52:55 jck Fixed some decompiler bugs
************************************************************************/
/************************************************************************
rslang.c 47 replace /users/jck/system
880708 12:15:04 jck Fixed another decompiler bug
************************************************************************/
/************************************************************************
rslang.c 48 replace /users/jck/system
881011 14:05:12 jck Made the handling of large vision inputs more robust
************************************************************************/
/************************************************************************
rslang.c 49 replace /users/jck/system
881018 07:54:30 jck Fixed pointer problem in decompiler's 'getSelector' routine.
************************************************************************/
/************************************************************************
rslang.c 50 replace /users/m2/backend
890503 15:29:05 m2 Changed printf() to IO_printf(), STD_printf() changes
************************************************************************/
| [
"tkowalczyk@factset.com"
] | tkowalczyk@factset.com |
f7f6a252badae88d847f3b5940f5218859903400 | 24bc4990e9d0bef6a42a6f86dc783785b10dbd42 | /base/allocator/partition_allocator/extended_api.h | 27359fa89c8893c9cd77b3614c9f64ddd678d8ac | [
"BSD-3-Clause"
] | permissive | nwjs/chromium.src | 7736ce86a9a0b810449a3b80a4af15de9ef9115d | 454f26d09b2f6204c096b47f778705eab1e3ba46 | refs/heads/nw75 | 2023-08-31T08:01:39.796085 | 2023-04-19T17:25:53 | 2023-04-19T17:25:53 | 50,512,158 | 161 | 201 | BSD-3-Clause | 2023-05-08T03:19:09 | 2016-01-27T14:17:03 | null | UTF-8 | C++ | false | false | 1,224 | h | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_ALLOCATOR_PARTITION_ALLOCATOR_EXTENDED_API_H_
#define BASE_ALLOCATOR_PARTITION_ALLOCATOR_EXTENDED_API_H_
#include "base/allocator/partition_allocator/partition_root.h"
#include "base/allocator/partition_allocator/partition_stats.h"
#include "base/allocator/partition_allocator/thread_cache.h"
namespace partition_alloc::internal {
// These two functions are unsafe to run if there are multiple threads running
// in the process.
//
// Disables the thread cache for the entire process, and replaces it with a
// thread cache for |root|.
void SwapOutProcessThreadCacheForTesting(ThreadSafePartitionRoot* root);
// Disables the current thread cache, and replaces it with the default for the
// process.
void SwapInProcessThreadCacheForTesting(ThreadSafePartitionRoot* root);
// Get allocation stats for the thread cache partition on the current
// thread. See the documentation of ThreadAllocStats for details.
ThreadAllocStats GetAllocStatsForCurrentThread();
} // namespace partition_alloc::internal
#endif // BASE_ALLOCATOR_PARTITION_ALLOCATOR_EXTENDED_API_H_
| [
"roger@nwjs.io"
] | roger@nwjs.io |
115eb343ad6f921c1628d92172f3708d066ead7f | 3660278af35965bb7580656ce44a23a07d098db1 | /WordTable.cpp | 35329558b5017031f526f683ee4e331a5c54997c | [] | no_license | JustinWillson/Willson_CSCI2270_FinalProject | 10450dbe240a5ca69da0d87438ebf57e5062cead | 3d31148aac9429a23fd60416cd52f73586247eb0 | refs/heads/master | 2020-12-24T21:36:37.001194 | 2016-05-03T20:06:44 | 2016-05-03T20:06:44 | 56,068,433 | 0 | 1 | null | 2016-05-03T20:06:44 | 2016-04-12T14:06:45 | C++ | UTF-8 | C++ | false | false | 5,845 | cpp | #include "WordTable.h"
using namespace std;
//We initialize the table to hold all blank words
//We also hold the location of the original blank word to avoid memory leaks
WordTable::WordTable(){
blankWord = new word;
blankWord->french = "";
blankWord->english = "";
blankWord->type = "";
for (int i = 0; i < 300; i++){
wordTable[i] = blankWord;
}
}
//Here we delete all the elements in the table as well as the
//blank word we created when we initalized the class
WordTable::~WordTable(){
for(int i = 0; i < 300; i++){
if ( wordTable[i]->french != "" ){
word* temp = wordTable[i];
while(temp != NULL){
word* toDelete = temp;
temp = temp->next;
delete toDelete;
}
}
}
delete blankWord;
}
//the next three methods allow the user to practice different types of speech
void WordTable::practiceNouns(){
string input;
int score = 0;
int count = 0;
for(int i = 0; i< 100; i++){
if (wordTable[i]->french != ""){
word* temp = wordTable[i];
while(temp != NULL){
cout << "What is " << temp->french << " in English." << endl;
cin.ignore();
getline(cin, input);
if(input == temp->english){
score++;
}
count++;
temp = temp->next;
}
}
}
cout<< "On nouns, you got " << score << " correct out of " << count << endl;
}
void WordTable::practiceVerbs(){
string input;
int score = 0;
int count = 0;
for(int i = 100; i< 200; i++){
if (wordTable[i]->french != ""){
word* temp = wordTable[i];
while(temp != NULL){
cout << "What is " << temp->french << " in English." << endl;
cin.ignore();
getline(cin, input);
if(input == temp->english){
score++;
}
count++;
temp = temp->next;
}
}
}
cout<< "On verbs, you got " << score << " correct out of " << count << endl;
}
void WordTable::practiceAdjectives(){
string input;
int score = 0;
int count = 0;
for(int i = 200; i< 300; i++){
if (wordTable[i]->french != ""){
word* temp = wordTable[i];
while(temp != NULL){
cout << "What is " << temp->french << " in English." << endl;
cin.ignore();
getline(cin, input);
if(input == temp->english){
score++;
}
count++;
temp = temp->next;
}
}
}
cout<< "On adjectives, you got " << score << " correct out of " << count << endl;
}
//Calculates the index to put a word at given the word in french and the type of speech
//TYPE CONVERSIONS
//Noun: 0**
//Verb: 1**
//Adjective: 2**
int WordTable::getIndex(string wordFrench, string type){
int sum = 0;
int typeNum;
if(type == "n"){
typeNum = 0;
} else if(type == "v"){
typeNum = 1;
} else if(type == "adj"){
typeNum = 2;
}
for (int i = 0; i<wordFrench.size(); i++){
sum += wordFrench.at(i);
}
int toReturn = sum%100 + 100*typeNum;
return toReturn;
}
//adds a single word to the table, used by the addFromFile() method
void WordTable::addWord(string french, string english, string type){
word* thisWord = new word;
thisWord->french = french;
thisWord->english = english;
thisWord->type = type;
int index = getIndex(french, type);
if(wordTable[index]->french == ""){
wordTable[index] = thisWord;
} else {
word* current = wordTable[index];
while(current->next != NULL){
current = current->next;
}
current->next = thisWord;
}
}
//adds a list of words to the table from a file
//the file must be a list of entries int the form:
//french,english,type
void WordTable::addFromFile(string filename){
ifstream file;
file.open (filename);
string line;
while( getline(file, line) ){
string french;
string english;
string type;
stringstream ss(line);
getline(ss, french, ',');
getline(ss, english, ',');
getline(ss, type, ',');
addWord(french, english, type);
}
}
void WordTable::englishFromFrench(string french){
//while we don't know if the word is a noun or not, we start as a noun
//so we can increment it by 100 until we find the word
int index = getIndex(french, "n");
string english;
bool found = false;
//we increment index by 100 each pass through the loop until it points to an
//index not in the hash table
while(index < 300 && !found){
word* current = wordTable[index];
while (current != NULL && !found) {
if(current->french == french){
found = true;
english = current->english;
}
current = current->next;
}
index+=100;
}
if ( !found ){
cout << "Word not found, please try again" << endl;
} else {
cout << french << " : " << english << endl;
}
}
//prints all items in the table
//mostly used for debugging
void WordTable::printTable(){
for(int i = 0; i < 300; i++){
if (wordTable[i]->french != ""){
word* temp = wordTable[i];
while(temp != NULL){
cout << "French: " << temp->french << " ... English: " << temp->english << "... index: " << i << endl;
temp = temp->next;
}
}
}
}
| [
"juwi8104@colorado.edu"
] | juwi8104@colorado.edu |
2bea8806a1c718eb5dd07f625d9050842b670e8a | ae9de48e6cdc19f817505aa9be1bcf0b82fa49b1 | /Filters/ParallelDIY2/vtkPResampleToImage.h | 201d913c66c7eae10842de431fc3d638f3253192 | [
"BSD-3-Clause"
] | permissive | quantumsteve/VTK | 60a3e055ce72e56ac402fe28b0e492ca0bfc797e | d071eb2cab5fe10e05d31ac38a338214a84548b9 | refs/heads/master | 2021-01-15T18:21:52.320326 | 2016-06-16T18:00:43 | 2016-06-16T18:00:43 | 61,330,687 | 0 | 1 | null | 2016-06-16T22:50:27 | 2016-06-16T22:50:27 | null | UTF-8 | C++ | false | false | 2,003 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPResampleToImage.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkPResampleToImage - sample dataset on a uniform grid in parallel
// .SECTION Description
// vtkPResampleToImage is a parallel filter that resamples the input dataset on
// a uniform grid. It internally uses vtkProbeFilter to do the probing.
// .SECTION See Also
// vtkResampleToImage vtkProbeFilter
#ifndef vtkPResampleToImage_h
#define vtkPResampleToImage_h
#include "vtkFiltersParallelDIY2Module.h" // For export macro
#include "vtkResampleToImage.h"
class vtkDataSet;
class vtkImageData;
class vtkMultiProcessController;
class VTKFILTERSPARALLELDIY2_EXPORT vtkPResampleToImage : public vtkResampleToImage
{
public:
vtkTypeMacro(vtkPResampleToImage, vtkResampleToImage);
void PrintSelf(ostream& os, vtkIndent indent);
static vtkPResampleToImage *New();
// Description:
// By defualt this filter uses the global controller,
// but this method can be used to set another instead.
virtual void SetController(vtkMultiProcessController*);
vtkGetObjectMacro(Controller, vtkMultiProcessController);
protected:
vtkPResampleToImage();
~vtkPResampleToImage();
virtual int RequestData(vtkInformation *, vtkInformationVector **,
vtkInformationVector *);
vtkMultiProcessController *Controller;
private:
vtkPResampleToImage(const vtkPResampleToImage&); // Not implemented.
void operator=(const vtkPResampleToImage&); // Not implemented.
};
#endif
| [
"sujin.philip@kitware.com"
] | sujin.philip@kitware.com |
5ac3322039a9406004caab2949fde80985882251 | 8830b5a92af1e76f1653d29092b398dec5d88184 | /code.cpp | 59921bed860960288d7c5beeaf8198d239bd41aa | [] | no_license | Thuzad/Voting-Machine | 07a11d8776169fcc780d84f91ed760a6a32d616d | 5532442cb3b41d4e41164a085ff20c3b6cf9ac60 | refs/heads/master | 2021-01-10T15:18:27.403792 | 2016-03-16T10:42:02 | 2016-03-16T10:42:02 | 54,022,991 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,127 | cpp | #include<stdio.h>
#include<winsock2.h>
#include<winbase.h>
#include<time.h>
#pragma comment(lib, "ws2_32")
#define RefreshTimes 1587
int cnt = 0;
char host[128];
char path[128];
char NUM[16] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
DWORD WINAPI SendThread(LPVOID lpparam);
void Setparam(){
char Host_Temp[] = "lvyou.baidu.com";
char Path_Temp[] = "/main/event/nanji/ajax/good?wcuid=oVFEBt7-gTCS2S7Rf-V6IcIF5Wug";
fflush(stdout);
strcpy_s(path, &Path_Temp[0]);
strcpy_s(host, &Host_Temp[0]);
}
void main(int argc, char* argv[]){
HANDLE hThread[RefreshTimes];
DWORD dwThread[RefreshTimes];
int i, num1, num2;
srand((unsigned)time(NULL));
Setparam();
for (i = 0; i < RefreshTimes; ++i){
hThread[i] = CreateThread(NULL, 0, SendThread, (LPVOID)i, 0, &dwThread[i]);
if (hThread == NULL){
printf("\tCreateThread Failed.\n");
exit(0);
}
num2 = (rand() % 100)+ 1000;
Sleep(num2);
CloseHandle(hThread);
}
system("pause");
}
DWORD WINAPI SendThread(LPVOID lpParam){
WSADATA wsd;
SOCKET local;
SOCKADDR_IN addr;
HOSTENT *Host = NULL;
if (WSAStartup(MAKEWORD(2, 2), &wsd) != 0){
printf("\tFailed To Load Winsock Library!\n");
exit(0);
}
local = socket(AF_INET, SOCK_STREAM, 0);
if (local == INVALID_SOCKET){
printf("\tFailed To Create Socket\n");
exit(0);
}
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.S_un.S_addr = inet_addr(host);
if (addr.sin_addr.S_un.S_addr == INADDR_NONE){
Host = gethostbyname(host);
if (Host == NULL){
printf("\tUnable To Resolve Server:%s\n", host);
return 0;
}
CopyMemory(&addr.sin_addr, Host->h_addr_list[0], Host->h_length);
printf("\tSend To:%s", inet_ntoa(addr.sin_addr));
}
if (SOCKET_ERROR == connect(local, (sockaddr*)&addr, sizeof(SOCKADDR))){
printf("\tFailed To Connect To The Server!\n");
exit(0);
}
//构造发送数据
srand((unsigned)time(NULL));
char baiduid[33];
memset(baiduid, '\0', sizeof(baiduid));
for (int i = 0; i < 32; ++i){
baiduid[i] = NUM[rand() % 16];
}
char SendBuf[640];
memset(SendBuf, '\0', sizeof(SendBuf));
char PartOne[] = " HTTP/1.1\r\nHost: lvyou.baidu.com\r\nConnection: keep-alive\r\nAccept: application/json, text/javascript, */*; q=0.01\r\nX-Rquested-With: XMLHttpRequest\r\nUser-Agent: Mozilla/5.0 (Linux; U; Android 4.3; en-us; SM-N900T Build/JSS15J) Applewebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile safari/534.30\r\nReferer: http://lvyou.baidu.com/main/event/nanji/user?wcuid=oVFEBt7-gTCS2S7Rf-V6IcIF5Wug&from=timeline&isappinstalled=0\r\nAccept-Encoding: gzip,deflate,sdch\r\nAccept-Language: zh-CN,zh;q=0.8\r\nCookie: BAIDUID=";
char PartTwo[] = ":FG=1;\r\n\r\n";
strcpy_s(SendBuf, "GET ");
strcat_s(SendBuf, path);
strcat_s(SendBuf, PartOne);
strcat_s(SendBuf, baiduid);
strcat_s(SendBuf, PartTwo);
if (send(local, SendBuf, strlen(SendBuf) + 1, 0) == SOCKET_ERROR){
printf("\tSend Data Error.\n");
}
closesocket(local);
WSACleanup();
printf(" %d\n", ++cnt);
return 0;
} | [
"Thuzad@users.noreply.github.com"
] | Thuzad@users.noreply.github.com |
80b4798c82e6009e56f4004f2ddba43b2c13893e | 957edf3a578504615a0e683430f76afe86a5598e | /qtncnn/mtcnn.cpp | 96876ef34e7c09d73be35339385146667aa432fc | [] | no_license | kokoliunian/qtcode | 6a5c763414f7bbca252468b932a0c3dcdfb50422 | 216beb0e3b7312737c803e69699a7bae614ef664 | refs/heads/master | 2020-08-02T02:33:31.505813 | 2019-10-21T03:14:31 | 2019-10-21T03:14:31 | 211,209,643 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 11,193 | cpp | #include "mtcnn.h"
MtcnnDetector::MtcnnDetector(string model_folder)
{
vector<string> param_files = {
model_folder + "/det1.param",
model_folder + "/det2.param",
model_folder + "/det3.param",
model_folder + "/det4.param"
};
vector<string> bin_files = {
model_folder + "/det1.bin",
model_folder + "/det2.bin",
model_folder + "/det3.bin",
model_folder + "/det4.bin"
};
this->Pnet.load_param(param_files[0].c_str());
this->Pnet.load_model(bin_files[0].c_str());
this->Rnet.load_param(param_files[1].c_str());
this->Rnet.load_model(bin_files[1].c_str());
this->Onet.load_param(param_files[2].c_str());
this->Onet.load_model(bin_files[2].c_str());
this->Lnet.load_param(param_files[3].c_str());
this->Lnet.load_model(bin_files[3].c_str());
}
MtcnnDetector::~MtcnnDetector()
{
this->Pnet.clear();
this->Rnet.clear();
this->Onet.clear();
this->Lnet.clear();
}
vector<FaceInfo> MtcnnDetector::Detect(ncnn::Mat img)
{
int img_w = img.w;
int img_h = img.h;
vector<FaceInfo> pnet_results = Pnet_Detect(img);
doNms(pnet_results, 0.7, "union");
refine(pnet_results, img_h, img_w, true);
vector<FaceInfo> rnet_results = Rnet_Detect(img, pnet_results);
doNms(rnet_results, 0.7, "union");
refine(rnet_results, img_h, img_w, true);
vector<FaceInfo> onet_results = Onet_Detect(img, rnet_results);
refine(onet_results, img_h, img_w, false);
doNms(onet_results, 0.7, "min");
Lnet_Detect(img, onet_results);
return onet_results;
}
vector<FaceInfo> MtcnnDetector::Pnet_Detect(ncnn::Mat img)
{
vector<FaceInfo> results;
int img_w = img.w;
int img_h = img.h;
float minl = img_w < img_h ? img_w : img_h;
double scale = 12.0 / this->minsize;
minl *= scale;
vector<double> scales;
while (minl > 12)
{
scales.push_back(scale);
minl *= this->factor;
scale *= this->factor;
}
for (auto it = scales.begin(); it != scales.end(); it++)
{
scale = (double)(*it);
int hs = (int) ceil(img_h * scale);
int ws = (int) ceil(img_w * scale);
ncnn::Mat in = resize(img, ws, hs);
in.substract_mean_normalize(this->mean_vals, this->norm_vals);
ncnn::Extractor ex = Pnet.create_extractor();
ex.set_light_mode(true);
ex.input("data", in);
ncnn::Mat score;
ncnn::Mat location;
ex.extract("prob1", score);
ex.extract("conv4_2", location);
vector<FaceInfo> bboxs = generateBbox(score, location, *it, this->threshold[0]);
doNms(bboxs, 0.5, "union");
results.insert(results.end(), bboxs.begin(), bboxs.end());
}
return results;
}
vector<FaceInfo> MtcnnDetector::Rnet_Detect(ncnn::Mat img, vector<FaceInfo> bboxs)
{
vector<FaceInfo> results;
int img_w = img.w;
int img_h = img.h;
for (auto it = bboxs.begin(); it != bboxs.end(); it++)
{
ncnn::Mat img_t;
copy_cut_border(img, img_t, it->y[0], img_h - it->y[1], it->x[0], img_w - it->x[1]);
ncnn::Mat in = resize(img_t, 24, 24);
in.substract_mean_normalize(this->mean_vals, this->norm_vals);
ncnn::Extractor ex = Rnet.create_extractor();
ex.set_light_mode(true);
ex.input("data", in);
ncnn::Mat score, bbox;
ex.extract("prob1", score);
ex.extract("conv5_2", bbox);
if ((float)score[1] > threshold[1])
{
for (int c = 0; c < 4; c++)
{
it->regreCoord[c] = (float)bbox[c];
}
it->score = (float)score[1];
results.push_back(*it);
}
}
return results;
}
vector<FaceInfo> MtcnnDetector::Onet_Detect(ncnn::Mat img, vector<FaceInfo> bboxs)
{
vector<FaceInfo> results;
int img_w = img.w;
int img_h = img.h;
for (auto it = bboxs.begin(); it != bboxs.end(); it++)
{
ncnn::Mat img_t;
copy_cut_border(img, img_t, it->y[0], img_h - it->y[1], it->x[0], img_w - it->x[1]);
ncnn::Mat in = resize(img_t, 48, 48);
in.substract_mean_normalize(this->mean_vals, this->norm_vals);
ncnn::Extractor ex = Onet.create_extractor();
ex.set_light_mode(true);
ex.input("data", in);
ncnn::Mat score, bbox, point;
ex.extract("prob1", score);
ex.extract("conv6_2", bbox);
ex.extract("conv6_3", point);
if ((float)score[1] > threshold[2])
{
for (int c = 0; c < 4; c++)
{
it->regreCoord[c] = (float)bbox[c];
}
for (int p = 0; p < 5; p++)
{
it->landmark[2 * p] = it->x[0] + (it->x[1] - it->x[0]) * point[p];
it->landmark[2 * p + 1] = it->y[0] + (it->y[1] - it->y[0]) * point[p + 5];
}
it->score = (float)score[1];
results.push_back(*it);
}
}
return results;
}
void MtcnnDetector::Lnet_Detect(ncnn::Mat img, vector<FaceInfo> &bboxes)
{
int img_w = img.w;
int img_h = img.h;
for (auto it = bboxes.begin(); it != bboxes.end(); it++)
{
int w = it->x[1] - it->x[0] + 1;
int h = it->y[1] - it->y[0] + 1;
int m = w > h ? w : h;
m = (int)round(m * 0.25);
if (m % 2 == 1) m++;
m /= 2;
ncnn::Mat in(24, 24, 15);
for (int i = 0; i < 5; i++)
{
int px = it->landmark[2 * i];
int py = it->landmark[2 * i + 1];
ncnn::Mat cut;
copy_cut_border(img, cut, py - m, img_h - py - m, px - m, img_w - px - m);
ncnn::Mat resized = resize(cut, 24, 24);
resized.substract_mean_normalize(this->mean_vals, this->norm_vals);
for (int j = 0; j < 3; j++)
memcpy(in.channel(3 * i + j), resized.channel(j), 24 * 24 * sizeof(float));
}
ncnn::Extractor ex = Lnet.create_extractor();
ex.set_light_mode(true);
ex.input("data", in);
ncnn::Mat out1, out2, out3, out4, out5;
ex.extract("fc5_1", out1);
ex.extract("fc5_2", out2);
ex.extract("fc5_3", out3);
ex.extract("fc5_4", out4);
ex.extract("fc5_5", out5);
if (abs(out1[0] - 0.5) > 0.35) out1[0] = 0.5f;
if (abs(out1[1] - 0.5) > 0.35) out1[1] = 0.5f;
if (abs(out2[0] - 0.5) > 0.35) out2[0] = 0.5f;
if (abs(out2[1] - 0.5) > 0.35) out2[1] = 0.5f;
if (abs(out3[0] - 0.5) > 0.35) out3[0] = 0.5f;
if (abs(out3[1] - 0.5) > 0.35) out3[1] = 0.5f;
if (abs(out4[0] - 0.5) > 0.35) out4[0] = 0.5f;
if (abs(out4[1] - 0.5) > 0.35) out4[1] = 0.5f;
if (abs(out5[0] - 0.5) > 0.35) out5[0] = 0.5f;
if (abs(out5[1] - 0.5) > 0.35) out5[1] = 0.5f;
it->landmark[0] += (int)round((out1[0] - 0.5) * m * 2);
it->landmark[1] += (int)round((out1[1] - 0.5) * m * 2);
it->landmark[2] += (int)round((out2[0] - 0.5) * m * 2);
it->landmark[3] += (int)round((out2[1] - 0.5) * m * 2);
it->landmark[4] += (int)round((out3[0] - 0.5) * m * 2);
it->landmark[5] += (int)round((out3[1] - 0.5) * m * 2);
it->landmark[6] += (int)round((out4[0] - 0.5) * m * 2);
it->landmark[7] += (int)round((out4[1] - 0.5) * m * 2);
it->landmark[8] += (int)round((out5[0] - 0.5) * m * 2);
it->landmark[9] += (int)round((out5[1] - 0.5) * m * 2);
}
}
vector<FaceInfo> MtcnnDetector::generateBbox(ncnn::Mat score, ncnn::Mat loc, float scale, float thresh)
{
int stride = 2;
int cellsize = 12;
float *p = score.channel(1);
float inv_scale = 1.0f / scale;
vector<FaceInfo> results;
for (int row = 0; row < score.h; row++)
{
for (int col = 0; col < score.w; col++)
{
if (*p > thresh)
{
FaceInfo box;
box.score = *p;
box.x[0] = round((stride * col + 1) * inv_scale);
box.y[0] = round((stride * row + 1) * inv_scale);
box.x[1] = round((stride * col + 1 + cellsize) * inv_scale);
box.y[1] = round((stride * row + 1 + cellsize) * inv_scale);
box.area = (box.x[1] - box.x[0]) * (box.y[1] - box.y[0]);
int index = row * score.w + col;
for (int c = 0; c < 4; c++)
box.regreCoord[c] = loc.channel(c)[index];
results.push_back(box);
}
p++;
}
}
return results;
}
bool cmpScore(FaceInfo x, FaceInfo y)
{
if (x.score > y.score)
return true;
else
return false;
}
float calcIOU(FaceInfo box1, FaceInfo box2, string mode)
{
int maxX = max(box1.x[0], box2.x[0]);
int maxY = max(box1.y[0], box2.y[0]);
int minX = min(box1.x[1], box2.x[1]);
int minY = min(box1.y[1], box2.y[1]);
int width = ((minX - maxX + 1) > 0) ? (minX - maxX + 1) : 0;
int height = ((minY - maxY + 1) > 0) ? (minY - maxY + 1) : 0;
int inter = width * height;
if (!mode.compare("union"))
return float(inter) / (box1.area + box2.area - float(inter));
else if (!mode.compare("min"))
return float(inter) / (box1.area < box2.area ? box1.area : box2.area);
else
return 0;
}
void MtcnnDetector::doNms(vector<FaceInfo> &bboxs, float nms_thresh, string mode)
{
if (bboxs.empty())
return;
sort(bboxs.begin(), bboxs.end(), cmpScore);
for (int i = 0; i < bboxs.size(); i++)
if (bboxs[i].score > 0)
for (int j = i + 1; j < bboxs.size(); j++)
if (bboxs[j].score > 0)
{
float iou = calcIOU(bboxs[i], bboxs[j], mode);
if (iou > nms_thresh)
bboxs[j].score = 0;
}
for (auto it = bboxs.begin(); it != bboxs.end();)
if ((*it).score == 0)
bboxs.erase(it);
else
it++;
}
void MtcnnDetector::refine(vector<FaceInfo> &bboxs, int height, int width, bool flag)
{
if (bboxs.empty())
return;
for (auto it = bboxs.begin(); it != bboxs.end(); it++)
{
float bw = it->x[1] - it->x[0] + 1;
float bh = it->y[1] - it->y[0] + 1;
float x0 = it->x[0] + it->regreCoord[0] * bw;
float y0 = it->y[0] + it->regreCoord[1] * bh;
float x1 = it->x[1] + it->regreCoord[2] * bw;
float y1 = it->y[1] + it->regreCoord[3] * bh;
if (flag)
{
float w = x1 - x0 + 1;
float h = y1 - y0 + 1;
float m = (h > w) ? h : w;
x0 = x0 + w * 0.5 - m * 0.5;
y0 = y0 + h * 0.5 - m * 0.5;
x1 = x0 + m - 1;
y1 = y0 + m - 1;
}
it->x[0] = round(x0);
it->y[0] = round(y0);
it->x[1] = round(x1);
it->y[1] = round(y1);
if (it->x[0] < 0) it->x[0] = 0;
if (it->y[0] < 0) it->y[0] = 0;
if (it->x[1] > width) it->x[1] = width - 1;
if (it->y[1] > height) it->y[1] = height - 1;
it->area = (it->x[1] - it->x[0]) * (it->y[1] - it->y[0]);
}
}
| [
"14782340@qq.com"
] | 14782340@qq.com |
1cd0f5e78af3ba89ef942434ff8702db9fdc682d | 4d717cbdf637da119fe02c69ceccaf0387dcd2ad | /funkcionalno_programiranje/CTacka.cpp | 1017e53c8c706a79e535f30f7ae370da44d494a0 | [] | no_license | mirkovicmatija/objektnocpp | 325b9b11c191c03e4cba60610a155998dd024b41 | 7de475dc5935ae58d47dd6ad7c6816d8d816f5a9 | refs/heads/master | 2023-04-05T10:34:13.655666 | 2021-04-17T19:17:02 | 2021-04-17T19:17:02 | 305,648,138 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | #include <iostream>
#include <cmath>
class cTacka
{
double dX, dY;
public:
cTacka(double a, double b) { dX = a; dY = b;}
~cTacka(){}
double getdX(){return dX;}
double getdY(){return dY;}
double point(){return pow(dX,2) + pow(dY,2);}
};
int main() {
cTacka T(2,3);
cTacka K(4,5);
double x = T.point() - K.point();
std::cout<<x<<std::endl;
return 0;
}
| [
"matija.mirkovic@jsguru.com"
] | matija.mirkovic@jsguru.com |
733653a1112da9e2f555d8511548ca08c7ea4cc4 | 99288d3f22e824810363145f70b36d328591e694 | /src/list.cpp | b412db08412ff48f739b95b77da61d95b39dbafe | [] | no_license | pvastig/list | 4448d58c6e11862c19cfb4fbb6bd51746f0ded05 | 26eb3980b76a4caca38544ea39246206536f0aeb | refs/heads/master | 2023-04-04T08:33:28.902514 | 2023-03-23T14:47:32 | 2023-03-23T14:47:32 | 195,686,139 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,812 | cpp | #include "list.h"
namespace pa {
/*
template<class Type,
class UnqualifiedType = std::remove_cv_t<Type>>
class ForwardIterator : public std::iterator<std::forward_iterator_tag,
UnqualifiedType,
std::ptrdiff_t,
Type*,
Type&>
{
friend class List<UnqualifiedType>;
typename List<UnqualifiedType>::Node* m_it;
explicit ForwardIterator(typename List<UnqualifiedType>::Node* it)
: m_it(it)
{
}
public:
ForwardIterator() : m_it(nullptr)
{
}
void swap(ForwardIterator& other) noexcept
{
using std::swap;
swap(m_it, other.iter);
}
ForwardIterator& operator++()
{
assert(m_it != nullptr && "Out-of-bounds iterator increment!");
m_it = m_it->next;
return *this;
}
ForwardIterator operator++(int)
{
assert(m_it != nullptr && "Out-of-bounds iterator increment!");
ForwardIterator tmp(*this);
m_it = m_it->next;
return tmp;
}
// two-way comparison: v.begin() == v.cbegin() and vice versa
template<class OtherType>
bool operator==(ForwardIterator<OtherType> const& rhs) const
{
return m_it == rhs.m_it;
}
template<class OtherType>
bool operator != (ForwardIterator<OtherType> const& rhs) const
{
return m_it != rhs.m_it;
}
Type& operator*() const
{
assert(m_it != nullptr && "Invalid iterator dereference!");
return m_it->value;
}
Type& operator->() const
{
assert(m_it != nullptr && "Invalid iterator dereference!");
return m_it->value;
}
// One way conversion: iterator -> const_iterator
operator ForwardIterator<const Type>() const
{
return ForwardIterator<const Type>(m_it);
}
};
using iterator = ForwardIterator<T>;
using const_iterator = ForwardIterator<const T>;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
const_iterator cbegin() const;
const_iterator cend() const;
template<class T>
typename List<T>::iterator List<T>::begin()
{
return iterator(m_head);
}
template<class T>
typename List<T>::iterator List<T>::end()
{
return iterator(nullptr);
}
template<class T>
typename List<T>::const_iterator List<T>::begin() const
{
return const_iterator(m_head);
}
template<class T>
typename List<T>::const_iterator List<T>::end() const
{
return const_iterator(nullptr);
}
template<class T>
typename List<T>::const_iterator List<T>::cbegin() const
{
return const_iterator(m_head);
}
template<class T>
typename List<T>::const_iterator List<T>::cend() const
{
return const_iterator(nullptr);
}
//TODO: rewrite using iterators
template<class T>
bool List<T>::erase(iterator it)
{
return remove(*it);
}
*/
}//end namepace pa
| [
"pavel.astigeevich.contractor@draeger.com"
] | pavel.astigeevich.contractor@draeger.com |
0803d7c0e0ad26f9e68b0a4ab64af34d0dc32358 | 2a7e77565c33e6b5d92ce6702b4a5fd96f80d7d0 | /fuzzedpackages/crawl/src/CTCRWSAMPLE.cpp | 6d3ecf1c7c4a3c1f41573fc0b415b843c3e2decd | [] | no_license | akhikolla/testpackages | 62ccaeed866e2194652b65e7360987b3b20df7e7 | 01259c3543febc89955ea5b79f3a08d3afe57e95 | refs/heads/master | 2023-02-18T03:50:28.288006 | 2021-01-18T13:23:32 | 2021-01-18T13:23:32 | 329,981,898 | 7 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,564 | cpp | // -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
#include "RcppArmadillo.h"
// [[Rcpp::depends(RcppArmadillo)]]
using namespace Rcpp;
using namespace arma;
// Function prototypes
arma::mat makeQ(const double& beta, const double& sig2, const double& delta, const double& active);
arma::mat makeT(const double& beta, const double& delta, const double& active);
arma::vec mvn(const arma::vec& mu, const arma::mat& V);
// [[Rcpp::export]]
Rcpp::List CTCRWSAMPLE(const arma::mat& y, const arma::mat& Hmat,
const arma::vec& beta, const arma::vec& sig2, const arma::vec& delta,
const arma::vec& noObs,const arma::vec& active, const arma::colvec& a,
const arma::mat& P)
{
int I = y.n_rows;
// SIMULATION RELATED MATRICES
arma::mat y_plus(I, 2);
arma::mat alpha_plus(4,I+1, fill::zeros);
alpha_plus.col(0) = mvn(a,P);
arma::mat alpha_plus_hat(4,I+1, fill::zeros);
alpha_plus_hat.col(0) = a;
arma::mat v_plus(2,I, fill::zeros);
arma::colvec r_plus(4, fill::zeros);
arma::mat sim(I,4);
// KFS MATRICES FOR DATA INFORMED PART
arma::mat Z(2,4, fill::zeros); Z(0,0) = 1; Z(1,2) = 1;
arma::mat T(4,4, fill::zeros); T(0,0) = 1; T(2,2) = 1;
arma::mat Q(4,4, fill::zeros);
arma::cube F(2,2,I, fill::zeros);
arma::mat H(2,2, fill::zeros);
arma::cube K(4,2,I, fill::zeros);
arma::cube L(4,4,I, fill::zeros);
arma::mat v(2,I, fill::zeros);
arma::mat alpha_hat(4,I+1, fill::zeros);
alpha_hat.col(0) = a;
arma::cube P_hat(4,4,I+1, fill::zeros);
P_hat.slice(0)=P;
arma::colvec r(4, fill::zeros);
double ll=0;
//Forward filter and simulation
for(int i=0; i<I; i++){
Q = makeQ(beta(i), sig2(i), delta(i), active(i));
T = makeT(beta(i), delta(i), active(i));
if(active(i)==0){
alpha_plus.col(i+1) = alpha_plus.col(i);
} else{
alpha_plus.col(i+1) = mvn(T*alpha_plus.col(i), Q);
}
if(noObs(i)==1){
alpha_hat.col(i+1) = T*alpha_hat.col(i);
P_hat.slice(i+1) = T*P_hat.slice(i)*T.t() + Q;
L.slice(i) = T;
alpha_plus_hat.col(i+1) = T*alpha_plus_hat.col(i);
} else {
H(0,0) = Hmat(i,0);
H(1,1) = Hmat(i,1);
H(0,1) = Hmat(i,2);
H(1,0) = Hmat(i,2);
// KF simulation for data section
v.col(i) = y.row(i).t()-Z*alpha_hat.col(i);
F.slice(i) = Z*P_hat.slice(i)*Z.t() + H;
ll += - (log(det(F.slice(i))) + dot(v.col(i),solve(F.slice(i),v.col(i))))/2;
K.slice(i) = T*P_hat.slice(i)*Z.t()*F.slice(i).i();
L.slice(i) = T - K.slice(i)*Z;
alpha_hat.col(i+1) = T*alpha_hat.col(i) + K.slice(i)*v.col(i);
P_hat.slice(i+1) = T*P_hat.slice(i)*L.slice(i).t() + Q;
// Simulation component
y_plus.row(i) = mvn(Z*alpha_plus.col(i), H).t();
v_plus.col(i) = y_plus.row(i).t()-Z*alpha_plus_hat.col(i);
alpha_plus_hat.col(i+1) = T*alpha_plus_hat.col(i) + K.slice(i)*v_plus.col(i);
}
}
// Backward smooth
for(int j=I; j>0; j--){
if(noObs(j-1)==1 || F.slice(j-1)(0,0)*F.slice(j-1)(1,1)==0){
r = L.slice(j-1).t() * r;
r_plus = L.slice(j-1).t() * r_plus;
} else{
r = Z.t()*solve(F.slice(j-1),v.col(j-1)) + L.slice(j-1).t() * r;
r_plus = Z.t()*solve(F.slice(j-1),v_plus.col(j-1)) + L.slice(j-1).t() * r_plus;
}
alpha_hat.col(j-1) += P_hat.slice(j-1)*r;
alpha_plus_hat.col(j-1) += P_hat.slice(j-1)*r_plus;
}
sim = (alpha_hat.cols(0,I-1) - (alpha_plus.cols(0,I-1)-alpha_plus_hat.cols(0,I-1))).t();
return Rcpp::List::create(
Rcpp::Named("ll") = ll,
Rcpp::Named("sim") = sim
);
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
3786774ecbae1f5bf50204caa945179c60dc4a85 | 75a5dea15ae24c1664726d5e0ada7a41dcc81744 | /test/string_buffer.cpp | 2ec69102b09c443433de6ee20dcfcaf7617e055e | [
"BSD-3-Clause",
"BSL-1.0",
"Apache-2.0",
"MIT"
] | permissive | StuartRyder/roq-api | 54bd5ee86e91fb34d90941ed9de7a7edd8cab92c | 73f0a30dd46de21d67d98bdfec3bd9862f5454c4 | refs/heads/master | 2023-08-23T13:06:38.755173 | 2021-09-27T03:47:12 | 2021-09-27T03:47:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,816 | cpp | /* Copyright (c) 2017-2021, Hans Erik Thrane */
#include <gtest/gtest.h>
#include "roq/string_buffer.h"
using namespace roq;
using namespace roq::literals;
TEST(string_buffer, empty) {
roq::string_buffer<4> s;
EXPECT_EQ(s.size(), 4);
EXPECT_EQ(s.length(), 0);
auto sv = static_cast<std::string_view>(s);
EXPECT_TRUE(sv.empty());
EXPECT_EQ(sv.length(), 0);
}
TEST(string_buffer, partial) {
constexpr auto text = "12"_sv;
roq::string_buffer<4> s = text;
EXPECT_EQ(s.size(), 4);
EXPECT_EQ(s.length(), 2);
auto sv = static_cast<std::string_view>(s);
EXPECT_FALSE(sv.empty());
EXPECT_EQ(sv.length(), 2);
EXPECT_EQ(sv, text);
}
TEST(string_buffer, almost_full) {
constexpr auto text = "123"_sv;
roq::string_buffer<4> s = text;
EXPECT_EQ(s.size(), 4);
EXPECT_EQ(s.length(), 3);
auto sv = static_cast<std::string_view>(s);
EXPECT_FALSE(sv.empty());
EXPECT_EQ(sv.length(), 3);
EXPECT_EQ(sv, text);
}
TEST(string_buffer, full) {
constexpr auto text = "1234"_sv;
roq::string_buffer<4> s = text;
EXPECT_EQ(s.size(), 4);
EXPECT_EQ(s.length(), 4);
auto sv = static_cast<std::string_view>(s);
EXPECT_FALSE(sv.empty());
EXPECT_EQ(sv.length(), 4);
EXPECT_EQ(sv, text);
}
TEST(string_buffer, construct) {
roq::string_buffer<4>();
roq::string_buffer<4>("1"_sv);
roq::string_buffer<4>("12"_sv);
roq::string_buffer<4>("123"_sv);
roq::string_buffer<4>("1234"_sv);
EXPECT_THROW(roq::string_buffer<4>("12345"_sv), LengthError);
}
TEST(string_buffer, push_back) {
roq::string_buffer<4> s;
EXPECT_EQ(s.length(), 0);
s.push_back('1');
EXPECT_EQ(s.length(), 1);
s.push_back('2');
EXPECT_EQ(s.length(), 2);
s.push_back('3');
EXPECT_EQ(s.length(), 3);
s.push_back('4');
EXPECT_EQ(s.length(), 4);
EXPECT_THROW(s.push_back('5'), LengthError);
}
| [
"thraneh@gmail.com"
] | thraneh@gmail.com |
9b44107f580436ffa8d29ccd0a45752a584b8975 | ce317d4552d6d5b4d43e5ba0b79e2767622dd6f6 | /OptionCalculator/OptionCalculator.h | 26672d8a3fbb116ee189137750f5d5f265347f21 | [] | no_license | Finaxys/OptionCalculator_AMP | 9366b02444695d6caff1bece2850ec622ae4c49a | 7c8642820aff78afd5d75a67ee9b8174c96b0879 | refs/heads/master | 2021-01-22T06:54:51.050614 | 2014-03-11T14:57:28 | 2014-03-11T14:57:28 | 17,630,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,027 | h | #pragma once
#include <iostream>
#include <time.h>
#include <amp_math.h>
#include <vector>
#include <fstream>
#include <amp.h>
#include <algorithm>
#include "amp_tinymt_rng.h"
class OptionCalculator
{
public:
OptionCalculator(const float volatility, const float rate, const float maturity,
const float initial_share_prices, const float strike, const int nb_realisation);
~OptionCalculator();
void fill_gauss_values();
void parrallel_realisation(int nb_realisations);
void EDOstoch(const int simulation_number);
float EDOstochWreturn(const int simulation_number);
const std::vector<float> &getRealisations() const;
inline float CPU_time()
{
return ((float(clock()) / CLOCKS_PER_SEC));
};
private:
const float _two_pi = 6.28318530718f;
const int _M = 365;
const int _T = 1;
const float _dt = float(_T) / float(_M);
float m_volatility;
std::vector<float> m_realisation_values;
float m_rate;
float m_maturity;
float m_initial_share_prices;
float m_strike;
float m_sdt;
int m_nb_realisation;
};
| [
"vcouvignou@finaxys.com"
] | vcouvignou@finaxys.com |
2a301a5c8f4180226ccb8c08da6b343c53e4c6e0 | 9d0eb151e38069813196996448a49726c94ece46 | /main.cpp | 54d4f50e6c10f05e6ff14fe9ad2cbedaf93c0038 | [] | no_license | barbkm/Snake_game | e6b719b328844f0cce5f37beefe8197c855d1e3f | a764d0ec7afc1b19eff35fdc6eae2891f95ffbd3 | refs/heads/master | 2020-05-15T01:30:07.718352 | 2019-04-21T20:29:45 | 2019-04-21T20:29:45 | 182,031,197 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 147 | cpp | #include <iostream>
#include "GameField.h"
#include "PlayGame.h"
int main()
{
PlayGame playGame{10};
playGame.startGame();
return 0;
} | [
"noreply@github.com"
] | barbkm.noreply@github.com |
2a6b208a4cac255291a5a40fdfea1161af2742f7 | 5f9dd13db819853bb445d71ea14b4b43bcd31b00 | /SDL2-GUI/GUIManager.h | 1868796236008b3e4fd6be51cf7e62cb3b88fee4 | [] | no_license | pieisgood/SDL2-GUI | 2bf0bfb1356ec18ccb9dcab05c9446ecaec5ccd9 | 6a989aaf9afac68b4b0013ccfd899e1680d91714 | refs/heads/master | 2021-01-22T02:53:17.461147 | 2015-02-13T04:32:14 | 2015-02-13T04:32:14 | 20,318,947 | 16 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,951 | h | /**
* \class GUIManager
*
* \ingroup SDL2-GUI
*
* \brief Manages all Elements and a seperate framebuffer
*
* This class manages the rendering, events and processing
* of elements in the element tree. It also manages a seperate
* framebuffer so that SDL2-GUI rendering does not interfere
* with user rendering.
*
* \note Needs to be created using a GUIFactory
*
* \author Lee Jacobs
*
* \version 1.0
*
* \date 2014/06/10
*
* Contact: leemichaeljacobs@gmail.com
*
* Created on: 2014/05/28
*
* $Id: doxygen-howto.html,v 1.5 2005/04/14 14:16:20 bv Exp $
*
*/
#ifndef SDLGUIMANAGER
#define SDLGUIMANAGER
#include "GUIEvent.h"
#include "Element.h"
#include "GUILayout.h"
#include "GUIButton.h"
#include "GUITextBox.h"
#include "FrameBuffer.h"
#include <glm\gtc\type_ptr.hpp>
#include <glm\gtx\transform.hpp>
namespace SDLGUI {
class GUIManager {
private:
std::shared_ptr<Element> m_window;
std::map< std::string , std::shared_ptr<Element>> m_idMap;
std::shared_ptr<FrameBuffer> m_GUIFrameBuffer;
std::shared_ptr<GLSLProgram> m_panelProgram;
std::shared_ptr<GUITextBox> m_fps; //a box to render fps with
std::shared_ptr<GUIView> m_view;
std::shared_ptr<GUIEvent> m_event;
std::shared_ptr<Element> m_focus; //element we are currently focused on
public:
GUIManager( std::shared_ptr<Element> window );
GUIManager();
virtual ~GUIManager();
void draw();
void onEvent( SDL_Event* event );
void pollGUIEvent( std::shared_ptr<GUIEvent> in_event );
void assignWindow( std::shared_ptr<Element> window );
void assignProgram( std::shared_ptr<GLSLProgram> program );
void drawFPS();
void updateMs( float ms ); //we update the ms that have passed since each frame
Element* getElement( const char* id );
void assignView( std::shared_ptr<GUIView> view ){
m_view = view;
}
void assignFPS( std::shared_ptr<GUITextBox> fpsBox ){
m_fps = fpsBox;
}
std::shared_ptr<Element> getWindow();
};
}
#endif | [
"leemichaeljacobs@gmail.com"
] | leemichaeljacobs@gmail.com |
017e3d805088be5cd90f49ff964e032d6ff38654 | 0373ebdb8a577bb42e4291f57f2a5fd9a7799818 | /Numero_mayor_menor.cpp | 6e3a69743e1e90066e44955246ef4b7a55741330 | [] | no_license | SystemsEngineeringUDI/NumeroMayorMenor | 57ecc9cf5ab5f2172a220485c2ff36f86ebb7dab | 3bfb0a1bdc755823c7cda8de5ed02e1b25d94ab8 | refs/heads/master | 2021-04-27T02:35:14.781785 | 2018-02-24T03:50:09 | 2018-02-24T03:50:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 635 | cpp | /*
@autor:
* Jhon velasco
* @ frediv0406
* Estudiante: Ing.Sistemas UDI
*/
#include <iostream>
using namespace std;
int main(){
int a,b,c,mayor,menor;
cout<<"Digite el numero A:\n";
cin>>a;
cout<<"Digite el numero B:\n";
cin>>b;
cout<<"Digite el numero C:\n";
cin>>c;
if(a>b){
if(a>c){
mayor=a;
}
else{
mayor=c;
}
if(c<b){
menor=c;
}
else{
menor=b;
}
}
else{
if(b>c){
mayor=b;
}
else{
mayor=c;
}
if(c<a){
menor=c;
}
else{
menor=a;
}
}
cout<<"El numero mayor es: "<<mayor;
cout<<"\nEl numero menor es: "<<menor;
}
| [
"noreply@github.com"
] | SystemsEngineeringUDI.noreply@github.com |
9e66cb0c888b67e47485d76607609687a216e83c | 73dbbaa135a2a5bbd813f0307cf67787d6ad4f0f | /libcef/browser/osr/web_contents_view_osr.cc | d8f315d7cb5d2f4dab839e3e462e12820e2d84ae | [
"BSD-3-Clause"
] | permissive | waterbesnow/cef | 98c1fe911cc0708211df352b02e615ae96050650 | cf1074cf49fa6afe32e5985166751eaee8e3fcf6 | refs/heads/master | 2023-04-09T05:09:11.602460 | 2021-04-18T01:12:54 | 2021-04-18T01:23:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,159 | cc | // Copyright (c) 2014 The Chromium Embedded Framework Authors.
// Portions copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libcef/browser/osr/web_contents_view_osr.h"
#include "libcef/browser/alloy/alloy_browser_host_impl.h"
#include "libcef/browser/osr/render_widget_host_view_osr.h"
#include "libcef/common/drag_data_impl.h"
#include "content/browser/browser_plugin/browser_plugin_embedder.h"
#include "content/browser/browser_plugin/browser_plugin_guest.h"
#include "content/browser/web_contents/web_contents_impl.h"
#include "content/public/browser/render_widget_host.h"
CefWebContentsViewOSR::CefWebContentsViewOSR(SkColor background_color,
bool use_shared_texture,
bool use_external_begin_frame)
: background_color_(background_color),
use_shared_texture_(use_shared_texture),
use_external_begin_frame_(use_external_begin_frame),
web_contents_(nullptr) {}
CefWebContentsViewOSR::~CefWebContentsViewOSR() {}
void CefWebContentsViewOSR::WebContentsCreated(
content::WebContents* web_contents) {
DCHECK(!web_contents_);
web_contents_ = web_contents;
RenderViewCreated();
}
void CefWebContentsViewOSR::RenderViewCreated() {
if (web_contents_) {
auto host = web_contents_->GetRenderViewHost();
CefRenderWidgetHostViewOSR* view =
static_cast<CefRenderWidgetHostViewOSR*>(host->GetWidget()->GetView());
if (view)
view->InstallTransparency();
}
}
gfx::NativeView CefWebContentsViewOSR::GetNativeView() const {
return gfx::NativeView();
}
gfx::NativeView CefWebContentsViewOSR::GetContentNativeView() const {
return gfx::NativeView();
}
gfx::NativeWindow CefWebContentsViewOSR::GetTopLevelNativeWindow() const {
return gfx::NativeWindow();
}
gfx::Rect CefWebContentsViewOSR::GetContainerBounds() const {
return GetViewBounds();
}
void CefWebContentsViewOSR::Focus() {}
void CefWebContentsViewOSR::SetInitialFocus() {}
void CefWebContentsViewOSR::StoreFocus() {}
void CefWebContentsViewOSR::RestoreFocus() {}
void CefWebContentsViewOSR::FocusThroughTabTraversal(bool reverse) {}
void CefWebContentsViewOSR::GotFocus(
content::RenderWidgetHostImpl* render_widget_host) {
if (web_contents_) {
content::WebContentsImpl* web_contents_impl =
static_cast<content::WebContentsImpl*>(web_contents_);
if (web_contents_impl)
web_contents_impl->NotifyWebContentsFocused(render_widget_host);
}
}
void CefWebContentsViewOSR::LostFocus(
content::RenderWidgetHostImpl* render_widget_host) {
if (web_contents_) {
content::WebContentsImpl* web_contents_impl =
static_cast<content::WebContentsImpl*>(web_contents_);
if (web_contents_impl)
web_contents_impl->NotifyWebContentsLostFocus(render_widget_host);
}
}
void CefWebContentsViewOSR::TakeFocus(bool reverse) {
if (web_contents_->GetDelegate())
web_contents_->GetDelegate()->TakeFocus(web_contents_, reverse);
}
content::DropData* CefWebContentsViewOSR::GetDropData() const {
return nullptr;
}
gfx::Rect CefWebContentsViewOSR::GetViewBounds() const {
CefRenderWidgetHostViewOSR* view = GetView();
return view ? view->GetViewBounds() : gfx::Rect();
}
void CefWebContentsViewOSR::CreateView(gfx::NativeView context) {}
content::RenderWidgetHostViewBase* CefWebContentsViewOSR::CreateViewForWidget(
content::RenderWidgetHost* render_widget_host) {
if (render_widget_host->GetView()) {
return static_cast<content::RenderWidgetHostViewBase*>(
render_widget_host->GetView());
}
return new CefRenderWidgetHostViewOSR(background_color_, use_shared_texture_,
use_external_begin_frame_,
render_widget_host, nullptr);
}
// Called for popup and fullscreen widgets.
content::RenderWidgetHostViewBase*
CefWebContentsViewOSR::CreateViewForChildWidget(
content::RenderWidgetHost* render_widget_host) {
CefRenderWidgetHostViewOSR* view = GetView();
CHECK(view);
return new CefRenderWidgetHostViewOSR(background_color_, use_shared_texture_,
use_external_begin_frame_,
render_widget_host, view);
}
void CefWebContentsViewOSR::SetPageTitle(const base::string16& title) {}
void CefWebContentsViewOSR::RenderViewReady() {
RenderViewCreated();
}
void CefWebContentsViewOSR::RenderViewHostChanged(
content::RenderViewHost* old_host,
content::RenderViewHost* new_host) {}
void CefWebContentsViewOSR::SetOverscrollControllerEnabled(bool enabled) {}
#if defined(OS_MAC)
bool CefWebContentsViewOSR::CloseTabAfterEventTrackingIfNeeded() {
return false;
}
#endif // defined(OS_MAC)
void CefWebContentsViewOSR::StartDragging(
const content::DropData& drop_data,
blink::DragOperationsMask allowed_ops,
const gfx::ImageSkia& image,
const gfx::Vector2d& image_offset,
const blink::mojom::DragEventSourceInfo& event_info,
content::RenderWidgetHostImpl* source_rwh) {
CefRefPtr<AlloyBrowserHostImpl> browser = GetBrowser();
if (browser.get()) {
browser->StartDragging(drop_data, allowed_ops, image, image_offset,
event_info, source_rwh);
} else if (web_contents_) {
static_cast<content::WebContentsImpl*>(web_contents_)
->SystemDragEnded(source_rwh);
}
}
void CefWebContentsViewOSR::UpdateDragCursor(
ui::mojom::DragOperation operation) {
CefRefPtr<AlloyBrowserHostImpl> browser = GetBrowser();
if (browser.get())
browser->UpdateDragCursor(operation);
}
CefRenderWidgetHostViewOSR* CefWebContentsViewOSR::GetView() const {
if (web_contents_) {
return static_cast<CefRenderWidgetHostViewOSR*>(
web_contents_->GetRenderViewHost()->GetWidget()->GetView());
}
return nullptr;
}
AlloyBrowserHostImpl* CefWebContentsViewOSR::GetBrowser() const {
CefRenderWidgetHostViewOSR* view = GetView();
if (view)
return view->browser_impl().get();
return nullptr;
}
| [
"magreenblatt@gmail.com"
] | magreenblatt@gmail.com |
e4640d0402d7e237a11c3778391710807d05a4e9 | 54c607ab7a63c1a614551d7ad8c200e5ee6f5f7b | /inc/dos_header.hh | 38d17e083e8e1d6e790b50ad28b1b665989109da | [] | no_license | DarkerSquirrel/PE_stuff | 97b03e21cbf811a6de4800f4965d36bf8ebe6b6b | 9a705c131b451ea7b405f2aff406b01fc2f39a29 | refs/heads/master | 2021-05-29T02:22:53.906538 | 2015-06-18T18:12:34 | 2015-06-18T18:12:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 529 | hh | #ifndef DOS_HEADER_HH
# define DOS_HEADER_HH
# include <cstdint>
struct DOSHeader
{
uint16_t e_magic;
uint16_t e_cblp;
uint16_t e_cp;
uint16_t e_crlc;
uint16_t e_cparhdr;
uint16_t e_minalloc;
uint16_t e_maxalloc;
uint16_t e_ss;
uint16_t e_sp;
uint16_t e_csum;
uint16_t e_ip;
uint16_t e_cs;
uint16_t e_lfarlc;
uint16_t e_ovno;
uint16_t e_res[4];
uint16_t e_oemid;
uint16_t e_oeminfo;
uint16_t e_res2[10];
uint32_t e_lfanew;
};
#endif // DOS_HEADER_HH
| [
"0x2adr1@gmail.com"
] | 0x2adr1@gmail.com |
0be556207f13bbb54b00409fd51ce81108d25604 | f47c9dee31785c1754f0f2af7269083e37826ed3 | /Domaci/Domaci1/ZadatakA.cpp | 4d8b675d13f17f170775ab2d04b75a4db3d81a08 | [] | no_license | Aleksa-Jovanovic/IOADomaci | 3726e07858fcbe53078b6ce9a39bba36f51ec090 | 6988e898adb756d2df66d7315a0c40f66c86faa1 | refs/heads/main | 2023-02-22T11:09:23.002082 | 2021-01-29T12:10:15 | 2021-01-29T12:10:15 | 334,133,872 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 667 | cpp | #include<stdio.h>
int main()
{
bool found = false;
long long counter = 0;
int num1, num2, num3, num4;
for (num1 = 0; num1 < 712; num1++)
{
for (num2 = 0; num2 < 712; num2++)
{
for (num3 = 0; num3 < 712; num3++)
{
for (num4 = 0; num4 < 712; num4++)
{
counter++;
if ((num1 + num2 + num3 + num4) == 711 &&
(num1 * num2 * num3 * num4) == 711000000)
{
found = true;
break;
}
}
if (found)
break;
}
if (found)
break;
}
//printf("%lld\n", counter);
if (found)
break;
}
if (found) {
printf("%lld\n", counter);
printf("Cene su: %d, %d, %d, %d", num1, num2, num3, num4);
}
} | [
"aca.1998.aj@gmail.com"
] | aca.1998.aj@gmail.com |
2bc3fc7c61380b7fd837ee9912fa493929b95fc7 | f20d5f9ebadbfd7a0a66070deba2cb0a83e955ec | /APItest/APItest/APIENTRY.cpp | 15c795fca167aafc8fa0e3ffd56e7f17a5bfb29a | [] | no_license | shirataki27/Ctest | 5cf0ff95dd0954c1a592816023d293d41abf794f | 22b686f8304c62685f617bc3bf49582886b1ce8f | refs/heads/master | 2021-01-15T18:14:11.164007 | 2013-10-19T05:37:31 | 2013-10-19T05:37:31 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,707 | cpp | //2010/06/15 Shirao
//簡単なキーロガー
//動作中に押されたキーを取得する(shift-ctrlで終了)
#define WIN32_LEAN_AND_MEAN //exe縮小
#include <windows.h>
#include <stdio.h>
int APIENTRY WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nShowCmd)
{
FILE *fp; //ログを書き込むファイルポインタ
if(fopen_s(&fp, "log.txt", "a") != 0){
MessageBox(GetActiveWindow(), L"fopen error", L"error", MB_ICONERROR);
return -1;
}
MessageBox(GetActiveWindow(), L"Key Logger Start", L"Message", MB_OK);
bool cntf = true;
while(cntf){
int c, k;
//アルファベットキースキャンループ
for(c = 'A'; c <= 'Z'; c++){
//shiftが押されているか否か
if(GetAsyncKeyState(VK_SHIFT) & 0x8000)
k = c; //大文字
else
k = c+('a'-'A'); //小文字
//押されていたなら適切に出力
if(GetAsyncKeyState(c) & 0x0001){
fputc(k, fp); fflush(fp);
continue;
}
if(GetAsyncKeyState(VK_MENU)){
fputc('Alt',fp);fflush(fp);
}
if(GetAsyncKeyState(VK_F1)){
fputc('F1',fp);fflush(fp);
}
//Enterで改行
if(GetAsyncKeyState(VK_RETURN) & 0x0001){
fputc('\n', fp); fflush(fp);
}
}
//shift-ctrlで終了する
if( (GetAsyncKeyState(VK_SHIFT) & 0x8000) &&
(GetAsyncKeyState(VK_CONTROL) & 0x8000))
cntf = false;
Sleep(50);
}
_fcloseall(); //ファイルを閉じる
MessageBox(GetActiveWindow(), L"Key Logger End", L"Message", MB_OK);
return 0;
}
| [
"r64_01@hotmail.co.jp"
] | r64_01@hotmail.co.jp |
630e6b242a39118da156d1ac8b7a520a9cd3a775 | f3578ced68e8048fe04c68490d7b7a616c3dda09 | /src/SnakesLadders/Board.h | d5502c3c64f0c53f0143666fa222cca30838ed9f | [
"MIT"
] | permissive | subhakantasahoo/design | 765b2298e66db4848dcef0f37db821c10e75f8d5 | ea0a9775723f7b5072d5e0715d3c29d6c8fc04ef | refs/heads/master | 2021-05-28T12:18:11.444891 | 2014-12-28T17:34:05 | 2014-12-28T17:34:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,619 | h | /*
The MIT License (MIT)
Copyright (c) 2013 Rajendra Kumar Uppal
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef Board_INCLUDED
#define Board_INCLUDED
#include "GameData.h"
#include <vector>
using std::vector;
using std::pair;
class Board
{
public:
static Board * getBoard(size_t size);
static void releaseBoard();
static size_t getBoardSize();
private:
static Board * _board;
GameData::Snakes _snakes;
GameData::Ladders _ladders;
static size_t _size;
explicit Board(size_t size);
~Board();
Board(const Board&);
Board& operator = (const Board&);
};
#endif // Board_INCLUDED
| [
"rajen.iitd@gmail.com"
] | rajen.iitd@gmail.com |
39551f7796ed9a530895ab3b7f01307c78cb6e01 | ab9d5427af62f915f6b0c11774bf38ea93554ac4 | /lib/mdi/tests/MDI_Test_Codes/lib_cxx_cxx/engine_lib_cxx_cxx.cpp | 38831dabee59249b76b15f3956806684e6a92acd | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | MolSSI-MDI/MDI_NEB_Driver | 4e12250b2a8358a13e1e8b1fe8d6e718f113e005 | 7765e2f5a25d0d67255ae2634797de1d3b949d29 | refs/heads/master | 2023-05-05T11:56:07.738126 | 2021-05-12T22:22:10 | 2021-05-12T22:22:10 | 192,952,418 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | cpp | #include <mpi.h>
#include <iostream>
#include <stdexcept>
#include <string.h>
#include "mdi.h"
#include "engine_lib_cxx_cxx.h"
int engine_lib_cxx_create(MPI_Comm mpi_comm) {
MPI_Comm world_comm = mpi_comm;
// Call MDI_Init
int argc_mdi = 2;
int options_length = 256;
char* options = (char*) malloc( options_length * sizeof(char) );
snprintf(options, options_length, "-role ENGINE -method LINK -name MM");
char* mdi_arg = (char*) malloc( options_length * sizeof(char) );
snprintf(mdi_arg, options_length, "-mdi");
char** argv_mdi = (char**) malloc( argc_mdi * sizeof(char*) );
argv_mdi[0] = mdi_arg;
argv_mdi[1] = options;
MDI_Init(&argc_mdi, &argv_mdi);
free(options);
free(mdi_arg);
free(argv_mdi);
// Get the MPI intra-communicator for this code
MDI_MPI_set_world_comm(&world_comm);
// Set the execute_command callback
void* engine_obj;
MDI_Set_Execute_Command_Func(execute_command, engine_obj);
return 0;
}
int execute_command(const char* command, MDI_Comm comm, void* class_obj) {
return 0;
}
| [
"taylor.a.barnes@gmail.com"
] | taylor.a.barnes@gmail.com |
0487afa68f301d1bfed5a9cdfa278d908d53c9ab | 183e4126b2fdb9c4276a504ff3ace42f4fbcdb16 | /VII семестр/КС - Комп'ютерні системи/Software/transputer/src/Grid/GridCellBase.cpp | 1a79714019b004fdfafffa49a7e9bba28f8579aa | [] | no_license | Computer-engineering-FICT/Computer-engineering-FICT | ab625e2ca421af8bcaff74f0d37ac1f7d363f203 | 80b64b43d2254e15338060aa4a6d946e8bd43424 | refs/heads/master | 2023-08-10T08:02:34.873229 | 2019-06-22T22:06:19 | 2019-06-22T22:06:19 | 193,206,403 | 3 | 0 | null | 2023-07-22T09:01:05 | 2019-06-22T07:41:22 | HTML | UTF-8 | C++ | false | false | 26,734 | cpp | // GridCellBase.cpp : implementation file
//
// MFC Grid Control - Main grid cell base class
//
// Provides the implementation for the base cell type of the
// grid control. No data is stored (except for state) but default
// implementations of drawing, printingetc provided. MUST be derived
// from to be used.
//
// Written by Chris Maunder <cmaunder@mail.com>
// Copyright (c) 1998-2002. All Rights Reserved.
//
// This code may be used in compiled form in any way you desire. This
// file may be redistributed unmodified by any means PROVIDING it is
// not sold for profit without the authors written consent, and
// providing that this notice and the authors name and all copyright
// notices remains intact.
//
// An email letting me know how you are using it would be nice as well.
//
// This file is provided "as is" with no expressed or implied warranty.
// The author accepts no liability for any damage/loss of business that
// this product may cause.
//
// For use with CGridCtrl v2.22+
//
// History:
// Ken Bertelson - 12 Apr 2000 - Split CGridCell into CGridCell and CGridCellBase
// C Maunder - 19 May 2000 - Fixed sort arrow drawing (Ivan Ilinov)
// C Maunder - 29 Aug 2000 - operator= checks for NULL font before setting (Martin Richter)
// C Maunder - 15 Oct 2000 - GetTextExtent fixed (Martin Richter)
// C Maunder - 1 Jan 2001 - Added ValidateEdit
// Yogurt - 13 Mar 2004 - GetCellExtent fixed
//
// NOTES: Each grid cell should take care of it's own drawing, though the Draw()
// method takes an "erase background" paramter that is called if the grid
// decides to draw the entire grid background in on hit. Certain ambient
// properties such as the default font to use, and hints on how to draw
// fixed cells should be fetched from the parent grid. The grid trusts the
// cells will behave in a certain way, and the cells trust the grid will
// supply accurate information.
//
/////////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "GridCtrl.h"
#include "GridCellBase.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
IMPLEMENT_DYNAMIC(CGridCellBase, CObject)
/////////////////////////////////////////////////////////////////////////////
// GridCellBase
CGridCellBase::CGridCellBase()
{
Reset();
}
CGridCellBase::~CGridCellBase()
{
}
/////////////////////////////////////////////////////////////////////////////
// GridCellBase Operations
void CGridCellBase::Reset()
{
m_nState = 0;
}
void CGridCellBase::operator=(const CGridCellBase& cell)
{
if (this == &cell) return;
SetGrid(cell.GetGrid()); // do first in case of dependencies
SetText(cell.GetText());
SetImage(cell.GetImage());
SetData(cell.GetData());
SetState(cell.GetState());
SetFormat(cell.GetFormat());
SetTextClr(cell.GetTextClr());
SetBackClr(cell.GetBackClr());
SetFont(cell.IsDefaultFont()? NULL : cell.GetFont());
SetMargin(cell.GetMargin());
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Attributes
// Returns a pointer to a cell that holds default values for this particular type of cell
CGridCellBase* CGridCellBase::GetDefaultCell() const
{
if (GetGrid())
return GetGrid()->GetDefaultCell(IsFixedRow(), IsFixedCol());
return NULL;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Operations
// EFW - Various changes to make it draw cells better when using alternate
// color schemes. Also removed printing references as that's now done
// by PrintCell() and fixed the sort marker so that it doesn't draw out
// of bounds.
BOOL CGridCellBase::Draw(CDC* pDC, int nRow, int nCol, CRect rect, BOOL bEraseBkgnd /*=TRUE*/)
{
// Note - all through this function we totally brutalise 'rect'. Do not
// depend on it's value being that which was passed in.
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0 || rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
//TRACE3("Drawing %scell %d, %d\n", IsFixed()? _T("Fixed ") : _T(""), nRow, nCol);
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Set up text and background colours
COLORREF TextClr, TextBkClr;
TextClr = (GetTextClr() == CLR_DEFAULT)? pDefaultCell->GetTextClr() : GetTextClr();
if (GetBackClr() == CLR_DEFAULT)
TextBkClr = pDefaultCell->GetBackClr();
else
{
bEraseBkgnd = TRUE;
TextBkClr = GetBackClr();
}
// Draw cell background and highlighting (if necessary)
if ( IsFocused() || IsDropHighlighted() )
{
// Always draw even in list mode so that we can tell where the
// cursor is at. Use the highlight colors though.
if(GetState() & GVIS_SELECTED)
{
TextBkClr = ::GetSysColor(COLOR_HIGHLIGHT);
TextClr = ::GetSysColor(COLOR_HIGHLIGHTTEXT);
bEraseBkgnd = TRUE;
}
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
if (bEraseBkgnd)
{
TRY
{
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
// Don't adjust frame rect if no grid lines so that the
// whole cell is enclosed.
if(pGrid->GetGridLines() != GVL_NONE)
{
rect.right--;
rect.bottom--;
}
if (pGrid->GetFrameFocusCell())
{
// Use same color as text to outline the cell so that it shows
// up if the background is black.
TRY
{
CBrush brush(TextClr);
pDC->FrameRect(rect, &brush);
}
CATCH(CResourceException, e)
{
//e->ReportError();
}
END_CATCH
}
pDC->SetTextColor(TextClr);
// Adjust rect after frame draw if no grid lines
if(pGrid->GetGridLines() == GVL_NONE)
{
rect.right--;
rect.bottom--;
}
//rect.DeflateRect(0,1,1,1); - Removed by Yogurt
}
else if ((GetState() & GVIS_SELECTED))
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
pDC->FillSolidRect(rect, ::GetSysColor(COLOR_HIGHLIGHT));
rect.right--; rect.bottom--;
pDC->SetTextColor(::GetSysColor(COLOR_HIGHLIGHTTEXT));
}
else
{
if (bEraseBkgnd)
{
rect.right++; rect.bottom++; // FillRect doesn't draw RHS or bottom
CBrush brush(TextBkClr);
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
pDC->SetTextColor(TextClr);
}
// Draw lines only when wanted
if (IsFixed() && pGrid->GetGridLines() != GVL_NONE)
{
CCellID FocusCell = pGrid->GetFocusCell();
// As above, always show current location even in list mode so
// that we know where the cursor is at.
BOOL bHiliteFixed = pGrid->GetTrackFocusCell() && pGrid->IsValid(FocusCell) &&
(FocusCell.row == nRow || FocusCell.col == nCol);
// If this fixed cell is on the same row/col as the focus cell,
// highlight it.
if (bHiliteFixed)
{
rect.right++; rect.bottom++;
pDC->DrawEdge(rect, BDR_SUNKENINNER /*EDGE_RAISED*/, BF_RECT);
rect.DeflateRect(1,1);
}
else
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(pOldPen);
rect.DeflateRect(1,1);
}
}
// Draw Text and image
#if !defined(_WIN32_WCE_NO_PRINTING) && !defined(GRIDCONTROL_NO_PRINTING)
if (!pDC->m_bPrinting)
#endif
{
CFont *pFont = GetFontObject();
ASSERT(pFont);
if (pFont)
pDC->SelectObject(pFont);
}
rect.DeflateRect(GetMargin(), 0); //- changed by Yogurt
// rect.DeflateRect(GetMargin(), GetMargin());
rect.right++;
rect.bottom++;
if (pGrid->GetImageList() && GetImage() >= 0)
{
IMAGEINFO Info;
if (pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
// would like to use a clipping region but seems to have issue
// working with CMemDC directly. Instead, don't display image
// if any part of it cut-off
//
// CRgn rgn;
// rgn.CreateRectRgnIndirect(rect);
// pDC->SelectClipRgn(&rgn);
// rgn.DeleteObject();
/*
// removed by Yogurt
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
int nImageHeight = Info.rcImage.bottom-Info.rcImage.top+1;
if( nImageWidth + rect.left <= rect.right + (int)(2*GetMargin())
&& nImageHeight + rect.top <= rect.bottom + (int)(2*GetMargin()) )
{
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
}
*/
// Added by Yogurt
int nImageWidth = Info.rcImage.right-Info.rcImage.left;
int nImageHeight = Info.rcImage.bottom-Info.rcImage.top;
if ((nImageWidth + rect.left <= rect.right) && (nImageHeight + rect.top <= rect.bottom))
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
//rect.left += nImageWidth+GetMargin();
}
}
// Draw sort arrow
if (pGrid->GetSortColumn() == nCol && nRow == 0)
{
CSize size = pDC->GetTextExtent(_T("M"));
int nOffset = 2;
// Base the size of the triangle on the smaller of the column
// height or text height with a slight offset top and bottom.
// Otherwise, it can get drawn outside the bounds of the cell.
size.cy -= (nOffset * 2);
if (size.cy >= rect.Height())
size.cy = rect.Height() - (nOffset * 2);
size.cx = size.cy; // Make the dimensions square
// Kludge for vertical text
BOOL bVertical = (GetFont()->lfEscapement == 900);
// Only draw if it'll fit!
//if (size.cx + rect.left < rect.right + (int)(2*GetMargin())) - changed / Yogurt
if (size.cx + rect.left < rect.right)
{
int nTriangleBase = rect.bottom - nOffset - size.cy; // Triangle bottom right
//int nTriangleBase = (rect.top + rect.bottom - size.cy)/2; // Triangle middle right
//int nTriangleBase = rect.top + nOffset; // Triangle top right
//int nTriangleLeft = rect.right - size.cx; // Triangle RHS
//int nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
//int nTriangleLeft = rect.left; // Triangle LHS
int nTriangleLeft;
if (bVertical)
nTriangleLeft = (rect.right + rect.left - size.cx)/2; // Triangle middle
else
nTriangleLeft = rect.right - size.cx; // Triangle RHS
CPen penShadow(PS_SOLID, 0, ::GetSysColor(COLOR_3DSHADOW));
CPen penLight(PS_SOLID, 0, ::GetSysColor(COLOR_3DHILIGHT));
if (pGrid->GetSortAscending())
{
// Draw triangle pointing upwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + size.cy + 1);
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + size.cy + 1);
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft, nTriangleBase + size.cy );
pDC->SelectObject(pOldPen);
}
else
{
// Draw triangle pointing downwards
CPen *pOldPen = (CPen*) pDC->SelectObject(&penLight);
pDC->MoveTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + (size.cx / 2) + 1, nTriangleBase + size.cy + 1 );
pDC->LineTo( nTriangleLeft + size.cx + 1, nTriangleBase + 1 );
pDC->LineTo( nTriangleLeft + 1, nTriangleBase + 1 );
pDC->SelectObject(&penShadow);
pDC->MoveTo( nTriangleLeft, nTriangleBase );
pDC->LineTo( nTriangleLeft + (size.cx / 2), nTriangleBase + size.cy );
pDC->LineTo( nTriangleLeft + size.cx, nTriangleBase );
pDC->LineTo( nTriangleLeft, nTriangleBase );
pDC->SelectObject(pOldPen);
}
if (!bVertical)
rect.right -= size.cy;
}
}
// We want to see '&' characters so use DT_NOPREFIX
GetTextRect(rect);
rect.right++;
rect.bottom++;
DrawText(pDC->m_hDC, GetText(), -1, rect, GetFormat() | DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Mouse and Cursor events
// Not yet implemented
void CGridCellBase::OnMouseEnter()
{
TRACE0("Mouse entered cell\n");
}
void CGridCellBase::OnMouseOver()
{
//TRACE0("Mouse over cell\n");
}
// Not Yet Implemented
void CGridCellBase::OnMouseLeave()
{
TRACE0("Mouse left cell\n");
}
void CGridCellBase::OnClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn up in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnClickDown( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse Left btn down in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnRClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse right-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
void CGridCellBase::OnDblClick( CPoint PointCellRelative)
{
UNUSED_ALWAYS(PointCellRelative);
TRACE2("Mouse double-clicked in cell at x=%i y=%i\n", PointCellRelative.x, PointCellRelative.y);
}
// Return TRUE if you set the cursor
BOOL CGridCellBase::OnSetCursor()
{
#ifndef _WIN32_WCE_NO_CURSOR
SetCursor(AfxGetApp()->LoadStandardCursor(IDC_ARROW));
#endif
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase editing
void CGridCellBase::OnEndEdit()
{
ASSERT( FALSE);
}
BOOL CGridCellBase::ValidateEdit(LPCTSTR str)
{
UNUSED_ALWAYS(str);
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CGridCellBase Sizing
BOOL CGridCellBase::GetTextRect( LPRECT pRect) // i/o: i=dims of cell rect; o=dims of text rect
{
if (GetImage() >= 0)
{
IMAGEINFO Info;
CGridCtrl* pGrid = GetGrid();
CImageList* pImageList = pGrid->GetImageList();
if (pImageList && pImageList->GetImageInfo( GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left+1;
pRect->left += nImageWidth + GetMargin();
}
}
return TRUE;
}
// By default this uses the selected font (which is a bigger font)
CSize CGridCellBase::GetTextExtent(LPCTSTR szText, CDC* pDC /*= NULL*/)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
BOOL bReleaseDC = FALSE;
if (pDC == NULL || szText == NULL)
{
if (szText)
pDC = pGrid->GetDC();
if (pDC == NULL || szText == NULL)
{
CGridDefaultCell* pDefCell = (CGridDefaultCell*) GetDefaultCell();
ASSERT(pDefCell);
return CSize(pDefCell->GetWidth(), pDefCell->GetHeight());
}
bReleaseDC = TRUE;
}
CFont *pOldFont = NULL,
*pFont = GetFontObject();
if (pFont)
pOldFont = pDC->SelectObject(pFont);
CSize size;
int nFormat = GetFormat();
// If the cell is a multiline cell, then use the width of the cell
// to get the height
if ((nFormat & DT_WORDBREAK) && !(nFormat & DT_SINGLELINE))
{
CString str = szText;
int nMaxWidth = 0;
while (TRUE)
{
int nPos = str.Find(_T('\n'));
CString TempStr = (nPos < 0)? str : str.Left(nPos);
int nTempWidth = pDC->GetTextExtent(TempStr).cx;
if (nTempWidth > nMaxWidth)
nMaxWidth = nTempWidth;
if (nPos < 0)
break;
str = str.Mid(nPos + 1); // Bug fix by Thomas Steinborn
}
CRect rect;
rect.SetRect(0,0, nMaxWidth+1, 0);
pDC->DrawText(szText, -1, rect, nFormat | DT_CALCRECT);
size = rect.Size();
}
else
size = pDC->GetTextExtent(szText,(int)_tcslen(szText));
// Removed by Yogurt
//TEXTMETRIC tm;
//pDC->GetTextMetrics(&tm);
//size.cx += (tm.tmOverhang);
if (pOldFont)
pDC->SelectObject(pOldFont);
size += CSize(2*GetMargin(), 2*GetMargin());
// Kludge for vertical text
LOGFONT *pLF = GetFont();
if (pLF->lfEscapement == 900 || pLF->lfEscapement == -900)
{
int nTemp = size.cx;
size.cx = size.cy;
size.cy = nTemp;
size += CSize(0, 4*GetMargin());
}
if (bReleaseDC)
pGrid->ReleaseDC(pDC);
return size;
}
CSize CGridCellBase::GetCellExtent(CDC* pDC)
{
CSize size = GetTextExtent(GetText(), pDC);
CSize ImageSize(0,0);
int nImage = GetImage();
if (nImage >= 0)
{
CGridCtrl* pGrid = GetGrid();
ASSERT(pGrid);
IMAGEINFO Info;
if (pGrid->GetImageList() && pGrid->GetImageList()->GetImageInfo(nImage, &Info))
{
ImageSize = CSize(Info.rcImage.right-Info.rcImage.left,
Info.rcImage.bottom-Info.rcImage.top);
if (size.cx > 2*(int)GetMargin ())
ImageSize.cx += GetMargin();
ImageSize.cy += 2*(int)GetMargin ();
}
}
size.cx += ImageSize.cx + 1;
size.cy = max(size.cy, ImageSize.cy) + 1;
if (IsFixed())
{
size.cx++;
size.cy++;
}
return size;
}
// EFW - Added to print cells so that grids that use different colors are
// printed correctly.
BOOL CGridCellBase::PrintCell(CDC* pDC, int /*nRow*/, int /*nCol*/, CRect rect)
{
#if defined(_WIN32_WCE_NO_PRINTING) || defined(GRIDCONTROL_NO_PRINTING)
return FALSE;
#else
COLORREF crFG, crBG;
GV_ITEM Item;
CGridCtrl* pGrid = GetGrid();
if (!pGrid || !pDC)
return FALSE;
if( rect.Width() <= 0
|| rect.Height() <= 0) // prevents imagelist item from drawing even
return FALSE; // though cell is hidden
int nSavedDC = pDC->SaveDC();
pDC->SetBkMode(TRANSPARENT);
if (pGrid->GetShadedPrintOut())
{
// Get the default cell implementation for this kind of cell. We use it if this cell
// has anything marked as "default"
CGridDefaultCell *pDefaultCell = (CGridDefaultCell*) GetDefaultCell();
if (!pDefaultCell)
return FALSE;
// Use custom color if it doesn't match the default color and the
// default grid background color. If not, leave it alone.
if(IsFixed())
crBG = (GetBackClr() != CLR_DEFAULT) ? GetBackClr() : pDefaultCell->GetBackClr();
else
crBG = (GetBackClr() != CLR_DEFAULT && GetBackClr() != pDefaultCell->GetBackClr()) ?
GetBackClr() : CLR_DEFAULT;
// Use custom color if the background is different or if it doesn't
// match the default color and the default grid text color.
if(IsFixed())
crFG = (GetBackClr() != CLR_DEFAULT) ? GetTextClr() : pDefaultCell->GetTextClr();
else
crFG = (GetBackClr() != CLR_DEFAULT) ? GetTextClr() : pDefaultCell->GetTextClr();
// If not printing on a color printer, adjust the foreground color
// to a gray scale if the background color isn't used so that all
// colors will be visible. If not, some colors turn to solid black
// or white when printed and may not show up. This may be caused by
// coarse dithering by the printer driver too (see image note below).
if(pDC->GetDeviceCaps(NUMCOLORS) == 2 && crBG == CLR_DEFAULT)
crFG = RGB(GetRValue(crFG) * 0.30, GetGValue(crFG) * 0.59,
GetBValue(crFG) * 0.11);
// Only erase the background if the color is not the default
// grid background color.
if(crBG != CLR_DEFAULT)
{
CBrush brush(crBG);
rect.right++; rect.bottom++;
pDC->FillRect(rect, &brush);
rect.right--; rect.bottom--;
}
}
else
{
crBG = CLR_DEFAULT;
crFG = RGB(0, 0, 0);
}
pDC->SetTextColor(crFG);
CFont *pFont = GetFontObject();
if (pFont)
pDC->SelectObject(pFont);
/*
// ***************************************************
// Disabled - if you need this functionality then you'll need to rewrite.
// Create the appropriate font and select into DC.
CFont Font;
// Bold the fixed cells if not shading the print out. Use italic
// font it it is enabled.
const LOGFONT* plfFont = GetFont();
if(IsFixed() && !pGrid->GetShadedPrintOut())
{
Font.CreateFont(plfFont->lfHeight, 0, 0, 0, FW_BOLD, plfFont->lfItalic, 0, 0,
ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS,
#ifndef _WIN32_WCE
PROOF_QUALITY,
#else
DEFAULT_QUALITY,
#endif
VARIABLE_PITCH | FF_SWISS, plfFont->lfFaceName);
}
else
Font.CreateFontIndirect(plfFont);
pDC->SelectObject(&Font);
// ***************************************************
*/
// Draw lines only when wanted on fixed cells. Normal cell grid lines
// are handled in OnPrint.
if(pGrid->GetGridLines() != GVL_NONE && IsFixed())
{
CPen lightpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DHIGHLIGHT)),
darkpen(PS_SOLID, 1, ::GetSysColor(COLOR_3DDKSHADOW)),
*pOldPen = pDC->GetCurrentPen();
pDC->SelectObject(&lightpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.left, rect.top);
pDC->LineTo(rect.left, rect.bottom);
pDC->SelectObject(&darkpen);
pDC->MoveTo(rect.right, rect.top);
pDC->LineTo(rect.right, rect.bottom);
pDC->LineTo(rect.left, rect.bottom);
rect.DeflateRect(1,1);
pDC->SelectObject(pOldPen);
}
rect.DeflateRect(GetMargin(), 0);
if(pGrid->GetImageList() && GetImage() >= 0)
{
// NOTE: If your printed images look like fuzzy garbage, check the
// settings on your printer driver. If it's using coarse
// dithering and/or vector graphics, they may print wrong.
// Changing to fine dithering and raster graphics makes them
// print properly. My HP 4L had that problem.
IMAGEINFO Info;
if(pGrid->GetImageList()->GetImageInfo(GetImage(), &Info))
{
int nImageWidth = Info.rcImage.right-Info.rcImage.left;
pGrid->GetImageList()->Draw(pDC, GetImage(), rect.TopLeft(), ILD_NORMAL);
rect.left += nImageWidth+GetMargin();
}
}
// Draw without clipping so as not to lose text when printed for real
// DT_NOCLIP removed 01.01.01. Slower, but who cares - we are printing!
DrawText(pDC->m_hDC, GetText(), -1, rect,
GetFormat() | /*DT_NOCLIP | */ DT_NOPREFIX);
pDC->RestoreDC(nSavedDC);
return TRUE;
#endif
}
/*****************************************************************************
Callable by derived classes, only
*****************************************************************************/
LRESULT CGridCellBase::SendMessageToParent(int nRow, int nCol, int nMessage)
{
CGridCtrl* pGrid = GetGrid();
if( pGrid)
return pGrid->SendMessageToParent(nRow, nCol, nMessage);
else
return 0;
} | [
"mazanyan027@gmail.com"
] | mazanyan027@gmail.com |
fefb83146f896e51aa845be3d28fec47abbd0211 | a33aac97878b2cb15677be26e308cbc46e2862d2 | /program_data/PKU_raw/66/26.c | b35e452536cb5b8a252538dc815e147c49bc5fe4 | [] | no_license | GabeOchieng/ggnn.tensorflow | f5d7d0bca52258336fc12c9de6ae38223f28f786 | 7c62c0e8427bea6c8bec2cebf157b6f1ea70a213 | refs/heads/master | 2022-05-30T11:17:42.278048 | 2020-05-02T11:33:31 | 2020-05-02T11:33:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | c | int main(int argc, char* argv[])
{ int year,month,day;
scanf("%d %d %d",&year,&month,&day);
int j=1;
int s=year%400;
int mday=0;
for(j=0;j<s;j++){
if((j%4==0&&j%100!=0)||j%400==0)mday=mday+366;
else mday=mday+365;
}
int p[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
int i=1;
for(i=1;i<month+1;i++){
mday=mday+p[i-1];
}
if((year%4==0&&year%100!=0)||year%400==0){
if(month>=3){
mday=mday+1;}
else {
mday=mday;
}
}
long n;
n=mday+day;
int m;
m=n%7;
switch(m)
{
case 1:printf("Sat.");break;
case 2:printf("Sun.");break;
case 3:printf("Mon.");break;
case 4:printf("Tue.");break;
case 5:printf("Wed.");break;
case 6:printf("Thu.");break;
default:printf("Fri."); }
return 0;
}
| [
"bdqnghi@gmail.com"
] | bdqnghi@gmail.com |
f245f7a3afbb7d24c7f864243365d8d1bb082f97 | e17546794b54bb4e7f65320fda8a046ce28c7915 | /CLR/Libraries/SPOT/SPOT_Messaging/spot_messaging_fastcompile.cpp | f5c6f2c4a17edaead06fca673adbd46ff25cc0f4 | [
"BSD-3-Clause",
"OpenSSL",
"MIT",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows",
"Apache-2.0"
] | permissive | smaillet-ms/netmf-interpreter | 693e5dc8c9463ff0824c515e9240270c948c706f | 53574a439396cc98e37b82f296920c7e83a567bf | refs/heads/dev | 2021-01-17T22:21:36.617467 | 2016-09-05T06:29:07 | 2016-09-05T06:29:07 | 32,760,598 | 2 | 1 | null | 2016-04-26T02:49:52 | 2015-03-23T21:44:01 | C# | UTF-8 | C++ | false | false | 671 | cpp | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Copyright (c) Microsoft Corporation. All rights reserved.
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "spot_native_Microsoft_SPOT_Messaging_EndPoint.cpp"
#include "spot_native_Microsoft_SPOT_Messaging_Message.cpp"
#include "spot_native_Microsoft_SPOT_Messaging_Message__RemotedException.cpp"
| [
"morteza.ghandehari@microsoft.com"
] | morteza.ghandehari@microsoft.com |
69946b11661213df4b80644a84260134d1b5f9a6 | 2eeab40a405a7b27a52386f52f6f9753672cde78 | /Old_items/Vjudge/Recap Marathon/D - Spreadsheet.cpp | 5f25fd800851cf445e27ed3006605263a07b3600 | [] | no_license | rifatr/Competitive-Programming | c562c56f5090b9b76510d8c57e74a2c90d723643 | e802d9e73624607904223fddf7f29950fa429341 | refs/heads/master | 2023-05-24T02:02:56.062656 | 2023-05-22T08:08:02 | 2023-05-22T08:08:02 | 611,465,080 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,433 | cpp | #include<bits/stdc++.h>
#include<vector>
using namespace std;
int main()
{
int r, c, sum, i, j;
scanf("%d %d", &r, &c);
int mat[r + 1][c + 1];
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
scanf("%d", &mat[i][j]);
}
for(i = 0; i <= c; i++)
mat[r][i] = 0;
for(j = 0; j <= r; j++)
mat[j][c] = 0;
for(i = 0; i < r; i++) {
for(j = 0; j < c; j++)
mat[r][j] += mat[i][j];
}
for(i = 0; i < c; i++) {
for(j = 0; j < r; j++)
mat[j][c] += mat[j][i];
}
for(i = 0; i < c; i++) {
for(j = 0; j < r; j++)
mat[r][c] += mat[j][i];
}
for(i = 0; i <= r; i++) {
for(j = 0; j <= c; j++) {
if(j < c)
printf("%d ", mat[i][j]);
else
printf("%d", mat[i][j]);
}
//printf("%d ", mat[i][j]);
printf("\n");
}
/*for(i = 0; i < r; i++) {
sum = 0;
for(j = 0; j < c; j++) {
printf("%d ", mat[i][j]);
sum += mat[i][j];
}
printf("%d\n", sum);
}
for(i = 0; i < r; i++) {
sum = 0;
for(j = 0; j < c; j++) {
// printf("%d ", mat[i][j]);
sum += mat[j][i];
}
printf("%d ", sum);
}*/
return 0;
}
| [
"rifatrraazz@gmail.com"
] | rifatrraazz@gmail.com |
99e48159aa087c007cdff1a74ecf2bdab18fe916 | 337f830cdc233ad239a5cc2f52c6562fbb671ea8 | /case5cells/0.5/polyMesh/boundary | 1bc0969172d40910faaaac9775b4573be826c3aa | [] | no_license | j-avdeev/laplacianFoamF | dba31d0941c061b2435532cdfbd5a5b337e6ffe9 | 6e1504dc84780dc86076145c18862f1882078da5 | refs/heads/master | 2021-06-25T23:52:36.435909 | 2017-02-05T17:28:45 | 2017-02-05T17:28:45 | 26,997,393 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,304 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class polyBoundaryMesh;
location "0.5/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
3
(
walls
{
type wall;
inGroups 1(wall);
nFaces 64;
startFace 144;
}
inlet
{
type wall;
inGroups 1(wall);
nFaces 16;
startFace 208;
}
outlet
{
type wall;
inGroups 1(wall);
nFaces 16;
startFace 224;
}
)
// ************************************************************************* //
| [
"j-avdeev@ya.ru"
] | j-avdeev@ya.ru | |
582f072232472f4aef4bf4fed29492e8f9ac4d6c | adefa5c91e2ddebfebeedb0c88ad50e48872d822 | /code/chap05/main.cpp | a8e29d6c014117600f0c6d797d1d30fa629c6d14 | [] | no_license | gitter-badger/csc212 | 53bf6ed8ceb02aea3f812661c9daf251d9fd0775 | a228de0b60cc8bc44ce1368c06d634980140bb05 | refs/heads/master | 2020-04-26T05:39:40.541853 | 2019-03-01T17:26:24 | 2019-03-01T17:26:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 214 | cpp | #include <iostream>
#include "node1.h"
using namespace main_savitch_5;
int main(){
node* tail = new node(1.0);
node* second = new node(2.0, tail);
node* third = new node(3.0, second);
return 0;
}
| [
"story645@gmail.com"
] | story645@gmail.com |
8e21c0af5735b28d09e0fd75f03fddb6acb508ba | 9be3d865e4d3f141f6b03fd5daaf09adaed03038 | /src/platform/ESP32/ESP32Utils.cpp | b90cb2c220b287ab2677849be883a2464034481c | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | winnieli1129/connectedhomeip | 17ffc14d3bb4b94da35cad7b074a46e430f4888d | 5cb5d880e2be1427798c767aaf8c67f696046df8 | refs/heads/master | 2023-06-30T23:16:50.506830 | 2021-07-23T09:57:05 | 2021-07-23T09:57:05 | 388,645,941 | 0 | 0 | Apache-2.0 | 2021-07-23T09:57:06 | 2021-07-23T01:37:25 | null | UTF-8 | C++ | false | false | 9,600 | cpp | /*
*
* Copyright (c) 2020 Project CHIP Authors
* Copyright (c) 2018 Nest Labs, 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.
*/
/**
* @file
* General utility methods for the ESP32 platform.
*/
/* this file behaves like a config.h, comes first */
#include <platform/internal/CHIPDeviceLayerInternal.h>
#include <platform/ESP32/ESP32Utils.h>
#include <support/CodeUtils.h>
#include <support/ErrorStr.h>
#include <support/logging/CHIPLogging.h>
#include "esp_event.h"
#include "esp_netif.h"
#include "esp_netif_net_stack.h"
#include "esp_wifi.h"
using namespace ::chip::DeviceLayer::Internal;
using chip::DeviceLayer::Internal::DeviceNetworkInfo;
CHIP_ERROR ESP32Utils::IsAPEnabled(bool & apEnabled)
{
wifi_mode_t curWiFiMode;
esp_err_t err = esp_wifi_get_mode(&curWiFiMode);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_get_mode() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
apEnabled = (curWiFiMode == WIFI_MODE_AP || curWiFiMode == WIFI_MODE_APSTA);
return CHIP_NO_ERROR;
}
bool ESP32Utils::IsStationProvisioned(void)
{
wifi_config_t stationConfig;
return (esp_wifi_get_config(WIFI_IF_STA, &stationConfig) == ERR_OK && stationConfig.sta.ssid[0] != 0);
}
CHIP_ERROR ESP32Utils::IsStationConnected(bool & connected)
{
wifi_ap_record_t apInfo;
connected = (esp_wifi_sta_get_ap_info(&apInfo) == ESP_OK);
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::StartWiFiLayer(void)
{
int8_t ignored;
bool wifiStarted;
// There appears to be no direct way to ask the ESP WiFi layer if esp_wifi_start()
// has been called. So use the ESP_ERR_WIFI_NOT_STARTED error returned by
// esp_wifi_get_max_tx_power() to detect this.
esp_err_t err = esp_wifi_get_max_tx_power(&ignored);
switch (err)
{
case ESP_OK:
wifiStarted = true;
break;
case ESP_ERR_WIFI_NOT_STARTED:
wifiStarted = false;
break;
default:
return ESP32Utils::MapError(err);
}
if (!wifiStarted)
{
ChipLogProgress(DeviceLayer, "Starting ESP WiFi layer");
err = esp_wifi_start();
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_start() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::EnableStationMode(void)
{
wifi_mode_t curWiFiMode;
// Get the current ESP WiFI mode.
esp_err_t err = esp_wifi_get_mode(&curWiFiMode);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_get_mode() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
// If station mode is not already enabled (implying the current mode is WIFI_MODE_AP), change
// the mode to WIFI_MODE_APSTA.
if (curWiFiMode == WIFI_MODE_AP)
{
ChipLogProgress(DeviceLayer, "Changing ESP WiFi mode: %s -> %s", WiFiModeToStr(WIFI_MODE_AP),
WiFiModeToStr(WIFI_MODE_APSTA));
err = esp_wifi_set_mode(WIFI_MODE_APSTA);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_set_mode() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::SetAPMode(bool enabled)
{
wifi_mode_t curWiFiMode, targetWiFiMode;
targetWiFiMode = (enabled) ? WIFI_MODE_APSTA : WIFI_MODE_STA;
// Get the current ESP WiFI mode.
esp_err_t err = esp_wifi_get_mode(&curWiFiMode);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_get_mode() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
// If station mode is not already enabled (implying the current mode is WIFI_MODE_AP), change
// the mode to WIFI_MODE_APSTA.
if (curWiFiMode != targetWiFiMode)
{
ChipLogProgress(DeviceLayer, "Changing ESP WiFi mode: %s -> %s", WiFiModeToStr(curWiFiMode), WiFiModeToStr(targetWiFiMode));
err = esp_wifi_set_mode(targetWiFiMode);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_set_mode() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
}
return CHIP_NO_ERROR;
}
int ESP32Utils::OrderScanResultsByRSSI(const void * _res1, const void * _res2)
{
const wifi_ap_record_t * res1 = (const wifi_ap_record_t *) _res1;
const wifi_ap_record_t * res2 = (const wifi_ap_record_t *) _res2;
if (res1->rssi > res2->rssi)
{
return -1;
}
if (res1->rssi < res2->rssi)
{
return 1;
}
return 0;
}
const char * ESP32Utils::WiFiModeToStr(wifi_mode_t wifiMode)
{
switch (wifiMode)
{
case WIFI_MODE_NULL:
return "NULL";
case WIFI_MODE_STA:
return "STA";
case WIFI_MODE_AP:
return "AP";
case WIFI_MODE_APSTA:
return "STA+AP";
default:
return "(unknown)";
}
}
struct netif * ESP32Utils::GetStationNetif(void)
{
return GetNetif("WIFI_STA_DEF");
}
struct netif * ESP32Utils::GetNetif(const char * ifKey)
{
struct netif * netif = NULL;
esp_netif_t * netif_handle = NULL;
netif_handle = esp_netif_get_handle_from_ifkey(ifKey);
netif = (struct netif *) esp_netif_get_netif_impl(netif_handle);
return netif;
}
bool ESP32Utils::IsInterfaceUp(const char * ifKey)
{
struct netif * netif = GetNetif(ifKey);
return netif != NULL && netif_is_up(netif);
}
bool ESP32Utils::HasIPv6LinkLocalAddress(const char * ifKey)
{
struct esp_ip6_addr if_ip6_unused;
return esp_netif_get_ip6_linklocal(esp_netif_get_handle_from_ifkey(ifKey), &if_ip6_unused) == ESP_OK;
}
CHIP_ERROR ESP32Utils::GetWiFiStationProvision(Internal::DeviceNetworkInfo & netInfo, bool includeCredentials)
{
wifi_config_t stationConfig;
esp_err_t err = esp_wifi_get_config(WIFI_IF_STA, &stationConfig);
if (err != ESP_OK)
{
return ESP32Utils::MapError(err);
}
VerifyOrReturnError(stationConfig.sta.ssid[0] != 0, CHIP_ERROR_INCORRECT_STATE);
netInfo.NetworkId = kWiFiStationNetworkId;
netInfo.FieldPresent.NetworkId = true;
memcpy(netInfo.WiFiSSID, stationConfig.sta.ssid,
min(strlen(reinterpret_cast<char *>(stationConfig.sta.ssid)) + 1, sizeof(netInfo.WiFiSSID)));
// Enforce that netInfo wifiSSID is null terminated
netInfo.WiFiSSID[kMaxWiFiSSIDLength] = '\0';
if (includeCredentials)
{
static_assert(sizeof(netInfo.WiFiKey) < 255, "Our min might not fit in netInfo.WiFiKeyLen");
netInfo.WiFiKeyLen = static_cast<uint8_t>(min(strlen((char *) stationConfig.sta.password), sizeof(netInfo.WiFiKey)));
memcpy(netInfo.WiFiKey, stationConfig.sta.password, netInfo.WiFiKeyLen);
}
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::SetWiFiStationProvision(const Internal::DeviceNetworkInfo & netInfo)
{
wifi_config_t wifiConfig;
char wifiSSID[kMaxWiFiSSIDLength + 1];
size_t netInfoSSIDLen = strlen(netInfo.WiFiSSID);
// Ensure that ESP station mode is enabled. This is required before esp_wifi_set_config(ESP_IF_WIFI_STA,...)
// can be called.
ReturnErrorOnFailure(ESP32Utils::EnableStationMode());
// Enforce that wifiSSID is null terminated before copying it
memcpy(wifiSSID, netInfo.WiFiSSID, min(netInfoSSIDLen + 1, sizeof(wifiSSID)));
if (netInfoSSIDLen + 1 < sizeof(wifiSSID))
{
wifiSSID[netInfoSSIDLen] = '\0';
}
else
{
wifiSSID[kMaxWiFiSSIDLength] = '\0';
}
// Initialize an ESP wifi_config_t structure based on the new provision information.
memset(&wifiConfig, 0, sizeof(wifiConfig));
memcpy(wifiConfig.sta.ssid, wifiSSID, min(strlen(wifiSSID) + 1, sizeof(wifiConfig.sta.ssid)));
memcpy(wifiConfig.sta.password, netInfo.WiFiKey, min((size_t) netInfo.WiFiKeyLen, sizeof(wifiConfig.sta.password)));
wifiConfig.sta.scan_method = WIFI_ALL_CHANNEL_SCAN;
wifiConfig.sta.sort_method = WIFI_CONNECT_AP_BY_SIGNAL;
// Configure the ESP WiFi interface.
esp_err_t err = esp_wifi_set_config(WIFI_IF_STA, &wifiConfig);
if (err != ESP_OK)
{
ChipLogError(DeviceLayer, "esp_wifi_set_config() failed: %s", esp_err_to_name(err));
return ESP32Utils::MapError(err);
}
ChipLogProgress(DeviceLayer, "WiFi station provision set (SSID: %s)", netInfo.WiFiSSID);
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::ClearWiFiStationProvision(void)
{
wifi_config_t stationConfig;
// Clear the ESP WiFi station configuration.
memset(&stationConfig, 0, sizeof(stationConfig));
esp_wifi_set_config(WIFI_IF_STA, &stationConfig);
return CHIP_NO_ERROR;
}
CHIP_ERROR ESP32Utils::MapError(esp_err_t error)
{
if (error == ESP_OK)
{
return CHIP_NO_ERROR;
}
return ChipError::Encapsulate(ChipError::Range::kPlatform, error);
}
| [
"noreply@github.com"
] | winnieli1129.noreply@github.com |
8d83fdb91176003dfddad1dbbbecfe9a1113ef67 | 20a5975e1ffe7d03a84b404af87bda6638ba7c18 | /allCodes/4.Massivlar(80-100)/example-83/index.cpp | 043ca523330abed7d7ef261ca0281f0dba9fd9d9 | [] | no_license | qobulovasror/c-da-oddiy-dasturlar | 8442c6d0ae175048ea17d444ee01632dffef4951 | d7a413e18cdea0973dd36ef1d7a5b8aedea0a802 | refs/heads/main | 2023-02-18T19:56:20.513970 | 2023-02-08T11:39:25 | 2023-02-08T11:39:25 | 324,215,466 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 818 | cpp | // 83. Butun sonli bir o’lchovli massivdan, berilgan songa teng bo’lgan,
//agar u bor bo’lsa, elementni o’chiring. Agar bunday elementlar bir nechta bo’lsa,
//u holda oxirgi topilganini o’chiring.
#include <iostream>
using namespace std;
int main()
{
int i,s=0,n,m,l;
cout<<"n=";cin>>n;
int A[n];
cout<<"m=";cin>>m;
for(i=0;i<n;i++)
{
int t=0;
cin>>t;
A[i]=t;
if(t==m){
++s;
l=i;
}
}
if(s>0){
if(s==1){
int k=0;
for(i=0;i<n;i++)
if(A[i]==m)
k=i;
for(i=k; i<n-1;i++)
A[i]=A[i+1];
}else{
for(i=l;i<n-1;i++)
A[i]=A[i-1];
}
for(i=0;i<n-1;i++)
count<<"A["+i+"]= "<<A[i]<<endl;
}
count<<"there isn't value";
return 0;
}
| [
"qobulovasror0@gmail.com"
] | qobulovasror0@gmail.com |
47ad817e28ac79e9cd58c22ac3cb308357677d1f | 156c03dc94ba4268f4a3f79aa8b69eaba24791f4 | /main.ino | 70124133308ff3fa8102daea53088270db374d6b | [] | no_license | neverased/MediaServer | dcd25b087459f632dad869f255a55c9e97779d45 | 2cfd08335aeb2ec51096641a6d5a98bf01c41031 | refs/heads/master | 2021-04-26T22:29:00.992225 | 2020-02-03T13:29:39 | 2020-02-03T13:29:39 | 124,099,504 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,453 | ino | #include <Ethernet.h>
#include <EthernetClient.h>
#include <EthernetServer.h>
#include <EthernetUdp.h>
#include <avr/pgmspace.h>
#include <SPI.h>
#include "SdFat.h"
#include "FreeStack.h"
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 5, 6, 7); //Informacja o podlaczeniu nowego wyswietlacza
/************ ETHERNET STUFF ************/
byte mac[] = { 0x02, 0xAC, 0xCB, 0xCC, 0xDD, 0x04 };
byte ip[] = { 192, 168, 10, 3};
EthernetServer server(80);
const char legalChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890/.-_~";
unsigned int requestNumber = 0;
unsigned long connectTime[MAX_SOCK_NUM];
/************ SDCARD STUFF ************/
SdFat sd;
SdFile file;
SdFile dirFile;
File myFile;
int clientCount = 0;
int k;
uint8_t tBuf[100];
// Number of files found.
uint16_t n = 0;
uint16_t x = 0;
const uint16_t nMax = 50;
// Position of file's directory entry.
uint16_t dirIndex[nMax];
char myChar;
const char Style[] PROGMEM =
"<html>"
"<head>"
"<style>"
"body {"
" margin: 0;"
" font-family: -apple-system, BlinkMacSystemFont, Roboto, Arial, sans-serif;"
" font-size: 1em;"
" font-weight: 400;"
" line-height: 1.5em;"
" color: #111;"
" text-align: left;"
" background-color: #fff;"
"}"
""
"ul {"
" width: 700px;"
"}"
"li:before {"
" display: flex;"
" margin-right: 0.55rem;"
" margin-top: 5px;"
" content: url(data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9ImN1cnJlbnRDb2xvciIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiIGNsYXNzPSJmZWF0aGVyIGZlYXRoZXItZGlzYyI+PGNpcmNsZSBjeD0iMTIiIGN5PSIxMiIgcj0iMTAiPjwvY2lyY2xlPjxjaXJjbGUgY3g9IjEyIiBjeT0iMTIiIHI9IjMiPjwvY2lyY2xlPjwvc3ZnPg==);"
"}"
"li {"
" align-items: center;"
" display: flex;"
" justify-content: flex-start;"
" padding: 0.55rem;"
""
" margin-bottom: -1px;"
" background-color: #fff;"
" border: 1px solid rgba(0, 0, 0, 0.125);"
" overflow: hidden;"
"}"
"li:hover {"
" color: #111;"
" text-decoration: none;"
" background-color: #f012be;"
"}"
""
"li:first-child {"
" border-top-left-radius: 0.55rem;"
" border-top-right-radius: 0.55rem;"
"}"
""
"li:last-child {"
" margin-bottom: 0;"
" border-bottom-right-radius: 0.55rem;"
" border-bottom-left-radius: 0.55rem;"
"}"
""
"li a {"
" text-decoration: none;"
" color: #111;"
"}"
"</style>"
"</head>"
"<body>"
;
//------------------------------------------------------------------------------
void setup() {
Serial.begin(9600);
lcd.begin(16, 2); //Deklaracja typu
lcd.setCursor(0, 0); //Ustawienie kursora
lcd.print("IP Address:"); //Wyswietlenie tekstu
lcd.setCursor(0, 1); //Ustawienie kursora
while (!Serial) {}
delay(1000);
if (!sd.begin(4)) {
sd.initErrorHalt();
}
Serial.print(F("FreeStack: "));
Serial.println(FreeStack());
Serial.println();
// List files in root directory.
if (!dirFile.open("/", O_READ)) {
sd.errorHalt("open root failed");
}
while (n < nMax && file.openNext(&dirFile, O_READ)) {
// ukryj podfoldery i ukryte pliki
if (!file.isSubDir() && !file.isHidden()) {
// Save dirIndex of file in directory.
dirIndex[n] = file.dirIndex();
// Print the file number and name.
Serial.print(n++);
Serial.write(' ');
file.printName(&Serial);
Serial.println();
}
file.close();
}
Ethernet.begin(mac, ip);
Serial.print(Ethernet.localIP());
server.begin();
lcd.print(Ethernet.localIP()); //Wyswietlenie ip po DHCP
}
void ListFiles(EthernetClient client) {
dirFile.rewind ();
client.println("<ul>");
while (x < nMax && file.openNext(&dirFile, O_READ)) {
if (!file.isSubDir() && !file.isHidden()) {
// Save dirIndex of file in directory.
dirIndex[n] = file.dirIndex();
// Print the file number and name.
client.print("<li><a href=\"");
file.printName(&client);
client.print("\">");
}
// print file name with possible blank fill
file.printName(&client);
client.print("</a>");
file.close();
client.println("</li>");
}
client.println("</ul>");
}
//------------------------------------------------------------------------------
#define BUFSIZE 100
void loop() {
char clientline[BUFSIZE];
int index = 0;
EthernetClient client = server.available();
if (client) {
// an http request ends with a blank line
boolean current_line_is_blank = true;
// reset the input buffer
index = 0;
while (client.connected()) {
if (client.available()) {
char c = client.read();
// If it isn't a new line, add the character to the buffer
if (c != '\n' && c != '\r') {
clientline[index] = c;
index++;
// are we too big for the buffer? start tossing out data
if (index >= BUFSIZE)
index = BUFSIZE -1;
// continue to read more data!
continue;
}
// got a \n or \r new line, which means the string is done
clientline[index] = 0;
// Print it out for debugging
Serial.println(clientline);
// Look for substring such as a request to get the root file
if (strstr(clientline, "GET / ") != 0) {
// send a standard http response header
client.println("HTTP/1.1 200 OK");
client.println("Content-Type: text/html");
client.println();
for (k = 0; k < strlen_P(Style); k++)
{
myChar = pgm_read_byte_near(Style + k);
Serial.print(myChar);
client.print(myChar);
}
// print all the files, use a helper to keep it clean
client.println("<h2>Pliki:</h2>");
ListFiles(client);
client.println("</body>");
client.println("</html>");
} else if (strstr(clientline, "GET /") != 0) {
char *filename;
filename = clientline + 5; // po "GET /" (5 znaków)
// szukaj " HTTP/1.1"
// zamien peirwszy znak substringa na 0
(strstr(clientline, " HTTP"))[0] = 0;
// print the file we want
Serial.println(filename);
if (! file.open(&dirFile, filename, O_READ)) {
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: audio/mpeg3");
client.println();
client.println("<h2>File Not Found!</h2>");
break;
}
Serial.println("Opened!");
while(file.available()) {
clientCount = file.read(tBuf,sizeof(tBuf));
client.write(tBuf,clientCount);
}
// close the file:
file.close();
} else {
// everything else is a 404
client.println("HTTP/1.1 404 Not Found");
client.println("Content-Type: text/html");
client.println();
client.println("<h2>File Not Found!</h2>");
}
break;
}
}
// czas dla przegladarki na odebranie pliku
delay(1);
client.stop();
}
Serial.flush();
delay(100);
}
| [
"noreply@github.com"
] | neverased.noreply@github.com |
87ff159b2cb0c8fb0a6891de40491a9af7f8ed62 | 68703baa37bb2c50f4c86bfec54e42553ee20497 | /nme6/nme6d/code/timer.h | e2c98fb2cc3d6a60c3736a6a685bf71731d3870c | [] | no_license | bimmlerd/nme | 4ce4c64f429a8e6232069a2cff525b117cf687f1 | c63a11fcfce0dd98cc3576bd8af286cd28f82ff2 | refs/heads/master | 2020-05-18T04:22:53.895741 | 2016-01-21T13:40:41 | 2016-01-21T13:40:41 | 42,814,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | h | #include <chrono>
typedef std::chrono::high_resolution_clock::time_point time_t_;
//! Class implementing a simple chronometer, similar to tic-toc of Matlab
//! Just hit start() to start the timer, stop() to increment the timer (with time since last start/stop or reset)
//! Hit reset() to reset to 0 elapsed time
//! Get elapsed time with elapsed() or averaged time with avg()
template<typename duration_t_ = std::chrono::nanoseconds>
class timer {
public:
timer() {
elapsed_ = duration_t_::zero();
leaps_ = 0;
}
//! Just save current time
void start() {
start_ = std::chrono::high_resolution_clock::now();
}
//! Increment timer by tme since last start, calls start()
void stop() {
++leaps_;
elapsed_ += std::chrono::duration_cast<duration_t_>(std::chrono::high_resolution_clock::now() - start_);
start();
}
//! Reset timer to 0, calls start()
void reset() {
leaps_ = 0;
elapsed_ = duration_t_::zero();
start();
}
//! Get sum of all start()/stop() cycles
duration_t_ elapsed() const {
return elapsed_;
}
//! Get average of all start()/stop() cycles
duration_t_ avg() const {
return elapsed_ / leaps_;
}
//! Print elapsed time
void print() const {
std::cout << elapsed().count() << std::endl;
}
//! Print averaged elapsed time
void print_avg() const {
std::cout << avg().count() << std::endl;
}
private:
//! Number of cycles
unsigned int leaps_;
//! Time of start()
time_t_ start_;
//! Elapsed until last stop()
duration_t_ elapsed_;
};
| [
"bimmlerd@student.ethz.ch"
] | bimmlerd@student.ethz.ch |
f8462891dbb99499c9447411104bb04703be8c3b | a2a0ca2d2fc7d9a136dee137b39bc3a11489d1bf | /FireKeeper/MatchSvr/MatchImp.cpp | 030206a52fa1bfbb3384665f37dccdadd66af199 | [] | no_license | tommypan/FireKeeper | 0b70abb05d6135233917a7148206e22942072ee5 | 6da259632eed19bfa81f45703e1a75146025637f | refs/heads/master | 2020-09-23T18:46:16.437797 | 2019-12-09T12:00:47 | 2019-12-09T12:00:47 | 225,561,324 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 560 | cpp | #include "MatchImp.h"
#include "servant/Application.h"
using namespace std;
//////////////////////////////////////////////////////
void MatchImp::initialize()
{
//initialize servant here:
//...
}
//////////////////////////////////////////////////////
void MatchImp::destroy()
{
//destroy servant here:
//...
}
int MatchImp::AddInMatchList(unsigned long uid,tars::TarsCurrentPtr current)
{
return 0;
}
int MatchImp::Dotransmit(const ClientProto::PKG& pkg,tars::TarsCurrentPtr current)
{
return 0;
}
void MatchImp::DoMatch()
{
}
| [
"709450846@qq.com"
] | 709450846@qq.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.