language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C++
UTF-8
25,006
2.59375
3
[ "MIT" ]
permissive
#include <stdlib.h> #include <limits.h> #include <math.h> #include "utils.h" #include "solutions.h" SOLUTION* solveEmpty(const JOB * j);//empty implementation SOLUTION* solveBellmanFord(const JOB * j);//bellman ford shortest pathfinding algorithm SOLUTION* solveBellmanFordLimit(const JOB * j);//bellman ford s upravou (orezanie prehladavania podla doposial najdenej cesty) SOLUTION* solveBellmanFordGeom(const JOB * j);//bellman ford s upravou (orezanie prehladavania podla geometrickych informacii) SOLUTION* solveDijkstra(const JOB * j);//dijkstra shortest pathfinding algorithm SOLUTION* solveDijkstraHeap(const JOB * j);//dijkstra shortest pathfinding algorithm + heap SOLUTION* solveDijkstraHeapGeom(const JOB * j);//dijkstra shortest pathfinding algorithm + heap + use of geometric informations /* Always update these fields together */ /**/unsigned int ALGCOUNT = 7; //number of algorithms in this unit /**/ /**/char* AlgNames[] = {"empty", "dijkstra", "bellmanford", "dijkstraheap", "bellmanfordlimit", "dijkstraheapgeom", "bellmanfordgeom"};//array of names /**/SOLUTION* (*(Algs[]))(const JOB *) = {solveEmpty, solveDijkstra, solveBellmanFord, solveDijkstraHeap, solveBellmanFordLimit, solveDijkstraHeapGeom, solveBellmanFordGeom }; //array of func pointers (according to AlgNames) /*****************************************/ SOLUTION* solveEmpty(const JOB * j){ //for(int rpc = 0; rpc < 1000;rpc++); SOLUTION * rv = new SOLUTION; rv->exists = false; rv->l=0; rv->V=NULL; rv->vertNo=0; return(rv); } SOLUTION* solveDijkstra(const JOB * j){ int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc< hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int * F = new int[j->vertNo]; F[0] = src; //najprv je tam len src int Fs = 0; //aj je fronta neprazdna, index prveho prvku int Fe = 1; //index prveho volneho miesta int Fc = 1; //pocet prvkov vo fronte hilimit=j->vertNo+1; for (int rpc = 1;rpc<hilimit;rpc++) Vd[rpc] = INT_MAX; Vd[src]=0; int minI; //index minima int vminI; //index vrchola na prebranie while (Fc){ //kym nieje vrchol V[dst] prebrany a Fronta je neprazdna minI = Fs; for (int rpc = Fs+1; rpc < Fe; rpc++) minI = (Vd[F[minI]] < Vd[F[rpc]])? minI : rpc;//najde index minima vminI = F[minI]; if (vminI==dst) break; //uz je preberany cielovy vrchol, takze sa lepsia cesta donho nenajde, mozme skoncit F[minI] = F[--Fe]; Fc--; //ak bol vminI == dst, skonci sa uz skor a vo fronte je aspon 1 prvok, podla toho sa rozlisi uspesne najdenie cesty hilimit = Vs[vminI]+Vc[vminI]; for (int rpc=Vs[vminI]; rpc< hilimit; rpc++){ if (Vd[Vi[rpc]]==INT_MAX) { F[Fe++]=Vi[rpc]; Fc++; } if (Vd[Vi[rpc]]>Vd[vminI]+Vl[rpc]){ Vd[Vi[rpc]]=Vd[vminI]+Vl[rpc]; Vp[Vi[rpc]]=vminI; } } } /*navrat riesenia*/ SOLUTION * rv = new SOLUTION; if (!Fc) { //ak to skoncilo vyprazdnenim fronty rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vl; delete[] Vd; delete[] F; return(rv); } SOLUTION* solveDijkstraHeap(const JOB * j){ int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc< hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int * H = new int[j->vertNo+1]; //indexuje sa od 1, 0 v Hp = ze tam nieje int * Hp = new int[j->vertNo+1]; //pozicie vrcholov v heape H[1] = src; //najprv je tam len src hilimit = j->vertNo+1; for (int rpc=0; rpc<hilimit;rpc++){ Vd[rpc] = INT_MAX; Hp[rpc]=0; } Hp[src] = 1; int Hc = 1; //pocet hodnot v heape Vd[src]=0; int vminI; //index vrchola na prebranie while (Hc){ //kym nieje vrchol V[dst] prebrany a Fronta je neprazdna /*vyber minima z heapu*/ vminI = H[1]; Hp[vminI] = 0; /**/ if (vminI==dst) break; //uz je preberany cielovy vrchol, takze sa lepsia cesta donho nenajde, mozme skoncit //oprava struktury heapu Hc--; //ak bol vminI == dst, skonci sa uz skor a v Fc je aspon 1, podla toho sa rozlisi ci sa nasla cesta if (Hc){ int X = H[Hc+1]; int j = 1; int n; bool pokracovat = 2<=Hc; while (pokracovat) { n=2*j; n+=((n<Hc)&&(Vd[H[n+1]]<Vd[H[n]])); if (Vd[X]>Vd[H[n]]){ H[j] = H[n]; Hp[H[j]] = j; j=n; pokracovat = 2*j <= Hc; } else pokracovat = false; } H[j] = X; Hp[X] = j; } hilimit = Vs[vminI]+Vc[vminI]; for (int rpc=Vs[vminI]; rpc< hilimit; rpc++) if (Vd[Vi[rpc]]>Vd[vminI]+Vl[rpc]){ Vd[Vi[rpc]]=Vd[vminI]+Vl[rpc]; Vp[Vi[rpc]]=vminI; //pridat alebo upravit poziciu Vi[rpc] v heape pretoze sa zmenila vzdialenost int j = Hp[Vi[rpc]]; int p; int X = Vi[rpc]; if (!j)//ak tam nie je treba ho pridat j = ++Hc; bool pokracovat = j > 1; while (pokracovat){ p = j / 2; if (Vd[X] < Vd[H[p]]){ H[j] = H[p]; Hp[H[j]] = j; j=p; pokracovat = j>1; } else pokracovat = false; } H[j] = X; Hp[X] = j; } } /*navrat riesenia*/ SOLUTION * rv = new SOLUTION; if (!Hc) { //ak to skoncilo vyprazdnenim fronty rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vl; delete[] Vd; delete[] H; delete[] Hp; return(rv); } SOLUTION* solveDijkstraHeapGeom(const JOB * j){//s vyuzitim geometrickych udajov int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vm = new int[j->vertNo+1]; //minimalna dlzka cesty spocitana ako eukl. vzdialenost int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int dx=j->V[j->dst].x, dy=j->V[j->dst].y, dz=j->V[j->dst].z; int rx,ry,rz; for (int rpc = 1; rpc<hilimit; rpc++){ //spocitanie minimalnych vzdialenosti rx = j->V[rpc].x - dx; ry = j->V[rpc].y - dy; rz = j->V[rpc].z - dz; Vm[rpc] = int(floor(sqrt(double(rx*rx+ry*ry+rz*rz)))); //ulozene ako druha odmocnina } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc< hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int * H = new int[j->vertNo+1]; //indexuje sa od 1, 0 v Hp = ze tam nieje int * Hp = new int[j->vertNo+1]; //pozicie vrcholov v heape H[1] = src; //najprv je tam len src hilimit = j->vertNo+1; for (int rpc=0; rpc<hilimit;rpc++){ Vd[rpc] = INT_MAX; Hp[rpc]=0; } Hp[src] = 1; int Hc = 1; //pocet hodnot v heape Vd[src]=0; int vminI; //index vrchola na prebranie while (Hc){ //kym nieje vrchol V[dst] prebrany a Fronta je neprazdna /*vyber minima z heapu*/ vminI = H[1]; Hp[vminI] = 0; /**/ if (vminI==dst) break; //uz je preberany cielovy vrchol, takze sa lepsia cesta donho nenajde, mozme skoncit //oprava struktury heapu Hc--; //ak bol vminI == dst, skonci sa uz skor a v Fc je aspon 1, podla toho sa rozlisi ci sa nasla cesta if (Hc){ int X = H[Hc+1]; int j = 1; int n; bool pokracovat = 2<=Hc; while (pokracovat) { n=2*j; n+=((n<Hc)&&(Vd[H[n+1]]<Vd[H[n]])); if (Vd[X]>Vd[H[n]]){ H[j] = H[n]; Hp[H[j]] = j; j=n; pokracovat = 2*j <= Hc; } else pokracovat = false; } H[j] = X; Hp[X] = j; } if (Vd[vminI]+Vm[vminI] > Vd[dst]) continue;//ak je vzdialenost vrchola + minimalna dlzka cesty do ciela vacsia ako sucasna, vynechame vrchol hilimit = Vs[vminI]+Vc[vminI]; for (int rpc=Vs[vminI]; rpc< hilimit; rpc++) if (Vd[Vi[rpc]]>Vd[vminI]+Vl[rpc]){ Vd[Vi[rpc]]=Vd[vminI]+Vl[rpc]; Vp[Vi[rpc]]=vminI; //pridat alebo upravit poziciu Vi[rpc] v heape pretoze sa zmenila vzdialenost int j = Hp[Vi[rpc]]; int p; int X = Vi[rpc]; if (!j)//ak tam nie je treba ho pridat j = ++Hc; bool pokracovat = j > 1; while (pokracovat){ p = j / 2; if (Vd[X] < Vd[H[p]]){ H[j] = H[p]; Hp[H[j]] = j; j=p; pokracovat = j>1; } else pokracovat = false; } H[j] = X; Hp[X] = j; } } /*navrat riesenia*/ SOLUTION * rv = new SOLUTION; if (!Hc) { //ak to skoncilo vyprazdnenim fronty rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vl; delete[] Vm; delete[] Vd; delete[] H; delete[] Hp; return(rv); } SOLUTION* solveBellmanFord(const JOB * j){ int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc< hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int Fsize = 4*(j->vertNo+1); //pociatocna velkost fronty int * F = new int[Fsize]; //indexuje sa od 1 int * Fp = new int[j->vertNo+1]; //pozicia vrchola vo fronte, 0 = nieje tam hilimit=j->vertNo+1; for (int rpc=0;rpc<hilimit;rpc++) { Fp[rpc] = 0; Vd[rpc] = INT_MAX; } F[1] = src; //najprv je tam len src Fp[src] = 1; // a to na pozici 1 v F1 Vd[src]=0; //vzialenost do pociatku je 0 int Fs = 1; //ak je fronta neprazdna, index prveho prvku int Fe = 2; //index prveho volneho miesta int Fc = 1; //pocet prvkov vo fronte int fvI; //index prveho vrchola (vybraneho z fronty) while(Fc){ //kym je vo fronte nejaky vrchol do {fvI = F[Fs]; Fs=(Fs % (Fsize-1))+1; Fc--; Fp[fvI] = 0;//zmena indexu (Fs % (Fsize-1))+1 je ok,pretoze sa indexuje od 1 po Fsize-1 }while ((Fc>0)&&(fvI==0));//0 su prazdne miesta if (fvI==0) break;//uz tam nieje nic hilimit = Vs[fvI]+Vc[fvI]; for (int rpc = Vs[fvI]; rpc<hilimit; rpc++){//preberie nasledovnikov if (Vd[Vi[rpc]]>Vd[fvI]+Vl[rpc]){ Vp[Vi[rpc]] = fvI; //nastavi noveho predchodcu Vd[Vi[rpc]] = Vd[fvI]+Vl[rpc]; //nastavi novu vzdialenost if (Fp[Vi[rpc]]) //ak je vo fronte, je najprv prepisany nulou F[Fp[Vi[rpc]]] = 0; if (Fc == Fsize-1){ //uz by do fronty nevosiel //prealokovat frontu int * tmp = new int[Fsize*2];//raz tolko int hilimit=__min(Fsize-Fs,Fc); for(int rpc=0; rpc<hilimit; rpc++) tmp[rpc+1]=F[Fs+rpc];//skopiruje od Fs po koniec pola int hilimit2 = Fc-hilimit;//zostava skopirovat Fc - hilimit for(int rpc=0; rpc<hilimit2; rpc++) tmp[rpc+hilimit+1]=F[1+rpc];//skopiruje zvysok Fs = 1; Fe = Fc+1; delete[] F; Fsize *= 2; F = tmp; hilimit = Fc+1; for(int rpc=1; rpc<hilimit; rpc++) Fp[F[rpc]]=rpc;//prepise zaradenie } F[Fe] = Vi[rpc];//prida nakoniec Fp[Vi[rpc]] = Fe;//zapise kam ho zaradil Fe=(Fe % (Fsize-1))+1;//posunie koniec Fc++;//zvysi pocet zaznamov vo fronte } } } //vytvorenie vysledku SOLUTION * rv = new SOLUTION; if (Vd[dst]==INT_MAX) { //ak to dobehlo bez dosiahnutia ciela rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vl; delete[] Vd; delete[] Fp; delete[] F; return(rv); } SOLUTION* solveBellmanFordLimit(const JOB * j){ int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc < hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int Fsize = 4*(j->vertNo+1); //pociatocna velkost fronty int * F = new int[Fsize]; //indexuje sa od 1 int * Fp = new int[j->vertNo+1]; //pozicia vrchola vo fronte, 0 = nieje tam hilimit=j->vertNo+1; for (int rpc=0;rpc<hilimit;rpc++) { Fp[rpc] = 0; Vd[rpc] = INT_MAX; } F[1] = src; //najprv je tam len src Fp[src] = 1; // a to na pozici 1 v F1 Vd[src]=0; //vzialenost do pociatku je 0 int Fs = 1; //ak je fronta neprazdna, index prveho prvku int Fe = 2; //index prveho volneho miesta int Fc = 1; //pocet prvkov vo fronte int fvI; //index prveho vrchola (vybraneho z fronty) while(Fc){ //kym je vo fronte nejaky vrchol do {fvI = F[Fs]; Fs=(Fs % (Fsize-1))+1; Fc--; Fp[fvI] = 0;//zmena indexu (Fs % (Fsize-1))+1 je ok,pretoze sa indexuje od 1 po Fsize-1 }while ( Fc &&(!fvI));//0 su prazdne miesta if (fvI==0) break;//uz tam nieje nic if (Vd[fvI] > Vd[dst]) continue;//pokracuje ak teraz cestou cez tento vrchol nemoze zlepsit hilimit = Vs[fvI]+Vc[fvI]; for (int rpc = Vs[fvI]; rpc<hilimit; rpc++){//preberie nasledovnikov if (Vd[Vi[rpc]]>Vd[fvI]+Vl[rpc]){ Vp[Vi[rpc]] = fvI; //nastavi noveho predchodcu Vd[Vi[rpc]] = Vd[fvI]+Vl[rpc]; //nastavi novu vzdialenost if (Fp[Vi[rpc]]) //ak je vo fronte, je najprv prepisany nulou F[Fp[Vi[rpc]]] = 0; if (Fc == Fsize-1){ //uz by do fronty nevosiel //prealokovat frontu int * tmp = new int[Fsize*2];//raz tolko int hilimit=__min(Fsize-Fs,Fc); for(int rpc=0; rpc<hilimit; rpc++) tmp[rpc+1]=F[Fs+rpc];//skopiruje od Fs po koniec pola int hilimit2 = Fc-hilimit;//zostava skopirovat Fc - hilimit for(int rpc=0; rpc<hilimit2; rpc++) tmp[rpc+hilimit+1]=F[1+rpc];//skopiruje zvysok Fs = 1; Fe = Fc+1; delete[] F; Fsize *= 2; F = tmp; hilimit = Fc+1; for(int rpc=1; rpc<hilimit; rpc++) Fp[F[rpc]]=rpc;//prepise zaradenie } F[Fe] = Vi[rpc];//prida nakoniec Fp[Vi[rpc]] = Fe;//zapise kam ho zaradil Fe=(Fe % (Fsize-1))+1;//posunie koniec Fc++;//zvysi pocet zaznamov vo fronte } } } //vytvorenie vysledku SOLUTION * rv = new SOLUTION; if (Vd[dst]==INT_MAX) { //ak to dobehlo bez dosiahnutia ciela rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vl; delete[] Vd; delete[] Fp; delete[] F; return(rv); } SOLUTION* solveBellmanFordGeom(const JOB * j){ int * Vs = new int[j->vertNo+1]; //index kde zacina zoznam nasledovnikov vo Vi int * Vc = new int[j->vertNo+1]; //pocet zaznamov vo Vi pre dany vrchol int * Vp = new int[j->vertNo+1]; //predchodcovia na ceste zo src int * Vm = new int[j->vertNo+1]; //minimalna dlzka cesty spocitana ako eukl. vzdialenost int * Vi = new int[(j->edgeNo)*2]; //zoznam naslednikov, naslednici pre i zacinaju od Vi[Vs[i]] int * Vl = new int[(j->edgeNo)*2]; //dlzky hran int src = j->src; //pociatok int dst = j->dst; //koniec int cumc = 0; //kumulativne cetnosti int hilimit = j->vertNo+1; for (int rpc = 1; rpc< hilimit; rpc++ ) { Vs[rpc] = cumc; //zoznam zacina v poli Vi na indexe cumc Vc[rpc] = 0; //pocet naslednikov ulozeny pre kazdy vrchol je zatial 0 cumc+=j->V[rpc].deg; //posun o stupen vrchola } int dx=j->V[j->dst].x, dy=j->V[j->dst].y, dz=j->V[j->dst].z; int rx,ry,rz; for (int rpc = 1; rpc<hilimit; rpc++){ //spocitanie minimalnych vzdialenosti rx = j->V[rpc].x - dx; ry = j->V[rpc].y - dy; rz = j->V[rpc].z - dz; Vm[rpc] = int(floor(sqrt(double(rx*rx+ry*ry+rz*rz)))); } int v1,v2; hilimit=j->edgeNo; for (int rpc=0; rpc < hilimit; rpc++){ EDGE e = j->E[rpc]; v1 = e.v1; v2 = e.v2; Vl[Vs[v1]+Vc[v1]]=e.l; //dlzka cesty Vi[Vs[v1]+Vc[v1]++]=v2; //v1 prida do zoznamu naslednikov v2 a zvysi pocet vo Vc[v1] Vl[Vs[v2]+Vc[v2]]=e.l; Vi[Vs[v2]+Vc[v2]++]=v1; } int * Vd = new int[j->vertNo+1]; //vzdialenost do vrchola z source, INT_MAX pre neprebrany int Fsize = 4*(j->vertNo+1); //pociatocna velkost fronty int * F = new int[Fsize]; //indexuje sa od 1 int * Fp = new int[j->vertNo+1]; //pozicia vrchola vo fronte, 0 = nieje tam hilimit=j->vertNo+1; for (int rpc=0;rpc<hilimit;rpc++) { Fp[rpc] = 0; Vd[rpc] = INT_MAX; } F[1] = src; //najprv je tam len src Fp[src] = 1; // a to na pozici 1 v F1 Vd[src]=0; //vzialenost do pociatku je 0 int Fs = 1; //ak je fronta neprazdna, index prveho prvku int Fe = 2; //index prveho volneho miesta int Fc = 1; //pocet prvkov vo fronte int fvI; //index prveho vrchola (vybraneho z fronty) while(Fc){ //kym je vo fronte nejaky vrchol do {fvI = F[Fs]; Fs=(Fs % (Fsize-1))+1; Fc--; Fp[fvI] = 0;//zmena indexu (Fs % (Fsize-1))+1 je ok,pretoze sa indexuje od 1 po Fsize-1 }while ( Fc &&(!fvI));//0 su prazdne miesta if (fvI==0) break;//uz tam nieje nic if (Vd[fvI] + Vm[fvI] > Vd[dst]) continue;//pokracuje ak teraz cestou cez tento vrchol nemoze zlepsit hilimit = Vs[fvI]+Vc[fvI]; for (int rpc = Vs[fvI]; rpc<hilimit; rpc++){//preberie nasledovnikov if (Vd[Vi[rpc]]>Vd[fvI]+Vl[rpc]){ Vp[Vi[rpc]] = fvI; //nastavi noveho predchodcu Vd[Vi[rpc]] = Vd[fvI]+Vl[rpc]; //nastavi novu vzdialenost if (Fp[Vi[rpc]]) //ak je vo fronte, je najprv prepisany nulou F[Fp[Vi[rpc]]] = 0; if (Fc == Fsize-1){ //uz by do fronty nevosiel //prealokovat frontu int * tmp = new int[Fsize*2];//raz tolko int hilimit=__min(Fsize-Fs,Fc); for(int rpc=0; rpc<hilimit; rpc++) tmp[rpc+1]=F[Fs+rpc];//skopiruje od Fs po koniec pola int hilimit2 = Fc-hilimit;//zostava skopirovat Fc - hilimit for(int rpc=0; rpc<hilimit2; rpc++) tmp[rpc+hilimit+1]=F[1+rpc];//skopiruje zvysok Fs = 1; Fe = Fc+1; delete[] F; Fsize *= 2; F = tmp; hilimit = Fc+1; for(int rpc=1; rpc<hilimit; rpc++) Fp[F[rpc]]=rpc;//prepise zaradenie } F[Fe] = Vi[rpc];//prida nakoniec Fp[Vi[rpc]] = Fe;//zapise kam ho zaradil Fe=(Fe % (Fsize-1))+1;//posunie koniec Fc++;//zvysi pocet zaznamov vo fronte } } } //vytvorenie vysledku SOLUTION * rv = new SOLUTION; if (Vd[dst]==INT_MAX) { //ak to dobehlo bez dosiahnutia ciela rv->exists=false; rv->l=0; rv->V=NULL; rv->vertNo=0; } else { //vytvorenie navratovej hodnoty v tvare: (dlzkacesty)src,v1,v2,...,vn,dst rv->exists = true; rv->l = Vd[dst]; int i = dst,count = 1; do { i = Vp[i]; count++; } while (i!=src); rv->vertNo = count; rv->V = new unsigned int[count]; unsigned int * P = rv->V; i = dst; P[--count] = dst; do { i = Vp[i]; P[--count] = i; } while (i!=src); } //uvolnovanie delete[] Vs; delete[] Vc; delete[] Vp; delete[] Vi; delete[] Vm; delete[] Vl; delete[] Vd; delete[] Fp; delete[] F; return(rv); }
Markdown
UTF-8
2,163
3.15625
3
[]
no_license
--- title: 二八定律与长尾理论 date: 2017-09-18 09:08:00 categories: - 数据分析思维 tags: - 数据分析思维 --- # 二八定律 前面,我们整理了[《帕累托的故事》](https://yuguiyang.github.io/2017/09/18/jotting-01/),里面有说过“帕累托法则”,就是这个二八定律,简单说来,就是 > 世界上20%的人占有80%的财富,即财富的分布式是不平衡的 这里理论不单单应用在经济学领域,其他领域也一样适用。比如: 在零售或销售行业,80%的利润可能来自20%的客户,所以运用该分析方法,就可以专注于维护这20%的客户,而不是将主要精力放在那80%的客户身上,因为他们只产生了20%的利润。通过80/20分析方法,可以有效的找到影响利润的主要因素 ## 二八定律应用场景 这里列举几个广泛使用的场景 * 在管理学中,企业80%的利润来自20%的项目或客户 * 心理学中,20%的人身上集中了80%的智慧,他们一出生就鹤立鸡群 * 20%的有目标,80%的人爱瞎想 * 20%的人把握机会,80%错失机会 * 20%的人会坚持,80%的人会放弃 <!-- more --> # 长尾理论 长尾理论的关注点和二八定律不同,上面是说要关注产生重大影响的20%,而长尾理论则提倡关注剩下的那80%,在一些互联网公司,如果那80%的尾巴足够长,就可能会产生超过前面20%的那部分产生的利润。 ![长尾理论](http://upload-images.jianshu.io/upload_images/76024-6262d4b48f4a778d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 在互联网时代,关注成本或是生产、运输成本都大大的降低,这长尾巴就产生了优势。 该理论在Google、亚马逊、沃尔玛,都用数据证实过,互联网行业尤其适用。 # 小结 二八定律的话,告诉我们关注可以产生重大影响的事情,抓住主要的; 长尾理论的应用应该还是处在互联网公司中,等看看那本书,详细了解下。 有的时候,换个角度看问题,的确可以发现不一样的世界。 # 参考资料 资料来源“百度百科”,“维基百科”
C++
UTF-8
589
2.53125
3
[]
no_license
#pragma once struct StuffFileEntry { dword fileSize; dword filenameLength; string filename; string stuffFilename; dword fileOffset; ifstream* handle; void Unstuff(CString path, CString start = "", int makedir=0); }; class StuffFile { public: dword filescount; bool loaded; vector<StuffFileEntry> files; vector<ifstream*> handles; StuffFile():loaded(false){} void LoadDir(string dir); void LoadFile(const string &filename); ~StuffFile(); }; void close(ifstream *in); void func(char &c); bool operator < (const StuffFileEntry& left, const StuffFileEntry& right);
Markdown
UTF-8
809
2.65625
3
[ "Apache-2.0" ]
permissive
# Redoodle FAQ ## Table of Contents - [Is Redoodle a replacement for Redux? Do I need both?](#replacement) <a id="replacement"></a> ### Is Redoodle a replacement for Redux? Do I need both? Redoodle was **not** designed to be a replacement for the Redux library: Redux-powered applications can start integrating any of Redoodle's addons piecewise without gutting all of their existing Actions, Reducers, or Store wiring. It is fully encouraged that consumers continue to use Redux for store management, along with the many other fantastic community extensions for Redux as listed on [awesome-redux](https://github.com/xgrommx/awesome-redux). However, after writing Redoodle the only thing missing to be a drop-in replacement for Redux was the `createStore()` function, so we added it to Redoodle in 2.1.
Ruby
UTF-8
2,049
4.03125
4
[]
no_license
def greetings puts "Hello, this is William's corner. May I know your name, please?" puts ">" $name = gets.chomp puts " Hi #{$name}!" puts "> Here's the menu! Please put your order." end def showMenu menu = [ {item: "Bottled Water", price: 10}, {item: "Cola", price: 20}, {item: "Fried Chicken", price: 50}, {item: "Hamburger", price: 35}, {item: "Spaghetti", price: 40} ] puts menu gets end def getOrder puts "How many Hamburger/s?" num = gets.chomp.to_i price = num* 35 puts "How many Fried Chicken/s?" numa = gets.chomp.to_i price1 = numa*50 puts "How many Spaghetti/s?" numb = gets.chomp.to_i price2 = numb*40 puts "How many cola/s?" numc = gets.chomp.to_i price3 = numc*20 puts "How many bottled water/s?" numd = gets.chomp.to_i price4 = numd*10 order = gets.chomp puts "LIST OF ORDERS" puts "#{num} X Hamburger = #{price} pesos" puts "#{numa} X Fried Chicken = #{price1} pesos" puts "#{numb} X Spaghetti = #{price2} pesos" puts "#{numc} X cola = #{price3} pesos" puts "#{numd} X bottled water = #{price4} pesos" $prices = price.to_i + price1.to_i + price2.to_i + price3.to_i + price4.to_i price = gets.chomp puts "TOTAL PRICE IS #{$prices}" end def orderUp puts "How much money you have?" $money = gets.chomp.to_i if $money.to_i < $prices.to_i puts "I'm sorry this isn't enough." puts "You have a remaining balance of #{$prices.to_i-$money.to_i}" orderUp else finishProgram end end def finishOrder puts "Do you want to have a printed receipt? yes or no?" receipt = gets.chomp case receipt when "yes" puts "Ok, here's your receipt." when "no" puts "" end puts "Thank you! Please come again!" end def finishProgram if $money.to_i - $prices.to_i == 0 puts "Thanks #{$name}! Do you want a receipt?" else puts "Thanks #{$name}! Here's you change of #{$money.to_i-$prices.to_i}!" end end def startProgram greetings showMenu getOrder orderUp finishOrder end startProgram
C#
UTF-8
3,261
3.140625
3
[]
no_license
using System; using System.Collections.Generic; namespace Observer { /// <summary> /// Subject class /// </summary> internal abstract class HeadQuarters { private string _information; private List<IOperator> _operators=null; protected HeadQuarters(string information) { _operators = new List<IOperator>(); Information = information; } public string Information { get { return _information; } set { _information = value; NotifyOperators(); } } public void AddOperator(IOperator opt) { _operators.Add(opt); } public void RemoveOperator(IOperator opt) { _operators.Remove(opt); } public void NotifyOperators() { foreach (IOperator opt in _operators) { opt.Update(this); } } } /// <summary> /// Concrete Subject class /// </summary> internal class RedFleetBase :HeadQuarters { public RedFleetBase(string information) :base(information) { } public RedFleetBase() :base("...") { } } /// <summary> /// Observer class /// </summary> internal interface IOperator { void Update(HeadQuarters headQuarters); } /// <summary> /// Concrete Observer class /// </summary> internal class PlatoonOperator :IOperator { public string OperatorName { get; set; } #region IOperator Members public void Update(HeadQuarters headQuarters) { Console.WriteLine("[{0}] : {1}",OperatorName,headQuarters.Information); } #endregion } /// <summary> /// Concrete Observer Class /// </summary> internal class TankOperator : IOperator { public int TankId { get; set; } #region IOperator Members public void Update(HeadQuarters headQuarters) { Console.WriteLine("[{0}] : {1}", TankId, headQuarters.Information); } #endregion } /// <summary> /// Client App /// </summary> class Program { static void Main() { RedFleetBase redFleetBase = new RedFleetBase {Information = "Süper işlemciler piyasada"}; redFleetBase.Information = "İşlemciler gelişiyor"; redFleetBase.AddOperator(new PlatoonOperator { OperatorName="Azman"} ); redFleetBase.AddOperator(new PlatoonOperator { OperatorName = "Kara Şahin"}); redFleetBase.AddOperator(new PlatoonOperator { OperatorName="Kartal Kondu"}); redFleetBase.Information = "Tüm birlikler Sarı Alarma! Sarı Alarma!"; Console.WriteLine(""); redFleetBase.Information = "Emir iptal! Emir iptal!"; Console.WriteLine(""); redFleetBase.AddOperator(new TankOperator{TankId=701}); redFleetBase.AddOperator(new TankOperator{TankId=801}); redFleetBase.Information = "Sınır ihlali."; } } }
Java
UTF-8
1,063
2.09375
2
[]
no_license
package e.abimuliawans.p3l_mobile; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; public class CitiesDAO { @SerializedName("id") @Expose public String idCities; @SerializedName("province_id") @Expose public String province_id; @SerializedName("name") @Expose public String nameCities; public CitiesDAO(String idCities, String province_id, String nameCities) { this.idCities = idCities; this.province_id = province_id; this.nameCities = nameCities; } public String getIdCities() { return idCities; } public void setIdCities(String idCities) { this.idCities = idCities; } public String getProvince_id() { return province_id; } public void setProvince_id(String province_id) { this.province_id = province_id; } public String getNameCities() { return nameCities; } public void setNameCities(String nameCities) { this.nameCities = nameCities; } }
Java
UTF-8
330
1.882813
2
[]
no_license
package com.pay.base.Dialect; import org.apache.ibatis.mapping.BoundSql; import org.apache.ibatis.session.Configuration; public abstract class Dialect { public abstract String getBoundSqlForPage(String sql); public abstract void addParameterToBoundSql(Configuration configuration, BoundSql boundSql, int offset, int limit); }
C#
UTF-8
3,986
2.515625
3
[]
no_license
using System; using System.Data.SqlClient; using AdventureWorks2017.Models; namespace AdventureWorks2017.SqlServer.DataAccessObjects { public class ShoppingCartItemDao : AbstractDaoWithPrimaryKey<ShoppingCartItemModel,ShoppingCartItemModelPrimaryKey> { public override string SelectQuery => @"select [ShoppingCartItemID], [ShoppingCartID], [Quantity], [ProductID], [DateCreated], [ModifiedDate] from [Sales].[ShoppingCartItem]"; protected override ShoppingCartItemModel ToModel(SqlDataReader dataReader) { var result = new ShoppingCartItemModel(); result.ShoppingCartItemID = (int)(dataReader["ShoppingCartItemID"]); result.ShoppingCartID = (string)(dataReader["ShoppingCartID"]); result.Quantity = (int)(dataReader["Quantity"]); result.ProductID = (int)(dataReader["ProductID"]); result.DateCreated = (DateTime)(dataReader["DateCreated"]); result.ModifiedDate = (DateTime)(dataReader["ModifiedDate"]); return result; } public override string InsertQuery => @"Insert Into [Sales].[ShoppingCartItem] ( [ShoppingCartID], [Quantity], [ProductID], [DateCreated], [ModifiedDate] ) output inserted.[ShoppingCartItemID] VALUES ( @ShoppingCartID, @Quantity, @ProductID, @DateCreated, @ModifiedDate )"; public override void InsertionGeneratedAutoIdMapping(object id, ShoppingCartItemModel inserted) { inserted.ShoppingCartItemID = (int)id; } public override void InsertionParameterMapping(SqlCommand sqlCommand, ShoppingCartItemModel inserted) { sqlCommand.Parameters.AddWithValue("@ShoppingCartID", inserted.ShoppingCartID); sqlCommand.Parameters.AddWithValue("@Quantity", inserted.Quantity); sqlCommand.Parameters.AddWithValue("@ProductID", inserted.ProductID); sqlCommand.Parameters.AddWithValue("@DateCreated", inserted.DateCreated); sqlCommand.Parameters.AddWithValue("@ModifiedDate", inserted.ModifiedDate); } public override string UpdateQuery => @"Update [Sales].[ShoppingCartItem] Set [ShoppingCartID]=@ShoppingCartID, [Quantity]=@Quantity, [ProductID]=@ProductID, [DateCreated]=@DateCreated, [ModifiedDate]=@ModifiedDate Where [ShoppingCartItemID]=@ShoppingCartItemID "; public override void UpdateParameterMapping(SqlCommand sqlCommand, ShoppingCartItemModel updated) { sqlCommand.Parameters.AddWithValue("@ShoppingCartID", updated.ShoppingCartID); sqlCommand.Parameters.AddWithValue("@Quantity", updated.Quantity); sqlCommand.Parameters.AddWithValue("@ProductID", updated.ProductID); sqlCommand.Parameters.AddWithValue("@DateCreated", updated.DateCreated); sqlCommand.Parameters.AddWithValue("@ModifiedDate", updated.ModifiedDate); } public override void UpdateWhereParameterMapping(SqlCommand sqlCommand, ShoppingCartItemModel updated) { sqlCommand.Parameters.AddWithValue("@ShoppingCartItemID", updated.ShoppingCartItemID); } public override string DeleteQuery => @"delete from [Sales].[ShoppingCartItem] where [ShoppingCartItemID]=@ShoppingCartItemID "; public override void DeleteWhereParameterMapping(SqlCommand sqlCommand, ShoppingCartItemModel deleted) { sqlCommand.Parameters.AddWithValue("@ShoppingCartItemID", deleted.ShoppingCartItemID); } public override string ByPrimaryWhereConditionWithArgs => @"ShoppingCartItemID=@ShoppingCartItemID "; public override void MapPrimaryParameters(ShoppingCartItemModelPrimaryKey key, SqlCommand sqlCommand) { sqlCommand.Parameters.AddWithValue("@ShoppingCartItemID", key.ShoppingCartItemID); } } }
PHP
UTF-8
1,112
2.515625
3
[ "MIT" ]
permissive
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateCartOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('cart_orders', function (Blueprint $table) { $table->id(); $table->string('Bill_Id'); $table->string('serial_id'); $table->string('product_name'); $table->string('product_price'); $table->string('product_category'); $table->string('product_size'); $table->integer('sell_quantity'); $table->integer('sell_discount'); $table->string('image'); $table->string('product_details'); $table->string('Brand_name'); $table->string('user_gmail'); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('cart_orders'); } }
Markdown
UTF-8
610
2.828125
3
[]
no_license
# Face Amidst Beans ## Description: ## Instructions: * Ask audience to see how long it takes them to spot the face within the picture. * It is thought that those who spot the face within 3 seconds have a right-dominant brain. ## The Illusion ![alt text](FaceAmidstBeans.jpg "'Coffee Beans'") ## What Your Brain Is Doing: * Not much...this illusion is simply marked by confusion. The confusing elements and colour play a large role in its deception. ## Why Its Cool * Once you find the face in this coffee beans pile, every next time you look at this picture you will see it immediately!
C++
UTF-8
569
3.28125
3
[]
no_license
#include <iostream> int numbers[2]; int result; bool read_data() { bool flag = true; numbers[0] = numbers[1] = 0; std::cin >> numbers[0]; if (numbers[0] == 0) return false; std::cin >> numbers[1]; if (numbers[0] == 0 || numbers[1] == 0) flag = false; return flag; } void process_data() { result = numbers[1] + numbers[0]; } void write_data() { std::cout << "X = " << result << '\n'; } int main() { bool flag = true; flag = read_data(); while (flag) { process_data(); write_data(); flag = read_data(); } return 0; }
JavaScript
UTF-8
190
2.78125
3
[]
no_license
const {reverse}= require('./reverse'); // Index 2 holds the first actual command line argument let argument = process.argv[2]; console.log(argument); console.log( reverse(argument));
Shell
UTF-8
797
2.53125
3
[]
no_license
#!/bin/bash ## if [ -d /cgroup/cpu/user ]; then ## mkdir -m 0700 /cgroup/cpu/user/wm ## echo $$ > /cgroup/cpu/user/wm/tasks ## echo 2048 > /cgroup/cpu/user/wm/cpu.shares ## fi if [ -e /cgroup/blkio/tasks ]; then mkdir -m 0700 /cgroup/blkio/wm echo $$ > /cgroup/blkio/wm/tasks echo 1000 > /cgroup/blkio/wm/blkio.weight fi export MOZ_DISABLE_PANGO=1 xrdb -merge ~/.Xresources xset m 1/1 xset b off setxkbmap -option terminate:ctrl_alt_bksp pkill -9 -f ssh-agent eval `ssh-agent -s` tint2 & if [ ! -z "$WM_BACKDROP" -a -e "$WM_BACKDROP" ]; then xsetbg "$WM_BACKDROP" & else xsetroot -solid DimGray fi if [ -x ~/dropbox.py ]; then ( ~/dropbox.py running if [ $? = 0 ]; then ~/dropbox.py start fi )& fi exec openbox-session
PHP
UTF-8
2,327
2.5625
3
[]
no_license
<?php namespace FormularioBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\Extension\Core\Type\NumberType; use Symfony\Component\Form\Forms; use Symfony\Component\Form\FormError; use Symfony\Component\Form\Extension\Core\Type\FormType; use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension; class DefaultController extends Controller { public function indexAction(Request $request) { $form = $this->createTestForm(); return $this->render('FormularioBundle:Default:index.html.twig', array( 'formulario' => $form->createView(), )); } public function calculoAction(Request $request){ $form = $this->createTestForm(); $form->handleRequest($request); echo $form->get('numero1')->getData(); if(!is_numeric($form->get('numero1')->getData())){ $form->get('numero1')->addError(new FormError("Debes meter un numero amigo")); } if($form->isSubmitted() && $form->isValid()){ $data = $form->getData(); $resultado = $data['numero1']+$data['numero2']; return $this->redirect($this->generateUrl('formulario_resultado', array( 'dato' => $resultado, ))); } return $this->render('FormularioBundle:Default:index.html.twig', array( 'formulario' => $form->createView(), )); } public function resultadoAction(Request $request, $dato){ return $this->render('FormularioBundle:Default:resultado.html.twig', array( 'dato' => $dato )); } private function createTestForm(){ $formFactory = Forms::createFormFactoryBuilder() ->addExtension(new HttpFoundationExtension()) ->getFormFactory(); return $formFactory->createBuilder(FormType::Class,null,array( 'action' =>$this->generateUrl('formulario_calculo'), 'method' =>'POST')) ->add('numero1',NumberType::class,array( 'required' => true, )) ->add('numero2',TextType::class) ->getForm(); } }
Python
UTF-8
240
2.671875
3
[]
no_license
# print('one game') # temp=input('enter num:') # guess=int(temp) # if guess==8: # print('you good') # print('good no promgrm') # else: # print('you not meeting') # print('game over') # print(dir(__builtins__)) print(help(abs))
JavaScript
UTF-8
8,058
2.890625
3
[]
no_license
/* * Creates an content object * @param url the path to the content file * @param contentBaseUrlParam (optional) the path to the content base, this * is used to change the relative assets paths to absolute paths. if this * param is provided, it will change the assets paths, if it is not, it will * not change the assets paths. */ function createContent(url, contentBaseUrlParam){ return function(url, contentBaseUrlParam){ var url = url; var contentBaseUrl = contentBaseUrlParam; //make sure the contentBaseUrl ends with '/' if(contentBaseUrl != null && contentBaseUrl.charAt(contentBaseUrl.length - 1) != '/') { contentBaseUrl += '/'; } var contentString; var contentXML; var contentJSON; var contentLoaded = false; var MAX_TIME = 30000; var timer; /** * Fires event alert if eventManager exists, alerts message otherwise */ var msg = function(text){ if(typeof notificationManager != 'undefined'){ notificationManager.notify(text,3); } else { alert(text); }; }; /** * If content has been previously loaded, returns the content * in the format of the given type, otherwise, retrieves the * content and then returns the content in the format of the * given type. */ var getContent = function(type){ if(contentLoaded){ return contentType(type); } else { return retrieveContent(type); }; }; /** * returns the content in the format of the given type */ var contentType = function(type){ if(type=='xml'){ return contentXML; } else if(type=='json'){ return contentJSON; } else if(type=='string'){ return contentString; } else { return null; }; }; /** * Makes a synchronous XHR request, parses the response as * string, xml and json (when possible) and returns the content * in the format of the given type. */ var retrieveContent = function(type){ //make synchronous request timer = setTimeout('eventManager.fire("contentTimedOut","' + url + '")',MAX_TIME); var req = new XMLHttpRequest(); req.open('GET', url, false); req.send(null); clearTimeout(timer); //parse the response in various formats if any response format has a value if(req.responseText.match('content="login for portal"') != null) { /* * we received a login page as the response which means the user session has timed out * we will logout the user from the vle */ view.forceLogout(); } else if(req.responseText || req.responseXML){ //xml if(req.responseXML){ contentXML = req.responseXML; } else {//create xmlDoc from string setContentXMLFromString(req.responseText); }; //string if(req.responseText){ contentString = req.responseText; } else {//serialize xml to string if(window.ActiveXObject){ contentString = req.responseXML.xml; } else { contentString = (new XMLSerializer()).serializeToString(req.responseXML); }; }; if(contentBaseUrl != null) { //change the relative assets path to an absolute path contentString = contentString.replace(new RegExp('\"./assets', 'g'), '\"'+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\"/assets', 'g'), '\"'+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\"assets', 'g'), '\"'+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\'./assets', 'g'), '\''+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\'/assets', 'g'), '\''+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\'assets', 'g'), '\''+contentBaseUrl + 'assets'); contentString = contentString.replace(new RegExp('\"url=assets', 'g'), '\"url='+contentBaseUrl + 'assets'); //contentString = contentString.replace(/^\.\/assets|^\/assets|^assets/gi, contentBaseUrl + 'assets'); } //json try{ contentJSON = $.parseJSON(contentString); } catch(e){ contentJSON = undefined; }; //set content loaded contentLoaded = true; //return appropriate response type return contentType(type); } else { msg('Error retrieving content for url: ' + url); return null; }; }; /** * Sets and parses this content object's content */ var setContent = function(content){ //check for different content types and parse to other types as appropriate if(typeof content=='string'){//string contentString = content; setContentXMLFromString(contentString); try{ contentJSON = $.parseJSON(contentString); } catch(e){ contentJSON = undefined; }; } else { if(window.ActiveXObject){//IE if(content.xml){//xml Doc in IE contentXML = content; contentString = content.xml; try{ contentJSON = $.parseJSON(contentString); } catch(e){ contentJSON = undefined; }; } else {//must be object contentJSON = content; try{ contentString = $.stringify(contentJSON); setContentXMLFromString(contentString); } catch(e){ contentJSON = undefined; }; }; } else {//not ie if(content instanceof Document){//xmlDoc contentXML = content; contentString = (new XMLSerializer()).serializeToString(contentXML); try{ contentJSON = $.parseJSON(contentString); } catch(e){ contentJSON = undefined; }; } else {//must be object contentJSON = content; try{ contentString = $.stringify(contentJSON); setContentXMLFromString(contentString); } catch(e){ contentString = undefined; }; }; }; }; //set content loaded contentLoaded = true; }; /** * Returns true if the given xmlDoc does not contain any parsererror * tag in non-IE browsers or the length of xmlDoc.xml is > 0 in IE * browers, returns false otherwise. */ var validXML = function(xml){ if(window.ActiveXObject){//IE if(xml.xml.length==0){ return false; } else { return true; }; } else {//not IE return xml.getElementsByTagName('parsererror').length < 1; }; }; /** * Sets the contentXML variable */ var setContentXMLFromString = function(str){ try { if(document.implementation && document.implementation.createDocument){ contentXML = new DOMParser().parseFromString(str, "text/xml"); } else if(window.ActiveXObject){ contentXML = new ActiveXObject("Microsoft.XMLDOM") contentXML.loadXML(str); }; } catch (exception) { contentXML = undefined; return; } if(!validXML(contentXML)){ contentXML = undefined; }; }; /* Returns the filename for this content given the contentBaseUrl */ var getFilename = function(contentBase){ return url.substring(url.indexOf(contentBase) + contentBase.length + 1, url.length); }; return { /* Returns this content as an xmlDoc if possible, else returns undefined */ getContentXML:function(){return getContent('xml');}, /* Returns this content as a JSON object if possible, else returns undefined */ getContentJSON:function(){return getContent('json');}, /* Returns this content as a string */ getContentString:function(){return getContent('string');}, /* Sets this content given any of: a string, json object, xmlDoc */ setContent:function(content){setContent(content);}, /* Retrieves the content but does not return it (for eager loading) */ retrieveContent:function(){getContent('string');}, /* Returns the url for this content */ getContentUrl:function(){return url;}, /* Returns the filename for this content given the contentBaseUrl */ getFilename:function(contentBase){return getFilename(contentBase);} }; }(url, contentBaseUrlParam); }; //used to notify scriptloader that this script has finished loading if(typeof eventManager != 'undefined'){ eventManager.fire('scriptLoaded', 'vle/content/content.js'); }
Java
UTF-8
4,166
2.6875
3
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package States; import Juego.EnumStates; import org.newdawn.slick.AngelCodeFont; import org.newdawn.slick.Color; import org.newdawn.slick.Font; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.Input; import org.newdawn.slick.SlickException; import org.newdawn.slick.Sound; import org.newdawn.slick.state.BasicGameState; import org.newdawn.slick.state.StateBasedGame; import org.newdawn.slick.state.transition.FadeInTransition; import org.newdawn.slick.state.transition.FadeOutTransition; /** * * @author Roberto */ public class MenuState extends BasicGameState { private Image fondomenu; private Sound opcion; private Sound enter; private Font font; /** * The menu options */ private final String[] options = new String[]{"Comenzar Juego", "Creditos", "Instrucciones", "Salir"}; /** * The index of the selected option */ private int selected; @Override public int getID() { return 1; } @Override public void init(GameContainer container, StateBasedGame game) throws SlickException { fondomenu = new Image("res/images/states/ImagenFondoMenu.png", true); font = new AngelCodeFont("res/fonts/demo2.fnt", "res/fonts/demo2_00.tga"); opcion = new Sound("res/sounds/opcion.wav"); enter = new Sound("res/sounds/enter.wav"); } @Override public void render(GameContainer container, StateBasedGame game, Graphics g) throws SlickException { fondomenu.draw(); g.setFont(font); g.setColor(Color.yellow); for (int i = 0; i < options.length; i++) { g.drawString(options[i], 400 - (font.getWidth(options[i]) / 2), 200 + (i * 50)); if (selected == i) { g.drawRect(200, 190 + (i * 50), 400, 50); } } } @Override public void update(GameContainer container, StateBasedGame sbg, int delta) throws SlickException { if (container.getInput().isKeyPressed(Input.KEY_H)) { sbg.enterState(EnumStates.INSTRUCCIONES.ordinal(), new FadeOutTransition(), new FadeInTransition()); } if (container.getInput().isKeyPressed(Input.KEY_P)) { sbg.enterState(EnumStates.PAUSA.ordinal(), new FadeOutTransition(), new FadeInTransition()); } if (container.getInput().isKeyPressed(Input.KEY_ESCAPE)) { sbg.enterState(EnumStates.MENU.ordinal(), new FadeOutTransition(), new FadeInTransition()); } if (container.getInput().isKeyPressed(Input.KEY_0)) { sbg.enterState(EnumStates.GAMEOVER.ordinal(), new FadeOutTransition(), new FadeInTransition()); } if (container.getInput().isKeyPressed(Input.KEY_ENTER)) { enter.play(); switch (selected) { case 0: sbg.enterState(EnumStates.GAME.ordinal(), new FadeOutTransition(), new FadeInTransition()); break; case 1: sbg.enterState(EnumStates.CREDITOS.ordinal(), new FadeOutTransition(), new FadeInTransition()); break; case 2: sbg.enterState(EnumStates.INSTRUCCIONES.ordinal(), new FadeOutTransition(), new FadeInTransition()); break; case 3: container.exit(); default: break; } } } @Override public void keyReleased(int key, char c) { if (key == Input.KEY_DOWN) { opcion.play(); selected++; if (selected >= options.length) { selected = 0; } } if (key == Input.KEY_UP) { opcion.play(); selected--; if (selected < 0) { selected = options.length - 1; } } } }
C++
UTF-8
419
3.0625
3
[]
no_license
#include "header.h" long long int potencia(long int, long int); //función recursiva long long int hashing(long int key) { long long int num1, res; num1 = ((key / 1000) + 1) / 2; res = (potencia(key,num1) / 100); res = res % 100; return res; } long long int potencia(long int x, long int y) { if (y==0) return 1; else return x*(potencia(x,y-1)); }
C++
UTF-8
392
2.9375
3
[]
no_license
#include "Arduino.h" #include "led.h" void initializeLED() { pinMode(LED_PIN, OUTPUT); } void blinkLED (int numberOfTimes, int delayTime) { int i; for (i = 0; i < numberOfTimes; i++) { Serial.print("LED Flashing.."); Serial.print(" "); Serial.println(i); digitalWrite(LED_PIN, HIGH); delay(delayTime); digitalWrite(LED_PIN, LOW); delay(delayTime); } }
Python
UTF-8
497
3.328125
3
[]
no_license
''' Created on 2017. 10. 11. @author: jihye ''' import turtle def draw_rectangle(x,y,w,h,edge_color='black',fill_color=''): mypen=turtle.Turtle() mypen.begin_fill() mypen.pencolor(edge_color) mypen.fillcolor(fill_color) mypen.penup() mypen.goto(x,y) mypen.pendown() mypen.forward(w) mypen.left(90) mypen.forward(h) mypen.left(90) mypen.forward(w) mypen.left(90) mypen.forward(h) mypen.end_fill() mypen.hideturtle()
SQL
ISO-8859-1
937
3.484375
3
[]
no_license
-- No puede haber dos o ms rallies con el mismo nombre. ALTER TABLE RALLY ADD CONSTRAINT rallyNombreUnico UNIQUE(nombre); -- El nmero de kilmetros de los que consta un tramo siempre tiene que ser mayor o igual que 20. ALTER TABLE TRAMO ADD CONSTRAINT tramoKmsValido CHECK(totalKms > 20); -- La fecha de celebracin de un rallie debe estar comprendida en 2009 ALTER TABLE RALLY ADD CONSTRAINT rallyFechaValida CHECK(Fecha > to_date('01/01/2009', 'dd/mm/yyyy') AND Fecha < to_date('31/12/2009', 'dd/mm/yyyy')); -- En un rallie no puede haberdos tramos de igual longitud. ALTER TABLE TRAMO ADD CONSTRAINT tramoLongitudesNoIguales UNIQUE(codRally, totalKms); -- Al borrar un rally de la tabla RALLY se deben borrar adems todos los tramos de los que consta dicho rally. ALTER TABLE TRAMO DROP CONSTRAINT tramoAjena; ALTER TABLE TRAMO ADD CONSTRAINT tramoAjena FOREIGN KEY (codRally) REFERENCES RALLY (codRally) ON DELETE CASCADE;
Ruby
UTF-8
1,955
3.515625
4
[]
no_license
# Write a SQL query to get the second highest salary from the Employee table. # +----+--------+ # | Id | Salary | # +----+--------+ # | 1 | 100 | # | 2 | 200 | # | 3 | 300 | # +----+--------+ # For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. # +---------------------+ # | SecondHighestSalary | # +---------------------+ # | 200 | # +---------------------+ SELECT (SELECT DISTINCT salary FROM employee ORDER BY salary DESC LIMIT 1 OFFSET 1) AS SecondHighestSalary # -------------------------------- # Given a table salary, such as the one below, that has m=male and f=female values. Swap all f and m values (i.e., change all f values to m and vice versa) with a single update query and no intermediate temp table. # For example: # | id | name | sex | salary | # |----|------|-----|--------| # | 1 | A | m | 2500 | # | 2 | B | f | 1500 | # | 3 | C | m | 5500 | # | 4 | D | f | 500 | # After running your query, the above salary table should have the following rows: # | id | name | sex | salary | # |----|------|-----|--------| # | 1 | A | f | 2500 | # | 2 | B | m | 1500 | # | 3 | C | f | 5500 | # | 4 | D | m | 500 | UPDATE salary SET sex = CASE sex WHEN 'm' THEN 'f' ELSE 'm' END # ---------------------------------- # Write a SQL query to find all duplicate emails in a table named Person. # +----+---------+ # | Id | Email | # +----+---------+ # | 1 | a@b.com | # | 2 | c@d.com | # | 3 | a@b.com | # +----+---------+ # For example, your query should return the following for the above table: # +---------+ # | Email | # +---------+ # | a@b.com | # +---------+ SELECT Email FROM Person GROUP BY Email HAVING COUNT(Email) > 1
JavaScript
UTF-8
1,097
3.9375
4
[]
no_license
/* Callbacks In javascript, a callback is simply a function that is passed to another function as a parameter and is invoked or executed inside the other function. Here a function needs to wait for another function to execute or return value and this makes the chain of the functionalities (when X is completed, then Y executed, and it goes on.). This is the reason callback is generally used in the asynchronous operation of javascript to provide the synchronous capability. */ const Greeting = (name) => { console.log(`Hello ${name}`); } const ProcessUserName = (callback) =>{ name="Greeks Frook"; callback(name); } ProcessUserName(Greeting); /* In the above example notice that Greeting passed as an argument (callback) to the ‘processUserName’ function. Before the ‘greeting’ function executed it waits for the event ‘processUserName’ to execute first. */ /* for 1000 -20 , 100-2 */ var today =new Date(); var year = `${today.getDay()}-${today.getMonth()}-${today.getFullYear()}`; var time = `${today.getHours()}:${today.getMinutes()} ${ampm}`; console.log(time)
Go
UTF-8
3,120
2.8125
3
[]
no_license
package sqlite import ( "context" "database/sql" "errors" "fmt" "time" "github.com/itiky/charge_scheduler/schema" ) func (s EventsStorage) GetSingleEvent(ctx context.Context, id int64) (retObj *schema.SingleEvent, retErr error) { dbObj := singleEvent{} err := s.Db.GetContext(ctx, &dbObj, "SELECT rowid, type, start_date_time, end_hours, end_minutes, created_at FROM single_events WHERE rowid=?", id) if err != nil { if errors.Is(err, sql.ErrNoRows) { return } retErr = fmt.Errorf("s.Db.GetContext: %w", err) return } obj, err := dbObj.ToSchema() if err != nil { retErr = fmt.Errorf("obj unmarshal: %w", err) return } retObj = &obj return } func (s EventsStorage) GetSingleEventsWithinRange(ctx context.Context, rangeStart, rangeEnd time.Time) (retObjs []schema.SingleEvent, retErr error) { var dbObjs []singleEvent err := s.Db.SelectContext(ctx, &dbObjs, "SELECT rowid, type, start_date_time, end_hours, end_minutes, created_at FROM single_events WHERE start_date_time >= ? AND start_date_time <= ?", rangeStart, rangeEnd) if err != nil { if errors.Is(err, sql.ErrNoRows) { return } retErr = fmt.Errorf("s.Db.SelectContext: %w", err) return } objs, err := s.unmarshalSingleEvents(dbObjs) if err != nil { retErr = err return } return objs, nil } func (s EventsStorage) GetPeriodicEvent(ctx context.Context, id int64) (retObj *schema.PeriodicEvent, retErr error) { dbObj := periodicEvent{} err := s.Db.GetContext(ctx, &dbObj, "SELECT rowid, type, rrule, end_hours, end_minutes, created_at FROM periodic_events WHERE rowid=?", id) if err != nil { if errors.Is(err, sql.ErrNoRows) { return } retErr = fmt.Errorf("s.Db.GetContext: %w", err) return } obj, err := dbObj.ToSchema() if err != nil { retErr = fmt.Errorf("obj unmarshal: %w", err) return } retObj = &obj return } func (s EventsStorage) GetAllPeriodicEvents(ctx context.Context) (retObjs []schema.PeriodicEvent, retErr error) { var dbObjs []periodicEvent err := s.Db.SelectContext(ctx, &dbObjs, "SELECT rowid, type, rrule, end_hours, end_minutes, created_at FROM periodic_events") if err != nil { if errors.Is(err, sql.ErrNoRows) { return } retErr = fmt.Errorf("s.Db.SelectContext: %w", err) return } objs, err := s.unmarshalPeriodicEvents(dbObjs) if err != nil { retErr = err return } return objs, nil } func (s EventsStorage) unmarshalSingleEvents(dbObjs []singleEvent) (retObjs []schema.SingleEvent, retErr error) { retObjs = make([]schema.SingleEvent, 0, len(dbObjs)) for i, dbObj := range dbObjs { obj, err := dbObj.ToSchema() if err != nil { retErr = fmt.Errorf("dbObj[%d] unmarshal: %w", i, err) return } retObjs = append(retObjs, obj) } return } func (s EventsStorage) unmarshalPeriodicEvents(dbObjs []periodicEvent) (retObjs []schema.PeriodicEvent, retErr error) { retObjs = make([]schema.PeriodicEvent, 0, len(dbObjs)) for i, dbObj := range dbObjs { obj, err := dbObj.ToSchema() if err != nil { retErr = fmt.Errorf("dbObj[%d] unmarshal: %w", i, err) return } retObjs = append(retObjs, obj) } return }
Java
UTF-8
708
2.46875
2
[ "Apache-2.0" ]
permissive
package controllers; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; public class LogoutController implements FrontController{ @Override public void process(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { HttpSession session = request.getSession(); if(session != null) { session.invalidate(); response.sendRedirect("static/index.html"); } else { response.sendError(HttpServletResponse.SC_NOT_FOUND); } } }
C++
UTF-8
4,985
2.96875
3
[]
no_license
#include "johnchess_app.h" #include <stdexcept> JohnchessApp::JohnchessApp(int argc, const char* argv[]) : m_app_opts(NULL), m_force_mode(false) { m_app_opts = parse_args(argc, argv); m_xboard_interface = new XBoardInterface(get_input_stream(), get_output_stream(), "Johnchess v0.1"); m_xboard_interface->add_feature("memory=1"); m_xboard_interface->add_feature("setboard=0"); m_xboard_interface->add_feature("ping=1"); m_xboard_interface->add_variant("normal"); show_welcome(); m_board = new Board(8, 8); m_ai = new RandomAI(Piece::BLACK); } JohnchessApp::~JohnchessApp() { if (m_app_opts) delete m_app_opts; delete m_xboard_interface; delete m_board; delete m_ai; } void JohnchessApp::make_ai_move() { std::string move_string = m_ai->make_move(m_board).to_string(); if(!m_board->move_piece(move_string)) throw std::runtime_error("AI seems to have generated a nonsense move"); m_xboard_interface->send_move(move_string); } void JohnchessApp::main_loop() { bool finished = false; while(!finished) { XBoardInterface::CommandReceived rcvd = m_xboard_interface->wait_for_command(); if (rcvd.is_invalid()){ m_xboard_interface->reply_invalid(rcvd); continue; } switch(rcvd.get_type()) { case XBoardInterface::CommandReceived::MOVE: { Piece::Colour colour_to_move = m_board->get_colour_to_move(); if(!m_board->move_piece(rcvd.get_move_string())) m_xboard_interface->reply_illegal_move(rcvd); else { if(!m_force_mode) { make_ai_move(); } } Board::Mate mate = m_board->get_mate(colour_to_move); if(mate != Board::NO_MATE) { if(mate == Board::STALEMATE) { // Do something for stalemate std::cout << "Stalemate" << std::endl; } else //if mate == Board::CHECKMATE { // Do something for checkmate std::cout << "Checkmate" << std::endl; } } break; } case XBoardInterface::CommandReceived::INFO_REQ: m_xboard_interface->reply_features(); break; case XBoardInterface::CommandReceived::INIT: m_xboard_interface->reply_newline(); break; case XBoardInterface::CommandReceived::PING: m_xboard_interface->reply_ping(rcvd); break; case XBoardInterface::CommandReceived::NEW: m_board->set_to_start_position(); break; case XBoardInterface::CommandReceived::MEMORY: // set max memory case XBoardInterface::CommandReceived::LEVEL: // set level case XBoardInterface::CommandReceived::POST: // set output pondering mode case XBoardInterface::CommandReceived::HARD: // set hard mode case XBoardInterface::CommandReceived::RANDOM: // set random mode case XBoardInterface::CommandReceived::TIME: case XBoardInterface::CommandReceived::OTIM: case XBoardInterface::CommandReceived::NONE: break; case XBoardInterface::CommandReceived::FORCE: m_force_mode = true; break; case XBoardInterface::CommandReceived::QUIT: finished = true; break; case XBoardInterface::CommandReceived::EDIT: m_board->set_from_edit_mode(m_xboard_interface->read_edit_mode()); break; case XBoardInterface::CommandReceived::GO: m_force_mode = false; // if there are 0 params, this is an immediate go (alternatively it's playother) if (rcvd.get_params().size() == 0) { make_ai_move(); } break; } } } void JohnchessApp::show_welcome() { m_xboard_interface->tell_info(" Johnchess 0.1"); m_xboard_interface->tell_info(" by John Wilson"); } std::istream& JohnchessApp::get_input_stream() { if (m_app_opts->in_stream) return *m_app_opts->in_stream; return std::cin; } std::ostream& JohnchessApp::get_output_stream() { if (m_app_opts->out_stream) return *m_app_opts->out_stream; return std::cout; } JohnchessApp::app_opts_t* JohnchessApp::parse_args(int argc, const char* argv[]) { JohnchessApp::app_opts_t *opts = new JohnchessApp::app_opts_t; return opts; }
SQL
UTF-8
3,353
3.515625
4
[ "Apache-2.0" ]
permissive
library OpioidCDSREC12 version '2.0.0' using FHIR version '4.0.0' include FHIRHelpers version '4.0.0' called FHIRHelpers include OpioidCDSCommon version '2.0.0' called Common include OpioidCDSCommonConfig version '2.0.0' called Config /* ** ** Recommendation #12 ** Clinicians should offer or arrange evidence-based treatment (usually ** medication-assisted treatment with buprenorphine or methadone in combination ** with behavioral therapies) for patients with opioid use disorder ** (recommendation category: A, evidence type: 2) ** ** When ** Patient is 18 years and older and not receiving evidence-based treatment for opioid use disorder, which may include medication treatment with buprenorphine or methadone, or opioid-specific behavioral counseling ** Patient has a diagnosis of opioid use disorder in the past 90 days ** Then ** Recommend opioid agonist or partial agonist treatment with methadone maintenance therapy, buprenorphine therapy, and/or behavioral therapy. Potential actions include: ** Order methadone or buprenorphine ** Refer to qualified treatment provider (i.e. substance disorder specialist) ** N/A - see comment; snooze 3 months ** */ // META: PlanDefinition: http://fhir.org/guides/cdc/opioid-cds-r4/PlanDefinition/opioid-cds-12 context Patient define "Opioid Use Disorder Lookback Period": Interval[Today() - 90 days, Today()] define "Is Recommendation Applicable?": "Inclusion Criteria" and not "Exclusion Criteria" define "Inclusion Criteria": "Patient 18 or Older?" and "Not Receiving Evidence-Based Treatment for Opioid Use Disorder" and "Presence of Diagnosis of Opioid Use Disorder" and "Positive Result from Opioid Use Disorder Evaluation Tool" define "Exclusion Criteria": false define "Patient 18 or Older?": Config."Age Less than 18 Years Is Enabled" and AgeInYears() >= 18 define "Not Receiving Evidence-Based Treatment for Opioid Use Disorder": Config."Evidence Based Treatment Criteria For Opioid Use Disorder" and not ( exists ( [MedicationRequest: Common."Buprenorphine and methadone medications"] MR where MR.status in { 'active', 'completed' } and date from MR.authoredOn during day of "Opioid Use Disorder Lookback Period" ) or exists ( [Procedure: Common."Substance misuse behavioral counseling"] P where P.status ~ 'completed' and P.performed during day of "Opioid Use Disorder Lookback Period" ) ) define "Presence of Diagnosis of Opioid Use Disorder": exists ( [Condition: Common."Opioid misuse disorders"] C where exists ( C.clinicalStatus.coding Coding where FHIRHelpers.ToCode(Coding) ~ Common."Active Condition" ) and date from C.recordedDate during day of "Opioid Use Disorder Lookback Period" ) define "Positive Result from Opioid Use Disorder Evaluation Tool": true define "Get Indicator": if "Is Recommendation Applicable?" then 'warning' else null define "Get Summary": if "Is Recommendation Applicable?" then 'Recommend opioid agonist or partial agonist treatment with methadone maintenance therapy or buprenorphine and/or behavioral therapy' else null define "Get Detail": if "Is Recommendation Applicable?" then null else null
Python
UTF-8
183
3.0625
3
[]
no_license
#!/usr/bin/python3 # -*- coding: UTF-8 -*- # filename:while.py # author: shuqing i = 0 while i < 10: print(i) i += 2 j = 0 while j in range(1, 9): print(j) j += 1
C#
UTF-8
486
2.96875
3
[]
no_license
 namespace TowerDefenseSpel { /// <summary> /// base class for all objects in the game. /// </summary> class Gameobject { protected int x; protected int y; public Gameobject(int x,int y) { this.x = x; this.y = y; } #region Attributes public int X { get { return x; } set { x = value; } } public int Y { get { return y; } set { y = value; } } #endregion } }
Markdown
UTF-8
4,248
3.59375
4
[]
no_license
# Using Word2Vec to analyze Reddit Comments The Blog Post for this Repository can be viewed here on Medium: https://medium.com/ml-2-vec/using-word2vec-to-analyze-reddit-comments-28945d8cee57 In this post, I am going to go over Word2Vec. I will talk about some background of what the algorithm is, and how it can be used to generate Word Vectors from. Then, I will walk through the code for training a Word2Vec model on the Reddit comments dataset, and exploring the results from it. What is Word2Vec? Word2Vec is an algorithm that generates Vectorized representations of words, based on their linguistic context. These Word Vectors are obtained by training a Shallow Neural Network (single hidden layer) on individual words in a text, and given surrounding words as the label to predict. By training a Neural Network on the data, we update the weights of the Hidden layer, which we extract at the end as the word vectors. To understand Word2Vec, let’s walk through it step by step. The input of the algorithm is text data, so for a string of sentences, the training data will consist of individual sentences, paired with the contextual words we are trying to predict. Let’s look at the following diagram (from Chris McCormick’s blog): ![](https://cdn-images-1.medium.com/max/1600/1*yiH5sZI-IBxDSQMKhvbcHw.png) We use a sliding window over the text, and for each “target word” in the set, we pair it with an adjacent word to obtain an x-y pair. In this case, the window size (denoted as C ) is 4, so there are 2 words on each side, except for edge words. The input words are then processed into one-hot vectors. One-hot vectors are a vectorial representation of data, in which we use a large vector of zeros which correspond to each word in the vocabulary, and set the position corresponding to the target word to 1. In this case, we have a total of V words, so each vector will be of V length, and will have the index corresponding to it’s position set to 1. In the example above, the vector corresponding to the last sentence will be 0 0 0 1 0 0 0 0, because the word “fox” is the 4th word in the vocabulary, and there are 8 words (counting “the” once). Having obtained the input, the next step is to design the Neural Network. Word2Vec is a shallow network, which means that there is a single-hidden layer in it. A traditional neural network diagram looks like this: ![](https://cdn-images-1.medium.com/max/1600/1*UA30b0mJUPYoPvN8yJr2iQ.jpeg) In the above diagram, the input data is fed through the Neural Network by applying the weight vectors and bias units. What this means is that for each x, we obtain the output as: ![](https://cdn-images-1.medium.com/max/1600/1*T3hoaDJPgF8yYc3HOIbPNw.gif) Neural Networks are trained iteratively, which means that once we do the forward calculation of y, we update the weight vectors w and bias units b with backwards calculation of how much they change w.r.t. error of prediction. Here are the update equations, although I will not be going over the actual derivation of backpropagation in this post: ![](https://cdn-images-1.medium.com/max/1600/1*cS9yeLKYsy2wS8W1EuNY-Q.gif) Let’s look at the Neural Network diagram of Word2Vec now: ![](https://cdn-images-1.medium.com/max/1600/1*uioavf2lFp7lJzT_lBaYKg.png) The above diagram summarizes the Word2Vec model well. We take as input one-hot vectorized representations of the words, applying W1 (and b1) to obtain the hidden layer representations, then feeding them again through a W2 and b2 , and applying a SoftMax activation to obtain the probabilities of the target word and each of their associated y values. However, we need Word2Vec to obtain vectorial representations of the input words. By training the model on the target words and their surrounding labels, we are updating the values of the hidden layer iteratively to the point where the cost (or the difference between the prediction and actual label) is minimum. Once the model has been trained, we extract this hidden representation as the Word Vector of the word, as there is a 1-to-1 correspondence between each. The size of the hidden units h is also an important consideration here, since it decides the length of the hidden layer representation for each word.
Swift
UTF-8
409
3.765625
4
[]
no_license
// 10-11 class Baby { var name: String var age: Int init?(name: String, age: Int) { if age < 0 { return nil } self.name = name self.age = age } } var cuteBaby = Baby(name: "小彼得", age: -1) if let cuteBaby = Baby(name: "小彼得", age: -1) { print("\(cuteBaby.age)歲的\(cuteBaby.name)") } else { print("生寶寶失敗") }
PHP
UTF-8
1,906
2.90625
3
[]
no_license
<?php /** * qFW - quick Framework, an PHP 7.2 Framework for speedup website development * * @mantainer Giovanni Manzoni (https://giovannimanzoni.com) * @license GNU GENERAL PUBLIC LICENSE Version 3 * */ declare(strict_types=1); namespace qFW\mvc\model\crypto\uniqid; /** * Class Uniqid * * -> http://php.net/manual/en/function.uniqid.php * -> https://stackoverflow.com/questions/38716613/generate-a-single-use-token-in-php-random-bytes-or-openssl-random-pseudo-bytes * * @package App\external\qFW\src\mvc\model\crypto\uniqid */ class Uniqid { /** * Uniqid constructor. */ public function __construct() { } /** * @param int $lenght * * @return string */ public function get($lenght = 13): string { try { $bytes = random_bytes((int)ceil($lenght / 2)); $ret = substr(bin2hex($bytes), 0, $lenght); } catch (\Exception $e) { if ($lenght > 13) { $moreEntropy = true; } else { $moreEntropy = false; } $ret = uniqid('', $moreEntropy); // cut only if generate string is > of cutting lenght if (($lenght != 13) && (($lenght < 22) && $moreEntropy)) { $ret = substr($ret, 0, $lenght); if ($moreEntropy) { $ret = str_replace('.', '', $ret); } } else { // Could not cut; add more characters do { usleep(100); $ret .= uniqid('', true); $ret = str_replace('.', '', $ret); } while ($ret < $lenght); //Cut $ret = substr($ret, 0, $lenght); $_SESSION['adminLog'] .= "Was not possible to gather sufficient entropy for random_bytes() : $e"; } } return $ret; } }
PHP
UTF-8
1,065
2.90625
3
[]
no_license
<?php $db_user = 'student'; $db_pass = 'pass.mysql'; $dbname = 'leveric'; $db_base = 'mysql:host=rp2.studenti.math.hr;dbname=' . $dbname . ';charset=utf8'; class DB { private static $db = null; final private function __construct() { } final private function __clone() { } public static function getConnection() { // Ako još nismo spajali na bazu, uspostavi konekciju. if (DB::$db === null) { global $db_base, $db_user, $db_pass; try { DB::$db = new PDO($db_base, $db_user, $db_pass); // Ako želimo da funkcije poput prepare, execute bacaju exceptione: DB::$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); DB::$db->setAttribute(PDO::ATTR_EMULATE_PREPARES, false); } catch (PDOException $e) { exit('Greška prilikom spajanja na bazu:' . $e->getMessage()); } } // Vrati novostvorenu ili od ranije postojeću konekciju. return DB::$db; } };
PHP
UTF-8
11,827
2.625
3
[]
no_license
<?php $config = null; function load_config(&$config) { $config = simplexml_load_file(__DIR__ . '/etc/config.xml'); } load_config($config); const THUMBNAIL_IMAGE_MAX_WIDTH = 150; const THUMBNAIL_IMAGE_MAX_HEIGHT = 150; const LIMIT = 500; const TYPE_NEW = 1; const TYPE_UPD = 2; const TYPE_DEL = 3; require_once __DIR__ . '/db.php'; require_once __DIR__ . '/cache.php'; /** * @param $source_image_path * @param $thumbnail_image_path * @return string */ function generate_image_thumbnail($source_image_path, $thumbnail_image_path) { list($source_image_width, $source_image_height, $source_image_type) = getimagesize($source_image_path); $source_gd_image = false; switch ($source_image_type) { case IMAGETYPE_GIF: $source_gd_image = imagecreatefromgif($source_image_path); break; case IMAGETYPE_JPEG: $source_gd_image = imagecreatefromjpeg($source_image_path); break; case IMAGETYPE_PNG: $source_gd_image = imagecreatefrompng($source_image_path); break; } if ($source_gd_image === false) { return false; } $source_aspect_ratio = $source_image_width / $source_image_height; $thumbnail_aspect_ratio = THUMBNAIL_IMAGE_MAX_WIDTH / THUMBNAIL_IMAGE_MAX_HEIGHT; if ($source_image_width <= THUMBNAIL_IMAGE_MAX_WIDTH && $source_image_height <= THUMBNAIL_IMAGE_MAX_HEIGHT) { $thumbnail_image_width = $source_image_width; $thumbnail_image_height = $source_image_height; } elseif ($thumbnail_aspect_ratio > $source_aspect_ratio) { $thumbnail_image_width = (int) (THUMBNAIL_IMAGE_MAX_HEIGHT * $source_aspect_ratio); $thumbnail_image_height = THUMBNAIL_IMAGE_MAX_HEIGHT; } else { $thumbnail_image_width = THUMBNAIL_IMAGE_MAX_WIDTH; $thumbnail_image_height = (int) (THUMBNAIL_IMAGE_MAX_WIDTH / $source_aspect_ratio); } $thumbnail_gd_image = imagecreatetruecolor($thumbnail_image_width, $thumbnail_image_height); imagecopyresampled($thumbnail_gd_image, $source_gd_image, 0, 0, 0, 0, $thumbnail_image_width, $thumbnail_image_height, $source_image_width, $source_image_height); $tmp_thumbnail_image_path = $thumbnail_image_path . DIRECTORY_SEPARATOR .'tmp' . DIRECTORY_SEPARATOR . time(); imagejpeg($thumbnail_gd_image, $tmp_thumbnail_image_path, 90); $hash = md5_file($tmp_thumbnail_image_path); $name = $hash . '.jpeg'; $thumbnail_image_path = $thumbnail_image_path . DIRECTORY_SEPARATOR . 'thumbnail' . DIRECTORY_SEPARATOR . $name; if (!file_exists($thumbnail_image_path)) { copy($tmp_thumbnail_image_path, $thumbnail_image_path); } unlink($tmp_thumbnail_image_path); imagedestroy($source_gd_image); imagedestroy($thumbnail_gd_image); return $name; } /** * @return bool|string */ function upload_file() { if (empty($_FILES['img']['tmp_name'])) { return false; } $dir = __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'media'; $name = generate_image_thumbnail($_FILES['img']['tmp_name'], $dir); return $name; } /** * @param $name * @return string */ function get_img_url($name) { return sprintf('media/thumbnail/%s', $name); } /** * init */ function init() { global $config; if (!(int)$config->app->installed) { header('Location: install.php'); } session_start(); if (!empty($_GET['s'])) { $_SESSION['s'] = get_sort_field($_GET['s']); } if (!empty($_GET['o'])) { $_SESSION['o'] = get_order($_GET['o']); } if (empty($_SESSION['s'])) { $_SESSION['s'] = 'id'; } if (empty($_SESSION['o'])) { $_SESSION['o'] = 'ASC'; } session_write_close(); } /** * @param $offset * @return array|mixed */ function load_products($offset) { $cache = cache_connect(); $key = get_cache_key($offset); $data = get_cache_data($cache, $key); if (!$data) { $connection = open_connection(); $data = get_products($connection, get_session_sort(), get_session_order(), LIMIT, $offset * LIMIT); if ($data) { set_cache_data($cache, $key, $data); } } return $data; } /** * @param $offset * @param $sort * @param $order * @param bool $cache * @param bool $connection * @param int $i * @param array $idxData * @return bool */ function warm_products($offset, $sort, $order, $cache = false, $connection = false, $i = 0, &$idxData = array()) { if (!$cache) { $cache = cache_connect(); } if (!$connection) { $connection = open_connection(); } $key = sprintf('%s_%s_%s', $sort, $order, $offset); $data = get_products($connection, $sort, $order, LIMIT, $offset * LIMIT); if ($data) { set_cache_data($cache, $key, $data); echo sprintf("%s - rebuilded \r\n", $key); $first = $data[0]; $last = $data[count($data) - 1]; if ($sort == 'price') { $idxData[] = array( 'min' => $order == 'ASC' ? $first['price'] : $last['price'], 'max' => $order == 'ASC' ? $last['price'] : $first['price'], 'key' => $offset ); } else { $idxData[] = array( 'min' => $order == 'ASC' ? $first['id'] : $last['id'], 'max' => $order == 'ASC' ? $last['id'] : $first['id'], 'key' => $offset ); } warm_products($offset + 1, $sort, $order, $cache, $connection, ++$i, $idxData); } else { return false; } if ($sort == 'price') { insert_price_idx($order, $idxData); } else { insert_id_idx($order, $idxData); } } /** * @param $order * @param $data */ function insert_price_idx($order, $data) { $table = 'price_idx_' . strtolower($order); insert_idx($data, $table); } /** * @param $order * @param $data */ function insert_id_idx($order, $data) { $table = 'id_idx_' . strtolower($order); insert_idx($data, $table); } /** * @param $data * @param $table */ function insert_idx($data, $table) { mysql_query('truncate table ' . $table); $full = ''; foreach ($data as $idxD) { $valStr = '(' . implode(',', $idxD) . ')'; if ($full) { $full = $full . ',' . $valStr; } else { $full = $valStr; } } $sql = 'INSERT INTO ' . $table . ' (`min`, `max`, `key`) VALUES ' . $full; mysql_query($sql); } /** * @return string */ function get_session_sort() { if (!empty($_SESSION['s'])) { return get_sort_field($_SESSION['s']); } return 'id'; } /** * @return string */ function get_session_order() { if (!empty($_SESSION['o'])) { return get_order($_SESSION['o']); } return 'ASC'; } /** * @param $sort * @return string */ function get_sort_field($sort) { if ($sort === 'p' || $sort === 'price') { $sort = 'price'; } else { $sort = 'id'; } return $sort; } /** * @param $order * @return string */ function get_order($order) { if ($order === 'a' || $order === 'ASC') { $order = 'ASC'; } else { $order = 'DESC'; } return $order; } /** * @param $cache * @param $connection * @param $price * @param $id * @param $type */ function update_cache($cache, $connection, $price, $id, $type) { update_id_asc($cache, $connection, $id, $type); update_id_desc($cache, $connection, $id, $type); update_price_asc($price, $cache, $connection, $type); update_price_desc($price, $cache, $connection, $type); } /** * @param $key * @param $cache * @param $connection * @param $sort * @param $order * @param $type * @param int $offset * @return bool */ function update_single_key($key, $cache, $connection, $sort, $order, $type, $offset = 0) { $d = get_cache_data($cache, $key); $d = count($d); switch ($type) { case TYPE_NEW: ++$d; break; case TYPE_DEL: --$d; break; } $data = get_products($connection, $sort, $order, $d, $offset); if ($data) { set_cache_data($cache, $key, $data); if (!isset($_SERVER['REQUEST_METHOD'])) { printf("%s - rebuilded \r\n", $key); } } else { return false; } } /** * @param $cache * @param $connection * @param $id * @param $type */ function update_id_desc($cache, $connection, $id, $type) { if ($type == TYPE_NEW) { $key = sprintf('%s_%s_%s', 'id', 'DESC', 0); update_single_key($key, $cache, $connection, 'id', 'DESC', $type); } else { $k = get_id_cache_key($id, 'desc'); $key = sprintf('%s_%s_%s', 'id', 'DESC', $k); update_single_key($key, $cache, $connection, 'id', 'DESC', $type, $k * LIMIT); } } /** * @param $cache * @param $connection * @param $id * @param $type */ function update_id_asc($cache, $connection, $id, $type) { if ($type == TYPE_NEW) { $total = get_total_keys($connection); $t = $total - 1; if ($t < 0) { $t = 0; } warm_products($t, 'id', 'ASC', $cache); } else { $k = get_id_cache_key($id, 'asc'); $key = sprintf('%s_%s_%s', 'id', 'ASC', $k); update_single_key($key, $cache, $connection, 'id', 'ASC', $type, $k * LIMIT); } } /** * @param $price * @param $cache * @param $connection * @param $type */ function update_price_asc($price, $cache, $connection, $type) { $k = get_price_cache_key($price, 'asc'); $key = sprintf('%s_%s_%s', 'price', 'ASC', $k); update_single_key($key, $cache, $connection, 'price', 'ASC', $type, $k * LIMIT); } /** * @param $price * @param $cache * @param $connection * @param $type */ function update_price_desc($price, $cache, $connection, $type) { $k = get_price_cache_key($price, 'desc'); $key = sprintf('%s_%s_%s', 'price', 'DESC', $k); update_single_key($key, $cache, $connection, 'price', 'DESC', $type, $k * LIMIT); } /** * @param $id * @param $order * @return bool|int */ function get_id_cache_key($id, $order) { $sql = 'SELECT `key` from price_idx_' . strtolower($order) . ' WHERE `max` > ' . $id . ' ORDER BY `key` ' . $order . ' limit 1'; $result = mysql_query($sql); $key = false; if ($result) { while ($row = mysql_fetch_assoc($result)) { $key = $row['key']; break; } } if($key === false) { if ($order == 'asc') { $sql = 'SELECT `key` from price_idx_' . strtolower($order) . ' ORDER BY `key` DESC limit 1'; $result = mysql_query($sql); if ($result) { while ($row = mysql_fetch_assoc($result)) { $key = $row['key']; break; } } } else { $key = 0; } } return $key; } /** * @param $price * @param $order * @return bool|int */ function get_price_cache_key($price, $order) { $sql = 'SELECT `key` from price_idx_' . strtolower($order) . ' WHERE `max` > ' . $price . ' ORDER BY `key` ' . $order . ' limit 1'; $result = mysql_query($sql); $key = false; if ($result) { while ($row = mysql_fetch_assoc($result)) { $key = $row['key']; break; } } if($key === false) { if ($order == 'asc') { $sql = 'SELECT `key` from price_idx_' . strtolower($order) . ' ORDER BY `key` DESC limit 1'; $result = mysql_query($sql); if ($result) { while ($row = mysql_fetch_assoc($result)) { $key = $row['key']; break; } } } else { $key = 0; } } return $key; }
Java
UTF-8
2,398
2.6875
3
[ "MIT" ]
permissive
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("22") class Record_3588 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 3588: FirstName is Chet") void FirstNameOfRecord3588() { assertEquals("Chet", customers.get(3587).getFirstName()); } @Test @DisplayName("Record 3588: LastName is Mccluney") void LastNameOfRecord3588() { assertEquals("Mccluney", customers.get(3587).getLastName()); } @Test @DisplayName("Record 3588: Company is Liberty Carton Co") void CompanyOfRecord3588() { assertEquals("Liberty Carton Co", customers.get(3587).getCompany()); } @Test @DisplayName("Record 3588: Address is 109 Mcnyll Rd") void AddressOfRecord3588() { assertEquals("109 Mcnyll Rd", customers.get(3587).getAddress()); } @Test @DisplayName("Record 3588: City is Sanford") void CityOfRecord3588() { assertEquals("Sanford", customers.get(3587).getCity()); } @Test @DisplayName("Record 3588: County is Lee") void CountyOfRecord3588() { assertEquals("Lee", customers.get(3587).getCounty()); } @Test @DisplayName("Record 3588: State is NC") void StateOfRecord3588() { assertEquals("NC", customers.get(3587).getState()); } @Test @DisplayName("Record 3588: ZIP is 27330") void ZIPOfRecord3588() { assertEquals("27330", customers.get(3587).getZIP()); } @Test @DisplayName("Record 3588: Phone is 919-776-5811") void PhoneOfRecord3588() { assertEquals("919-776-5811", customers.get(3587).getPhone()); } @Test @DisplayName("Record 3588: Fax is 919-776-9304") void FaxOfRecord3588() { assertEquals("919-776-9304", customers.get(3587).getFax()); } @Test @DisplayName("Record 3588: Email is chet@mccluney.com") void EmailOfRecord3588() { assertEquals("chet@mccluney.com", customers.get(3587).getEmail()); } @Test @DisplayName("Record 3588: Web is http://www.chetmccluney.com") void WebOfRecord3588() { assertEquals("http://www.chetmccluney.com", customers.get(3587).getWeb()); } }
SQL
UTF-8
18,976
3.03125
3
[]
no_license
/* Navicat MySQL Data Transfer Source Server : localhost_3306 Source Server Version : 50720 Source Host : localhost:3306 Source Database : wulang Target Server Type : MYSQL Target Server Version : 50720 File Encoding : 65001 Date: 2019-02-28 18:37:53 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for `category` -- ---------------------------- DROP TABLE IF EXISTS `category`; CREATE TABLE `category` ( `id` int(6) NOT NULL AUTO_INCREMENT, `cateName` varchar(200) DEFAULT NULL, `cateDesc` varchar(500) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of category -- ---------------------------- INSERT INTO `category` VALUES ('1', '复式房', '分类描述'); INSERT INTO `category` VALUES ('2', '高档住宅', '小型车描述'); INSERT INTO `category` VALUES ('3', '紧凑型', '紧凑型描述'); INSERT INTO `category` VALUES ('4', '普通住宅', '中型车描述'); INSERT INTO `category` VALUES ('5', '豪华住宅', '大型车描述'); INSERT INTO `category` VALUES ('6', '公寓式住宅', 'SUV描述'); INSERT INTO `category` VALUES ('8', '别墅', '跑车描述'); INSERT INTO `category` VALUES ('9', '廉租住房', 'MPV de描述i想你想'); -- ---------------------------- -- Table structure for `comment` -- ---------------------------- DROP TABLE IF EXISTS `comment`; CREATE TABLE `comment` ( `id` int(6) NOT NULL AUTO_INCREMENT, `homeId` int(6) DEFAULT NULL, `starts` int(1) DEFAULT NULL, `content` varchar(300) DEFAULT NULL, `cdesc` varchar(500) DEFAULT NULL, `fromName` varchar(100) DEFAULT NULL, `cTime` datetime DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of comment -- ---------------------------- INSERT INTO `comment` VALUES ('1', '1', '5', '这是评论', '有厨房,可以带狗狗,交通方便,体验极好', 'cj', '2019-02-27 11:13:35'); INSERT INTO `comment` VALUES ('2', '1', '5', '非常好的民宿', '还会再来,有地铁,适合一家子,可以带狗狗,支持带孩子去', 'cj', '2019-02-27 13:34:41'); INSERT INTO `comment` VALUES ('3', '1', '5', '非常好的民宿', '还会再来,有地铁,适合一家子,可以带狗狗,支持带孩子去', 'cj', '2019-02-27 13:34:43'); INSERT INTO `comment` VALUES ('4', '1', '5', '非常好的民宿', '还会再来,有地铁,适合一家子,可以带狗狗,支持带孩子去', 'cj', '2019-02-27 13:34:46'); INSERT INTO `comment` VALUES ('5', '1', '5', '由小霸王游戏机,超开心了', '支持带孩子去,娱乐设施齐全,还会再来', 'cj', '2019-02-27 13:36:12'); INSERT INTO `comment` VALUES ('6', '1', '4', '四星评论', '娱乐设施齐全,交通方便,适合一家子', 'cj', '2019-02-27 13:37:04'); INSERT INTO `comment` VALUES ('7', '1', '5', '这是评论内容', '环境不错,支持带孩子去,适合一家子,交通方便', 'cj', '2019-02-28 16:08:05'); INSERT INTO `comment` VALUES ('8', '15', '5', '修正HomeId错误', '支持带孩子去,适合一家子,有地铁,环境不错,交通方便,可以带狗狗', 'cj', '2019-02-28 16:09:43'); INSERT INTO `comment` VALUES ('9', '15', '5', '册数评论,id15', '环境不错,支持带孩子去,可以带狗狗,适合一家子,有厨房,交通方便', 'cj', '2019-02-28 16:12:17'); INSERT INTO `comment` VALUES ('10', '15', '5', '册数评论,id15 2', '', 'cj', '2019-02-28 16:12:29'); -- ---------------------------- -- Table structure for `homeinfo` -- ---------------------------- DROP TABLE IF EXISTS `homeinfo`; CREATE TABLE `homeinfo` ( `id` int(6) NOT NULL AUTO_INCREMENT, `cateId` int(6) NOT NULL, `count` int(5) DEFAULT NULL, `title` varchar(220) DEFAULT NULL, `desc` varchar(500) DEFAULT NULL, `status` int(1) NOT NULL DEFAULT '0' COMMENT '0可预约,1已被预约,2商品下架', `price` int(8) NOT NULL, `img` varchar(200) DEFAULT NULL, `subImgs` varchar(300) DEFAULT NULL, `richText` longtext, `review` int(8) NOT NULL DEFAULT '0', `createTime` datetime DEFAULT NULL, `city` varchar(10) DEFAULT NULL, `address` varchar(100) DEFAULT NULL, `uId` int(6) DEFAULT NULL, PRIMARY KEY (`id`), KEY `cateId` (`cateId`), CONSTRAINT `cateId` FOREIGN KEY (`cateId`) REFERENCES `category` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of homeinfo -- ---------------------------- INSERT INTO `homeinfo` VALUES ('1', '2', '1', '测试上传小型车12万', '车辆描述信息,这是一辆很牛逼的车车', '1', '120000', '0.451877588710045.png', '0.451877588710045.png,0.3934990624230239.png', '<h1><strong>这是富文本描述加粗</strong></h1><p><br></p><p><br></p><p><br></p><h1><strong><em><u>倾斜文字加粗下划线</u></em></strong></h1><p><br></p><ol><li>1231231</li><li>23423</li></ol><ul><li>12312312</li><li>12312311</li></ul><p class=\"ql-indent-8\"><a href=\"http://baidu.com\" target=\"_blank\">大苏打</a>连接到百度</p><p><br></p><p>添加图片</p><p><img src=\"//:0\"><img src=\"https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg\"><img src=\"https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg\"><img src=\"https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg\"></p><p><img src=\"https://gw.alipayobjects.com/zos/rmsportal/KDpgvguMpGfqaHPjicRK.svg\"></p>', '8', '2019-02-14 17:46:02', '湖南', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('2', '2', '1', '测试上传2', ' 这又是一款很牛逼的车车啊123', '1', '130000', '0.451877588710045.png', '0.451877588710045.png,0.451877588710045.png,0.3934990624230239.png', '<p>setImg</p><p><img src=\"https://gw.alipayobjects.com/zos/rmsportal/tXlLQhLvkEelMstLyHiN.svg\"></p><p><img src=\"https://gw.alipayobjects.com/zos/rmsportal/tXlLQhLvkEelMstLyHiN.svg\"></p>', '50', '2019-02-11 17:46:23', '湖南', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('3', '4', '1', '测试三', '折还是一辆很牛逼的车', '1', '230000', '0.21606447077867896.png', ',0.21606447077867896.png', '<p>this.state.<img src=\"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png\"></p>', '2', '2019-02-11 17:46:27', '广西', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('4', '3', '1', '测试第三次', '前两次图片处理不正确,第三次修复', '1', '600000', '0.21606447077867896.png', ',0.21606447077867896.png', '<p><img src=\"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png\"></p>', '3', '2019-02-11 17:49:11', '广西', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('5', '3', '1', '第四次测试', '图片状态为修改完成就调用get请求,导致上传空数据', '1', '500000', '0.21606447077867896.png', ',0.21606447077867896.png', '<p> axios.get(\"/addProduct\",{</p><p> params:{</p><p> cateId:this.state.categoryId,</p><p> pingpai:this.state.pingpai,</p><p> title:this.state.title,</p><p> desc:this.state.desc,</p><p> status:this.state.status,</p><p> price:this.state.price,</p><p> img:this.state.subImg[0],</p><p> subImgs:this.state.subImg,</p><p> richText:this.state.text</p><p> }</p><p> }).then((res)=&gt;{</p><p> console.log(res);</p><p> })</p>', '5', '2019-02-11 17:49:15', '福建', 'this is addressthis is address', '1'); INSERT INTO `homeinfo` VALUES ('6', '3', '1', '第四次测试', '图片状态为修改完成就调用get请求,导致上传空数据', '0', '500000', '0.21606447077867896.png', ',0.21606447077867896.png', '<p> axios.get(\"/addProduct\",{</p><p> params:{</p><p> cateId:this.state.categoryId,</p><p> pingpai:this.state.pingpai,</p><p> title:this.state.title,</p><p> desc:this.state.desc,</p><p> status:this.state.status,</p><p> price:this.state.price,</p><p> img:this.state.subImg[0],</p><p> subImgs:this.state.subImg,</p><p> richText:this.state.text</p><p> }</p><p> }).then((res)=&gt;{</p><p> console.log(res);</p><p> })</p>', '5', '2019-02-11 17:49:06', '广西', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('7', '6', '1', '测试第五次', '这是一辆车,很牛逼的车', '1', '450000', '0.21606447077867896.png', ',0.21606447077867896.png', '<p>this.state.</p><p><img src=\"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png\"></p>', '0', '2019-02-11 17:49:08', '湖南', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('8', '5', '1', '测试最后一次', '这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车这是一辆车,车车', '1', '450000', '0.6336654549891276png', '0.6336654549891276png,0.9908972830906131png,0.43426060023758306png,', '<p>123update</p><p><img src=\"https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png\"></p>', '0', '2019-02-06 17:49:01', '湖南', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('9', '2', '1', '新增第七量', '\n 这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息', '1', '120000', '0.3809164411969972.jpg', '0.3809164411969972.jpg,0.7209731645549564.png,', '<p>这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息</p>\n ', '0', '2019-02-11 17:48:55', '广西', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('10', '5', '1', '车辆名才', '这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息', '1', '150000', '0.03688790816803533.jpg', '0.03688790816803533.jpg,0.26512444901091636.png,', '<h1>这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息这是车辆描述信息</h1>', '12', '2019-02-11 17:48:58', '云南', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('11', '2', '1', '新增车辆11', '11', '1', '500000', '0.9939289023637934.jpg', '0.9939289023637934.jpg,0.8568716158584355.png,', '<p>11123</p>', '1', '2019-02-11 17:48:31', '深圳', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('12', '1', '1', '有图新', '\n 宝马有图好多图', '1', '230000', '\n0.8274463313161715.jpg', '0.8274463313161715.jpg,0.4266594556218293.jpg,0.5569691672944721.jpg,0.7020011737893335.jpg,', '<h1><br></h1><h1>富文本</h1>\n ', '29', '2019-02-16 09:20:12', '广州', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('13', '1', '1', '测试', '劳斯莱斯很强', '1', '880000', '0.2202802861112545.jpg', '0.2202802861112545.jpg,0.33182199972005266.png,0.7045064618445611.jpg,', '<p><img src=\"http://localhost:5000/0.7020011737893335.jpg\"></p>', '10', '2019-02-16 09:33:22', '福建', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('14', '8', '1', '这是这里面最贵的车', '最贵最贵的车最贵最贵的车最贵最贵的车最贵最贵的车最贵最贵的车最贵最贵的车最贵最贵的车', '1', '50000000', '0.9313191065454862.jpg', '0.9313191065454862.jpg,0.7762337539611002.png,0.7439693940503642.jpg,', '<p><img src=\"https://wx2.sinaimg.cn/mw690/006We1hygy1ftaxqqrp9wj304105w74j.jpg\"><img src=\"https://wx2.sinaimg.cn/mw690/006We1hygy1ftaxqqrp9wj304105w74j.jpg\"></p>', '5', '2019-02-16 19:17:05', '上海', 'this is address', '1'); INSERT INTO `homeinfo` VALUES ('15', '3', '20', '测试', '名宿测试', '1', '123', '0.04375480188906411.png', '0.7101916447474017.png,', '<p>mainImgmainImgaddress</p>', '59', '2019-02-25 15:57:58', '杭州', 'mainImgaddress', '1'); INSERT INTO `homeinfo` VALUES ('16', '5', '50', '民宿跟随用户ID外键', '测试民宿跟随用户ID外键描述', '1', '200', '0.44780192674265296.png', '0.8589484380240549.png,0.8707451431681188.jpg,', '<h1><strong>民宿跟随用户ID外键民宿跟随用户ID外键民宿跟随用户ID外键民宿跟随用户ID外键民宿跟随用户ID外键民宿跟随用户ID外键民宿跟随用户ID外键</strong></h1>', '5', '2019-02-25 17:19:20', '杭州', '民宿跟随用户ID外键地址', '1'); -- ---------------------------- -- Table structure for `order` -- ---------------------------- DROP TABLE IF EXISTS `order`; CREATE TABLE `order` ( `id` int(6) NOT NULL AUTO_INCREMENT, `homeId` int(6) NOT NULL, `userId` int(6) NOT NULL, `other` varchar(300) DEFAULT NULL, `startTime` datetime DEFAULT NULL, `endTime` datetime DEFAULT NULL, `ostatus` int(1) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of order -- ---------------------------- INSERT INTO `order` VALUES ('1', '15', '1', '7gdfgdf fg', '2019-02-11 00:00:00', '2019-02-20 00:00:00', '1'); INSERT INTO `order` VALUES ('2', '15', '1', '7527272', '2019-02-25 16:24:02', '2019-02-28 16:24:08', '1'); INSERT INTO `order` VALUES ('5', '15', '1', '明天中午十二点', '2019-02-28 00:00:00', '2019-03-15 00:00:00', '1'); INSERT INTO `order` VALUES ('6', '10', '1', '阿斯达岁的', '2019-02-28 00:00:00', '2019-03-15 00:00:00', '0'); INSERT INTO `order` VALUES ('7', '10', '1', '打撒打撒多阿萨德asdas', '2019-03-07 00:00:00', '2019-03-22 00:00:00', '0'); -- ---------------------------- -- Table structure for `story` -- ---------------------------- DROP TABLE IF EXISTS `story`; CREATE TABLE `story` ( `id` int(6) NOT NULL AUTO_INCREMENT, `wTime` datetime DEFAULT NULL, `uName` varchar(200) DEFAULT NULL, `title` varchar(200) DEFAULT NULL, `imgs` varchar(300) DEFAULT NULL, `richText` longtext, `homeId` int(6) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of story -- ---------------------------- INSERT INTO `story` VALUES ('0', '2019-02-28 17:32:07', 'cj', 'title', '0.54654455.jpg', '13傅艺伟别把', '15'); INSERT INTO `story` VALUES ('2', '2019-02-28 17:32:07', 'cj', 'title', '0.54654455.jpg', '13傅艺伟别把', '15'); INSERT INTO `story` VALUES ('3', '2019-02-28 17:30:39', 'cj', '123123123gu故事测试', '0.6315520291247505.png,0.006785808312297137.png,', '<h1>123123123gu故事测试123123123gu故事测试123123123gu故事测试123123123gu故事测试</h1>', '15'); INSERT INTO `story` VALUES ('4', '2019-02-28 17:39:11', 'cj', '123123123gu故事测试', '0.6315520291247505.png,0.006785808312297137.png,', '<h1>123123123gu故事测试123123123gu故事测试123123123gu故事测试123123123gu故事测试</h1>', '15'); INSERT INTO `story` VALUES ('5', '2019-02-28 17:39:13', 'cj', '123123123gu故事测试', '0.6315520291247505.png,0.006785808312297137.png,', '<h1>123123123gu故事测试123123123gu故事测试123123123gu故事测试123123123gu故事测试</h1>', '15'); INSERT INTO `story` VALUES ('6', '2019-02-28 17:39:13', 'cj', '123123123gu故事测试', '0.6315520291247505.png,0.006785808312297137.png,', '<h1>123123123gu故事测试123123123gu故事测试123123123gu故事测试123123123gu故事测试</h1>', '15'); INSERT INTO `story` VALUES ('7', '2019-02-28 17:40:21', 'cj', '123123123gu故事测试', '0.6315520291247505.png,0.006785808312297137.png,', '<h1>123123123gu故事测试123123123gu故事测试123123123gu故事测试123123123gu故事测试</h1>', '15'); INSERT INTO `story` VALUES ('8', '2019-02-28 17:42:58', 'cj', '测试上传', '0.05049672278891548.png,0.3594556486483691.png,', '<h1>阿斯达岁的 撒旦爱色</h1>', '15'); -- ---------------------------- -- Table structure for `user` -- ---------------------------- DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(6) NOT NULL AUTO_INCREMENT, `name` varchar(20) DEFAULT NULL, `pwd` varchar(20) DEFAULT NULL, `phone` varchar(20) DEFAULT NULL, `email` varchar(50) DEFAULT NULL, `isAdmin` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4; -- ---------------------------- -- Records of user -- ---------------------------- INSERT INTO `user` VALUES ('1', 'cj', '123', '13799418338', 'jery1997@foxmial.com', '1'); INSERT INTO `user` VALUES ('2', 'zd', '123', '137954654', 'zidan@qq,,com', '1'); INSERT INTO `user` VALUES ('3', 'cj2', '123', '13799418338', 'jery1997@foxmial.com', '0'); INSERT INTO `user` VALUES ('4', '123', '12', 'jery1996@foxmail.com', '13799418368', '0');
Rust
UTF-8
3,347
2.78125
3
[]
no_license
use crate::synth::dsp::audionode::AudioNode; use std::thread; use std::sync::mpsc::channel; use std::sync::mpsc::{Sender, Receiver}; use piston_window::*; /* ========================================= Viz ========================================= */ #[derive(Clone)] pub struct ScopeNodeData { pub value: f32, pub buffer: [f32; ScopeNode::BUFFER_SIZE], pub actual_size: usize, pub current_index: usize, } pub struct ScopeNode { data: ScopeNodeData, tx: Sender<ScopeNodeData> } impl ScopeNode { pub const BUFFER_SIZE: usize = 1_000; pub const INPUT_SIGNAL: i32 = 0; pub fn new() -> ScopeNode { let tx = ScopeNode::launch_scope(); let scope = ScopeNode { tx: tx, data: ScopeNodeData { value: 0.0, buffer:[0.0; ScopeNode::BUFFER_SIZE], actual_size: ScopeNode::BUFFER_SIZE, current_index: 0, } }; scope } pub fn launch_scope() -> Sender<ScopeNodeData> { let (tx, rx): (Sender<ScopeNodeData>, Receiver<ScopeNodeData>) = channel(); thread::spawn(move || { let mut window: PistonWindow = WindowSettings::new("Scope", [640, 480]) .resizable(false) .exit_on_esc(false) .build() .unwrap(); let mut buffer : [f32;ScopeNode::BUFFER_SIZE] = [0.0;ScopeNode::BUFFER_SIZE]; while let Some(event) = window.next() { let rec = rx.try_recv(); buffer = match rec { Ok(data) => data.buffer, _ => buffer }; // buffer = match rec { Ok(data) => data.buffer, _ => buffer }; let mut zero_cross = 0; for i in 1..320 { if buffer[i-1]<0.0 && buffer[i]>0.0 { zero_cross = i; } } window.draw_2d(&event, |context, graphics, _device| { clear([1.0; 4], graphics); rectangle([0.0, 0.0, 1.0, 1.0], [0.0, 240.0, 640.0 , 1.0 ], context.transform, graphics); rectangle([0.0, 0.0, 1.0, 1.0], [0.0, 40.0, 640.0 , 1.0 ], context.transform, graphics); rectangle([0.0, 0.0, 1.0, 1.0], [0.0, 440.0, 640.0 , 1.0 ], context.transform, graphics); for i in 0..640 { let value = (400.0*(buffer[i+zero_cross]+1.0)/2.0) as f64; rectangle([1.0, 0.0, 0.0, 1.0], [i as f64, value+40.0,1.0 , 1.0 ], context.transform, graphics); } }); } }); tx } } impl AudioNode for ScopeNode { fn set_input_value(&mut self, input: i32, value: f32) { match input { ScopeNode::INPUT_SIGNAL => { self.data.value = value; }, _ => () } } fn compute(&mut self) { self.data.current_index = (self.data.current_index+1)%self.data.actual_size; self.data.buffer[self.data.current_index] = self.data.value; if self.data.current_index == 0 { let _res = self.tx.send(self.data.clone()); } } fn get_output_value(&self, _ouput: i32) -> f32 { self.data.value } }
Java
UTF-8
504
3.015625
3
[]
no_license
import java.util.InvalidPropertiesFormatException; /** * Created by Cube27 on 04.08.2017. * Пара от X1 до X2, будет хранится в Aggregate */ public class Pair { private int x; private int x2; public Pair(int x, int x2){ if(x2>x){ this.x=x; this.x2=x2; } else{ this.x=x; this.x2=x; } } public int getX() { return x; } public int getX2() { return x2; } }
Java
UTF-8
6,220
1.84375
2
[]
no_license
package com.firefighterscalendar.album; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.firefighterscalendar.BaseActivity; import com.firefighterscalendar.MainActivity; import com.firefighterscalendar.R; import com.firefighterscalendar.adapter.AlbumAdapter; import com.firefighterscalendar.bean.AlbumBean; import com.firefighterscalendar.utils.AllAPICall; import com.firefighterscalendar.utils.onTaskComplete; import com.google.gson.Gson; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class AlbumActivity extends BaseActivity { private List<AlbumBean> listAlbums; private Toolbar toolbar; private LinearLayout layoutRight; private RecyclerView recyclerView; private AlbumAdapter albumAdapter; private HashMap<String, String> stringHashMap; private TextView textNoResult; int offset = 0, flag = 0; private GridLayoutManager layoutManager; private TextView textHeader; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_album); initControls(); } private void initControls() { listAlbums = new ArrayList<>(); toolbar = (Toolbar) findViewById(R.id.toolbar_inner); setSupportActionBar(toolbar); getSupportActionBar().setTitle(""); getSupportActionBar().setDisplayHomeAsUpEnabled(true); toolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackPressed(); } }); layoutRight = (LinearLayout) toolbar.findViewById(R.id.layoutRight); layoutRight.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(AlbumActivity.this, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }); textHeader = (TextView) findViewById(R.id.textHeader); assert textHeader != null; textHeader.setText(R.string.gallery); recyclerView = (RecyclerView) findViewById(R.id.recycleviewAlbums); assert recyclerView != null; recyclerView.setHasFixedSize(false); layoutManager = new GridLayoutManager(getApplicationContext(), 2); recyclerView.setLayoutManager(layoutManager); recyclerView.addOnScrollListener(onScrollListener); textNoResult = (TextView) findViewById(R.id.textNoResult); } @Override protected void onResume() { super.onResume(); albumAdapter = new AlbumAdapter(AlbumActivity.this, listAlbums, sessionManager.getStringDetail("subscription")); recyclerView.setAdapter(albumAdapter); if (utility.checkInternetConnection()) { offset = 0; flag = 0; listAlbums.clear(); getAllAlbumAPICall(offset); } } private void getAllAlbumAPICall(int pageNo) { stringHashMap = new HashMap<>(); stringHashMap.put("iUserId", sessionManager.getStringDetail("iUserId")); stringHashMap.put("offset", "" + pageNo); stringHashMap.put("eAlbumCategory", getIntent().getStringExtra("type")); new AllAPICall(this, stringHashMap, null, new onTaskComplete() { @Override public void onComplete(String response) { try { JSONArray jsonArray = new JSONArray(response); JSONObject jsonObject = jsonArray.getJSONObject(0); offset = jsonObject.getInt("offset"); if (jsonObject.getInt("response_status") == 1) { JSONArray arrayResult = jsonObject.getJSONArray("result"); Gson gson = new Gson(); for (int i = 0; i < arrayResult.length(); i++) { AlbumBean albumBean = gson.fromJson(arrayResult.getJSONObject(i).toString(), AlbumBean.class); listAlbums.add(albumBean); } albumAdapter.notifyDataSetChanged(); if (listAlbums.isEmpty()) { recyclerView.setVisibility(View.GONE); textNoResult.setVisibility(View.VISIBLE); } else { recyclerView.setVisibility(View.VISIBLE); textNoResult.setVisibility(View.GONE); } // recyclerView.scrollToPosition(layoutManager.findLastVisibleItemPosition()); if (arrayResult.length() == 0) { flag = -1; } } } catch (JSONException e) { e.printStackTrace(); } } }).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, URL_GET_ALL_ALBUMS); } RecyclerView.OnScrollListener onScrollListener = new RecyclerView.OnScrollListener() { @Override public void onScrollStateChanged(RecyclerView recyclerView, int newState) { super.onScrollStateChanged(recyclerView, newState); if (newState == RecyclerView.SCROLL_STATE_IDLE && flag != -1) { getAllAlbumAPICall(offset); } Log.i("last position", "" + layoutManager.findLastCompletelyVisibleItemPosition()); } @Override public void onScrolled(RecyclerView recyclerView, int dx, int dy) { super.onScrolled(recyclerView, dx, dy); } }; }
Python
UTF-8
7,439
2.921875
3
[ "MIT" ]
permissive
"""Test the metrics.""" import unittest import numpy as np import pytest from aisdc.metrics import ( _div, _tpr_at_fpr, get_metrics, get_probabilities, min_max_disc, ) # pylint: disable = invalid-name PREDICTED_CLASS = np.array([0, 1, 0, 0, 1, 1]) TRUE_CLASS = np.array([0, 0, 0, 1, 1, 1]) PREDICTED_PROBS = np.array( [[0.9, 0.1], [0.4, 0.6], [0.8, 0.2], [0.55, 0.45], [0.1, 0.9], [0.01, 0.99]] ) class DummyClassifier: """Mocks the predict and predict_proba methods.""" def predict(self, _): """Return dummy predictions.""" return PREDICTED_CLASS def predict_proba(self, _): """Return dummy predicted probabilities.""" return PREDICTED_PROBS class TestInputExceptions(unittest.TestCase): """Test that the metrics.py errors with a helpful error message if an invalid shape is supplied. """ def _create_fake_test_data(self): y_test = np.zeros(4) y_test[0] = 1 return y_test def test_wrong_shape(self): """Test the check which ensures y_pred_proba is of shape [:,:].""" y_test = self._create_fake_test_data() with pytest.raises(ValueError): y_pred_proba = np.zeros((4, 2, 2)) get_metrics(y_pred_proba, y_test) def test_wrong_size(self): """Test the check which ensures y_pred_proba is of size (:,2).""" y_test = self._create_fake_test_data() with pytest.raises(ValueError): y_pred_proba = np.zeros((4, 4)) get_metrics(y_pred_proba, y_test) def test_valid_input(self): """Test to make sure a valid array does not throw an exception.""" y_test = self._create_fake_test_data() y_pred_proba = np.zeros((4, 2)) returned = get_metrics(y_pred_proba, y_test) acc = returned["ACC"] auc = returned["AUC"] p_auc = returned["P_HIGHER_AUC"] tpr = returned["TPR"] self.assertAlmostEqual(0.75, acc) self.assertAlmostEqual(0.5, auc) self.assertAlmostEqual(0.5, p_auc) self.assertAlmostEqual(0.0, tpr) class TestProbabilities(unittest.TestCase): """Test the checks on the input parameters of the get_probabilites function.""" def test_permute_rows_errors(self): """ Test to make sure an error is thrown when permute_rows is set to True, but no y_test is supplied. """ clf = DummyClassifier() testX = [] with pytest.raises(ValueError): get_probabilities(clf, testX, permute_rows=True) def test_permute_rows_with_permute_rows(self): """Test permute_rows = True succeeds.""" clf = DummyClassifier() testX = np.zeros((4, 2)) testY = np.zeros((4, 2)) returned = get_probabilities(clf, testX, testY, permute_rows=True) # Check the function returns two arguments self.assertEqual(2, len(returned)) # Check that the second argument is the same shape as testY self.assertEqual(testY.shape, returned[1].shape) # Check that the function is returning the right thing: predict_proba self.assertEqual(clf.predict_proba(testX).shape, returned[0].shape) def test_permute_rows_without_permute_rows(self): """Test permute_rows = False succeeds.""" clf = DummyClassifier() testX = np.zeros((4, 2)) y_pred_proba = get_probabilities(clf, testX, permute_rows=False) # Check the function returns pnly y_pred_proba self.assertEqual(clf.predict_proba(testX).shape, y_pred_proba.shape) class TestMetrics(unittest.TestCase): """Test the metrics with some dummy predictions.""" def test_metrics(self): """Test each individual metric with dummy data.""" clf = DummyClassifier() testX = [] testy = TRUE_CLASS y_pred_proba = get_probabilities(clf, testX, testy, permute_rows=False) metrics = get_metrics(y_pred_proba, testy) self.assertAlmostEqual(metrics["TPR"], 2 / 3) self.assertAlmostEqual(metrics["FPR"], 1 / 3) self.assertAlmostEqual(metrics["FAR"], 1 / 3) self.assertAlmostEqual(metrics["TNR"], 2 / 3) self.assertAlmostEqual(metrics["PPV"], 2 / 3) self.assertAlmostEqual(metrics["NPV"], 2 / 3) self.assertAlmostEqual(metrics["FNR"], 1 / 3) self.assertAlmostEqual(metrics["ACC"], 4 / 6) self.assertAlmostEqual(metrics["F1score"], (8 / 9) / (2 / 3 + 2 / 3)) self.assertAlmostEqual(metrics["Advantage"], 1 / 3) self.assertAlmostEqual(metrics["AUC"], 8 / 9) def test_mia_extremecase(self): """Test the extreme case mia in metrics.py.""" # create actual values y = np.zeros(50000) y[:25] = 1 # exactly right and wrong predictions right = np.zeros(50000) right[:25] = 1 wrong = 1 - right # right predictions - triggers override for very small logp _, _, _, pval = min_max_disc(y, right) self.assertEqual(-115.13, pval) # wrong predictions - probaility very close to 1 so logp=0 _, _, _, pval = min_max_disc(y, wrong) self.assertAlmostEqual(0.0, pval) class TestFPRatTPR(unittest.TestCase): """Test code that computes TPR at fixed FPR.""" def test_tpr(self): """Test tpr at fpr.""" y_true = TRUE_CLASS y_score = PREDICTED_PROBS[:, 1] tpr = _tpr_at_fpr(y_true, y_score, fpr=0) self.assertAlmostEqual(tpr, 2 / 3) tpr = _tpr_at_fpr(y_true, y_score, fpr=0.001) self.assertAlmostEqual(tpr, 2 / 3) tpr = _tpr_at_fpr(y_true, y_score, fpr=0.1) self.assertAlmostEqual(tpr, 2 / 3) tpr = _tpr_at_fpr(y_true, y_score, fpr=0.4) self.assertAlmostEqual(tpr, 1) tpr = _tpr_at_fpr(y_true, y_score, fpr=1.0) self.assertAlmostEqual(tpr, 1) tpr = _tpr_at_fpr(y_true, y_score, fpr_perc=True, fpr=100.0) self.assertAlmostEqual(tpr, 1) class Test_Div(unittest.TestCase): """Tests the _div functionality.""" def test_div(self): """Test div for y=1 and 0.""" result = _div(8.0, 1.0, 99.0) self.assertAlmostEqual(result, 8.0) result2 = _div(8.0, 0.0, 99.0) self.assertAlmostEqual(result2, 99.0) class TestExtreme(unittest.TestCase): """Test the extreme metrics.""" def test_extreme_default(self): """Tets with the dummy data.""" pred_probs = DummyClassifier().predict_proba(None)[:, 1] maxd, mind, mmd, _ = min_max_disc(TRUE_CLASS, pred_probs) # 10% of 6 is 1 so: # maxd should be 1 (the highest one is predicted as1) # mind should be 0 (the lowest one is not predicted as1) self.assertAlmostEqual(maxd, 1.0) self.assertAlmostEqual(mind, 0.0) self.assertAlmostEqual(mmd, 1.0) def test_extreme_higer_prop(self): """Tets with the dummy data but increase proportion to 0.5.""" pred_probs = DummyClassifier().predict_proba(None)[:, 1] maxd, mind, mmd, _ = min_max_disc(TRUE_CLASS, pred_probs, x_prop=0.5) # 10% of 6 is 1 so: # maxd should be 1 (the highest one is predicted as1) # mind should be 0 (the lowest one is not predicted as1) self.assertAlmostEqual(maxd, 2 / 3) self.assertAlmostEqual(mind, 1 / 3) self.assertAlmostEqual(mmd, 1 / 3)
Java
UTF-8
632
1.8125
2
[]
no_license
package com.github.rafaelsouzaf.prot.client.view.product; import java.util.List; import com.github.rafaelsouzaf.prot.client.util.FileModel; import com.google.gwt.user.client.rpc.AsyncCallback; public interface ProductServiceAsync { public abstract void getAll(AsyncCallback<List<ProductModel>> callback); public abstract void insert(ProductModel model, AsyncCallback callback); public abstract void edit(ProductModel model, AsyncCallback callback); public abstract void delete(ProductModel model, AsyncCallback callback); public abstract void getPhotos(AsyncCallback<List<FileModel>> callback); }
C
ISO-8859-9
626
3.828125
4
[]
no_license
#include<stdio.h> void del(int A[], int size, int uw); int main() { //DZDEK STENMEYEN ELEMANI SLER int n=0; int x=0; printf("define the size of array:\n"); scanf("%d", &n); int arr[n]; int i; srand(time(NULL)); for(i=0; i<n; i++) { arr[i]=rand()%50; printf("%d. value: %d\n", i+1, arr[i]); } printf("which value you want to delete?\n"); scanf("%d", &x-1); del(arr, n, x-1); } void del(int A[], int size, int uw) { int i; for(i=0; i<size; i++) { if(A[i]!=A[uw]) { printf("%d\n", A[i]); } else if(A[i]==A[uw]) { printf(""); } } }
Java
UTF-8
2,317
2.28125
2
[]
no_license
package com.example.databasetest; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Toast; import java.util.concurrent.atomic.AtomicReference; import io.realm.Realm; import io.realm.RealmConfiguration; import io.realm.mongodb.App; import io.realm.mongodb.AppConfiguration; import io.realm.mongodb.Credentials; import io.realm.mongodb.User; public class MainActivity extends AppCompatActivity { private final String AppId ="databasetest-ureag"; private App app; private AtomicReference<User> user; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent( getApplicationContext() , MainActivity2.class)); } }); app = new App(new AppConfiguration.Builder(AppId).build()); Login(); } private void Login() { Credentials emailPasswordCredentials = Credentials.emailPassword(findViewById(R.id.email).toString() , findViewById(R.id.password).toString() ); user= new AtomicReference<User>(); app.loginAsync(emailPasswordCredentials , it ->{ if (it.isSuccess()){ Toast.makeText(this, "Successfully authenticated using an email and password.", Toast.LENGTH_SHORT).show(); user.set(app.currentUser()); }else { Toast.makeText(this, it.getError().toString() , Toast.LENGTH_SHORT).show(); } }); } private void Logout(){ user.get().logOutAsync( result -> { if (result.isSuccess()){ Toast.makeText(this, "Logout Successful", Toast.LENGTH_SHORT).show(); } else{ Toast.makeText(this , result.getError().toString() , Toast.LENGTH_LONG).show(); } }); } @Override protected void onStart() { super.onStart(); if (app.currentUser() != null) startActivity(new Intent( MainActivity.this , MainActivity2.class)); } }
C#
UTF-8
6,513
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using AllTheRickAndMorty.Models; using Xamarin.Forms; namespace AllTheRickAndMorty { public partial class FavoritesTab : ContentPage { // Favorites tab brings in favorite characters and episodes and puts them in list view List<CharacterInfo> FavoriteChar = new List<CharacterInfo>(); List<EpisodeInfo> favoriteEpi = new List<EpisodeInfo>(); UserData currentUser = new UserData(); public FavoritesTab() { InitializeComponent(); LoadFavorites(); MessagingCenter.Subscribe<List<CharacterInfo>>(this, "favoriteCharacter", (sender) => { foreach (CharacterInfo character in sender) { CharacterInfo favorite = new CharacterInfo(); favorite.CharImage = character.CharImage; favorite.CharName = character.CharName; favorite.CharGender = character.CharGender; favorite.CharSpecies = character.CharSpecies; favorite.CharStatus = character.CharStatus; FavoriteChar.Add(favorite); } }); MessagingCenter.Subscribe<EpisodeInfo>(this, "favoriteEpisode", (sender) => { EpisodeInfo episode = new EpisodeInfo(); episode.EpisodeName = sender.EpisodeName; episode.AirDate = sender.AirDate; favoriteEpi.Add(episode); }); MessagingCenter.Subscribe<UserData>(this, "currentUser", (sender) => { currentUser.UserName = sender.UserName; }); ToolbarItem SignOut = new ToolbarItem { Text = "", IconImageSource = ImageSource.FromFile("logout.png"), Order = ToolbarItemOrder.Primary, Priority = 0, }; this.ToolbarItems.Add(SignOut); SignOut.Clicked += SignOut_Clicked; characterButton.Clicked += CharacterButton_Clicked; episodeButton.Clicked += EpisodeButton_Clicked; listView.ItemSelected += ListView_ItemSelected; } private async void ListView_ItemSelected(object sender, SelectedItemChangedEventArgs e) { if (FavoriteChar.Contains(e.SelectedItem)) { bool answer = await DisplayAlert("Delete Favorite", "Are you sure you'd like to remove this favorite?", "Yes", "No"); if (answer == true) { FavoriteChar.Remove((CharacterInfo)e.SelectedItem); listView.ItemsSource = FavoriteChar; } } else { bool answer = await DisplayAlert("Delete Favorite", "Are you sure you'd like to remove this favorite?", "Yes", "No"); if (answer == true) { favoriteEpi.Remove((EpisodeInfo)e.SelectedItem); listView.ItemsSource = favoriteEpi; } } } private async void SignOut_Clicked(object sender, EventArgs e) { bool answer = await DisplayAlert("Leaving so soon?", "Are you sure you want to log out?", "Yes", "No"); if (answer == true) { string characterFileName = Path.Combine(App.FolderPath, $"{Path.GetRandomFileName()}.{currentUser.UserName}char.txt"); foreach (CharacterInfo character in FavoriteChar) { File.WriteAllLines(characterFileName, new string[] { character.CharImage, character.CharName, character.CharGender, character.CharSpecies, character.CharStatus }); } string episodeFileName = Path.Combine(App.FolderPath, $"{Path.GetRandomFileName()}.{currentUser.UserName}epi.txt"); foreach (EpisodeInfo episode in favoriteEpi) { File.WriteAllLines(episodeFileName, new string[] { episode.EpisodeName, episode.AirDate }); } await Navigation.PushAsync(new MainPage()); } } private void EpisodeButton_Clicked(object senders, EventArgs e) { DataTemplate dt = new DataTemplate(typeof(ImageCell)); dt.SetBinding(ImageCell.TextProperty, new Binding("EpisodeName")); dt.SetBinding(ImageCell.DetailProperty, new Binding("AirDate")); dt.SetValue(ImageCell.TextColorProperty, Color.Blue); listView.ItemTemplate = dt; listView.ItemsSource = favoriteEpi; } private void CharacterButton_Clicked(object senders, EventArgs e) { DataTemplate dt = new DataTemplate(typeof(ImageCell)); dt.SetBinding(ImageCell.ImageSourceProperty, new Binding("CharImage")); dt.SetBinding(ImageCell.TextProperty, new Binding("CharName")); dt.SetBinding(ImageCell.DetailProperty, new Binding("CharStatus")); dt.SetValue(ImageCell.TextColorProperty, Color.Blue); listView.ItemTemplate = dt; listView.ItemsSource = FavoriteChar; } public void LoadFavorites() { var charFiles = Directory.EnumerateFiles(App.FolderPath, "*.char.txt"); foreach (var filename in charFiles) { string[] lines = File.ReadAllLines(filename); FavoriteChar.Add(new CharacterInfo { CharImage = lines[0], CharName = lines[1], CharGender = lines[2], CharSpecies = lines[3], CharStatus = lines[4], }); } var epiFiles = Directory.EnumerateFiles(App.FolderPath, "*.epi.txt"); foreach (var filename in epiFiles) { File.Delete(filename); string[] lines = File.ReadAllLines(filename); favoriteEpi.Add(new EpisodeInfo { EpisodeName = lines[0], AirDate = lines[1], }); } } } }
Markdown
UTF-8
620
3.140625
3
[ "MIT" ]
permissive
# Inertia.js Progress This package adds an [NProgress](https://ricostacruz.com/nprogress/) page loading indicator to your Inertia.js app. ## Installation ```bash npm install @inertiajs/progress yarn add @inertiajs/progress ``` Once it's been installed, initialize it in your app: ```js import Progress from '@inertiajs/progress' Progress.init({ // The delay after which the progress bar will appear during navigation, in milliseconds. // The progress bar appears after 250ms by default. delay: 250, // Sets whether the NProgress spinner will be shown. // Defaults to false. showSpinner: false, }) ```
Java
UTF-8
746
2.3125
2
[]
no_license
package ejb.session.stateless; import entity.BookEntity; import java.util.List; import util.exception.BookNotFoundException; public interface BookEntitySessionBeanRemote { BookEntity createNewBook(BookEntity newBookEntity); List<BookEntity> retrieveAllBooks(); BookEntity retrieveBookByBookId(Long bookId) throws BookNotFoundException; BookEntity retriveBookByTitle(String title) throws BookNotFoundException; BookEntity retriveBookByIsbn(String title) throws BookNotFoundException; void updateBook(BookEntity bookEntity) throws BookNotFoundException; void deleteBook(Long bookId) throws BookNotFoundException; boolean isAvailable(Long bookId) throws BookNotFoundException; }
JavaScript
UTF-8
2,517
3.5625
4
[ "MIT" ]
permissive
var magic_number = Math.floor(Math.random() * (100 - 1) + 1); var n_tries = 0; var output = ""; document.addEventListener("keydown", keyDownHandler, false); document.addEventListener("input", isNumber, false); function keyDownHandler(e) { if (e.keyCode == 13) { user_tries = document.getElementById('numeroRespuestas').value; document.getElementById('numeroRespuestas').disabled = true; document.getElementById('numero').disabled = false; } } function isNumber() { if (document.getElementById('numeroRespuestas').disabled) { let aux = document.getElementById('numero').value; if (isNaN(aux)) { alert("Debes introducir un número"); document.getElementById('numero').value = ""; } else { if (aux < 1 || aux > 100) { alert("El número debe ser entre 1 y 100"); document.getElementById('numero').value = ""; } } } else { let aux = document.getElementById('numeroRespuestas').value; if (isNaN(aux)) { alert("Debes introducir un número"); document.getElementById('numeroRespuestas').value = ""; } else { if (aux < 1 || aux > 100) { alert("El número debe ser entre 1 y 100"); document.getElementById('numeroRespuestas').value = ""; } } } } function adivinar() { user_tries = document.getElementById('numeroRespuestas').value; let user_n = document.getElementById('numero').value; if (user_n == magic_number) { output += `<span class = "acertado">${user_n} - HAS ACERTADO!<span><br>`; reset(); } else if (user_n < magic_number) { output += `<span class = "error">${user_n} - El número que buscas es mayor<span><br>`; } else if (user_n > magic_number) { output += `<span class = "error">${user_n} - El número que buscas es menor<span><br>`; } n_tries++; if (n_tries == user_tries && user_n != magic_number) { output += `<span class = "fin">NO HAS ACERTADO!! El número era el ${magic_number}<span><br>`; reset(); } document.getElementById('numero').value = ""; document.getElementById('respuestas').innerHTML = output; return false; } function reset() { document.getElementById('numeroRespuestas').disabled = true; document.getElementById('numero').disabled = true; }
PHP
UTF-8
1,303
2.515625
3
[]
no_license
<?php namespace app\modules\yangiliklar\models; use Yii; /** * This is the model class for table "yangiliklar". * * @property int $id * @property int $b_id * @property int $m_id * @property string $nomi * @property string $matni * @property string $vaqti * @property int|null $yoqdi * @property int|null $yoqmadi * @property int|null $korishlarsoni */ class Yangiliklar extends \yii\db\ActiveRecord { /** * {@inheritdoc} */ public static function tableName() { return 'yangiliklar'; } /** * {@inheritdoc} */ public function rules() { return [ [['b_id', 'm_id', 'yoqdi', 'yoqmadi', 'korishlarsoni'], 'integer'], [['nomi', 'matni', 'vaqti'], 'required'], [['matni'], 'string'], [['vaqti'], 'safe'], [['nomi'], 'string', 'max' => 50], ]; } /** * {@inheritdoc} */ public function attributeLabels() { return [ 'id' => 'ID', 'b_id' => 'B ID', 'm_id' => 'M ID', 'nomi' => 'Nomi', 'matni' => 'Matni', 'vaqti' => 'Vaqti', 'yoqdi' => 'Yoqdi', 'yoqmadi' => 'Yoqmadi', 'korishlarsoni' => 'Korishlarsoni', ]; } }
Markdown
UTF-8
2,446
3.015625
3
[ "MIT" ]
permissive
# Intro to Nx Nx is a smart, fast and extensible build system with first class monorepo support and powerful integrations. ## Philosophy Nx has a similar design philosophy to Visual Studio Code. Code is a powerful text editor, and you can be very productive with it even if you don't install any extensions. The ecosystem of VSCode's extensions though is what can really level up your productivity. Nx is similar. The core of Nx is generic, simple, and unobtrusive. Nx plugins, although very useful for many projects, are completely optional. Most examples on this site use Nx plugins. It's just easier to demonstrate many features Nx offers when Nx generates all the boilerplate. However, the vast majority of the features will work the same way in a workspace with no plugins. ## Getting Started These guides will help you get started: - [Installing Nx CLI & creating a new Nx Workspace](/getting-started/nx-setup) - [Adding Nx to an existing monorepo](/migration/adding-to-monorepo) - [Using Nx without plugins](/getting-started/nx-core) - [Nx and TypeScript](/getting-started/nx-and-typescript) - [Nx and React](/getting-started/nx-and-react) - [Nx and Angular](/getting-started/nx-and-angular) - [CI Overview](/using-nx/ci-overview) ## Features **Best-in-Class Support for Monorepos** - [Smart rebuilds of affected projects](/using-nx/affected) - [Computation caching](/using-nx/caching) - [Distributed task execution](/using-nx/dte) - [Code sharing and ownership management](/structure/monorepo-tags) **Integrated Development Experience** - [High-quality editor plugins](/using-nx/console) & [GitHub apps](https://github.com/apps/nx-cloud) - [Powerful code generators](/generators/using-schematics) - [Workspace visualizations](/structure/dependency-graph) **Supports Your Ecosystem** - [Rich plugin ecosystem](/getting-started/nx-devkit) from Nrwl and the [community](/community) - Consistent dev experience for any framework - [Automatic upgrade to the latest versions of all frameworks and tools](/using-nx/updating-nx) ## Learn While Doing - [Using Nx without plugins](/getting-started/nx-core) - [Nx and TypeScript](/getting-started/nx-and-typescript) - [React: Interactive Nx Tutorial (with videos)](/react-tutorial/01-create-application) - [Node: Interactive Nx Tutorial (with videos)](/node-tutorial/01-create-application) - [Angular: Interactive Nx Tutorial (with videos)](/angular-tutorial/01-create-application)
Markdown
UTF-8
794
3.0625
3
[ "MIT" ]
permissive
Hello World =========== by [liangqing](https://github.com/liangqing) ## Hello World Of Programming Languages * Javascript * Scala * Bash * C++ * PHP * Java ## Javascript [](rotate=90) ```javascript var a = 100; console.log("Hello World") ``` ## Scala[](rotate=180) ```scala val a = List(1, 2, 3) println("Hello World") ``` ## Bash [](rotate=90) ```bash echo "Hello World" ``` ## C++ [](rotate-x=-45) ```C++ #include<iostream> using namespace std; int main() { cout << "Hello World" << endl; return 0; } ``` ## PHP [](rotate-x=-135) ```php echo "Hello World"; ``` ## Java [](rotate-y=-45) ```java public class HelloWorld { public static void main(String[] argv) { System.out.println("Hello World"); } } ``` ## Overview [](class=hide-title, scale=4, x=-1000)
PHP
UTF-8
1,670
2.921875
3
[]
no_license
<?php /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * Description of physical_hazards * * @author etbmx */ class physical_hazards { protected $_DisplayValues = array('Code', 'Name'); protected $_Headers = array('Code', 'Name'); public function __construct() { } public function fetch_array($id) { $arr_query = "SELECT p.HMIS_PhysicalHazardID, Code, Name, Description from HMIS_PhysicalHazards as p inner join HazardEvaluationPhysicalHazards as ph on ph.HMIS_PhysicalHazardID = p.HMIS_PhysicalHazardID where HazardEvaluationID = $id"; $conn = odbc_connect('HazComDB', 'admin', 'kollani') or die('Could not connect to DB'); $result = odbc_exec($conn, $arr_query); $phys_array = array(); while ($row = odbc_fetch_array($result)) { $phys_array[] = $row; } odbc_free_result($result); odbc_close($conn); return (array) $phys_array; } public function render_table($id) { $physical_hazard_array = $this->fetch_array($id); echo "<div id='physical_hazard_block'>\r\n"; echo "<h2>Physical Hazards</h2>\r\n"; if (!empty($physical_hazard_array)) { echo "<table class='hazard_summary'>\r\n"; foreach ($this->_Headers as $val) { echo "\t\t<th>{$val}</th>\r\n"; } foreach ($physical_hazard_array as $row) { echo "\t<tr>\r\n"; foreach ($this->_DisplayValues as $val) { echo "\t\t<td>{$row[$val]}</td>\r\n"; } echo "\t</tr>\r\n"; } echo "</table>\r\n"; }else{ echo "<p>No physical hazards identified</p>\r\n"; } echo "</div>"; } } ?>
Python
UTF-8
1,551
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
''' See https://github.com/hms5232/CaiBiBa/tree/master/EricaCompanyBonus for more information. ''' ''' ...... ...... ...... 7 14 28 56 112 ...... 3 6 12 24 48 96 ...... 1 2 4 8 16 32 64 ...... -------------------------------- 1 5 17 49 129 ........ ? ''' # 計算「列」上第 n 個位置的數字 def row_calculate(n): if n % 2 != 0: return n else: return row_calculate(n - 1) * 2 def main(): user_input = int(input()) # 輸入要幾行/列 all_list = [[0] * user_input for i in range(user_input)] # 整體 all_list[0][0] = 1 # 起始值 for j in range(user_input): # 空白部分補 0 for k in range(j): all_list[j][k] = 0 # 計算數字囉 m = j # 前面空白的部分就不用計算了 while m < user_input: if j == m: # 每列的起點 if j == 0: # 起源 # 因為已經在上面設定過了所以直接跳過即可 m += 1 continue # 起點的話為該行往下一列的數字+1 all_list[j][m] = all_list[j-1][m] + 1 m += 1 continue # 剩下的則是左邊數字的兩倍 all_list[j][m] = all_list[j][m-1]*2 m += 1 print(all_list) # 最後算出每一行的總和 column_sum_list = [] # 每一行的和 for o in range(user_input): # column column_sum = 0 # 該行總和 for p in range(user_input): # row column_sum += all_list[p][o] # 找出o行p列的數字 column_sum_list.append(column_sum) print('------------ SUM ------------\n', column_sum_list) if __name__ == '__main__': main()
Java
UTF-8
2,050
3.59375
4
[]
no_license
import java.util.Scanner; import java.util.*; public class Booking { static int ROWS = 3; static int COLUMNS = 5; boolean[][] booking = new boolean[ROWS][COLUMNS]; static Scanner userInput = new Scanner(System.in); public Booking() { } /** * Shows the booking of seats */ public void printBooking() { System.out.println(" <TV> "); for (int i = 0; i < ROWS; i++) { for (int j = 0; j < COLUMNS; j++) { System.out.print(this.booking[i][j] == true ? " O " : " . "); } System.out.println(" "); } System.out.println(" "); } /** * Prints user menu of available options */ public void printMenu() { System.out.println("1. Book a seat "); System.out.println("2. View Booking "); } /** * Makes booking * Provide row and col and if it is not booked already it will be booked * By assigning true to the array booking */ public void makeBooking() { System.out.println("Enter row(1-3) : "); int row = userInput.nextInt(); if (row < 1 || row > 3) row = 1; System.out.println("Enter column(1-5) : "); int column = userInput.nextInt(); if (column < 1 || column > 5) column = 1; if (this.booking[row - 1][column - 1] == true) { System.out.println("This seat is already booked, please book another seat"); } else { this.booking[row - 1][column - 1] = true; } } public static void main(String[] args) { Booking booking = new Booking(); booking.printBooking(); while (true) { booking.printMenu(); int choice = userInput.nextInt(); if (choice == 1) { booking.makeBooking(); } else { booking.printBooking(); } } } } // javac -d bin -sourcepath src src/com/ali/chat/Client.java // javac Booking.java && java Booking
JavaScript
UTF-8
592
2.828125
3
[]
no_license
const { fstat } = require("fs"); const fs = require("fs"); const colorData = require("./assets/colors.json"); //check if "Created With Node" exists or not and create one if does not present const dirName = "Test Files With Node"; if(!fs.existsSync(dirName)) { fs.mkdirSync(`./${dirName}`); } colorData.colorList.forEach((color) => { // appendFile() create a new file if does not exist and add text at the last part fs.appendFile(`./${dirName}/colors.txt`, `${color.color} : ${color.hex}\n`, err => { if(err) { console.log(err.message); } }); })
Java
UTF-8
335
2.703125
3
[]
no_license
/** * Checked Exception thrown when requested food and drink are not available * @author mdalton31 * @version 1 */ public class FoodAndDrinkNotFoundException extends Exception { /** * Constructor * @param msg exception message */ public FoodAndDrinkNotFoundException(String msg) { super(msg); } }
Java
UTF-8
741
2.03125
2
[]
no_license
package org.minispm.sale.service; import org.minispm.sale.entity.Source; import org.minispm.sale.dao.SourceDao; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; /** * User: shibaoxu * Date: 12-12-29 * Time: 下午9:00 */ @Service @Transactional(readOnly = true) public class SourceService { private SourceDao sourceDao; public List<Source> findAll(){ return sourceDao.findAll(); } public SourceDao getSourceDao() { return sourceDao; } @Autowired public void setSourceDao(SourceDao sourceDao) { this.sourceDao = sourceDao; } }
PHP
UTF-8
364
2.5625
3
[ "MIT" ]
permissive
<?php namespace App; use Illuminate\Database\Eloquent\Model; class UserProfile extends Model { const MALE = "male"; const FEMALE = "female"; protected $table = 'user_profiles'; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'first_name', 'last_name', 'gender' ]; }
Python
UTF-8
964
3.953125
4
[]
no_license
import time def Task1(func): '''Function decorator which executes the passed in function and prints its execution time. Also, the decorator tracks the number of times the function was called. The original name of function and docstring will be preserved.''' # function call tracker count = 0 def wrapper(*args, **kwargs): # saving the information from the passed in function to the wrapper function wrapper.__name__ = func.__name__ wrapper.__doc__ = func.__doc__ # calculate execution time timeVar = time.time() output = func(*args, **kwargs) timeVar = time.time() - timeVar # manage function call trace nonlocal count count += 1 # print the tracked information print(f"Function {func.__name__} was called {count} times.") print(f"Execution time of this call is {timeVar} seconds.") return output return wrapper
Markdown
UTF-8
1,536
2.734375
3
[]
no_license
# mccloskey-portfolio Public portfolio for my data vizzes. # /ABOUT ME 👨‍💻 Hello and welcome to my portfolio! My name is Garrett McCloskey (he/him) and over the past few years, I have spent time pivoting from performer to administrator through various arts management roles. My arts management journey began at the National Music Festival in Chestertown, Maryland and the experience inspired me to pursue further education in the field through the Master of Arts Management program in Carnegie Mellon University's Heinz College. I am currently completing my second year of the program and hold an Artistic Operations Internship position with the Pittsburgh Festival Opera. I hope to work in a marketing, artistic, or operations position at a performing arts center or with an orchestra in the near future, but I'll just have to see what's out there come May! Before coming to CMU, I earned a Bachelor of Arts in Music and Music Business Certificate from the University of Georiga in Athens, Georgia. I was born and raised in Charlotte, North Carolina. # /WHAT I HOPE TO LEARN 📚 I hope to learn the basic data visualization principles and best practices so that I can feel comfortable creating vizzes in future positions regardless of the discipline. I hope to learn my personal preferences when it comes to free visualization tools since there are so many out there! I also hope that I learn the most efficient way to find relevant data sets. # /PORTFOLIO 📊 Click [here](/portfoliopage_main.md) to check out my visualizations!
Markdown
UTF-8
482
2.734375
3
[ "MIT" ]
permissive
# Redux Custom project This is a project that you will conceive and build. The only requirements are: - It must be built with React - It must use Redux ## Scope Since class is only 6 weeks long and you will have other work and other classes you'll need to limit the scope of your project. It is okay to think big and imagine a large scale and complex project. For this assignment you can build only a subset, proof of concept, or first version of the idea.
Python
UTF-8
3,305
3.09375
3
[]
no_license
#!/usr/bin/python # @mpalonso SharifCTF2016 - Forensic 150 (concatenate the part of flag) cadena2 = "cb13bbb59dde" partecadena1 = "95cd605b" parte2cadena1 = "9065f44530" #TEORIA 1 ############################################## #Si hacemos el bucle tenemos una longitud de: # 95cd605b (+1) 9065f44530 # 19 digitos en una parte # 12 digitos en la cadena 2 # TOTAL: 31 digitos #Si quitamos la "i" # 95cd605b9065f44530 # 18 digitos en una parte # 12 digitos en la otra # TOTAL: 30 digitos # asumimos que esta es la correcta, pero de ser asi en que digito nos estamos equivocando dic = "abcdef0123456789" dicmay = "ABCDEF0123456789" print "\n" print "######################################################################" print "CADENA 1 + CADENA 2 minus" print "######################################################################" print "\n" for i in dic: for j in i: print "SharifCTF{" + partecadena1 + i + parte2cadena1 + cadena2 + "}" print "\n" print "######################################################################" print "CADENA 2 + CADENA 1 minus " print "######################################################################" print "\n" for i in dic: for j in i: print "SharifCTF{" + cadena2 + partecadena1 + i + parte2cadena1 + "}" print "\n" print "######################################################################" print "CADENA NORMAL minus" print "######################################################################" print "\n" print "SharifCTF{" + partecadena1 + parte2cadena1 + cadena2 + "}" print "SharifCTF{" + cadena2 + partecadena1 + parte2cadena1 + "}" print "\n" print "######################################################################" print "CADENA 1 + CADENA 2 mayus" print "######################################################################" print "\n" for i in dicmay: for j in i: print "SharifCTF{" + partecadena1.upper() + i + parte2cadena1.upper() + cadena2.upper() + "}" print "\n" print "######################################################################" print "CADENA 2 + CADENA 1 mayus " print "######################################################################" print "\n" for i in dicmay: for j in i: print "SharifCTF{" + cadena2.upper() + partecadena1.upper() + i + parte2cadena1.upper() + "}" print "\n" print "######################################################################" print "CADENA NORMAL mayus" print "######################################################################" print "\n" print "SharifCTF{" + partecadena1.upper() + parte2cadena1.upper() + cadena2.upper() + "}" print "SharifCTF{" + cadena2.upper() + partecadena1.upper() + parte2cadena1.upper() + "}" print "\n" print "\n" for i in dic: for j in i: print partecadena1 + i + parte2cadena1 + cadena2 for i in dic: for j in i: print cadena2 + partecadena1 + i + parte2cadena1 print partecadena1 + parte2cadena1 + cadena2 print cadena2 + partecadena1 + parte2cadena1 for i in dicmay: for j in i: print partecadena1.upper() + i + parte2cadena1.upper() + cadena2.upper() for i in dicmay: for j in i: print cadena2.upper() + partecadena1.upper() + i + parte2cadena1.upper() print partecadena1.upper() + parte2cadena1.upper() + cadena2.upper() print cadena2.upper() + partecadena1.upper() + parte2cadena1.upper()
TypeScript
UTF-8
1,444
2.78125
3
[]
no_license
import axios from 'axios'; import { API_PEOPLE } from '../config'; import { FilmsSuccessResponse, PersonsFilms } from '../types/films'; import { PeopleSuccessResponse, Person } from '../types/people'; import { PlanetsSuccessResponse } from '../types/planets'; async function genericFetch<T>(url: string): Promise<T> { try { const response = await axios.get(url); return response.data; } catch (error) { throw new Error(error); } } export async function fetchPeopleBySearchTerm(name: string) { const url = `${API_PEOPLE}?search=${name}`; return genericFetch<PeopleSuccessResponse>(url); } export async function fetchPersonById(id: string) { const url = `${API_PEOPLE}/${id}`; return genericFetch<Person>(url); } export async function fetchPlanet(url: string) { return genericFetch<PlanetsSuccessResponse>(url); } export async function fetchFilm(url: string): Promise<FilmsSuccessResponse> { return genericFetch<FilmsSuccessResponse>(url); } export async function fetchPersonsFilms( id: string ): Promise<{ data?: PersonsFilms; error?: string }> { try { const person = await fetchPersonById(id); if (!person?.films) { throw new Error(); } const films = await Promise.all(person.films.map((url) => fetchFilm(url))); return { data: { personsName: person.name, films, }, }; } catch (error) { return { error: 'Character not found' }; } }
Java
UTF-8
1,295
3.515625
4
[]
no_license
package java8; import java.util.Arrays; import java.util.List; import java.util.function.Consumer; import java.util.function.Function; /** * todo * * @author zhouq * @email zhouqiao@gmail.com * @date 2018/8/4 17:00 */ public class MethodReference { private static <T> void useConsumer(Consumer<T> consumer,T t){ consumer.accept(t); } public static void main(String[] args) { Consumer<String> consumer = (s) -> System.out.println(s); useConsumer(consumer,"Hello zhouq"); useConsumer(s -> System.out.println(s),"Hello zhouq"); useConsumer(System.out::println,"Hello zhouq"); System.out.println("================================"); List<Apple> apples = Arrays.asList(new Apple("green", 100), new Apple("abc", 300), new Apple("bd", 200)); System.out.println(apples); apples.sort((a1,a2) -> a1.getColor().compareTo(a2.getColor())); System.out.println(apples); System.out.println("================================"); apples.stream().forEach(System.out::println); int i = Integer.parseInt("123"); System.out.println(i); Function<String,Integer> f = Integer::parseInt; Integer result = f.apply("123"); System.out.println(result); } }
Java
UTF-8
5,374
2.203125
2
[]
no_license
package com.yangc.blog.service.impl; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.apache.commons.collections.MapUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.yangc.blog.bean.CategoryTree; import com.yangc.blog.bean.TBlogCategory; import com.yangc.blog.service.ArticleService; import com.yangc.blog.service.CategoryService; import com.yangc.dao.BaseDao; import com.yangc.dao.JdbcDao; @Service public class CategoryServiceImpl implements CategoryService { @Autowired private BaseDao baseDao; @Autowired private JdbcDao jdbcDao; @Autowired private ArticleService articleService; @Override public void addOrUpdateCategory(Long categoryId, String categoryName, Long serialNum, Long parentCategoryId) { TBlogCategory category = (TBlogCategory) this.baseDao.get(TBlogCategory.class, categoryId); if (category == null) { category = new TBlogCategory(); } category.setCategoryName(categoryName); category.setSerialNum(serialNum); category.setParentCategoryId(parentCategoryId); this.baseDao.save(category); } @Override public void updateParentCategoryId(Long categoryId, Long parentCategoryId) { this.baseDao.updateOrDelete("update TBlogCategory set parentCategoryId = ? where id = ?", new Object[] { parentCategoryId, categoryId }); } @Override public void delCategory(Long categoryId) throws IllegalStateException { int totalCount = this.baseDao.getCount("select count(c) from TBlogCategory c where c.parentCategoryId = ?", new Object[] { categoryId }); if (totalCount > 0) { throw new IllegalStateException("该类别下存在子类别"); } if (this.articleService.getArticleListBycategoryId_count(categoryId) > 0) { throw new IllegalStateException("该类别下存在文章"); } this.baseDao.updateOrDelete("delete TBlogCategory where id = ?", new Object[] { categoryId }); } @Override public List<CategoryTree> getCategoryTreeListByParentCategoryId(Long parentCategoryId) { String sql = JdbcDao.SQL_MAPPING.get("blog.category.getCategoryTreeListByParentCategoryId"); Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("parentCategoryId", parentCategoryId); List<Map<String, Object>> mapList = this.jdbcDao.findAll(sql, paramMap); if (mapList == null || mapList.isEmpty()) return null; List<CategoryTree> categoryTreeList = new ArrayList<CategoryTree>(); for (Map<String, Object> map : mapList) { CategoryTree categoryTree = new CategoryTree(); categoryTree.setLeaf(MapUtils.getLongValue(map, "TOTALCOUNT") == 0); categoryTree.setCategoryId(MapUtils.getLong(map, "ID")); categoryTree.setCategoryName(MapUtils.getString(map, "CATEGORY_NAME")); categoryTree.setSerialNum(MapUtils.getLong(map, "SERIAL_NUM")); categoryTree.setParentCategoryId(parentCategoryId); categoryTreeList.add(categoryTree); } return categoryTreeList; } @Override public List<TBlogCategory> getCategoryListSameLevel() { String sql = JdbcDao.SQL_MAPPING.get("blog.category.getCategoryList"); List<Map<String, Object>> mapList = this.jdbcDao.findAll(sql, null); if (mapList == null || mapList.isEmpty()) return null; List<TBlogCategory> categoryList = new ArrayList<TBlogCategory>(); for (Map<String, Object> map : mapList) { TBlogCategory category = new TBlogCategory(); category.setId(MapUtils.getLong(map, "ID")); category.setCategoryName(MapUtils.getString(map, "CATEGORY_NAME")); category.setParentCategoryId(MapUtils.getLong(map, "PARENT_CATEGORY_ID")); categoryList.add(category); } return categoryList; } @Override public List<TBlogCategory> getCategoryListDiffLevel() { String sql = JdbcDao.SQL_MAPPING.get("blog.category.getCategoryList"); List<Map<String, Object>> mapList = this.jdbcDao.findAll(sql, null); if (mapList == null || mapList.isEmpty()) return null; Map<Long, TBlogCategory> tempMap = new LinkedHashMap<Long, TBlogCategory>(); for (Map<String, Object> map : mapList) { Long id = MapUtils.getLong(map, "ID"); String categoryName = MapUtils.getString(map, "CATEGORY_NAME"); Long pid = MapUtils.getLong(map, "PARENT_CATEGORY_ID"); if (pid == 0) { TBlogCategory category = new TBlogCategory(); category.setId(id); category.setCategoryName(categoryName); category.setParentCategoryId(pid); category.setChildRenCategory(new ArrayList<TBlogCategory>()); tempMap.put(id, category); } else { TBlogCategory parentCategory = tempMap.get(pid); if (parentCategory == null) continue; TBlogCategory category = new TBlogCategory(); category.setId(id); category.setCategoryName(categoryName); category.setParentCategoryId(pid); List<TBlogCategory> childRenCategory = parentCategory.getChildRenCategory(); childRenCategory.add(category); parentCategory.setChildRenCategory(childRenCategory); } } List<TBlogCategory> categoryList = new ArrayList<TBlogCategory>(); for (Entry<Long, TBlogCategory> entry : tempMap.entrySet()) { categoryList.add(entry.getValue()); } return categoryList; } }
PHP
UTF-8
1,156
2.53125
3
[]
no_license
<?php use yii\db\Migration; /** * Class m200215_173611_fuel2types_ch4 */ class m200215_173611_fuel2types_ch4 extends Migration { /** * {@inheritdoc} */ public function safeUp() { try{ if(empty($this->getDb()->getSchema()->getTableSchema('fueltypes')->getColumn('EmissionCH4'))) { $this->addColumn('fueltypes', 'EmissionCH4', 'float(2,2) not null'); } }catch(Exception $ex){ echo $ex; return false; } } /** * {@inheritdoc} */ public function safeDown() { try{ if(empty($this->getDb()->getSchema()->getTableSchema('fueltypes')->getColumn('EmissionCH4'))) { $this->dropColumn('fueltypes', 'EmissionCH4'); } }catch(Exception $ex){ echo $ex; } } /* // Use up()/down() to run migration code without a transaction. public function up() { } public function down() { echo "m200215_173611_fuel2types_ch4 cannot be reverted.\n"; return false; } */ }
Python
UTF-8
318
3.0625
3
[]
no_license
#!/usr/bin/python3 # -*- coding: utf-8 -*- def fib ( c ) : ''' возвращает числа Фибоначи ''' if C == 1 : return [ 0 ] if C == 1 : return [ 0, 1 ] Result = [ 0, 1 ] for k in range(2,C) : Result.append( Result[-2] + Result[-1] ) return Result
Go
UTF-8
2,530
3.09375
3
[ "Apache-2.0" ]
permissive
package dag import ( "fmt" "sync" "gitlab.com/alephledger/consensus-go/pkg/gomel" ) type fiberMap struct { content map[int]gomel.SlottedUnits width uint16 length int mx sync.RWMutex } type noSuchFiberError struct { value int } func newNoSuchFiberError(value int) *noSuchFiberError { return &noSuchFiberError{value} } func (e *noSuchFiberError) Error() string { return fmt.Sprintf("value %v does not exist", e.value) } func newFiberMap(width uint16, initialLen int) *fiberMap { newMap := &fiberMap{ content: make(map[int]gomel.SlottedUnits), width: width, length: initialLen, } for i := 0; i < initialLen; i++ { newMap.content[i] = newSlottedUnits(width) } return newMap } func (fm *fiberMap) getFiber(value int) (gomel.SlottedUnits, error) { fm.mx.RLock() defer fm.mx.RUnlock() result, ok := fm.content[value] if !ok { return nil, newNoSuchFiberError(value) } return result, nil } func (fm *fiberMap) Len() int { fm.mx.RLock() defer fm.mx.RUnlock() return fm.length } func (fm *fiberMap) extendBy(nValues int) { fm.mx.Lock() defer fm.mx.Unlock() for i := fm.length; i < fm.length+nValues; i++ { fm.content[i] = newSlottedUnits(fm.width) } fm.length += nValues } // get takes a list of heights (of length nProc) and returns a slice (of length nProc) of slices // of corresponding units. The second returned value is the number of unknown units // (no units for that creator-height pair). func (fm *fiberMap) get(heights []int) ([][]gomel.Unit, int) { if len(heights) != int(fm.width) { panic("wrong number of heights passed to fiber map") } result := make([][]gomel.Unit, fm.width) unknown := 0 fm.mx.RLock() defer fm.mx.RUnlock() for pid, h := range heights { if h == -1 { continue } if su, ok := fm.content[h]; ok { result[pid] = su.Get(uint16(pid)) } if len(result[pid]) == 0 { unknown++ } } return result, unknown } // above takes a list of heights (of length nProc) and returns all units above those heights. func (fm *fiberMap) above(heights []int) []gomel.Unit { if len(heights) != int(fm.width) { panic("wrong number of heights passed to fiber map") } min := heights[0] for _, h := range heights[1:] { if h < min { min = h } } var result []gomel.Unit fm.mx.RLock() defer fm.mx.RUnlock() for height := min + 1; height < fm.length; height++ { su := fm.content[height] for i := uint16(0); i < fm.width; i++ { if height > heights[i] { result = append(result, su.Get(i)...) } } } return result }
Markdown
UTF-8
9,740
3.3125
3
[]
no_license
## Лекция 17. Всего по-немногу про хранение объектов Темы на сегодня: * объектно-реляционные принципы хранения * убер-коллекции (модуль collections) * Структуры данных * Алгоритмы. Введение ***Задача:*** хотим узнать, каким образом можно сохранить информацию про объекты за пределами работающего кода? ### Шаг 1. Объектно-реляционный принцип хранения данных. ***ОРпх*** - принцип, согласно которому, объекты сохраняются совместимо со своей внутренней структурой. Рассмотрим 2 варианта данного принцпа: * Использование сериализации * Использование табличных представлений ### Шаг 2. Использование сериализации для ОРпх ***Сериализация*** - это способ представления объекта в виде байтовой последовательности. ***Десериализация*** - это способ сборки объекта из байтовой последовательности. ***Существует*** 2 достаточно популярных механизмов сериализации : * низкоуровненвая сериализация ```pickle``` * высокоуровненвая сериализация ```json``` ### Шаг 3. Высокоуровневая сериализация ```json``` ``` data = [ {"id":1, "name":"bob"}, {"id":501, "name" :"alice"}, {"id":None, "name" : "petya"}, ] # Хотелка - хотим сохранить этот объект data с его структурой import json """ JavaScript Object Notation """ # 1. Нативная сераилизация with open("data.json", "w") as fhand: json.dump(data, fhand, indent=4) ``` На этапе ```.dump``` происходят следующие действия: * Представление объекта ```data``` в виде байтовой последовательности * Затем байтовая последовательность транслируется в ```.js``` код * После чего данный код записывается в ```.json``` файл Теперь в обратном порядке - ***десериализация***: ``` import json # 2. Нативная десериализация new_data = None with open("data.json", "r") as fhand: new_data = json.load(fhand) print("Read from json:", new_data) print("Type:", type(new_data)) ``` На этапе ```.load``` происходят следующие действия: * Все, что написано в файле ```data.json``` представляем в виде байтовой последовательности * Затем байтовая последовательность транслируется в ```.py``` код * После чего объект, получившийся на прошлом этапе, помещается в какую-либо переменную ### Шаг 4. Низкоуровневая сериализация ```pickle``` Теперь главная задача - это посмотреть на саму байтовую последовательность, и может быть мы даже захотим эту последовательность сохранять в исходном виде. ``` import pickle """ Модуль низкоуровневой сериализации в Python """ data = [ {"id":1, "name":True}, {"id":501, "name" :"alice"}, {"id":None, "name" : "petya"}, ] # 3. Сериализация в байтовый файл with open("data.pickle", "wb") as fhand: pickle.dump(data, fhand) # 4. Десериализация из байтового файла new_data = None with open("data.pickle", "rb") as fhand: new_data = pickle.load(fhand) print(new_data) ``` Сериализация и десериализация при помощи модуля ```pickle``` позволяет конвертировать (и реконвертировать) объект с сохраняем его вложенной структуры по отношению к байтовым последовательностям на прямую (не создается дополнительного файла, содержащего код другого ЯП). ***Какие преимущества в работе с сериализованными объектами***?: * Гораздо ускоренное время обращения как к байтовому файлу, так и к его содержимому * Сохранение структуры объекта ### Шаг 5. А что можно сериализовать? * примитивы (базовые типы, базоовые коллекции) * пользовательские обхекты * функции * классы ### Шаг 6. Использование табличных представлений ***Предоложение***: давайте использовать для хранения объектов реляционные базы данных. Это очень удобно, модностильнопопулярно (хотя > 60 лет этой технологии). Добавочное классное свойство - способность взаимодействовать с объектами - через ```SQL```. ***База данных*** - это набор структурированных (информационных) представлений. ***С базами данных неразрывно связана некая система менеджмента данных*** - это ***СУБД*** (система управления базами данных). ***СУБД*** бывают: * реляционные * столбчатые * колончатые * нереляционные * и прочие. Будем рассматривать реляционные СУБД. ***РСУБД*** - это сисетма управления базами данных основанная на принципе отношений между таблицами. Данные в реляционных СУБД располагаются в виде наборов таблиц , между которым (чаще всего) сущесвуют связи (реляции, отношений). ### Шаг 7. Хотелка * Посмотреть на основные ```SQL``` команды (запросы) * Попробовать выполнить их с использованием простейшей РСУБД * Научить наши объекты (в контексте Python) взаимодействовать с такими базами данных ***Замечание***: * Learning SQL . Книга, Алан Болье * Введение в системы баз данных Книга, Кристофер Дейт ### Шаг 7.1 Основные запросы на языке SQL ***Запрос на яызке SQL*** - это команда кмпилятору (СУБД) что-нибудь сделать с данными или таблицами. ***Запросов бывает 2 семейства:*** * запросы на изменение/создание/сброс структуры хранения данных * запросы на изменение/создание/сброс данных в таблицах ``` /* This is comment on SQL */ /* Хотим хранить книги */ /* Книга представляет из себя следующий набор */ /* Название строка(текст) */ /* Автор строка(текст)*/ /* Количество страниц (целое число)*/ /* Цена (вещественное число)*/ /* Первый запрос на создание таблицы для хранения информации про книги */ CREATE TABLE IF NOT EXISTS books (title TEXT, author TEXT, pages INT, price REAL); /* Несколько запросов по работе с данными в таблице books */ /* Допустим у меня есть книга ("LOTR:1", "J.J.Tolkin", 750, 14.99) */ INSERT INTO books (title, author, pages, price) VALUES("LOTR:1", "J.J.Tolkin", 750, 14.99); /* Теперь хочу прочитать из таблицы */ SELECT * FROM books; /* Теперь я понял, что ошибься в цене товара, хочу поменять */ UPDATE books SET price = 149.99 WHERE title = "LORT:1"; /* Теперь удалим какую-нибудь книжку */ DELETE FROM books WHERE title = "LOTR:1"; ``` ### Шаг 7.2 Существующие РСУБД * ```PostgreSQL``` - круто мощно молодежно (бесплатно) * ```MySQL``` - круто мощно молодежно (бесплатно) * ```SQLite``` - относительно круто, не мощно, но молодежно (СРАЗУ ВШИТО В ИНТЕРПРЕТАТОР PYTHON). Попробуем теперь сосредоточить свое внимание на ```sqlite```. ### Шаг 7.3 Подключение sqlite и создание базы данных
Python
UTF-8
1,021
3.421875
3
[]
no_license
#!/usr/bin/env python3 import wiki import redis def populate_from_category(redis_server, cat, level=0): """ Populates a redis set 'foo' with wikipedia subcategories. """ if not redis_server.sismember('foo', cat) and level < 5: redis_server.sadd('foo', cat) subcat = wiki.get_subcategories(cat) print(level, cat, subcat) for c in subcat: populate_from_category(redis_server, c, level+1) def main(): # Connection to redis server r = redis.StrictRedis(host='localhost', port=6379, db=0) # To start from scratch, delete the 'foo' set from redis. #r.delete('foo') # Add subcategories to the redis set 'foo'. # Choose one of these as starting points. populate_from_category(r, 'Anatomy') #populate_from_category(r, 'Animal anatomy') #populate_from_category(r, 'Organs (anatomy)') #populate_from_category(r, 'Thorax (human anatomy)') #populate_from_category(r, 'Human anatomy') if __name__ == "__main__": main()
Java
UTF-8
976
2.171875
2
[]
no_license
package com.zf.servletInitializer; import com.zf.config.RootConfig; import com.zf.config.WebConfig; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer; /** * @author 郑凡 * @create 2020-09-29 16:28 * web容器启动的时候创建对象 调用方法来初始化以前前端控制器 */ public class MyAbstractAnnotationConfigDispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { // 获取根容器的配置类 @Override protected Class<?>[] getRootConfigClasses() { return new Class[]{RootConfig.class}; } // 获取web容器的配置类 spring mvc的配置文件 子容器 @Override protected Class<?>[] getServletConfigClasses() { return new Class[]{WebConfig.class}; } // 获取servlet 的映射信息 拦截所有请求 @Override protected String[] getServletMappings() { return new String[]{"/"}; } }
JavaScript
UTF-8
1,075
3.65625
4
[ "BSD-3-Clause" ]
permissive
/** * 基于 {@link Color.spaces.rgb|rgb 色彩空间} ,获取或设置 Color 对象的红色值。 * @see {@link Color#green} * @see {@link Color#blue} * @see {@link Color#value} * @access public * @func Color.prototype.red * @param {number} [value] - 红色。取值范围为 `0 - 255` 。如果省略此参数则获取并返回当前值。否则将根据本参数修改当前值并返回当前 Color 对象。 * @param {boolean} [relative=false] * @param {boolean} relative.false - 绝对赋值。将对象的色度设置为 `value` 。 * @param {boolean} relative.true - 增量赋值。将对象当前色度增加 `value` 。 * @returns {Color|number} * @example * var tiffanyblue = new Color('#60DFE5'); * console.log(tiffanyblue.css(0)); // #60DFE5 * console.log(tiffanyblue.red()); // 96 * console.log(tiffanyblue.red(380).red()); // 255 * console.log(tiffanyblue.red(-30, true).red()); // 225 * console.log(tiffanyblue.red(-90, true).red()); // 135 * console.log(tiffanyblue.css(0)); // #87DFE5 */
Java
UTF-8
4,585
1.640625
2
[ "Apache-2.0", "BSD-2-Clause", "Apache-1.1" ]
permissive
/* * The Apache Software License, Version 1.1 * * Copyright (c) 2000 The Apache Software Foundation. All rights * reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * 3. The end-user documentation included with the redistribution, if * any, must include the following acknowlegement: * "This product includes software developed by the * Apache Software Foundation (http://www.apache.org/)." * Alternately, this acknowlegement may appear in the software itself, * if and wherever such third-party acknowlegements normally appear. * * 4. The names "The Jakarta Project", "Tomcat", and "Apache Software * Foundation" must not be used to endorse or promote products derived * from this software without prior written permission. For written * permission, please contact apache@apache.org. * * 5. Products derived from this software may not be called "Apache" * nor may "Apache" appear in their names without prior written * permission of the Apache Group. * * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.tools.ant.types; import org.apache.tools.ant.Path; /* * * @author thomas.haas@softwired-inc.com */ public class CommandlineJava { private Commandline vmCommand = new Commandline(); private Commandline javaCommand = new Commandline(); private Path classpath = new Path(); private String vmVersion; public CommandlineJava() { setVm("java"); setVmversion(org.apache.tools.ant.Project.getJavaVersion()); } public Commandline.Argument createArgument() { return javaCommand.createArgument(); } public Commandline.Argument createVmArgument() { return vmCommand.createArgument(); } public void setVm(String vm) { vmCommand.setExecutable(vm); } public void setVmversion(String value) { vmVersion = value; } public void setClassname(String classname) { javaCommand.setExecutable(classname); } public Path createClasspath() { return classpath; } public String getVmversion() { return vmVersion; } public String[] getCommandline() { int size = vmCommand.size() + javaCommand.size(); if (classpath.size() > 0) { size += 2; } String[] result = new String[size]; System.arraycopy(vmCommand.getCommandline(), 0, result, 0, vmCommand.size()); if (classpath.size() > 0) { result[vmCommand.size()] = "-classpath"; result[vmCommand.size()+1] = classpath.toString(); } System.arraycopy(javaCommand.getCommandline(), 0, result, result.length-javaCommand.size(), javaCommand.size()); return result; } public String toString() { return Commandline.toString(getCommandline()); } public int size() { int size = vmCommand.size() + javaCommand.size(); if (classpath.size() > 0) { size += 2; } return size; } }
Python
UTF-8
575
3.921875
4
[]
no_license
# Program to print the numbers first which has highest frequency of appearance # e.g. Input: 2,3,2,2,2,3,3,3,4,3,4,4,4,5,4,4,4 # Output: 4,4,4,4,4,4,4,3,3,3,3,3,2,2,2,2,5 numbers = [int(x) for x in input().split(",")] num_count = {} count = len(numbers) for i in numbers: if i not in num_count.keys(): num_count[i] = 1 else: num_count[i] += 1 for key, value in sorted(num_count.items(), reverse=True, key=lambda x: x[1]): for j in range(value): print(key, end="") count -= 1 if count != 0: print(",", end="")
Python
UTF-8
17,755
3.46875
3
[]
no_license
import random from typing import List import os import time from prettytable import PrettyTable import numpy as np # Classes required for BlackJack # Card class that will represent each single card. class Card: CLUB = "\u2663" HEART = "\u2665" DIAMOND = "\u2666" SPADE = "\u2660" def __init__(self, pip, suit, value): self.pip = pip self.suit = suit self.value = value def show(self): print(f"{self.pip} {self.showSuit(self.suit)}", end='') def __str__(self): return f"{self.pip} {self.showSuit(self.suit)}" def showSuit(self, suit): if suit == 'CLUB': return Card.CLUB elif suit == 'SPADE': return Card.SPADE elif suit == 'DIAMOND': return Card.DIAMOND elif suit == 'HEART': return Card.HEART # Deck Class that will contain a deck of complete 52 cards i.e 52 objects of Card class. class Deck: def __init__(self): self.cards = [] self.build() def build(self): PIPS = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K") VALUES = (11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10) SUITS = ('CLUB', 'SPADE', 'DIAMOND', 'HEART') for s in SUITS: for pip, v in zip(PIPS, VALUES): self.cards.append(Card(pip, s, v)) def show(self): print('Deck Includes : ') for c in self.cards: print(c) def shuffle(self): random.shuffle(self.cards) def drawCard(self): return self.cards.pop() class Player: def __init__(self, name: str, bet_value=20, chips: int = 100): self.name = name self.hands = [] self.handsValue = 0 self.stand = False self.aces = 0 self.chips = chips self.bet_value = bet_value self.results = {'wins': 0, 'losses': 0, 'busts': 0} def hit(self, deck: Deck): card = deck.drawCard() self.hands.append(card) self.handsValue += card.value if card.value == 11: self.aces += 1 self.adjust_for_aces() def show_hand(self) -> None: print(f'{self.name} Hand : ') for card in self.hands: print(card) def adjust_for_aces(self): while self.handsValue > 21 and self.aces: self.handsValue -= 10 self.aces -= 1 def display_results(self): print(f"\n{self.name} : WINS -> {self.results.get('wins')}, LOSSES -> {self.results.get('losses')} & BUSTS -> {self.results.get('busts')}") def reset_hand(self): self.hands = [] self.handsValue = 0 self.stand = False self.aces = 0 self.bet_value = 20 class Dealer: def __init__(self, players: List[Player]): self.name = "DEALER" self.hands = [] self.handsValue = 0 self.aces = 0 self.players = players def show_some(self) -> None: print(f'{self.name} Hand : ') print('1 dealer card hidden!') print(self.hands[1]) def show_hand(self) -> None: print(f'{self.name} Hand : ') for card in self.hands: print(card) def hit(self, deck: Deck): card = deck.drawCard() self.hands.append(card) self.handsValue += card.value if card.value == 11: self.aces += 1 self.adjust_for_aces() return self def adjust_for_aces(self): while self.handsValue > 21 and self.aces: self.handsValue -= 10 self.aces -= 1 # def settle(self, players: List[Player]): # for player in players: # if player.hand.winningHand: # player.chips += BET_VALUE class BlackJack: def __init__(self, players: List[Player]): self.players = players self.dealer = Dealer(players) self.gameOn = False os.system('cls') # Starting the Game self.start_game() def start_game(self): # Create & shuffle the deck, deal two cards to each player deck = Deck() deck.shuffle() player = self.players[0] player.hit(deck) player.hit(deck) self.dealer.hit(deck) self.dealer.hit(deck) self.player_bet(player) # Show cards (but keep one dealer card hidden) # self.display_board_partial(self.players, self.dealer) self.game_screen(player, partial=True) if player.handsValue == 21: self.player_wins(player, self.dealer) else: while not player.stand: # We will continue untill player decides to stand or busts # Prompt for Player to Hit or Stand self.hit_or_stand(player, deck) # #Show cards (but keep one dealer card hidden) # self.display_board(self.players, self.dealer) self.game_screen(player, partial=True) # If player's hand exceeds 21, run player_busts() and break out of loop if player.handsValue > 21: self.player_busts(player, self.dealer) # Resseting player game attributes player.reset_hand() # Inform Player of their chips total player.display_results() print(f"\n{player.name}'s winnings stand at : {player.chips}") return None elif player.handsValue == 21: self.player_wins(player, self.dealer) # Resseting player game attributes player.reset_hand() # Inform Player of their chips total player.display_results() print(f"\n{player.name}'s winnings stand at : {player.chips}") return # If Player hasn't busted, play Dealer's hand until Dealer reaches 17 os.system('cls') print(f"Player standing on {player.handsValue}. Its Dealers Turn!") time.sleep(0.50) print("Dealer's hand will be continued until Dealer reaches 17") time.sleep(2.5) if player.handsValue <= 21: while self.dealer.handsValue < 17: self.game_screen_dealer() print(f'{self.dealer.name} : Drawing the CARD from DECK . . . ') self.dealer.hit(deck) # hit() function defined above time.sleep(1) print(f'{self.dealer.name} : The card drawn is - ', end='', flush=True) time.sleep(0.75) print(f' {self.dealer.hands[-1]}') time.sleep(2) # Show all cards self.game_summary() print("This is the Final Scorecard ...") time.sleep(3) # Run different winning scenarios if self.dealer.handsValue > 21: self.dealer_busts(player, self.dealer) elif self.dealer.handsValue > player.handsValue: self.dealer_wins(player, self.dealer) elif self.dealer.handsValue < player.handsValue: self.player_wins(player, self.dealer) else: self.push(player, self.dealer) # Resseting player game attributes player.reset_hand() # Inform Player of their chips total player.display_results() print(f"\n{player.name}'s winnings stand at : {player.chips}") def player_bet(self, player: Player): print(f'{player.name}, you have got {player.chips} Chips') while True: try: player.bet_value = int(input('Enter the amount of chips you want to bet : ')) except Exception: print('Please enter a valid integer chips amount!') else: if player.bet_value < 1: print(f'Bet should be at lease 1!') continue if player.bet_value > player.chips: print(f'Insufficient Chips! Your chips : {player.chips}') continue else: break def hit_or_stand(self, player: Player, deck: Deck): while True: x = input(f"{player.name} :Would you like to Hit or Stand? Enter 'h' or 's' ") if x[0].lower() == 'h': print(f'{player.name} : Drawing the CARD from DECK . . . ') player.hit(deck) # hit() function defined above time.sleep(1) print(f'{player.name} : The card drawn is - ', end='', flush=True) time.sleep(0.75) print(f' {player.hands[-1]}') time.sleep(1.75) elif x[0].lower() == 's': print(f"{player.name} will STAND on {player.handsValue}") time.sleep(2) player.stand = True else: print("Sorry, please try again.") continue break def player_wins(self, player: Player, dealer: Dealer): self.game_summary() if player.handsValue == 21: print("!!!!--CONGRATS! YOU'VE HIT A BLACKJACK--!!!!") print(f"!!!--------------{player.name} WINS!--------------!!!") print(f"!!!------------ WINNER : {player.name} -----------!!!") player.results['wins'] += 1 player.chips += player.bet_value def player_busts(self, player: Player, dealer: Dealer): self.game_summary() print(f"!!!--------------{player.name} BUSTS!--------------!!!") print(f"!!!------------ WINNER : {dealer.name} -----------!!!") player.results['busts'] += 1 player.chips -= player.bet_value def dealer_busts(self, player: Player, dealer: Dealer): self.game_summary() print(f"!!!--------------{dealer.name} BUSTS!--------------!!!") print(f"!!!------------ WINNER : {player.name} -----------!!!") player.results['wins'] += 1 player.chips += player.bet_value def dealer_wins(self, player: Player, dealer: Dealer): self.game_summary() if dealer.handsValue == 21: print("!!!!--DEALER HAS HIT A BLACKJACK--!!!!") print(f"!!!--------------{dealer.name} WINS!--------------!!!") print(f"!!!------------ WINNER : {dealer.name} -----------!!!") player.results['losses'] += 1 player.chips -= player.bet_value def push(self, player: Player, dealer: Dealer): self.game_summary() print("Dealer and Player tie! It's a push.") def display_board(self, players: List[Player], dealer: Dealer): headers = [dealer.name] lens = [len(dealer.hands)] for player in players: lens.append(len(player.hands)) headers.append(player.name) max_len = max(lens) delear_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(dealer.hands): delear_hand_arr[i] = card arr = np.array([delear_hand_arr]) for player in players: player_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(player.hands): player_hand_arr[i] = card arr = np.append(arr, [player_hand_arr], axis=0) arr = arr.T t = PrettyTable(headers) for row in arr: t.add_row(row) print(t) def display_board_partial(self, players: List[Player], dealer: Dealer): headers = [dealer.name] lens = [len(dealer.hands)] for player in players: lens.append(len(player.hands)) headers.append(player.name) max_len = max(lens) delear_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(dealer.hands): if i == 0: delear_hand_arr[i] = 'HIDDEN' else: delear_hand_arr[i] = card arr = np.array([delear_hand_arr]) for player in players: player_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(player.hands): player_hand_arr[i] = card arr = np.append(arr, [player_hand_arr], axis=0) arr = arr.T t = PrettyTable(headers) for row in arr: t.add_row(row) print(t) def display_summary_board(self): headers = [self.dealer.name] lens = [len(self.dealer.hands)] for player in self.players: lens.append(len(player.hands)) headers.append(player.name) max_len = max(lens) + 2 delear_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(self.dealer.hands): delear_hand_arr[i] = card delear_hand_arr[-2] = '------------' delear_hand_arr[-1] = self.dealer.handsValue arr = np.array([delear_hand_arr]) for player in self.players: player_hand_arr = ['' for i in range(max_len)] for i, card in enumerate(player.hands): player_hand_arr[i] = card player_hand_arr[-2] = '------------' player_hand_arr[-1] = player.handsValue arr = np.append(arr, [player_hand_arr], axis=0) arr = arr.T t = PrettyTable(headers) for row in arr: t.add_row(row) print(t) def game_screen(self, player, partial=False): os.system('cls') print(f'-------PLAYERS (bet value) {len(self.players)} nos. : ', end='') for ply in self.players: print(f"{ply.name} ({ply.bet_value}), ", end='') print('-------\n-----------------------------------------------------------------------') if partial: self.display_board_partial(self.players, self.dealer) else: self.display_board(self.players, self.dealer) print('-----------------------------------------------------------------------') print(f"CURRENT TURN : {player.name}") print(f"{player.name}'s previous hit - {player.hands[-1]}") print('-----------------------------------------------------------------------') def game_screen_dealer(self): os.system('cls') print(f'-------PLAYERS (bet value) {len(self.players)} nos. : ', end='') for ply in self.players: print(f"{ply.name} ({ply.bet_value}), ", end='') print('-------\n-----------------------------------------------------------------------') self.display_board(self.players, self.dealer) print('-----------------------------------------------------------------------') print(f"CURRENT TURN : {self.dealer.name}") print(f"{self.dealer.name}'s previous hit - {self.dealer.hands[-1]}") print('-----------------------------------------------------------------------') def game_summary(self): os.system('cls') print(f'-------PLAYERS (bet value) {len(self.players)} nos. : ', end='') for ply in self.players: print(f"{ply.name} ({ply.bet_value}), ", end='') print('-------\n-----------------------------------------------------------------------') self.display_summary_board() print('-----------------------------------------------------------------------') # Printing an opening statements print('> Welcome to BlackJack! Get as close to 21 as you can without going over!\n\ > Dealer hits until she reaches 17. Aces count as 1 or 11.') print("""> Example summary window of a BlackJack Game : -------------------------------------------------------- -------PLAYERS (bet value) 1 nos. : Suraj (53), ------- -------------------------------------------------------- +--------------+--------------+ | DEALER | Suraj | +--------------+--------------+ | A ♦ | 3 ♠ | | 4 ♣ | 10 ♠ | | | Q ♣ | | ------------ | ------------ | | 15 | 23 | +--------------+--------------+ ------------------------------------------------------- !!!--------------Suraj BUSTS!--------------!!! !!!------------ WINNER : DEALER -----------!!! Suraj : WINS -> 0, LOSSES -> 0 & BUSTS -> 1 ------------------------------------------------------- """) input('Pless enter to start the Game... ') # Geeting the player name to set the player object player_name = '' while True: os.system('cls') print('> Welcome to BlackJack!') player_name = input('> Enter Your Name - ') if player_name == '': continue break player_1 = Player(player_name.upper()) while True: game = BlackJack([player_1]) # Ask to play again if player_1.chips > 1: new_game = input("Would you like to play another hand? Enter 'y' or 'n' ") else: print("You have exhausted your chips! Well played! Seeya Later!") print("Thanks for playing!") time.sleep(5) exit() if new_game[0].lower() != 'n': continue else: print("Thanks for playing!") time.sleep(10) exit()
TypeScript
UTF-8
5,741
3.09375
3
[ "MIT" ]
permissive
const DEFAULT_AUDIO_CONSTRAINTS = {}; const DEFAULT_VIDEO_CONSTRAINTS = { facingMode: 'user', frameRate: 30, height: 720, width: 1280 }; const FACING_MODES = [ 'user', 'environment' ]; const ASPECT_RATIO = 16 / 9; const STANDARD_OFFER_OPTIONS = { icerestart: 'IceRestart', offertoreceiveaudio: 'OfferToReceiveAudio', offertoreceivevideo: 'OfferToReceiveVideo', voiceactivitydetection: 'VoiceActivityDetection' }; const SDP_TYPES = [ 'offer', 'pranswer', 'answer', 'rollback' ]; function getDefaultMediaConstraints(mediaType) { switch (mediaType) { case 'audio': return DEFAULT_AUDIO_CONSTRAINTS; case 'video': return DEFAULT_VIDEO_CONSTRAINTS; default: throw new TypeError(`Invalid media type: ${mediaType}`); } } function extractString(constraints, prop) { const value = constraints[prop]; const type = typeof value; if (type === 'object') { for (const v of [ 'exact', 'ideal' ]) { if (value[v]) { return value[v]; } } } else if (type === 'string') { return value; } } function extractNumber(constraints, prop) { const value = constraints[prop]; const type = typeof value; if (type === 'number') { return Number.parseInt(value); } else if (type === 'object') { for (const v of [ 'exact', 'ideal', 'max', 'min' ]) { if (value[v]) { return Number.parseInt(value[v]); } } } } function normalizeMediaConstraints(constraints, mediaType) { switch (mediaType) { case 'audio': return constraints; case 'video': { const c = { deviceId: extractString(constraints, 'deviceId'), facingMode: extractString(constraints, 'facingMode'), frameRate: extractNumber(constraints, 'frameRate'), height: extractNumber(constraints, 'height'), width: extractNumber(constraints, 'width') }; if (!c.deviceId) { delete c.deviceId; } if (!FACING_MODES.includes(c.facingMode)) { c.facingMode = DEFAULT_VIDEO_CONSTRAINTS.facingMode; } if (!c.frameRate) { c.frameRate = DEFAULT_VIDEO_CONSTRAINTS.frameRate; } if (!c.height && !c.width) { c.height = DEFAULT_VIDEO_CONSTRAINTS.height; c.width = DEFAULT_VIDEO_CONSTRAINTS.width; } else if (!c.height && c.width) { c.height = Math.round(c.width / ASPECT_RATIO); } else if (!c.width && c.height) { c.width = Math.round(c.height * ASPECT_RATIO); } return c; } default: throw new TypeError(`Invalid media type: ${mediaType}`); } } /** * Utility for creating short random strings from float point values. * We take 4 characters from the end after converting to a string. * Conversion to string gives us some letters as we don't want just numbers. * Should be suitable to pass for enough randomness. * * @return {String} 4 random characters */ function chr4() { return Math.random().toString(16).slice(-4); } /** * Put together a random string in UUIDv4 format {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} * * @return {String} uuidv4 */ export function uniqueID(): string { return `${chr4()}${chr4()}-${chr4()}-${chr4()}-${chr4()}-${chr4()}${chr4()}${chr4()}`; } /** * Utility for deep cloning an object. Object.assign() only does a shallow copy. * * @param {Object} obj - object to be cloned * @return {Object} cloned obj */ export function deepClone<T>(obj: T): T { return JSON.parse(JSON.stringify(obj)); } /** * Checks whether an SDP type is valid or not. * * @param type SDP type to check. * @returns Whether the SDP type is valid or not. */ export function isSdpTypeValid(type: string): boolean { return SDP_TYPES.includes(type); } /** * Normalize options passed to createOffer(). * * @param options - user supplied options * @return Normalized options */ export function normalizeOfferOptions(options: object = {}): object { const newOptions = {}; if (!options) { return newOptions; } // Convert standard options into WebRTC internal constant names. // See: https://github.com/jitsi/webrtc/blob/0cd6ce4de669bed94ba47b88cb71b9be0341bb81/sdk/media_constraints.cc#L113 for (const [ key, value ] of Object.entries(options)) { const newKey = STANDARD_OFFER_OPTIONS[key.toLowerCase()]; if (newKey) { newOptions[newKey] = String(Boolean(value)); } } return newOptions; } /** * Normalize the given constraints in something we can work with. */ export function normalizeConstraints(constraints) { const c = deepClone(constraints); for (const mediaType of [ 'audio', 'video' ]) { const mediaTypeConstraints = c[mediaType]; const typeofMediaTypeConstraints = typeof mediaTypeConstraints; if (typeofMediaTypeConstraints !== 'undefined') { if (typeofMediaTypeConstraints === 'boolean') { if (mediaTypeConstraints) { c[mediaType] = getDefaultMediaConstraints(mediaType); } } else if (typeofMediaTypeConstraints === 'object') { c[mediaType] = normalizeMediaConstraints(mediaTypeConstraints, mediaType); } else { throw new TypeError(`constraints.${mediaType} is neither a boolean nor a dictionary`); } } } return c; }
C#
UTF-8
579
2.765625
3
[]
no_license
using System; using System.Collections.Generic; using System.Text; namespace HW6 { class AveragePriceTypeCommand:ICommand { AveragePriceTypeReceiver receiver; List<ProductCar> cars; string type; public AveragePriceTypeCommand(AveragePriceTypeReceiver receiver, List<ProductCar> cars, string type) { this.receiver = receiver; this.cars = cars; this.type = type; } public void Execute() { receiver.CalculateAveragePriceType(cars, type); } } }
Java
UTF-8
6,972
3.296875
3
[]
no_license
/*---------------------------------------------------------------------------- # File: Elevator.java # Date: Tue Sep 13 17:13:24 EDT 2011 # Author: Ellery Coleman <ellerycoleman@fas.harvard.edu> # Abstract: Implements an Elevator class for cscie160, hw1. #----------------------------------------------------------------------------- # Revision: $Id$ #---------------------------------------------------------------------------*/ package cscie160.hw1; public class Elevator { //----------------------- // Constants //----------------------- /** * defines the base floor in the building */ public static final int baseFloor = 1; /** * defines the top floor in the building */ public static final int maxFloor = 7; /** * defines the max capacity of an elevator */ public static final int maxCapacity = 10; /** * The direction of an elevator is set with an * integer variable; 1 for UP. */ public static final int UP = 1; /** * The direction of an elevator is set with an * integer variable; 0 for DOWN. */ public static final int DOWN = 0; //----------------------- // Constructor //----------------------- /** * A constructor that doesn't take any arguments; initializes * the elevator with zero passengers, first floor position, and * a direction of UP. */ public Elevator() { System.out.println("Initializing elevator...\n"); this.passengers=0; this.floor= 1; this.direction= UP; } //----------------------- // Data Members //----------------------- private int floor; private int passengers; private int direction; // 1 is up, 0 is down private int destRequests[]= new int[maxFloor+1]; private int passengersToFloor[]= new int[maxFloor+1]; //----------------------- // Method Members //----------------------- /*--------------------------------------------------------------------- | method name: toString | return type: String | Abstract: Overrides toString() method of java.lang.Object; | returns string with status of elevator. +--------------------------------------------------------------------*/ /** * Returns string with status of elevator. */ public String toString() { String status,requests; requests=""; status= "+--------Elevator-----------" + "\n" + "| current Floor: " + this.floor + "\n" + "| current passengers: " + this.passengers + "\n" + "| current direction: " + ((this.direction == UP) ? "up":"down") + "\n" + "| destination requests: "; for(int i=1; i<=maxFloor; i++) { if((destRequests[i] != 0) || (passengersToFloor[i] != 0)) { requests+= "\n" + "| Floor_" + (i) + "--> requests: " + destRequests[i] + ", " + " passengers destined for floor: " + passengersToFloor[i] + "\n"; } } if(requests.isEmpty()) { status+= "none\n"; } else { status+= requests; } status+= "+---------------------------\n\n\n\n"; return status; } /*--------------------------------------------------------------------- | method name: move | return type: void | Abstract: Moves elevator by one floor depending on current | direction. +--------------------------------------------------------------------*/ /** * Moves elevator by one floor depending on current direction. * Changes direction as appropriate. */ public void move() { if((this.direction == UP) && (this.floor < maxFloor)) { this.floor++; } else if((this.direction == UP) && (this.floor == maxFloor)) { this.direction=DOWN; this.floor--; } else if ((this.direction == DOWN) && (this.floor > baseFloor)) { this.floor--; } else if ((this.direction == DOWN) && (this.floor == baseFloor)) { this.direction=UP; this.floor++; } if(destRequests[this.floor] > 0) { stop(); } } /*--------------------------------------------------------------------- | method name: stop | return type: void | Abstract: Stops the elevator, does the appropriate book keeping, | and then displays the state of the elevator after the | processing. +--------------------------------------------------------------------*/ /** * Stops the elevator, does the appropriate book keeping, * and then displays the state of the elevator after the * processing. */ public void stop() { System.out.print("\n\n\nElevator stopped at floor " + this.floor + ", "); int unloading= destRequests[floor]; destRequests[floor]=0; passengersToFloor[floor]-= unloading; passengers-= unloading; System.out.println("dropped off " + unloading + " passenger(s)."); System.out.println(this.toString()); } /*--------------------------------------------------------------------- | method name: boardPassenger | return type: void | Abstract: Adds a passenger to the elevator and handles the | appropriate accounting. +--------------------------------------------------------------------*/ /** * Adds a passenger to the elevator and handles the appropriate class * book keeping of increasing the passenger count on the elevator, * registering the destination request, and increasing the count of * passengers headed to the destination floor. */ public void boardPassenger(int floor) { System.out.println("Boarding one passenger for floor " + floor + "."); this.passengers++; destRequests[floor]++; passengersToFloor[floor]++; } //---------------------------------- // Main Method (test harness) //---------------------------------- /** * A test harness for the Elevator class. According to HW1 Spec, this * method boards 2 passengers for the 2nd floor and 1 for the 3rd floor. * In accordance with the Spec the elevator continues to sweep the building * after servicing these passengers. */ public static void main(String args[]) throws InterruptedException { Elevator ev1= new Elevator(); ev1.boardPassenger(2); ev1.boardPassenger(2); ev1.boardPassenger(3); while(true) { ev1.move(); Thread.sleep(1000); //sleep - helps interpret output in real time } } }
JavaScript
UTF-8
1,758
3.3125
3
[]
no_license
function solve(input) { const collected = { shards: 0, fragments: 0, motes: 0 }; const junk = {}; const materials = input.split(' '); for (let i = 0; i < materials.length; i += 2) { const currentMaterial = materials[i + 1].toLowerCase(); const quantity = Number(materials[i]); if (currentMaterial === 'shards' || currentMaterial === 'fragments' || currentMaterial === 'motes') { collected[currentMaterial] += quantity; if (collected[currentMaterial] >= 250) { let forgedItem = ''; switch (currentMaterial) { case 'shards': forgedItem = 'Shadowmourne'; break; case 'fragments': forgedItem = 'Valanyr'; break; case 'motes': forgedItem = 'Dragonwrath'; break; } console.log(`${forgedItem} obtained!`); collected[currentMaterial] -= 250; break; } } else { if (!junk.hasOwnProperty(currentMaterial)) { junk[currentMaterial] = 0; } junk[currentMaterial] += quantity; } } Object.entries(collected) .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])) .forEach(kvp => console.log(`${kvp[0]}: ${kvp[1]}`)); Object.entries(junk) .sort((a, b) => a[0].localeCompare(b[0])) .forEach(kvp => console.log(`${kvp[0]}: ${kvp[1]}`)) } solve( '3 Motes 5 stones 5 Shards 6 leathers 255 fragments 7 Shards' )
C++
UTF-8
1,326
2.84375
3
[]
no_license
#include "server.h" string Server::readSocket(tcp::socket &socket) { streambuf buf; boost::system::error_code error; read_until(socket, buf, "\n", error); if (error && error != error::eof){ std::cerr << "Read error: " << error.message() << std::endl; return "Server couldn't read message\n"; } string data = buffer_cast<const char*>(buf.data()); return data; } void Server::sendSocket(tcp::socket &socket, const string &message) { string msg = message; if (msg.back() != '\n') msg += '\n'; boost::system::error_code error; write(socket, buffer(msg), error); if (error){ std::cerr << "Send error: " << error.message() << std::endl; } } void Server::startClientSession(const Server::socket_ptr &socket) { string message = readSocket(*socket); sendSocket(*socket, message); socket->close(); } void Server::run() { tcp::acceptor acceptor(ioContext, tcp::endpoint(ip::address::from_string(ip), port)); while(true) { socket_ptr socket(new ip::tcp::socket(ioContext)); acceptor.accept(*socket); boost::thread(&Server::startClientSession, this, socket); } } Server::Server(string ip, int port) : ip(std::move(ip)), port(port) {}
C
UTF-8
711
3.390625
3
[]
no_license
#include <stdlib.h> #include <stdio.h> #include <string.h> #include <ctype.h> #include "indocente.h" #include "inalumno.h" int main() { int opcion, contprof, contalum; printf("Este programa permite ingresar y mostrar a docentes y alumnos."); do { system("cls"); printf("Que desea hacer?\n"); printf("1- Info del maestro\n"); printf("2- Info de alumnos\n"); printf("3- Salir\n"); scanf("%i", &opcion); switch(opcion) { case 1: indocente(); break; case 2: inalumno(); break; } }while(opcion!=3); system("pause"); return 0; }
Shell
UTF-8
1,050
3.875
4
[]
no_license
#!/bin/bash # ## build script for docu with asciidoc and daps ## (c) 2018 peters@suse.com # function usage() { echo "Usage: $0 asciidoc_filename_with_extention.adoc" exit 1; } #check for parameters if [ $# -eq 0 ] then echo "No arguments supplied."; usage; exit 1; fi while [ $# -gt 0 ]; do case "$1" in -h) usage; exit 1;; --help) usage; exit 1;; --) shift; break;; -*) echo >&2 "Error: Invalid option \"$1\""; echo; usage; exit 1;; *) if [ "adoc" != "${1##*.}" ];then echo "ERROR: invalid extension, need .adoc";usage; exit 2;else INPUTFILE=$1; fi;; esac shift done FN=`basename $INPUTFILE .adoc` mkdir -p ./xml ./build # get rid of former processing rm ./xml/$FN.xml # run asciidoc asciidoc --doctype=article --backend=docbook --out-file=./xml/$FN.xml ./$INPUTFILE # create DAPS DC file cat << EOF > DC-$FN MAIN="$FN.xml" STYLEROOT="/usr/share/xml/docbook/stylesheet/suse2013-ns" EOF # rund daps and generate PDF daps -d DC-$FN pdf # show pdf evince ./build/$FN/*.pdf
Markdown
UTF-8
1,198
3.109375
3
[]
no_license
import { Meta, Canvas, Story } from '@storybook/addon-docs/blocks'; import Pagination from 'src/components/pagination'; <Meta title="Components/Pagination" component={Pagination} /> # Pagination Custom style for the pagination component integrated with pagy. ## Examples We currently only support one type of pagination style. export const Template = (args) => <Pagination {...args} /> <Canvas isColumn> <Story name="with just 2 pages" args={{ prev: null, next: 2, page: 1, last: 2 }}> {Template.bind({})} </Story> <Story name="with a small total number of pages" args={{ prev: 1, next: 3, page: 2, last: 6 }}> {Template.bind({})} </Story> <Story name="with just a single page" args={{ prev: null, next: null, page: 1, last: 1 }}> {Template.bind({})} </Story> <Story name="with many pages" args={{ prev: 15, next: 17, page: 16, last: 30 }}> {Template.bind({})} </Story> <Story name="close to the last page" args={{ prev: 28, next: 30, page: 29, last: 30 }}> {Template.bind({})} </Story> </Canvas>
C
UTF-8
16,738
2.578125
3
[]
no_license
/* * File: main.c * Author: Daniel Bradley * * Created on April 2, 2018, 3:00 PM */ #include <p18f8722.h> #include "Messages.h" #include "PIC18LCDDisplayDriver.h" #include <delays.h> #include <stdio.h> #include <stdlib.h> #pragma config OSC = HSPLL // Oscillator selection: HS with PLL enabled #pragma config FCMEN = OFF // Fail-safe clock monitor disabled #pragma config IESO = OFF // Internal/External Oscillator switchover disabled #pragma config PWRT = OFF // Power-up Timer disabled #pragma config BOREN = OFF // Brown out reset disabled #pragma config WDT = OFF // Watchdog timer Off #pragma config MCLRE = ON // MCLR pin enabled, RE3 input pin disabled #pragma config LVP = OFF // Single supply ICSP disabled #pragma config XINST = OFF // Instruction set extension and indexed addressing mode disabled (legacy mode) #define LED0 PORTDbits.RD0 #define LED1 PORTDbits.RD1 #define LED2 PORTDbits.RD2 #define LED3 PORTDbits.RD3 #define LED4 PORTDbits.RD4 #define LED5 PORTDbits.RD5 #define LED6 PORTDbits.RD6 #define LED7 PORTDbits.RD7 int scoreForOne = 0; int scoreForTwo = 0; int speedValue = 255; int flashCount; int loop = 0; int starting; unsigned char d = 200; // delay between character display int B0Button = 0; int A5Button = 0; void convertScores(void){ // Define function to convert scores from type INT to individual char's in array scores int t = 3; // Array index value for Player 2 int i = 14; // Array index value for Player 1 if (scoreForOne == 0){ // If score for player 1 is zero, print zero to LCD scores[13] = '0'; }else{ while(scoreForOne){ // While scoreForOne has a non-zero value loop find it's modulus, convert to ASCII and store in the scores array at index i where i starts at 3 and decreases by 1 for each number scores[i]=(scoreForOne%10)+'0'; scoreForOne= scoreForOne/10; i--; } } if(scoreForTwo == 0){ // If score for player 2 is zero, print zero to LCD scores[2] = '0'; } else{ while(scoreForTwo){ scores[t]=(scoreForTwo%10)+'0'; scoreForTwo = scoreForTwo/10; t--; } } } void EndGameInterrupt(void); // Function prototype for Game interrupt void main(void){ // Set up ports and bits LCDInit(); // Run initialization of LCD screen LCDClear(); // Clear the entire LCD screen TRISAbits.RA5 = 1; // Set up PORTA, A5 as input TRISBbits.RB0 = 1; // Set up PORTB, B0 as input TRISBbits.RB2 = 1; // Set up PORTB, B2 as input TRISD = 0; // Set up all PORTD as output PORTD = 0x00; // Turn off all LED's starting = 1; // Set up variable 'starting' so that game can begin T0CON = 0b00000011; // Timer0, 16-bit mode, 1:16 prescale // Set up interrupts INTCONbits.INT0IF = 0; // Clear RB0 interrupt flag INTCONbits.INT0IE = 1; // Enable RB0 as interrupt source INTCONbits.TMR0IF = 0; // Clear TMR0 interrupt flag INTCONbits.TMR0IE = 1; // Enable TMR0 as interrupt source INTCON3bits.INT2IF= 0; // Clear RB2 as interrupt source INTCON3bits.INT2IE= 1; // Enable RB2 as interrupt source INTCON2bits.INTEDG0 = 0; // Make RB0 negative edge - remember button press high to low INTCON2bits.INTEDG2 = 0; // Make RB1 negative edge - remember button press high to low INTCONbits.GIE = 1; // Enable all interrupts globally while (1){ // Loop to check if B0Button or A5Button are equal to one if (B0Button == 1){ // If B0Button is equal to one due to interrupt being activated run below code T0CONbits.TMR0ON = 0; // Stop the TMR0 when the button is pressed TMR0H = 0x48; // Reload timer value for first part of a 16bit timer TMR0L = 0xE5; // Reload timer value for second part of a 16bit timer scoreForTwo = scoreForTwo+1; // Increase score value for player two by one PORTD = 0x00; // Turn off all LED's on PORTD LED7 = 1; // Turn on the LED closest to button B0 Delay10KTCYx(speedValue); // Delay between LED bitshift's (Delay function starts being passed 250 and decreases by 5 with each rebound of the 'Ball') Delay10KTCYx(speedValue); starting = 0; // Since game has started, starting variable is set to 0; while (LED0 != 1){ // While the lit LED is not the last LED in the strip opposite to the button pushed (RB0), run the below code PORTD = PORTD >> 1; // Bitshift PORTD to the right by 1 Delay10KTCYx(speedValue); // Delay between LED bitshift's (Delay function starts being passed 250 and decreases by 5 with each rebound of the 'Ball') Delay10KTCYx(speedValue); } B0Button = 0; // Reset value of B0Button to zero so code block is exited loop continues to check variable values T0CONbits.TMR0ON = 1; // Start TMR0 to count down to end game if A5Button is not pushed } if (A5Button == 1){ // If A5Button is equal to one due to interrupt being activated run below code T0CONbits.TMR0ON = 0; // Stop the TMR0 when the button is pressed TMR0H = 0x48; // Reload timer value for first part of a 16bit timer TMR0L = 0xE5; // Reload timer value for second part of a 16bit timer scoreForOne = scoreForOne+1; // Increase score value for player one by on PORTD = 0x00; // Turn off all LED's on PORTD LED0 = 1; // Turn on the LED closest to button A5 Delay10KTCYx(speedValue); // Delay between LED bitshift's (Delay function starts being passed 250 and decreases by 5 with each rebound of the 'Ball') Delay10KTCYx(speedValue); starting = 0; // Since game has started, starting variable is set to 0; while (LED7 != 1){ // While the lit LED is not the last LED in the strip opposite to the button pushed (RA5), run the below code PORTD = PORTD << 1; // Bitshift PORTD to the left by 1 Delay10KTCYx(speedValue); // Delay between LED bitshift's (Delay function starts being passed 250 and decreases by 5 with each rebound of the 'Ball') Delay10KTCYx(speedValue); } A5Button = 0; // Reset value of A5Button to zero so code block is exited loop continues to check variable values T0CONbits.TMR0ON = 1; // Start TMR0 to count down to end game if B0Button is not pushed } } } #pragma code My_HighPriority_Interrupt=0x08 // Direct the high priority interrupt at memory location 0x08 to the function "EndGameInterrupt" void My_HighPriority_Interrupt(void){ _asm GOTO EndGameInterrupt _endasm } #pragma interrupt EndGameInterrupt void EndGameInterrupt(void){ // Interrupt function if((INTCON3bits.INT2IF == 1 && LED0 != 1 && starting == 0)||(INTCONbits.TMR0IF == 1 && LED0 == 1)){ // If the RA5 is pressed and LED0 is not on and it's not the start of the game or RB0 is pushed and LED0 is on, run the code block below INTCONbits.TMR0IF = 0; // Set the TMR0 interrupt flag to 0 T0CONbits.TMR0ON = 0; // Turn off the timer TMR0 TMR0H = 0x48; // Reload timer value for first part of a 16bit timer TMR0L = 0xE5; // Reload timer value for second part of a 16bit timer INTCON3bits.INT2IF = 0; // Set the INT2 interrupt flag to 0 INTCONbits.INT0IF = 0; // Set the TMR0 interrupt flag to 0 PORTD = 0x00; // Turn off all LED's attached to PORTD for(flashCount = 0; flashCount <= 9; flashCount = flashCount++){ // Loop the complement of LED7's state 9 times to make it flash on and off 5 times LED7 = ~LED7; Delay10KTCYx(250); } PORTD = 0xFF; // Turn all LED's on PORTD on LCDLine_1(); // Write to line 1 of the display d_write_line_delay(lineClear, 20); // Clear line 2 with a delay of 20 between the characters LCDLine_1(); // Write to line 1 of the display d_write_line_delay(playerTitle, d); // Write the text "Player2 Player1" to line one of the LCD with a delay of 200 between the characters convertScores(); // Call the function convertScores to write the scores for each player to the variable scores LCDLine_2(); // Write to line 2 of the display d_write_line_delay(scores, 0); // Write the value of the variable "scores" to line two of the LCD with a delay of 0 between the characters Delay10KTCYx(250); // Maximum value of delay function called 4 times to allow score to remain on the LCD Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); LCDLine_2(); // Write to line 2 of the display d_write_line_delay(lineClear, 0); // Clear line 2 with a delay of 0 between the characters LCDLine_2(); // Write to line 2 of the display d_write_line_delay(winnerTwo, d); // Write the word "Winner" to line 2 under Player 2 with a delay of 200 between each character Delay10KTCYx(250); // Maximum value of delay function called 4 times to allow the word "Winner" to remain on the LCD Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); LCDLine_2(); // Write to line 2 of the display d_write_line_delay(lineClear, 0); // Clear line 2 with a delay of 0 between the characters LCDLine_1(); // Write to line 1 of the display d_write_line_delay(lineClear, 0); // Clear line 1 with a delay of 0 between the characters PORTD = 0x00; // Turn off all LED's attached to PORTD starting = 1; // Reset value of starting variable for next game B0Button = 0; // Reset value of B0Button variable for next game A5Button = 0; // Reset value of A5Button variable for next game speedValue = 255; // Reset value of speedValue variable for next game scores[13] = ' '; scores[12] = ' '; scores[11] = ' '; scores[2] = ' '; scores[1] = ' '; scores[0] = ' '; main(); // Call main function to restart check for button state variable }else if((INTCONbits.INT0IF == 1 && LED7 != 1 && starting == 0)||(INTCONbits.TMR0IF == 1 && LED7 == 1)){ // If the RB0 is pressed and LED7 is not on and it's not the start of the game or RA5 is pushed and LED7 is on, run the code block below INTCONbits.TMR0IF = 0; // Set the TMR0 interrupt flag to 0 T0CONbits.TMR0ON = 0; // Turn off the timer TMR0 TMR0H = 0x48; // Reload timer value for first part of a 16bit timer TMR0L = 0xE5; // Reload timer value for second part of a 16bit timer INTCON3bits.INT2IF = 0; // Set the INT2 interrupt flag to 0 INTCONbits.INT0IF = 0; // Set the INT0 interrupt flag to 0 PORTD = 0x00; // Turn off all LED's attached to PORTD for(flashCount = 0; flashCount <= 9; flashCount = flashCount++){ // Loop the complement of LED7's state 9 times to make it flash on and off 5 times LED0 = ~LED0; Delay10KTCYx(250); } PORTD = 0xFF; // Turn all LED's on PORTD on LCDLine_1(); // Write to line 1 of the display d_write_line_delay(lineClear, 20); // Clear line 2 with a delay of 20 between the characters LCDLine_1(); // Write to line 1 of the display d_write_line_delay(playerTitle, d); // Write the text "Player2 Player1" to line one of the LCD with a delay of 200 between the characters convertScores(); // Call the function convertScores to write the scores for each player to the variable scores LCDLine_2(); // Write to line 2 of the display d_write_line_delay(scores, 0); // Write the value of the variable "scores" to line two of the LCD with a delay of 0 between the characters Delay10KTCYx(250); // Maximum value of delay function called 4 times to allow score to remain on the LCD Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); LCDLine_2(); // Write to line 2 of the display d_write_line_delay(lineClear, 0); // Clear line 2 with a delay of 0 between the characters LCDLine_2(); // Write to line 2 of the display d_write_line_delay(winnerOne, d); // Write the word "Winner" to line 2 under Player 1 with a delay of 200 between each character Delay10KTCYx(250); // Maximum value of delay function called 4 times to allow the word "Winner" to remain on the LCD Delay10KTCYx(250); Delay10KTCYx(250); Delay10KTCYx(250); LCDLine_1(); // Write to line 1 of the display d_write_line_delay(lineClear, 0); // Clear line 1 with a delay of 0 between the characters LCDLine_2(); // Write to line 1 of the display d_write_line_delay(lineClear, 0); // Clear line 2 with a delay of 0 between the characters PORTD = 0x00; // Turn off all LED's attached to PORTD starting = 1; // Reset value of starting variable for next game B0Button = 0; // Reset value of B0Button variable for next game A5Button = 0; // Reset value of A5Button variable for next game speedValue = 255; // Reset value of speedValue variable for next game scores[13] = ' '; scores[12] = ' '; scores[11] = ' '; scores[2] = ' '; scores[1] = ' '; scores[0] = ' '; main(); // Call main function to restart check for button state variable }else if(INTCONbits.INT0IF == 1 && (LED7 == 1 || starting == 1)){ // If interrupt is activated when LED7 or starting variable is 1, run code block INTCON3bits.INT2IF = 0; // Set the INT2 interrupt flag to 0 INTCONbits.INT0IF = 0; // Set the INT0 interrupt flag to 0 if (speedValue != 5){ speedValue = speedValue - 5; // Decrease the speedValue variable by 5; } B0Button = 1; // Set B0Button variable to 1; }else if(INTCON3bits.INT2IF == 1 && (LED0 == 1 || starting == 1)){ // If interrupt is activated when LED0 or starting variable is 1, run code block INTCON3bits.INT2IF = 0; // Set the INT2 interrupt flag to 0 INTCONbits.INT0IF = 0; // Set the INT0 interrupt flag to 0 if (speedValue != 5){ speedValue = speedValue - 5; // Decrease the speedValue variable by 5; } A5Button = 1; // Set B0Button variable to 1; } }
Markdown
UTF-8
684
3.6875
4
[]
no_license
[question](https://leetcode.com/problems/maximum-subarray/) 求一个数组中连续几个相邻元素的和最大值,对于这一类问题没有太大的思路,看了视频讲解,这个问题是属于动态规划。思路也是很简单的。对于到当前元素要不要加到之前的和上,需要看之前和是否是大于零。 ```js /** * @param {number[]} nums * @return {number} */ var maxSubArray = function (nums) { const length = nums.length; const sumArr = new Array(length); sumArr[0] = nums[0]; for (let i = 1; i < nums.length; i++) { sumArr[i] = sumArr[i -1] > 0 ? nums[i] + sumArr[i -1] : nums[i]; } return Math.max(...sumArr); }; ```
Ruby
UTF-8
1,199
2.71875
3
[ "MIT" ]
permissive
# frozen_string_literal: true module DeliveriesManager class ChaosGenerator NORMAL = [ [100, NoOp], ].freeze ADVANCED = [ [10, MessageDropper], [10, MessageReorder], [10, MessageDuplicator], [100, NoOp], ].freeze EXTREME = [ [4, MessageDropper], [4, MessageReorder], [4, MessageDuplicator], [4, MessageTimeFudger], [2, MessageKeyFudger], [4, MessageContentFudger], [1, MessageStructureFudger], [100, NoOp], ].freeze def initialize @probability_sum = cumulative_probability_sum end def perform(statuses) select_operation.new.perform(statuses) statuses end private def select_operation random_value = SecureRandom.rand @probability_sum.select { |item| item[0] >= random_value }.first[1] end def cumulative_probability_sum sum = 0.0 probabilities = NORMAL probabilities = ADVANCED if ENV['ADVANCED'] probabilities = EXTREME if ENV['EXTREME'] res = probabilities.map do |item| sum += item[0] [sum, item[1]] end res.map { |item| [item[0] / sum, item[1]] } end end end
Java
UTF-8
1,917
2.21875
2
[]
no_license
package service; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.AuthcMicroService; import com.entity.ShopRole; import com.service.RoleService; import com.utils.PageUtil; import com.utils.ServerResponse; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest(classes=AuthcMicroService.class) public class RoleServiceImplTest { /** * 自动注入RoleService实例 */ @Autowired private RoleService roleService; /** * 测试增加角色 */ @Test public void testAddRole() { ShopRole role=new ShopRole("罗宾", "考古学家", new Date(), 1, null, null,0); ServerResponse<Integer> sr=roleService.addRole(role); System.out.println(sr.getMsg()); } /** * 测试逻辑删除角色 */ @Test public void testTombRole() { Map<String, Object> map = new HashMap<>(); map.put("roleId", 42); map.put("isDel", 0); ServerResponse<Integer> sr = roleService.tombRole(map); System.out.println(sr.getMsg()); } /** * 测试删除角色 */ @Test public void testDelRole() { ServerResponse<Integer> sr = roleService.delRole(42); System.out.println(sr.getMsg()); } /** * 测试修改角色 */ @Test public void testUpdateRole() { ShopRole role=new ShopRole("罗宾", "考古学家", new Date(), 1, null, null,1); ServerResponse<Integer> sr=roleService.addRole(role); System.out.println(sr.getMsg()); } /** * 测试查询角色 */ @Test public void testFindRole() { ServerResponse<PageUtil<List<ShopRole>>> sr = roleService.page(1, 5, 0, null); System.out.println(sr.getData().getData()); System.out.println(sr.getData().getCount()); } }
Java
UTF-8
3,279
2.703125
3
[]
no_license
package com.yc.wowo.user.controller; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Random; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.yc.wowo.user.dto.SessionKeyConstant; /** * 图形验证码 * company 源辰信息 * @author navy * @date 2020年10月25日 * Email haijunzhou@hnit.edu.cn */ @Controller @RequestMapping public class CreateCodeController { @RequestMapping("/code") public void createCode(HttpServletRequest request, HttpServletResponse response) throws IOException{ // 处理缓存 response.setHeader("Pragma", "no-cache"); response.setHeader("Cache-Control", "no-cache"); response.setDateHeader("Expires", 0); // 生成验证码 String code = getRandomCode(); // 将验证码存到session中 request.getSession().setAttribute(SessionKeyConstant.VERIFICATIONCODE, code); // 创建验证码图片并返回 BufferedImage image = this.getCodeImage(code, 110, 38); ImageIO.write(image, "JPEG", response.getOutputStream()); } private BufferedImage getCodeImage(String code, int width, int height) { BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); // 绘制图片 -> 获取一个绘笔 Graphics g = image.getGraphics(); // 先绘制背景色 -> 设置绘笔的颜色 g.setColor(this.getRandomColor(210, 45)); // 绘制背景 g.fillRect(0, 0, width, height); // 绘制干扰线 int x1, y1, x2, y2; Random rd = new Random(); for (int i = 0; i < 50; i ++) { // 给每条干扰线一种颜色 g.setColor(this.getRandomColor(140, 50)); x1 = rd.nextInt(width); y1 = rd.nextInt(height); x2 = rd.nextInt(width); y2 = rd.nextInt(height); g.drawLine(x1, y1, x2, y2); } // 绘制验证码 // 设置验证码的字体 g.setFont(new Font("Couriew New", Font.ITALIC, 24)); char[] codes = code.toCharArray(); for (int i = 0, len = codes.length; i < len; i ++) { // 给每一个字体一种颜色 g.setColor(this.getRandomColor(40, 80)); g.drawString(String.valueOf(codes[i]), 10 + 24 * i, 28); } return image; } /** * 生成验证码的方法 * @return */ private String getRandomCode() { Random rd = new Random(); StringBuffer sbf = new StringBuffer(); int flag = 0; for (int i = 0; i < 4; i ++) { flag = rd.nextInt(3); switch (flag) { case 0: sbf.append(rd.nextInt(10)); break; case 1: sbf.append((char)(rd.nextInt(26) + 65)); break; default: sbf.append((char)(rd.nextInt(26) + 97)); break; } } return sbf.toString(); } /** * 生成随机颜色 * @param start 开始值 * @param bound 范围 * @return */ private Color getRandomColor(int start, int bound) { Random rd = new Random(); int r = start + rd.nextInt(bound); int g = start + rd.nextInt(bound); int b = start + rd.nextInt(bound); return new Color(r, g, b); } }
C#
UTF-8
3,030
3.328125
3
[]
no_license
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lesson30_10 { class Program { public static void Task2() { Console.WriteLine("Введите вашу строку: "); string str = Console.ReadLine(); char[] reverse = str.Reverse().ToArray(); Console.WriteLine(reverse); } static void Main(string[] args) { Console.WriteLine("Упражнение 8.1"); BankAccount a = new BankAccount(); Console.WriteLine("Введите номер первого аккаунта: "); a.Number = int.Parse(Console.ReadLine()); Console.WriteLine("Введите тип аккаунта: "); a.Type = Console.ReadLine(); Console.WriteLine("Введите количество денег на счету: "); a.Count = int.Parse(Console.ReadLine()); Console.WriteLine("Тип банковского аккаунта " + a.Type + ", Номер счета " + a.Number + ", Количество денег " + a.Count); BankAccount b = new BankAccount(); Console.WriteLine("Введите номер второго аккаунта: "); b.Number = int.Parse(Console.ReadLine()); Console.WriteLine("Введите тип аккаунта: "); b.Type = Console.ReadLine(); Console.WriteLine("Введите количество денег на счету: "); b.Count = int.Parse(Console.ReadLine()); Console.WriteLine("Тип банковского аккаунта " + b.Type + ", Номер счета " + b.Number + ", Количество денег " + b.Count); a.GetMoney(b, -200); b.GetMoney(a, 200); Console.WriteLine($"Успешный перевод!\n Номер счета: {a.Number}, Количество денег: {a.Count}\n Номер счета: { b.Number}, Количество денег {b.Count}"); Console.WriteLine("Упражнение 8.2"); Task2(); Console.WriteLine("Упражнение 8.3"); Console.Write("Введите название файла: "); string path = @".\..\..\Res\"; string userFileName = Console.ReadLine(); if (File.Exists(path + userFileName)) { string test = File.ReadAllText(path + userFileName); File.WriteAllText(path + "finish.txt", test.ToUpper()); Console.WriteLine("Результат успешно записан в файл с именем finish"); } else { Console.WriteLine($"Ошибка, файл с таким именем не найден."); } Console.ReadKey(); } } }
Markdown
UTF-8
2,827
3.859375
4
[ "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-public-domain" ]
permissive
###URL params plus input forms Users can submit information to the backend of an application via the address bar in their browser but that's not a very user friendly model and it's not very secure. Imagine if every time you submitted a password or credit card number to a website and it just lingered there in your navigation bar for all of the world to see. We're more used to interacting with web applications by clicking buttons and typing in information that we want posted on the internet by filling out forms. Forms are created using HTML form and input tags. When we submit a form we send the information to the controller through a new type of HTTP request called POST. We use this naming convention to reflect the fact that we are posting information to the site (as opposed to getting information from the site). A POST request is also slightly more secure than a GET request because the information we are submitting will not be displayed in the URL parameters in the navigation bar of our browser. In `demo3.rb` we have both a get request (to get the HTML and display the form) and a post request that takes the information being submitted via the form and displays the params hash in our browser at `localhost:4567/results`. Now take a look at `index.erb` in the views folder. It starts out with a form tag that has two attributes: a **method** and **action**. The `method` attribute stores the type of http request that we are making - in this case it is a post request. The `action` attribute stores the appropriate route for the post request. When the form is submitted it will connect with the method in the controller that corresponds to these two attributes. In this case a `post '/results'` method. The next part of the form is an input tag. The `type` attribute of the input tag stores the type of information that is being submitted. The `name` attribute stores the name of the variable where this information will be stored. So if this form was filled out by a user and submitted with the species "Emperor" the value that would be submitted to the back end of our application via a params hash looks like this: ```ruby params = {:species => "Emperor"} ``` If we wanted to take in information about the size of the penguin, we could add an additional input to our form that would look something like this: ```html Size: <input type="text" name="size"> ``` The last part of any form is the submit button. The type attribute needs to be equal to submit for the form to work properly. ###Challenge 1. Boot up the site by running `ruby demo3.rb` and try submitting different penguin species to the form on `localhost:4567/` and seeing the resulting params on `localhost:4567/results`. 2. Now that you've used the form try adding your own inputs to it, like the example that we gave with size.
Java
UTF-8
1,272
3.65625
4
[]
no_license
package exercicios2; import java.util.Scanner; public class ordem_crescente { public static void main(String[] args) { Scanner entrada = new Scanner(System.in); System.out.println("Digite o primeiro valor."); int valor1 = entrada.nextInt(); System.out.println("Digite o segundo valor"); int valor2 = entrada.nextInt(); System.out.println("Digite o terceiro valor"); int valor3 = entrada.nextInt(); if(valor1<valor2 && valor2<valor3) { System.out.println("\nOrdem crescente:"+valor1+"-"+valor2+"-"+valor3+""); }else { if(valor2<valor1 && valor1<valor3) { System.out.println("\nOrdem crescente:"+valor2+"-"+valor1+"-"+valor3+""); }else { if(valor3<valor2 && valor2<valor1) { System.out.println("\nOrdem crescente:"+valor3+"-"+valor2+"-"+valor1+""); }else { if(valor2<valor3 && valor3<valor1) { System.out.println("\nOrdem crescente:"+valor2+"-"+valor3+"-"+valor1+""); }else { if(valor1<valor3 && valor3<valor2) { System.out.println("\nOrdem crescente:"+valor1+"-"+valor3+"-"+valor2+""); }else { if(valor3<valor1 && valor1<valor2) { System.out.println("\nOrdem crescente:"+valor3+"-"+valor1+"-"+valor2+""); }else { } } } } } } } }
Java
UTF-8
295
2.296875
2
[ "Apache-2.0" ]
permissive
package au.org.noojee.irrigation.weather.units; import java.math.BigDecimal; public class Latitude { BigDecimal latitude; public Latitude(String latitude) { this.latitude = new BigDecimal(latitude); } @Override public String toString() { return "Latitude=" + latitude; } }
Java
UTF-8
1,129
3.703125
4
[]
no_license
import java.util.Scanner; public class string7 { public static void main(String[] args) { // TODO Auto-generated method stub //ejercicio 7 programa que de una frase nos diga mayusculas minusculas y numeros que tiene*/ Scanner teclado = new Scanner(System.in); int i; int contamayus; contamayus=0; int contaminus; contaminus = 0; int contanum; contanum = 0; String frase; System.out.println( "teclee una frase"); frase=teclado.nextLine(); while (frase.length() > 80){ System.out.println( "teclee una frase menor de 80 caracteres"); frase=teclado.nextLine(); }//end while for(i=0; i < frase.length(); i++){ if(frase.charAt(i)>=65 && frase.charAt(i)<=90){ contamayus ++; }else if(frase.charAt(i)>=97 && frase.charAt(i)<=122){ contaminus ++; }else if (frase.charAt(i)>=48 && frase.charAt(i)<=57){ contanum ++; }//end else if }//end for System.out.println( "se han introducido " + contamayus + " mayusculas " + contaminus + " minusculas y " + contanum + "numeros"); }//end main }//end class
Shell
UTF-8
3,649
4.15625
4
[ "Apache-2.0" ]
permissive
#!/bin/bash # ============================================================================ # Script for creating appliances exported from SUSE Studio # (http://susestudio.com) on your local system. # # Requires kiwi (http://opensuse.github.com/kiwi/). # # Author: James Tan <jatan@suse.de> # Contact: feedback@susestudio.com # ============================================================================ image_file='image/Crowbar_2.0.x86_64-0.0.4' image_arch='x86_64' schema_ver='5.2' base_system='12.2' declare -a repos=() dir="$(dirname $0)" src="$dir/source" dst="$dir/image" if ! [ -d "$src/" ] || ! [ -f "$src/config.xml" ]; then printf "%s: %s\n" \ "$0" "Cannot find appliance source." \ "$0" "cd into the appliance directory and run './create_appliance.sh'." \ >&2 exit 1 fi # Prints and runs the given command. Aborts if the command fails. function run_cmd { command=$1 echo $command $command if [ $? -ne 0 ]; then echo echo "** Appliance creation failed!" exit 1 fi } # Display usage. function usage { echo >&2 "Usage:" echo >&2 " create_appliance.sh" } function url_unknown { local repo="${1?}" [ -f /etc/kiwi/repoalias ] || return 0 ! grep -q "^{$repo}" /etc/kiwi/repoalias } function add_repo_url { local repo="${1?}" read -p "Enter repository URL for '$repo': " url mkdir -p /etc/kiwi echo "{$repo} $url" >> /etc/kiwi/repoalias \ && echo "{$repo} $url alias added to /etc/kiwi/repoalias" } # Check that we're root. if [ `whoami` != 'root' ]; then echo "Please run this script as root." exit 1 fi # Check that kiwi is installed. kiwi=`which kiwi 2> /dev/null` if [ $? -ne 0 ]; then echo "Kiwi is required but not found on your system." echo "Run the following command to install kiwi:" echo echo " zypper install kiwi kiwi-tools kiwi-desc-* kiwi-doc" echo exit 1 fi echo "Note: For a local build you will need a Kiwi version that supports building schemaversion $schema_ver or higher." if [ "$base_system" = "12.1" ] || [ "$base_system" = "12.2" ]; then # Check system and it's version for 12.1 (it can't be built on SLES/SLED or # earlier versions of openSUSE). sys_name=`head -1 /etc/SuSE-release` sys_ver=`grep VERSION /etc/SuSE-release | sed -e 's/^[^=]*= *//'` if [ `echo "$sys_name" | grep -c openSUSE` -eq 0 -o `echo "$sys_ver < 12.1" | bc` -eq 1 ]; then echo "This appliance should be built on openSUSE 12.1 or newer (you use '$sys_name')." while true; do read -p "Continue? [y/n] " yn case $yn in [Yy]* ) break;; [Nn]* ) exit;; esac done fi fi # Check architecture (i686, x86_64). sys_arch=`uname -m` linux32=`which linux32 2>/dev/null` if [ "$image_arch" = 'i686' ] && [ "$sys_arch" = 'x86_64' ]; then if [ "$linux32" = '' ]; then echo "'linux32' is required but not found." exit 1 else kiwi="$linux32 $kiwi" fi elif [ "$image_arch" = 'x86_64' ] && [ "$sys_arch" = 'i686' ]; then echo "Cannot build $image_arch image on a $sys_arch machine." exit 1 fi # Replace internal repositories in config.xml. echo "** Checking for internal repositories..." for repo in "${repos[@]}"; do if grep -q "{$repo}" $src/config.xml && url_unknown "$repo"; then add_repo_url "$repo" fi done # Create appliance. echo echo "** Creating appliance..." rm -rf build/root run_cmd "$kiwi --build $src/ -d $dst" # And we're done! qemu_options='-snapshot' [[ "$image_file" =~ \.iso$ ]] && qemu_options='-cdrom' echo echo "** Appliance created successfully! ($image_file)" echo "To boot the image using qemu-kvm, run the following command:" echo " qemu-kvm -m 512 $qemu_options $image_file &" echo
Python
UTF-8
1,114
4.65625
5
[]
no_license
""" Any string is True, except empty strings. Any number is True, except 0. Any list, tuple, set, and dictionary are True, except empty ones. """ bool("mediate") #output: True #note: Functions can Return a Boolean """ Operators for booleans == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10) is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y """ #EX print(6>=9) #False x = ["apple", "banana"] print("banana" in x) # returns True because a sequence with the value "banana" is in the list
C++
UTF-8
1,138
2.671875
3
[]
no_license
class TimerThread { public: struct Task; class Bucket; typedef uint64_t TaskId; const static TaskId INVALID_TASK_ID; TimerThread(); ~TimerThread(); // Start the timer thread. // This method should only be called once. // return 0 if success, errno otherwise. int start(const TimerThreadOptions* options); // Stop the timer thread. Later schedule() will return INVALID_TASK_ID. void stop_and_join(); // Schedule |fn(arg)| to run at realtime |abstime| approximately. // Returns: identifier of the scheduled task, INVALID_TASK_ID on error. TaskId schedule(void (*fn)(void*), void* arg, const timespec& abstime); // Prevent the task denoted by `task_id' from running. `task_id' must be // returned by schedule() ever. // Returns: // 0 - Removed the task which does not run yet // -1 - The task does not exist. // 1 - The task is just running. int unschedule(TaskId task_id); private: void run(); static void* run_this(void* arg); bool _started; butil::atomic<bool> _stop; std::mutex _mutex; Bucket* _buckets; int64_t _nearest_run_time; pthread_t _thread; };
C
UTF-8
626
2.71875
3
[]
no_license
#include <avr/io.h> void delay_timer0() { TCNT0 = 131; //load the timer counter register with 116 TCCR0A = 0x00; //set the Timer0 under normal mode TCCR0B = 0x04; //with 1:256 prescaler while ((TIFR0 & 0x01) == 0); //wait till timer overflow bit T0V0 is set TCCR0A = 0x00; //clear timer settings this stops the timer TCCR0B = 0x00; TIFR0 = 0x01; // clear the timer overflow bit T0V0 for the next round //in order to clear it,we should write 1 } int main(void){ DDRB|= (1<<5); //PB5 as output while (1){ PORTB=PORTB ^ (1<<5); //toggle delay_timer0(); } }
Java
UTF-8
444
1.835938
2
[]
no_license
package com.vdc.shop.dto; import lombok.Getter; import lombok.Setter; import java.util.List; @Getter @Setter public class ProductResponseDto { private String id; private String name; private long price; private String category; private BrandResponseDto brand; private List<IntAttributeDto> intAttributes; private List<StringAttributeDto> stringAttributes; private List<DoubleAttributeDto> doubleAttributes; }
C++
UTF-8
2,634
2.53125
3
[]
no_license
#pragma once #include <Framework.h> #include <RenderSystem.h> #include <CollisionSystem.h> #include <PhysicsSystem.h> #include <../dependancies/glm/glm.hpp> #include <../dependancies/glm/gtx/transform.hpp> namespace TransformChanges { static const Change position = 1 << 1; static const Change rotation = 1 << 2; static const Change scale = 1 << 3; static const Change all = position | rotation | scale; } struct TransformComponent : public IComponent, public AutoMapper<TransformComponent, PhysicsSystem, CollisionSystem, RenderSystem> { public: TransformComponent(IEntity* parent, const glm::vec3& pos = glm::vec3(), const glm::vec3& rot = glm::vec3(), const float fScale = 1) : pos(pos) , rot(rot) , scale(glm::vec3(fScale, fScale, fScale)) , IComponent(parent) , SYSTEMS({ SYSTEM_PRIORITY(RenderSystem, Priority::Low), SYSTEM_PRIORITY(CollisionSystem, Priority::VeryHigh), SYSTEM_PRIORITY(PhysicsSystem, Priority::High) }) { } inline void ChangeOccured(Change change, IComponent* subject) override { TransformComponent* transform = static_cast<TransformComponent*>(subject); if (change & TransformChanges::position) { pos = transform->GetPos(); } if (change & TransformChanges::rotation) { rot = transform->GetRot(); } if (change & TransformChanges::scale) { scale = transform->GetScale(); } } inline glm::mat4 GetModel() const { glm::mat4 posMat = glm::translate(pos); glm::mat4 scaleMat = glm::scale(scale); glm::mat4 rotX = glm::rotate(rot.x, glm::vec3(1.0, 0.0, 0.0)); glm::mat4 rotY = glm::rotate(rot.y, glm::vec3(0.0, 1.0, 0.0)); glm::mat4 rotZ = glm::rotate(rot.z, glm::vec3(0.0, 0.0, 1.0)); glm::mat4 rotMat = rotX * rotY * rotZ; return posMat * rotMat * scaleMat; } inline glm::mat4 GetMVP(const glm::mat4& VP) const { glm::mat4 M = GetModel(); return VP * M; } inline glm::vec3 GetPos() const { return pos; } inline glm::vec3 GetRot() const { return rot; } inline glm::vec3 GetScale() const { return scale; } inline void SetPos(glm::vec3& pos) { this->pos = pos; SINGLETON(SyncManager)->registerChanges(this, TransformChanges::position); } inline void SetRot(glm::vec3& rot) { this->rot = rot; SINGLETON(SyncManager)->registerChanges(this, TransformChanges::rotation); } inline void SetScale(glm::vec3& scale) { this->scale = scale; SINGLETON(SyncManager)->registerChanges(this, TransformChanges::scale); } protected: private: glm::vec3 pos; glm::vec3 rot; glm::vec3 scale; };
Java
UTF-8
1,484
2.25
2
[]
no_license
package com.enroll.service.services; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.enroll.service.entity.Enrollees; import com.enroll.service.exceptions.ResourceAlreadyExist; import com.enroll.service.exceptions.ResourceNotFoundException; import com.enroll.service.repository.EnrolleesRepository; @Service public class EnrollServiceImpl implements EnrollService { @Autowired EnrolleesRepository enrolleesRepository; @Override public Enrollees getEnrolleesById(long id) { // TODO Auto-generated method stub return enrolleesRepository.findByEnrollId(id); } @Override public Enrollees saveEnrollees(Enrollees enrollees) { Optional<Enrollees> enrolleesExists = Optional .ofNullable(enrolleesRepository.findByEnrollId(enrollees.getEnrollId())); if (enrolleesExists.isPresent()) { throw new ResourceAlreadyExist("Enrollees alreday exist"); } return enrolleesRepository.save(enrollees); } @Override public Enrollees updateEnrollees(Enrollees enrollees) { Optional<Enrollees> enrolleesExists = Optional .ofNullable(enrolleesRepository.findByEnrollId(enrollees.getEnrollId())); if (!enrolleesExists.isPresent()) { throw new ResourceNotFoundException(" resource not found"); } return enrolleesRepository.save(enrollees); } @Override public void deleteEnrolleesById(Long enrollId) { enrolleesRepository.deleteById(enrollId); } }