text stringlengths 1 2.12k | source dict |
|---|---|
python, performance, numpy, cython
integralEngine(molecule, basisObjects, nbasisObjects, "overlap")
integralEngine(molecule, basisObjects, nbasisObjects, "kinetic")
integralEngine(molecule, basisObjects, nbasisObjects, "eni")
integralEngine(molecule, basisObjects, nbasisObjects, "eri")
rank = comm.Get_rank()
if rank == 0:
with open("overlap."+inputfilename[:-4]+".txt", "w") as t:
for row in molecule.overlapmat:
for column in row:
t.write("{:10.3f}".format(column))
t.write("\n")
with open("kinetic."+inputfilename[:-4]+".txt", "w") as t:
for row in molecule.kineticmat:
for column in row:
t.write("{:10.3f}".format(column))
t.write("\n")
with open("nuclear."+inputfilename[:-4]+".txt", "w") as t:
for row in molecule.enimat:
for column in row:
t.write("{:10.3f}".format(column))
t.write("\n")
with open("electronic."+inputfilename[:-4]+".txt", "w") as t:
for axis1 in molecule.erimat:
for axis2 in axis1:
for axis3 in axis2:
for axis4 in axis3:
t.write("{:10.3f}".format(axis4))
t.write("\n")
t.write("\n")
t.write("\n")
molecule.nuclearenergy = nuclearenergy(atomObjects)
scfEngine(molecule, nbasisObjects)
with open("density."+inputfilename[:-4]+".txt", "w") as d:
savetxt(d, molecule.density, "%10.3f")
MPI.Finalize()
cython sections
oneelectron.pyx
import cython as cython
import numpy as np
cimport numpy as np
from scipy.special import comb, factorial2
from libc.math cimport exp, pow
from numpy import dot, pi | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def gaussiantheorem(np.ndarray[np.float64_t] center1, double exponent1, np.ndarray[np.float64_t] center2, double exponent2):
cdef np.ndarray gaussiancenter = np.zeros(3)
cdef double gaussianexponent = 0.0
cdef double gaussianintegral = 0.0
gaussiancenter = ((exponent1*center1)+(exponent2*center2))/(exponent1+exponent2)
gaussianexponent = (exponent1*exponent2)/(exponent1+exponent2)
gaussianintegral = exp(-1*gaussianexponent*dot(center1-center2, center1-center2))
return gaussiancenter, gaussianintegral
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double overlappgtos(double center1, double exponent1, int shell1, double center2, double exponent2, int shell2, double gaussiancenter):
cdef double t_overlap = 0.0
cdef double auxiliary = 0.0
cdef int counter1, counter2
for counter1 in range(0, shell1+1):
for counter2 in range(0, shell2+1):
if (counter1+counter2)%2 == 0:
auxiliary = comb(shell1, counter1)
auxiliary = auxiliary*comb(shell2, counter2)
auxiliary = auxiliary*factorial2(counter1+counter2-1)
auxiliary = auxiliary*pow(gaussiancenter-center1, shell1-counter1)
auxiliary = auxiliary*pow(gaussiancenter-center2, shell2-counter2)
auxiliary = auxiliary/pow(2*(exponent1+exponent2), 0.5*(counter1+counter2))
t_overlap = t_overlap+auxiliary
return t_overlap
@cython.boundscheck(False)
@cython.wraparound(False)
def overlapcgtos(basisobject1, basisobject2):
cdef np.ndarray center1 = basisobject1.center
cdef np.ndarray exponents1 = basisobject1.exponents
cdef np.ndarray coefficients1 = basisobject1.coefficients
cdef np.ndarray shell1 = basisobject1.shell
cdef np.ndarray normcoeffs1 = basisobject1.normcoeffs | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
cdef np.ndarray center2 = basisobject2.center
cdef np.ndarray exponents2 = basisobject2.exponents
cdef np.ndarray coefficients2 = basisobject2.coefficients
cdef np.ndarray shell2 = basisobject2.shell
cdef np.ndarray normcoeffs2 = basisobject2.normcoeffs
cdef double overlaptotal = 0.0
cdef index1 = 0
cdef index2 = 0
cdef exponent1 = 0
cdef exponent2 = 0
cdef np.ndarray gaussiancenter = np.zeros(3)
cdef double gaussianintegral = 0.0
for index1, exponent1 in enumerate(exponents1):
for index2, exponent2 in enumerate(exponents2):
gaussiancenter, gaussianintegral = gaussiantheorem(center1, exponent1, center2, exponent2)
overlapx = overlappgtos(center1[0], exponent1, shell1[0], center2[0], exponent2, shell2[0], gaussiancenter[0])
overlapy = overlappgtos(center1[1], exponent1, shell1[1], center2[1], exponent2, shell2[1], gaussiancenter[1])
overlapz = overlappgtos(center1[2], exponent1, shell1[2], center2[2], exponent2, shell2[2], gaussiancenter[2])
overlap = overlapx*overlapy*overlapz*gaussianintegral*pow(pi/(exponent1+exponent2), 1.5)
overlaptotal = overlaptotal+(normcoeffs1[index1]*normcoeffs2[index2]*coefficients1[index1]*coefficients2[index2])*overlap
return overlaptotal
@cython.boundscheck(False)
@cython.wraparound(False)
def kineticcgtos(basisobject1, basisobject2):
cdef np.ndarray center1 = basisobject1.center
cdef np.ndarray exponents1 = basisobject1.exponents
cdef np.ndarray coefficients1 = basisobject1.coefficients
cdef np.ndarray shell1 = basisobject1.shell
cdef np.ndarray normcoeffs1 = basisobject1.normcoeffs | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
cdef np.ndarray center2 = basisobject2.center
cdef np.ndarray exponents2 = basisobject2.exponents
cdef np.ndarray coefficients2 = basisobject2.coefficients
cdef np.ndarray shell2 = basisobject2.shell
cdef np.ndarray normcoeffs2 = basisobject2.normcoeffs
cdef double Kx = 0.0
cdef double Ky = 0.0
cdef double Kz = 0.0
cdef np.ndarray gaussiancenter = np.zeros(3)
cdef double gaussianintegral = 0.0
for index1, exponent1 in enumerate(exponents1):
for index2, exponent2 in enumerate(exponents2):
gaussiancenter, gaussianintegral = gaussiantheorem(center1, exponent1, center2, exponent2)
overlapx = overlappgtos(center1[0], exponent1, shell1[0], center2[0], exponent2, shell2[0], gaussiancenter[0])
overlapy = overlappgtos(center1[1], exponent1, shell1[1], center2[1], exponent2, shell2[1], gaussiancenter[1])
overlapz = overlappgtos(center1[2], exponent1, shell1[2], center2[2], exponent2, shell2[2], gaussiancenter[2])
overlapx11 = overlappgtos(center1[0], exponent1, shell1[0]-1, center2[0], exponent2, shell2[0]-1, gaussiancenter[0])
overlapx12 = overlappgtos(center1[0], exponent1, shell1[0]+1, center2[0], exponent2, shell2[0]-1, gaussiancenter[0])
overlapx13 = overlappgtos(center1[0], exponent1, shell1[0]-1, center2[0], exponent2, shell2[0]+1, gaussiancenter[0])
overlapx14 = overlappgtos(center1[0], exponent1, shell1[0]+1, center2[0], exponent2, shell2[0]+1, gaussiancenter[0]) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
overlapy11 = overlappgtos(center1[1], exponent1, shell1[1]-1, center2[1], exponent2, shell2[1]-1, gaussiancenter[1])
overlapy12 = overlappgtos(center1[1], exponent1, shell1[1]+1, center2[1], exponent2, shell2[1]-1, gaussiancenter[1])
overlapy13 = overlappgtos(center1[1], exponent1, shell1[1]-1, center2[1], exponent2, shell2[1]+1, gaussiancenter[1])
overlapy14 = overlappgtos(center1[1], exponent1, shell1[1]+1, center2[1], exponent2, shell2[1]+1, gaussiancenter[1])
overlapz11 = overlappgtos(center1[2], exponent1, shell1[2]-1, center2[2], exponent2, shell2[2]-1, gaussiancenter[2])
overlapz12 = overlappgtos(center1[2], exponent1, shell1[2]+1, center2[2], exponent2, shell2[2]-1, gaussiancenter[2])
overlapz13 = overlappgtos(center1[2], exponent1, shell1[2]-1, center2[2], exponent2, shell2[2]+1, gaussiancenter[2])
overlapz14 = overlappgtos(center1[2], exponent1, shell1[2]+1, center2[2], exponent2, shell2[2]+1, gaussiancenter[2])
kx = shell1[0]*shell2[0]*overlapx11
kx += -2*exponent1*shell2[0]*overlapx12
kx += -2*exponent2*shell1[0]*overlapx13
kx += 4*exponent1*exponent2*overlapx14
ky = shell1[1]*shell2[1]*overlapy11
ky += -2*exponent1*shell2[1]*overlapy12
ky += -2*exponent2*shell1[1]*overlapy13
ky += 4*exponent1*exponent2*overlapy14
kz = shell1[2]*shell2[2]*overlapz11
kz += -2*exponent1*shell2[2]*overlapz12
kz += -2*exponent2*shell1[2]*overlapz13
kz += 4*exponent1*exponent2*overlapz14 | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
Kx += 0.5*kx*overlapy*overlapz*gaussianintegral*pow(pi/(exponent1+exponent2), 1.5)*normcoeffs1[index1]*coefficients1[index1]*normcoeffs2[index2]*coefficients2[index2]
Ky += 0.5*ky*overlapx*overlapz*gaussianintegral*pow(pi/(exponent1+exponent2), 1.5)*normcoeffs1[index1]*coefficients1[index1]*normcoeffs2[index2]*coefficients2[index2]
Kz += 0.5*kz*overlapx*overlapy*gaussianintegral*pow(pi/(exponent1+exponent2), 1.5)*normcoeffs1[index1]*coefficients1[index1]*normcoeffs2[index2]*coefficients2[index2]
return Kx+Ky+Kz
twoelectron.pyx
import cython as cython
import numpy as np
cimport numpy as np
from scipy.special import comb, factorial2, factorial, hyp1f1
from libc.math cimport exp, pow, sqrt
from numpy import dot, pi
from numpy.linalg import norm
@cython.boundscheck(False)
@cython.wraparound(False)
def gaussiantheorem(np.ndarray[np.float64_t] center1, double exponent1, np.ndarray[np.float64_t] center2, double exponent2):
cdef np.ndarray gaussiancenter = np.zeros(3)
cdef double gaussianexponent = 0.0
cdef double gaussianintegral = 0.0
gaussiancenter = ((exponent1*center1)+(exponent2*center2))/(exponent1+exponent2)
gaussianexponent = (exponent1*exponent2)/(exponent1+exponent2)
gaussianintegral = exp(-1*gaussianexponent*dot(center1-center2, center1-center2))
return gaussiancenter, gaussianintegral | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double expansioncoeff1(int expansionindex, int shell1, float center1, int shell2, float center2, float gaussiancenter):
cdef double t_expansioncoeff = 0.0
cdef int counter = 0
cdef double auxiliary = 0.0
for counter in range(max(0, expansionindex-shell2), min(expansionindex, shell1)+1):
auxiliary = comb(shell1, counter)
auxiliary = auxiliary*comb(shell2, expansionindex-counter)
auxiliary = auxiliary*pow(gaussiancenter-center1, shell1-counter)
auxiliary = auxiliary*pow(gaussiancenter-center2, shell2+counter-expansionindex)
t_expansioncoeff = t_expansioncoeff+auxiliary
return t_expansioncoeff | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double expansioncoeff2(int expansionindex1, int expansionindex2, int expansionindex3, int shell1, float center1, int shell2, float center2, float atomcenter, float gaussiancenter, float gamma):
cdef double t_expansioncoeff = 0.0
cdef double epsilon = 1.0/(4*gamma)
t_expansioncoeff = expansioncoeff1(expansionindex1, shell1, center1, shell2, center2, gaussiancenter)
t_expansioncoeff = t_expansioncoeff*factorial(expansionindex1)
t_expansioncoeff = t_expansioncoeff*pow(-1, expansionindex1+expansionindex3)
t_expansioncoeff = t_expansioncoeff*pow(gaussiancenter-atomcenter, expansionindex1-(2*expansionindex2)-(2*expansionindex3))
t_expansioncoeff = t_expansioncoeff*pow(epsilon, expansionindex2+expansionindex3)
t_expansioncoeff = t_expansioncoeff/factorial(expansionindex3, exact=True)
t_expansioncoeff = t_expansioncoeff/factorial(expansionindex2, exact=True)
t_expansioncoeff = t_expansioncoeff/factorial(expansionindex1-(2*expansionindex2)-(2*expansionindex3), exact=True)
return t_expansioncoeff
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double boysfunction(int boysindex, double boysparameter):
return hyp1f1(0.5+boysindex, 1.5+boysindex, -1*boysparameter)/((2*boysindex)+1)
@cython.boundscheck(False)
@cython.wraparound(False)
def nuclearcgtos(basisobject1, basisobject2, atomobjects):
cdef double t_eniintegral = 0.0
cdef np.ndarray center1 = basisobject1.center
cdef np.ndarray exponents1 = basisobject1.exponents
cdef np.ndarray coefficients1 = basisobject1.coefficients
cdef np.ndarray shell1 = basisobject1.shell
cdef np.ndarray normcoeffs1 = basisobject1.normcoeffs | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
cdef np.ndarray center2 = basisobject2.center
cdef np.ndarray exponents2 = basisobject2.exponents
cdef np.ndarray coefficients2 = basisobject2.coefficients
cdef np.ndarray shell2 = basisobject2.shell
cdef np.ndarray normcoeffs2 = basisobject2.normcoeffs
for index1, exponent1 in enumerate(exponents1):
for index2, exponent2 in enumerate(exponents2):
t_nuclearintegral = 0.0
gamma = exponent1+exponent2
gaussiancenter, gaussianintegral = gaussiantheorem(center1, exponent1, center2, exponent2)
for atom in atomobjects:
for expansionindex1A in range(0, shell1[0]+shell2[0]+1):
for expansionindex1B in range(0, int(expansionindex1A//2)+1):
for expansionindex1C in range(0, int((expansionindex1A-(2*expansionindex1B))//2)+1):
auxiliary1A = expansioncoeff2(expansionindex1A, expansionindex1B, expansionindex1C, shell1[0], center1[0], shell2[0], center2[0], atom.center[0], gaussiancenter[0], gamma)
for expansionindex2A in range(0, shell1[1]+shell2[1]+1):
for expansionindex2B in range(0, int(expansionindex2A//2)+1):
for expansionindex2C in range(0, int((expansionindex2A-(2*expansionindex2B))//2)+1):
auxiliary2A = expansioncoeff2(expansionindex2A, expansionindex2B, expansionindex2C, shell1[1], center1[1], shell2[1], center2[1], atom.center[1], gaussiancenter[1], gamma) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
for expansionindex3A in range(0, shell1[2]+shell2[2]+1):
for expansionindex3B in range(0, int(expansionindex3A//2)+1):
for expansionindex3C in range(0, int((expansionindex3A-(2*expansionindex3B))//2)+1):
auxiliary3A = expansioncoeff2(expansionindex3A, expansionindex3B, expansionindex3C, shell1[2], center1[2], shell2[2], center2[2], atom.center[2], gaussiancenter[2], gamma)
boysindex = (expansionindex1A+expansionindex2A+expansionindex3A)-2*(expansionindex1B+expansionindex2B+expansionindex3B)-(expansionindex1C+expansionindex2C+expansionindex3C)
boysparam = dot(atom.center-gaussiancenter, atom.center-gaussiancenter)*gamma
auxiliary4A = boysfunction(boysindex, boysparam)
t_nuclearintegral = t_nuclearintegral+(auxiliary1A*auxiliary2A*auxiliary3A*auxiliary4A)*atom.charge*-1.0
t_eniintegral = t_eniintegral+(t_nuclearintegral*coefficients1[index1]*coefficients2[index2]*normcoeffs1[index1]*normcoeffs2[index2]*gaussianintegral*(2*pi/gamma))
return t_eniintegral
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double enigaussian(int shell1, int shell2, int nodes, float center1, float center2, float exponent1, float exponent2):
cdef double gamma = exponent1+exponent2
cdef double exponent = exponent1*(exponent2/gamma) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if (nodes < 0) or (nodes > (shell1+shell2)):
return 0
elif nodes == shell1 == shell2 == 0:
return exp(-1*exponent*pow(center1-center2, 2))
elif shell2 == 0:
return (1/(2*gamma))*enigaussian(shell1-1, shell2, nodes-1, center1, center2, exponent1, exponent2) - (exponent*(center1-center2)/exponent1)*enigaussian(shell1-1, shell2, nodes, center1, center2, exponent1, exponent2) + (nodes+1)*enigaussian(shell1-1, shell2, nodes+1, center1, center2, exponent1, exponent2)
else:
return (1/(2*gamma))*enigaussian(shell1, shell2-1, nodes-1, center1, center2, exponent1, exponent2) + (exponent*(center1-center2)/exponent2)*enigaussian(shell1, shell2-1, nodes, center1, center2, exponent1, exponent2) + (nodes+1)*enigaussian(shell1, shell2-1, nodes+1, center1, center2, exponent1, exponent2)
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double auxiliaryhermiteeri(int nodes1, int nodes2, int nodes3, int boysorder, float exponent, float xdist, float ydist, float zdist, float dist):
cdef double boysparam = exponent*pow(dist, 2)
cdef double auxhermite = 0.0 | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
if nodes1 == nodes2 == nodes3 == 0:
auxhermite += pow(-2*exponent, boysorder)*boysfunction(boysorder, boysparam)
elif nodes1 == nodes2 == 0:
if nodes3 > 1:
auxhermite += (nodes3-1)*auxiliaryhermiteeri(nodes1, nodes2, nodes3-2, boysorder+1, exponent, xdist, ydist, zdist, dist)
auxhermite += zdist*auxiliaryhermiteeri(nodes1, nodes2, nodes3-1, boysorder+1, exponent, xdist, ydist, zdist, dist)
elif nodes1 == 0:
if nodes2 > 1:
auxhermite += (nodes2-1)*auxiliaryhermiteeri(nodes1, nodes2-2, nodes3, boysorder+1, exponent, xdist, ydist, zdist, dist)
auxhermite += ydist*auxiliaryhermiteeri(nodes1, nodes2-1, nodes3, boysorder+1, exponent, xdist, ydist, zdist, dist)
else:
if nodes1 > 1:
auxhermite += (nodes1-1)*auxiliaryhermiteeri(nodes1-2, nodes2, nodes3, boysorder+1, exponent, xdist, ydist, zdist, dist)
auxhermite += xdist*auxiliaryhermiteeri(nodes1-1, nodes2, nodes3, boysorder+1, exponent, xdist, ydist, zdist, dist)
return auxhermite | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
cdef double eripgtos(exponent1, shell1, center1, exponent2, shell2, center2, exponent3, shell3, center3, exponent4, shell4, center4):
cdef double eripgto = 0.0
cdef np.ndarray gaussiancenterA = np.zeros(3)
cdef double gaussianintegralA = 0.0
cdef np.ndarray gaussiancenterB = np.zeros(3)
cdef double gaussianintegralB = 0.0
gaussiancenterA, gaussianintegralA = gaussiantheorem(center1, exponent1, center2, exponent2)
gaussiancenterB, gaussianintegralB = gaussiantheorem(center3, exponent3, center4, exponent4)
cdef double xdist = gaussiancenterA[0]-gaussiancenterB[0]
cdef double ydist = gaussiancenterA[1]-gaussiancenterB[1]
cdef double zdist = gaussiancenterA[2]-gaussiancenterB[2]
cdef double distance = norm(gaussiancenterA-gaussiancenterB)
cdef double combexponentA = exponent1+exponent2
cdef double combexponentB = exponent3+exponent4
cdef double combexponent = combexponentA*(combexponentB/(combexponentA+combexponentB)) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
cdef int index1 = 0
cdef int index2 = 0
cdef int index3 = 0
cdef int index4 = 0
cdef int index5 = 0
cdef int index6 = 0
for index1 in range(0, shell1[0]+shell2[0]+1):
for index2 in range(0, shell1[1]+shell2[1]+1):
for index3 in range(0, shell1[2]+shell2[2]+1):
for index4 in range(0, shell3[0]+shell4[0]+1):
for index5 in range(0, shell3[1]+shell4[1]+1):
for index6 in range(0, shell3[2]+shell4[2]+1):
erigaussianA = enigaussian(shell1[0], shell2[0], index1, center1[0], center2[0], exponent1, exponent2)
erigaussianB = enigaussian(shell1[1], shell2[1], index2, center1[1], center2[1], exponent1, exponent2)
erigaussianC = enigaussian(shell1[2], shell2[2], index3, center1[2], center2[2], exponent1, exponent2)
erigaussianD = enigaussian(shell3[0], shell4[0], index4, center3[0], center4[0], exponent3, exponent4)
erigaussianE = enigaussian(shell3[1], shell4[1], index5, center3[1], center4[1], exponent3, exponent4)
erigaussianF = enigaussian(shell3[2], shell4[2], index6, center3[2], center4[2], exponent3, exponent4)
erigaussianG = auxiliaryhermiteeri(index1+index4, index2+index5, index3+index6, 0, combexponent, xdist, ydist, zdist, distance)
result = erigaussianA*erigaussianB*erigaussianC*erigaussianD*erigaussianE*erigaussianF*erigaussianG*pow(-1, index4+index5+index6)
eripgto = eripgto+result
eripgto *= 2*pow(pi, 2.5)/(combexponentA*combexponentB*sqrt(combexponentA+combexponentB))
return eripgto | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def ericgtos(basisobject1, basisobject2, basisobject3, basisobject4):
cdef np.ndarray center1 = basisobject1.center
cdef np.ndarray exponents1 = basisobject1.exponents
cdef np.ndarray coefficients1 = basisobject1.coefficients
cdef np.ndarray shell1 = basisobject1.shell
cdef np.ndarray normcoeffs1 = basisobject1.normcoeffs
cdef np.ndarray center2 = basisobject2.center
cdef np.ndarray exponents2 = basisobject2.exponents
cdef np.ndarray coefficients2 = basisobject2.coefficients
cdef np.ndarray shell2 = basisobject2.shell
cdef np.ndarray normcoeffs2 = basisobject2.normcoeffs
cdef np.ndarray center3 = basisobject3.center
cdef np.ndarray exponents3 = basisobject3.exponents
cdef np.ndarray coefficients3 = basisobject3.coefficients
cdef np.ndarray shell3 = basisobject3.shell
cdef np.ndarray normcoeffs3 = basisobject3.normcoeffs
cdef np.ndarray center4 = basisobject4.center
cdef np.ndarray exponents4 = basisobject4.exponents
cdef np.ndarray coefficients4 = basisobject4.coefficients
cdef np.ndarray shell4 = basisobject4.shell
cdef np.ndarray normcoeffs4 = basisobject4.normcoeffs | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
cdef double ericgto = 0.0
for index1, exponent1 in enumerate(exponents1):
for index2, exponent2 in enumerate(exponents2):
for index3, exponent3 in enumerate(exponents3):
for index4, exponent4 in enumerate(exponents4):
result = eripgtos(exponent1, shell1, center1, exponent2, shell2, center2, exponent3, shell3, center3, exponent4, shell4, center4)
result *= coefficients1[index1]*normcoeffs1[index1]*coefficients2[index2]*normcoeffs2[index2]*coefficients3[index3]*normcoeffs3[index3]*coefficients4[index4]*normcoeffs4[index4]
ericgto = ericgto+result
return ericgto
hartreefock.pyx
import cython as cython
import numpy as np
cimport numpy as np
from scipy.special import comb, factorial2
from libc.math cimport exp, pow
from numpy import dot, pi, diag, amax, trace, isclose
from numpy.linalg import eigh, solve
@cython.boundscheck(False)
@cython.wraparound(False)
def computecorehamiltonian(np.ndarray[np.float64_t, ndim=2]kineticmat, np.ndarray[np.float64_t, ndim=2]enimat):
cdef int nbasis = kineticmat[0].size
cdef np.ndarray[np.float64_t, ndim=2] corehamiltonian = np.zeros((nbasis, nbasis))
corehamiltonian = kineticmat+enimat
return corehamiltonian | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def canonicalorthogonalization(np.ndarray[np.float64_t, ndim=2] overlapmat):
cdef int nbasis = overlapmat[0].size
cdef np.ndarray[np.float64_t, ndim=1] eigenvalues = np.zeros(nbasis)
cdef np.ndarray[np.float64_t, ndim=2] t_eigenvalues = np.zeros((nbasis, nbasis))
cdef np.ndarray[np.float64_t, ndim=2] eigenvectors = np.zeros((nbasis, nbasis))
cdef np.ndarray[np.float64_t, ndim=2] orthogonalmat = np.zeros((nbasis, nbasis))
eigenvalues, eigenvectors = eigh(overlapmat)
t_eigenvalues = diag((eigenvalues)**-0.5)
orthogonalmat = dot(eigenvectors, t_eigenvalues)
return orthogonalmat
@cython.boundscheck(False)
@cython.wraparound(False)
def computehamiltonian(np.ndarray[np.float64_t, ndim=2] densitymat, np.ndarray[np.float64_t, ndim=4] erimat):
cdef int nbasis = densitymat[0].size
cdef int index1
cdef int index2
cdef int index3
cdef int index4
cdef np.ndarray[np.float64_t, ndim=2] hamiltonian = np.zeros((nbasis, nbasis))
for index1 in range(0, nbasis):
for index2 in range(0, nbasis):
for index3 in range(0, nbasis):
for index4 in range(0, nbasis):
hamiltonian[index1, index2] = hamiltonian[index1, index2]+(densitymat[index3, index4]*(erimat[index1, index2, index3, index4]-0.5*(erimat[index1, index4, index3, index2])))
return hamiltonian | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def computedensity(int nelectrons, np.ndarray[np.float64_t, ndim=2] overlapmat):
cdef int nbasis = overlapmat[0].shape[0]
cdef np.ndarray[np.float64_t, ndim=2] densitymat = np.zeros((nbasis, nbasis))
cdef int index1
cdef int index2
cdef int index3
for index1 in range(0, nbasis):
for index2 in range(0, nbasis):
for index3 in range(0, int(nelectrons//2)):
densitymat[index1, index2] += 2.0*overlapmat[index1, index3]*overlapmat[index2, index3]
return densitymat
@cython.boundscheck(False)
@cython.wraparound(False)
def diisorthogonalization(np.ndarray[np.float64_t, ndim=2] overlapmat):
eigenvalues, eigenvectors = eigh(overlapmat)
halfeigmat = diag((eigenvalues)**-0.5)
rightmat = dot(eigenvectors, halfeigmat)
orthomat = dot(rightmat, eigenvectors.T)
return orthomat | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
def diisEngine(molecule, np.ndarray[np.float64_t, ndim=2] fock, np.ndarray[np.float64_t, ndim=2] density):
cdef int dimensions = fock[0].size
eigenvalues, eigenvectors = eigh(molecule.overlapmat)
halfeigmat = diag((eigenvalues)**-0.5)
rightmat = dot(eigenvectors, halfeigmat)
orthomat = dot(rightmat, eigenvectors.T)
t_errorvector = dot(fock, dot(density, molecule.overlapmat))-dot(molecule.overlapmat, dot(density, fock))
leftmat = dot(orthomat.T, t_errorvector)
errorvector = dot(leftmat, orthomat)
molecule.diisfock.append(fock)
molecule.diiserror.append(errorvector)
cdef int fockdimension = len(molecule.diisfock)
if fockdimension > 6:
del molecule.diisfock[0]
del molecule.diiserror[0]
fockdimension = fockdimension-1
cdef np.ndarray[np.float64_t, ndim=2] bmatrix = np.zeros((fockdimension+1, fockdimension+1))
bmatrix[-1,:] = -1.0
bmatrix[:,-1] = -1.0
bmatrix[-1,-1] = 0.0
for index1 in range(0, fockdimension):
for index2 in range(0, index1+1):
bmatrix[index1, index2] = trace(dot(molecule.diiserror[index1].T, molecule.diiserror[index2]))
bmatrix[index2, index1] = trace(dot(molecule.diiserror[index1].T, molecule.diiserror[index2]))
cdef np.ndarray[np.float64_t, ndim=1] residue = np.zeros(fockdimension+1)
residue[-1] = -1.0
cdef np.ndarray[np.float64_t, ndim=1] weights = solve(bmatrix, residue)
assert isclose(sum(weights[:-1]),1.0)
cdef np.ndarray[np.float64_t, ndim=2] newfock = np.zeros((dimensions, dimensions))
for index, fockelement in enumerate(molecule.diisfock):
newfock = newfock+(weights[index]*fockelement)
return newfock | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def restrictedhatreefock(int nelectrons, np.ndarray[np.float64_t, ndim=2] corehamiltonian, np.ndarray[np.float64_t, ndim=2] orthogonalmat, np.ndarray[np.float64_t, ndim=2] densitymat, np.ndarray[np.float64_t, ndim=4] erimat):
cdef int nbasis = corehamiltonian[0].size
cdef np.ndarray[np.float64_t, ndim=2] hamiltonianmat = computehamiltonian(densitymat, erimat)
cdef np.ndarray[np.float64_t, ndim=2] fockmatrix = hamiltonianmat+corehamiltonian
cdef np.ndarray[np.float64_t, ndim=2] orthofockmatrix = dot(orthogonalmat.conj().T, dot(fockmatrix, orthogonalmat))
cdef np.ndarray[np.float64_t, ndim=1] orbitalenergies = np.zeros(nbasis)
cdef np.ndarray[np.float64_t, ndim=2] orthocoeffs = np.zeros((nbasis, nbasis))
orbitalenergies, orthocoeffs = eigh(orthofockmatrix)
cdef np.ndarray[np.float64_t, ndim=2] canonicalcoeffs = dot(orthogonalmat, orthocoeffs)
cdef np.ndarray[np.float64_t, ndim=2] t_densitymat = computedensity(nelectrons, canonicalcoeffs)
cdef double maxdensitydiff
cdef double rmsdensitydiff
maxdensitydiff, rmsdensitydiff = checkconvergence(densitymat, t_densitymat)
return orthofockmatrix, fockmatrix, hamiltonianmat, orbitalenergies, canonicalcoeffs, t_densitymat, maxdensitydiff, rmsdensitydiff | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def restrictedhatreefockDIIS(molecule, int nelectrons, np.ndarray[np.float64_t, ndim=2] corehamiltonian, np.ndarray[np.float64_t, ndim=2] orthogonalmat, np.ndarray[np.float64_t, ndim=2] densitymat, np.ndarray[np.float64_t, ndim=4] erimat):
cdef int nbasis = corehamiltonian[0].size
cdef np.ndarray[np.float64_t, ndim=2] hamiltonianmat = computehamiltonian(densitymat, erimat)
cdef np.ndarray[np.float64_t, ndim=2] fockmatrix = hamiltonianmat+corehamiltonian
cdef np.ndarray[np.float64_t, ndim=2] diisfock = diisEngine(molecule, fockmatrix, densitymat)
cdef np.ndarray[np.float64_t, ndim=2] orthofockmatrix = dot(orthogonalmat.conj().T, dot(diisfock, orthogonalmat))
cdef np.ndarray[np.float64_t, ndim=1] orbitalenergies = np.zeros(nbasis)
cdef np.ndarray[np.float64_t, ndim=2] orthocoeffs = np.zeros((nbasis, nbasis))
orbitalenergies, orthocoeffs = eigh(orthofockmatrix)
cdef np.ndarray[np.float64_t, ndim=2] canonicalcoeffs = dot(orthogonalmat, orthocoeffs)
cdef np.ndarray[np.float64_t, ndim=2] t_densitymat = computedensity(nelectrons, canonicalcoeffs)
cdef double maxdensitydiff
cdef double rmsdensitydiff
maxdensitydiff, rmsdensitydiff = checkconvergence(densitymat, t_densitymat)
return orthofockmatrix, fockmatrix, hamiltonianmat, orbitalenergies, canonicalcoeffs, t_densitymat, maxdensitydiff, rmsdensitydiff
@cython.boundscheck(False)
@cython.wraparound(False)
def checkconvergence(np.ndarray[np.float64_t, ndim=2] densitymat, np.ndarray[np.float64_t, ndim=2] t_densitymat):
cdef np.ndarray[np.float64_t, ndim=2] densitydiff = t_densitymat-densitymat
cdef double maxdensitydiff = amax(densitydiff)
cdef double rmsdensitydiff = pow(sum(sum((densitydiff)**2))/4.0, 0.5)
return maxdensitydiff, rmsdensitydiff | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
@cython.boundscheck(False)
@cython.wraparound(False)
def totalenergy(float nucenergy, np.ndarray[np.float64_t, ndim=2] fockmatrix, np.ndarray[np.float64_t, ndim=2] densitymatrix, np.ndarray[np.float64_t, ndim=2] corehamiltonian):
cdef double t_energy = 0.0
cdef int nbasis = fockmatrix[0].size
for index1 in range(0, nbasis):
for index2 in range(0, nbasis):
t_energy = t_energy+(0.5*densitymatrix[index1,index2]*(fockmatrix[index1,index2]+corehamiltonian[index1,index2]))
return t_energy+nucenergy
```
Answer: Let's talk about structure and readability.
Use snake_case for naming, it's a standard practice in Python. nuclear_energy instead of nuclearenergy, get_atom instead of getatom, etc.. Much easier to read.
Don't use camelCase and, more importantly, don't mix naming conventions together:
periodictable = safe_load(periodic)
periodicTable = {y: x[y] for x in periodictable for y in x}
At first I thought you're assigning periodictable twice.
Don't pollute the global scope by creating names here. The piece above creates 2 names periodictable and periodicTable that will be accessible from anywhere in the code. Instead create a PeriodicTable class with a get_atom member method.
Let's look at this function:
def nuclearenergy(atomobjects):
atompairs = list(combinations(atomobjects,2))
nuclearenergy = 0.0
for atompair in atompairs:
center1 = atompair[0].center
charge1 = atompair[0].charge
center2 = atompair[1].center
charge2 = atompair[1].charge
distance = norm(center1-center2)
energy = charge1*charge2/distance
nuclearenergy = nuclearenergy+energy
return nuclearenergy
It can be rewritten as:
def get_nuclear_energy(atoms):
return sum([pair[0].charge * pair[1].charge / norm(pair[0].center - pair[1].center) for pair in combinations(atoms, 2)]) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
This is shorter and more readable while also being about 6% faster (according to a simple test via PyCharm profiling). The only information we lost is that norm(center1-center2) is distance, but I assume people who are going to contribute to this code are already familiar with the formulas.
Now this function:
def overlap(basisobjects):
overlaps = []
for basisobjecttuple in basisobjects:
result = overlapcgtos(basisobjecttuple[0], basisobjecttuple[1])
overlaps.append((result, basisobjecttuple[0].basisindex, basisobjecttuple[1].basisindex))
return overlaps
We see a similar structure: create an empty container-accumulator and fill it with stuff in a cycle. This is verbose and slow, since you have to call append() every time you're adding to the container. It can be rewritten like this:
def get_overlaps(bases):
return [(overlapcgtos(basis[0], basis[1]), basis[0].basis_index, basis[1].basis_index) for basis in bases]
Can't check the performance without compiling pyx, but should be about 44% faster (tested append in a cycle vs list comprehension via PyCharm profiler).
The same goes for the following 3 functions.
def integralEngine ...
def scfEngine ...
Can't tell what those functions are for by reading their name. Functions should be named with verbs that represent the action the function is doing, e.g. start_scf_engine.
if calctype == "overlap":
...
if calctype == "kinetic":
...
if calctype == "eni":
...
if calctype == "eri":
...
Consider defining an enum for that, so things don't break when you decide to change the string in one place and forget to change it in another. Also use elif to get rid of unnecessary checks.
pow(2, 2*totalangmomentum)*pow(2, 1.5)
Python has a pow operator: **
2 ** (2 * totalangmomentum) * 2 ** 2.5
[x for x in molecule.geometry]
This statement does nothing with molecule.geometry. If you wanted to copy it, there is a function for that in the copy package: copy.copy(molecule.geometry) | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
python, performance, numpy, cython
Consider using if __name__ == '__main__' construction to run the script.
In general, try running your code with a profiler and see what parts are the slowest. Try to speed them up first and don't bother with stuff that is already fast. And consider trying Numba, as @greybeard suggested in the comments. | {
"domain": "codereview.stackexchange",
"id": 44838,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, performance, numpy, cython",
"url": null
} |
c, vectors, macros
Title: C23 Vector Macro Implementation
Question: I'm trying to implement a simple type-generic Vector with macros using the newest features of C23. Looking for any advice about macro design and pitfalls because I generally avoid macros at all costs. Wondering how to extend this code to handle more complex data types as well.
Also, I'm not particularly happy with the hacky int vector_abort() used in the vector_at() ternary. Any portable advice here is greatly appreciated. Furthermore, if anyone has a way to make opaque structures with macros I would be very interested.
A major problem that I immediately notice is that there isn't an easy way to tell if vector_push() was successful. However, return values aren't permitted for macros and calling abort() or exit() doesn't seem great in this instance.
C23 features used:
nullptr constant from <stddef.h>
true and false keywords
free_sized() from <stdlib.h>
= {} empty initializer
function() empty function argument declaration
typeof operator
N3003 Improved Rules for Tag Compatibility
vector.h
#ifndef VECTOR_H
#define VECTOR_H
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int vector_abort(void) {
errno = EINVAL;
fprintf(stderr, "ERROR: %s.\n" "Invalid vector index.\n", strerror(errno));
errno = 0;
abort();
return 0;
}
#define vector(TYPE) struct vector_##TYPE {size_t length; size_t capacity; TYPE* array;}
#define vector_new(TYPE, CAPACITY) {.length = 0, .capacity = CAPACITY, .array = calloc(CAPACITY, sizeof(TYPE))} | {
"domain": "codereview.stackexchange",
"id": 44839,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, vectors, macros",
"url": null
} |
c, vectors, macros
#define vector_delete(VECTOR) \
do { \
VECTOR.length = 0; \
VECTOR.capacity = 0; \
free_sized(VECTOR.array, (VECTOR.length * sizeof(*(VECTOR.array)))); \
VECTOR.array = nullptr; \
} while (false)
#define vector_size(VECTOR) VECTOR.length
#define vector_at(VECTOR, INDEX) (VECTOR.length > INDEX) ? VECTOR.array[INDEX] : vector_abort()
#define vector_pop(VECTOR) if (VECTOR.length > 0) VECTOR.length--
#define vector_push(VECTOR, VALUE) \
do { \
if (VECTOR.length == VECTOR.capacity) { \
typeof(VECTOR.array) new_array = realloc(VECTOR.array, (VECTOR.capacity * 2 * sizeof(*(VECTOR.array)))); \
if (!new_array) break; \
VECTOR.capacity *= 2; \
VECTOR.array = new_array; \
} \
VECTOR.array[VECTOR.length] = VALUE; \
VECTOR.length++; \
} while (false)
#endif
main.c
#include "./vector.h"
#include <stdio.h> | {
"domain": "codereview.stackexchange",
"id": 44839,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, vectors, macros",
"url": null
} |
c, vectors, macros
#endif
main.c
#include "./vector.h"
#include <stdio.h>
int main(void) {
vector(int) v = {}; // or use = vector_new(type, capacity)
vector_push(v, 1);
vector_push(v, 2);
vector_push(v, 3);
for (size_t i = 0; i < vector_size(v); ++i) {
printf("Test Push %d\n", vector_at(v, i));
}
vector_pop(v);
for (size_t i = 0; i < vector_size(v); ++i) {
printf("Test Pop %d\n", vector_at(v, i));
}
vector_delete(v);
for (size_t i = 0; i < vector_size(v); ++i) {
printf("Test Delete %d\n", vector_at(v, i));
}
return EXIT_SUCCESS;
}
Polyfill
Here is a free_sized() polyfill if your implementation doesn't support it yet.
void free_sized(void* ptr, size_t /*size*/) {
free(ptr);
}
Compiler Flags
-Wall -Wextra -Werror -pedantic-errors -std=c2x
Answer: Improve macro safety
You seem to have hit the usual pitfalls of macros - remember these are text substitutions done by the C preprocessor, so we need to ensure that the the rules of precedence don't give an unexpected meaning to the expansion.
For example, consider vector_pop:
#define vector_pop(VECTOR) if (VECTOR.length > 0) VECTOR.length--
Since . binds very tightly and if can catch a following else, we really need extra parens and a do/while (0):
#define vector_pop(VECTOR) \
do { if ((VECTOR).length > 0) (VECTOR).length--; } while (false)
Similarly, vector_size should be defined to expand to ((VECTOR).length) rather than to the much less safe VECTOR.length.
Improve the "abort" function
Shouldn't vector_abort() be static? At present, it seems that we'll get a definition in each translation unit that includes the header, causing link-time errors.
This function has an unreachable return statement. The assignment of errno = 0 doesn't have any discernable value - unless you have a signal handler that uses it, which seems a poor choice.
I'd write:
static _Noreturn void vector_abort(void)
{
fprintf(stderr, "ERROR: %s.\nInvalid vector index.\n", strerror(EINVAL));
abort();
} | {
"domain": "codereview.stackexchange",
"id": 44839,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, vectors, macros",
"url": null
} |
c, vectors, macros
Handle allocation failures correctly
vector_push provides no feedback when realloc() fails - the calling program is required to test the vector size before and after (this checking is conspicuously absent from the demo program, suggesting others will forget this too).
vector_new violates the invariant (that array[capacity-1] is valid) whenever calloc() fails. | {
"domain": "codereview.stackexchange",
"id": 44839,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c, vectors, macros",
"url": null
} |
vba, excel
Title: Evaluating formulas greater than 255 characters
Question: Recently I was receiving Error 2015 when trying to use Application.Evaluate, then I realized it was because my formula was greater than 255 characters. As a workaround, I came up with this UDF:
Function AdvancedEvaluate(eformula As String)
ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Formula = eformula
AdvancedEvaluate = ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").Value
ThisWorkbook.Worksheets("Scripting Worksheet").Range("A1").ClearContents
End Function
Which I use in place of all of my Application.Evaluate. However, I'm not satisfied with this solution... is my solution sufficient, or is there a better way to evaluate a formula of greater than 255 characters?
Answer: The function is implicitly public, takes an implicitly ByRef parameter that has no reason to not be passed ByVal, and returns an implicit Variant that should be explicit.
It's also side-effecting, which makes it unusable as an actual UDF.
ThisWorkbook.Worksheets("Scripting Worksheet") suggests the procedure is using a purposely-made bogus (hidden?) sheet just for that. So why does that sheet need to be dereferenced 3 times in the same scope? Give it a meaningful code name, and use it!
Public Function AdvancedEvaluate(ByVal expression As String) As Variant
With ScriptingSheet.Range("A1")
.Formula = expression
AdvancedEvaluate = .Value
.ClearContents
End With
End Function | {
"domain": "codereview.stackexchange",
"id": 44840,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel",
"url": null
} |
vba, excel
Now, that's the exact same logic, just more explicit and unnoticeably more efficient in the handling of object references.
To the extent that the idea is to somehow get Excel's calc engine to do the work, other than getting the Excel devs to lift the 255-char limitation in the object model, I think that's as good as it's going to get. It's not a UDF though: in Excel a User-Defined Function refers to a function that can be invoked from a cell - but this function will only ever return an error value to Excel; VBA code can merrily consume it though. | {
"domain": "codereview.stackexchange",
"id": 44840,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "vba, excel",
"url": null
} |
java, benchmarking
Title: Performance testing app in Java (Release 2.0)
Question: I have greatly improved and expanded my my performance testing app
New features include:
Builder for type safe creation of a Measurer instances
Performs 10 runs of each procedure (default), or any number of runs a user chooses, and then calculates the average for each procedure
Provides more comprehensive comparison statistics. Minimum and maximum measurements are also output
The averages can be compared against the fastest procedure too (by default, they are still compared against the worst performer). Enum ReferencedProcedure is introduced for convenient customizing
measurer.compare() now accepts any number of arguments equal to or greater than two
Provides two types of defenses against the "warm-up" issue. A user may choose from the following WarmUpDefender constants: RESTLESS_POINTER (default) and WARM_UP_RUNS_DISCARDER. NONE is also available.
Tweaks:
NanoProcessingResult class – gone. nanoProcessor.process() now returns a regular array (I mapped it to an array anyway)
ComparisonLoggingIntermediary – gone. What with varargs, it no longer serves the app well
Qualification:
I tried to "separate my concerns" and add SLF4J support. The logging doesn't work, though! But let's imagine it does. I know this site is not about fixing code that doesn't work so I don't ask you anything on that. I guess the code itself is fine, but my configuration is faulty (I hate configurations!). If so, it's a client's job to configure it anyway (not my problem if they can't configure their logging) | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
Client code now may look like this. The example uses anonymous children, but MeasuredProcedureFactory providing some "oven-ready" procedures is still available
Measurer measurer = Measurer.builder()
.timesRun(15)
.warmUpDefender(WarmUpDefender.WARM_UP_RUNS_DISCARDER)
.compareAgainst(ReferencedProcedure.BEST)
.build();
measurer.compare(
new MeasuredProcedure("String.format()") {
@Override
void run() {
var res = String.format("%s%s%s%s%s%s%s%s%s%s", "str1", "str2", "str3", "str4", "str5",
"str6", "str7", "str8", "str9", "str10");
}
},
new MeasuredProcedure("plus concatenation") {
@Override
void run() {
var res = "str1" + "str2" + "str3" + "str4" + "str5" +
"str6" + "str7" + "str8" + "str9" + "str10";
}
},
new MeasuredProcedure("StringBuilder") {
@Override
void run() {
var res = new StringBuilder()
.append("str1").append("str2").append("str3")
.append("str4").append("str5").append("str6")
.append("str7").append("str8").append("str9")
.append("str10").toString();
}
}
);
Here's my new code:
abstract class MeasuredProcedure {
protected final String name;
private Collection<Long> measurements;
protected MeasuredProcedure(String name) {
this.name = name;
}
abstract void run();
public void setMeasurementsCollection(Collection<Long> measurements) {
this.measurements = measurements;
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
public void addMeasurement(long singleMeasurement) {
if (measurements == null) {
measurements = new ArrayList<>();
}
measurements.add(singleMeasurement);
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
public long getAverageMeasurement() {
ensureValidity();
return (long) measurements.stream()
.mapToLong(m -> m)
.average()
.getAsDouble();
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
public long getMinMeasurement() {
ensureValidity();
return measurements.stream()
.mapToLong(m -> m)
.min()
.getAsLong();
}
@SuppressWarnings("OptionalGetWithoutIsPresent")
public long getMaxMeasurement() {
ensureValidity();
return measurements.stream()
.mapToLong(m -> m)
.max()
.getAsLong();
}
private void ensureValidity() {
if (measurements == null) {
throw new IllegalStateException("The measurements Collection is null");
} else if (measurements.isEmpty()) {
throw new IllegalStateException("The measurements Collection is empty");
}
}
@Override
public String toString() {
return name;
}
}
@Slf4j
public class Measurer {
private final int timesRun;
private final ReferencedProcedure referencedProcedure;
private final WarmUpDefender warmUpDefender;
public Measurer() {
this.timesRun = Defaults.TIMES_RUN;
this.referencedProcedure = Defaults.REFERENCED_PROCEDURE;
this.warmUpDefender = Defaults.WARM_UP_DEFENDER;
}
private Measurer(int timesRun, ReferencedProcedure referencedProcedure,
WarmUpDefender warmUpDefender) {
this.timesRun = timesRun;
this.referencedProcedure = referencedProcedure;
this.warmUpDefender = warmUpDefender;
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
public static Builder builder() {
return new Builder();
}
public static class Builder {
private int timesRun = Defaults.TIMES_RUN;
private ReferencedProcedure compareAgainst = Defaults.REFERENCED_PROCEDURE;
private WarmUpDefender warmUpDefender = Defaults.WARM_UP_DEFENDER;
public Builder timesRun(int timesRun) {
if (timesRun < 1) {
throw Defaults.illegalTimesRunException(timesRun);
}
this.timesRun = timesRun;
return this;
}
public Builder compareAgainst(ReferencedProcedure compareAgainst) {
this.compareAgainst = compareAgainst;
return this;
}
public Builder warmUpDefender(WarmUpDefender warmUpDefender) {
this.warmUpDefender = warmUpDefender;
return this;
}
public Measurer build() {
return new Measurer(timesRun, compareAgainst,
warmUpDefender);
}
}
public long measureAverage(MeasuredProcedure measuredProcedure) {
measuredProcedure.setMeasurementsCollection(Defaults.measurementsCollection(timesRun));
warmUpDefender.performMeasurementsWithDefenses(new MeasurementInputs(List.of(measuredProcedure), timesRun));
log.info(averageMeasurementLog(measuredProcedure));
return measuredProcedure.getAverageMeasurement();
}
private static long measureOnce(MeasuredProcedure measuredProcedure) {
long start = System.nanoTime();
measuredProcedure.run();
long finish = System.nanoTime();
return finish - start;
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
public long compare(MeasuredProcedure firstMeasuredProcedure, MeasuredProcedure secondMeasuredProcedure,
MeasuredProcedure... otherMeasuredProcedures) {
List<MeasuredProcedure> allMeasuredProcedures =
composeComparedProcedures(firstMeasuredProcedure, secondMeasuredProcedure, otherMeasuredProcedures);
warmUpDefender.performMeasurementsWithDefenses(new MeasurementInputs(allMeasuredProcedures, timesRun));
log.info(comparisonStatsLog(allMeasuredProcedures));
return getSpreadOfAverages(allMeasuredProcedures);
}
private List<MeasuredProcedure> composeComparedProcedures(MeasuredProcedure firstMeasuredProcedure,
MeasuredProcedure secondMeasuredProcedure,
MeasuredProcedure[] otherMeasuredProcedures) {
List<MeasuredProcedure> allMeasuredProcedures =
new ArrayList<>(2 + otherMeasuredProcedures.length);
allMeasuredProcedures.addAll(List.of(
firstMeasuredProcedure, secondMeasuredProcedure
));
allMeasuredProcedures.addAll(Arrays.asList(otherMeasuredProcedures));
return allMeasuredProcedures;
}
private long getSpreadOfAverages(List<MeasuredProcedure> allMeasuredProcedures) {
long max = getMaxAverage(new MeasurementInputs(allMeasuredProcedures, timesRun));
long min = getMinAverage(new MeasurementInputs(allMeasuredProcedures, timesRun));
return max - min;
}
private static long getMaxAverage(MeasurementInputs inputs) {
List<MeasuredProcedure> measuredProcedures = inputs.measuredProcedures();
return measuredProcedures.stream()
.mapToLong(MeasuredProcedure::getAverageMeasurement)
.max().orElseThrow(() -> Defaults.illegalTimesRunException(inputs.timesRun()));
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
private static long getMinAverage(MeasurementInputs inputs) {
List<MeasuredProcedure> measuredProcedures = inputs.measuredProcedures();
return measuredProcedures.stream()
.mapToLong(MeasuredProcedure::getAverageMeasurement)
.min().orElseThrow(() -> Defaults.illegalTimesRunException(inputs.timesRun()));
}
private String averageMeasurementLog(MeasuredProcedure measuredProcedure) {
String renderedAverage = renderReadable(measuredProcedure.getAverageMeasurement());
String onAverageStringAsNecessary = (timesRun == 1) ? "" : "On average,";
String runSuffixAsNecessary = (timesRun == 1) ? "" : "s";
return new StringBuilder()
.append(onAverageStringAsNecessary).append(measuredProcedure)
.append(" took ").append(renderedAverage)
.append(" across ").append(timesRun)
.append(" run").append(runSuffixAsNecessary)
.toString();
}
private String comparisonStatsLog(List<MeasuredProcedure> measuredProcedures) {
measuredProcedures.sort((p1, p2) -> Math.toIntExact(p1.getAverageMeasurement() - p2.getAverageMeasurement()));
StringBuilder sb = new StringBuilder();
appendHeading(sb);
appendStats(sb, measuredProcedures);
return sb.toString();
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
private void appendHeading(StringBuilder stringBuilder) {
String tabLeader = Defaults.TAB_LEADER;
String titlePadding = Defaults.TITLE_PADDING;
String runSuffixAsNecessary = (timesRun == 1) ? "" : "s";
stringBuilder
.append("\n").append(titlePadding).append("Comparison statistics (").append(timesRun)
.append(" run").append(runSuffixAsNecessary).append(")").append(titlePadding).append("\n\n")
.append("PROCEDURE").append(tabLeader)
.append("AVERAGE").append(tabLeader)
.append("PERCENTAGE OF ").append(referencedProcedure).append(tabLeader)
.append("MIN").append(tabLeader)
.append("MAX").append("\n");
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
private void appendStats(StringBuilder stringBuilder, List<MeasuredProcedure> measuredProcedures) {
String tabLeader = Defaults.TAB_LEADER;
long referencedAverage = referencedProcedure.getReference(new MeasurementInputs(measuredProcedures, timesRun));
MeasuredProcedure currentProcedure;
long bestResult = measuredProcedures.get(0).getAverageMeasurement();
long currentAverage, averageAsPercentageOfReference;
String renderedCurrentAverage, renderedMarginToBestPerformerAsNecessary, renderedMin, renderedMax;
for (int i = 0; i < measuredProcedures.size(); i++) {
currentProcedure = measuredProcedures.get(i);
currentAverage = currentProcedure.getAverageMeasurement();
renderedCurrentAverage = renderReadable(currentAverage);
averageAsPercentageOfReference = (long) ((double) currentAverage / referencedAverage * 100);
renderedMarginToBestPerformerAsNecessary = (i == 0) ? "" :
" (+ " + renderReadable(currentAverage - bestResult) + ")";
renderedMin = renderReadable(currentProcedure.getMinMeasurement());
renderedMax = renderReadable(currentProcedure.getMaxMeasurement());
stringBuilder.append(i + 1).append(". ").append(currentProcedure).append(tabLeader)
.append(renderedCurrentAverage).append(renderedMarginToBestPerformerAsNecessary).append(tabLeader)
.append(averageAsPercentageOfReference).append("%").append(tabLeader)
.append(renderedMin).append(tabLeader)
.append(renderedMax).append("\n");
}
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
private static String renderReadable(long nanos) {
TimeUnit[] timeUnits = new NanoProcessor().process(nanos);
var joiner = new StringJoiner(", ");
for (TimeUnit unit : timeUnits) {
if (unit.value() == 0) {
continue;
}
String unitSuffixAsNecessary = (unit.value() % 10 == 1) ? "" : "s";
joiner.add(unit.value() + " " + unit.name() + unitSuffixAsNecessary);
}
return joiner.toString();
}
private static class Defaults {
static final int TIMES_RUN = 10;
static final ReferencedProcedure REFERENCED_PROCEDURE = ReferencedProcedure.WORST;
static final WarmUpDefender WARM_UP_DEFENDER = WarmUpDefender.RESTLESS_POINTER;
static final int NUM_OF_WARM_UP_RUNS = 2;
static final String TAB_LEADER = " " + "-".repeat(10) + " ";
static final String TITLE_PADDING = ":".repeat(20);
static RuntimeException illegalTimesRunException(int illegalTimesRun) {
return new IllegalArgumentException
("A procedure cannot be run less than one time. Your value: " + illegalTimesRun);
}
static Collection<Long> measurementsCollection(int initialCapacity) {
return new ArrayList<>(initialCapacity);
}
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
public enum WarmUpDefender {
RESTLESS_POINTER {
void performMeasurementsWithDefenses(MeasurementInputs inputs) {
List<MeasuredProcedure> allMeasuredProcedures = inputs.measuredProcedures();
MeasuredProcedure currentMeasuredProcedure;
int procedurePointer = 0;
for (int i = 0; i < inputs.timesRun() * allMeasuredProcedures.size(); i++) {
if (procedurePointer == allMeasuredProcedures.size()) {
procedurePointer = 0;
}
currentMeasuredProcedure = allMeasuredProcedures.get(procedurePointer);
long singleMeasurement = measureOnce(currentMeasuredProcedure);
currentMeasuredProcedure.addMeasurement(singleMeasurement);
procedurePointer++;
}
}
}, WARM_UP_RUNS_DISCARDER {
void performMeasurementsWithDefenses(MeasurementInputs inputs) {
List<MeasuredProcedure> allMeasuredProcedures = inputs.measuredProcedures();
warmUp(allMeasuredProcedures);
for (MeasuredProcedure measuredProcedure : allMeasuredProcedures) {
for (int i = 0; i < inputs.timesRun(); i++) {
long singleMeasurement = measureOnce(measuredProcedure);
measuredProcedure.addMeasurement(singleMeasurement);
}
}
}
private void warmUp(List<MeasuredProcedure> allMeasuredProcedures) {
for (int i = 0; i < numOfWarmUpRuns; i++) {
for (MeasuredProcedure measuredProcedure: allMeasuredProcedures) {
measureOnce(measuredProcedure);
}
}
}
}, NONE {
void performMeasurementsWithDefenses(MeasurementInputs inputs) { | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
}, NONE {
void performMeasurementsWithDefenses(MeasurementInputs inputs) {
List<MeasuredProcedure> allMeasuredProcedures = inputs.measuredProcedures();
MeasuredProcedure currentMeasuredProcedure;
for (MeasuredProcedure allMeasuredProcedure : allMeasuredProcedures) {
currentMeasuredProcedure = allMeasuredProcedure;
for (int ii = 0; ii < inputs.timesRun(); ii++) {
long singleMeasurement = measureOnce(currentMeasuredProcedure);
currentMeasuredProcedure.addMeasurement(singleMeasurement);
}
} | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
}
};
private static final int numOfWarmUpRuns = Defaults.NUM_OF_WARM_UP_RUNS;
abstract void performMeasurementsWithDefenses(MeasurementInputs inputs);
}
public enum ReferencedProcedure {
BEST {
long getReference(MeasurementInputs inputs) {
return getMinAverage(inputs);
}
}, WORST {
long getReference(MeasurementInputs inputs) {
return getMaxAverage(inputs);
}
};
abstract long getReference(MeasurementInputs inputs);
}
private record MeasurementInputs(List<MeasuredProcedure> measuredProcedures, int timesRun) {}
static class NanoProcessor {
TimeUnit[] process(long nanos) {
long minutes = extractLooseMinutes(nanos);
long seconds = extractLooseSeconds(nanos);
long milliseconds = extractLooseMilliseconds(nanos);
long nanoseconds = extractLooseNanoseconds(nanos);
return new TimeUnit[]{
new TimeUnit(TimeUnitName.MINUTE, minutes),
new TimeUnit(TimeUnitName.SECOND, seconds),
new TimeUnit(TimeUnitName.MILLISECOND, milliseconds),
new TimeUnit(TimeUnitName.NANOSECOND, nanoseconds)
};
}
private long extractLooseMinutes(long nanos) {
return nanos / 60_000_000_000L;
}
private long extractLooseSeconds(long nanos) {
return nanos % 60_000_000_000L / 1_000_000_000L;
}
private long extractLooseMilliseconds(long nanos) {
return nanos % 1_000_000_000L / 1_000_000L;
}
private long extractLooseNanoseconds(long nanos) {
return nanos % 1_000_000L;
}
record TimeUnit(TimeUnitName name, long value) {
enum TimeUnitName {
MINUTE, SECOND, MILLISECOND, NANOSECOND; | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
@Override
public String toString() {
return name().toLowerCase();
}
}
}
}
}
Some questions I have in mind:
I put the defaults in a nested static "container" class called Defaults. Is it good or bad design?
I removed a couple of unnecessary classes, but added another, MeasurementInputs. Bob Martin said the less you pass, the better so I figured I'll pass some container object instead of two parameters. (and I also read somewhere that if you pass the same collection of arguments over and over again, it may be the sign that you should encapsulate it) At any rate, you have to admit, it's awkward. Besides, it's mainly because I use the non-static timesRun field. What do you recommend?
Can I make my comparison output prettier? I guess I should make tab leaders dynamic in length somehow, is that correct?
The number of "warm-up" runs is hard-coded. It's a shame enum constants can't have their own fields and methods, not shared by other constants. I could do something like this
public enum WarmUpDefender {
WARM_UP_RUNS_DISCARDER {
private int numOfWarmUpRuns = Defaults.WARM_UP_DEFENDER;
public WarmUpDefender withNumOfWarmUpRuns(int numOfWarmUpRuns) {
this.numOfWarmUpRuns = numOfWarmUpRuns;
return this;
}
.warmUpDefender(WarmUpDefender.WARM_UP_RUNS_DISCARDER.withNumOfWarmUpRuns(10)) // doesn't work ((
What do you suggest instead?
If you run the test I pasted above, you get output that is kind of weird
::::::::::::::::::::Comparison statistics (15 runs):::::::::::::::::::: | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
::::::::::::::::::::Comparison statistics (15 runs)::::::::::::::::::::
PROCEDURE ---------- AVERAGE ---------- PERCENTAGE OF BEST ---------- MIN ---------- MAX
1. plus concatenation ---------- 153 nanoseconds ---------- 100% ---------- 100 nanoseconds ---------- 300 nanoseconds
2. StringBuilder ---------- 726 nanoseconds (+573 nanoseconds) ---------- 474% ---------- 600 nanoseconds ---------- 1500 nanoseconds
3. String.format() ---------- 41573 nanoseconds (+41420 nanoseconds) ---------- 27171% ---------- 15900 nanoseconds ---------- 81100 nanoseconds
It can't be true, can it? Plus concatenation must be the slowest, mustn't it? Which brings the question: did the JVM just "optimize my code into nothingness"? If so, why didn't it optimize into nothingness the String.format() code?
You may also need some way to safely "sink" results in way that guarantees that a result will be computed, to prevent the JVM from optimizing code into nothingness when it detects that the result is not used.
–Harold, the original post
Or was it something else?
What about all those "asNecessary" strings? Is there a better way to handle that?
UPD: As I thought, the logging issue had to do with my configuration, not the code. I fixed it adding this dependency, for those interested (thanks, ChatGPT!)
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.15.2</version>
</dependency>
Answer: Questions, as far as I chose to answer them
I put the defaults in a nested static "container" class called Defaults. Is it good or bad design?
I don't mind it, but I question why there are also "utility functions" on it.
Can I make my comparison output prettier? I guess I should make tab leaders dynamic in length somehow, is that correct? | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
There are some libraries to print text-mode tables, which can handle flexible-width columns. Fixed-width columns are easy but wouldn't deal gracefully with the variable-length benchmark names. Well, it's not as if flexible-width columns are difficult either.
The number of "warm-up" runs is hard-coded. It's a shame enum constants can't have their own fields and methods, not shared by other constants.
.warmUpDefender(WarmUpDefender.WARM_UP_RUNS_DISCARDER.withNumOfWarmUpRuns(10)) // doesn't work
What do you suggest instead?
Instead of an enum, you could use a class with several static factory functions. Then you could write:
WarmUpDefender.warmUpRunsDiscarder().withNumOfWarmUpRuns(10)
It can't be true, can it? Plus concatenation must be the slowest, mustn't it? Which brings the question: did the JVM just "optimize my code into nothingness"? If so, why didn't it optimize into nothingness the String.format() code?
There's a simpler issue.
The code was this:
var res = "str1" + "str2" + "str3" + "str4" + "str5" +
"str6" + "str7" + "str8" + "str9" + "str10"; | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
Given that the strings being "plussed together" (this strange terminology is just to avoid all doubt about how the strings are concatenated, which may matter for all I know, at least there is no a-priori reason to assume that all ways to concatenate strings are equivalent) are literal strings, there's nothing standing in the way of the java compiler itself (not even the JVM) doing the concatenation, which indeed is what happens. Note that there are various other (more powerful) string concatenation optimizations done by various different versions of the java compiler. That may get in the way of what you intended to measure, but that depends on what your intentions are, it's not inherently wrong to measure the performance of the above code, and then discover that something interesting happened.
Anyway, there is no actual concatenation happening for you to measure there, only at most loading a string constant from the constant pool and then immediately discarding it. That, in turn, may be optimized out by the JVM - which I did not confirm because getting an assembly listing of JIT compiled methods takes some strange set-up that I haven't done. If you wanted to measure the performance of an actual concatenation actually happening, you'll have to do more effort to guarantee that it actually happens (this "fighting the compiler to get it to actually produce the code that we wanted to benchmark" nonsense is the main reason why I prefer benchmarking assembly code instead of higher level code, but of course in this context you don't have that luxury). This specific thing isn't the frameworks fault, it couldn't have done anything to prevent it.
In general you probably still need a way to safely ignore results to prevent unwanted optimizations, though that alone would not fix this particular problem. | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
java, benchmarking
Warm-up
There is some warm-up protection now, but I think it's very little. I would not be confident that the right thing is being measured, nor that the CPU has come up to speed yet.
Danger zone
"Timing" code works well, and has a reasonable interpretation, for macroscopic chunks of code. At some point when scaling the code down, there comes a point where it no longer makes sense to talk about code "taking time" - latency and throughput will separate and go each their own way (with latency acting mostly the way you'd expect, but throughput becomes non-additive: to get the combined throughput of two snippets, you would have to reason about µops and execution ports, not their individual throughputs), and it becomes very important exactly how the code is structured, not just what's in it.
"plus concatenation", since it accidentally ended up doing essentially nothing (and doesn't have a well-defined latency), is far into this danger zone where code does not "take time" - it has a cost, and that cost eventually manifests in taking time, but that cost is not itself expressible as time. That does not mean that it's wrong to try to time it, you still get something that you can draw conclusions from (though the conclusion this time is probably "we accidentally benchmarked the wrong thing due to compiler optimizations"), but paradoxically you cannot get "the time it takes" from it. | {
"domain": "codereview.stackexchange",
"id": 44841,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, benchmarking",
"url": null
} |
python, exception
Title: User-defined Exceptions for Stack implementation
Question: I am learning about user-defined exceptions in python and I have tried to incorporate them in a basic python implementation of a stack. Objects of Stack class support push, pop and top operations. I have defined the following exceptions:
StackEmptyError: Raise an exception when pop/top operation is performed on an empty stack.
InvalidStackOpError: Raise an exception when an invalid operation is attempted
Here is the code
class StackEmptyError(Exception):
"Raised when pop/top operation is performed on empty stack"
pass
class InvalidStackOpError(Exception):
"Raised when an invalid stack operation is attempted"
pass
class stack:
def __init__(self):
self.s = list()
def push(self, x):
self.s.append(x)
def pop(self):
if not len(self.s):
raise StackEmptyError
popped = self.s.pop()
return popped
def top(self):
if not len(self.s):
raise StackEmptyError
return self.s[-1]
def perform_stackops(operations, values):
st = stack()
val_idx = 0
for op in operations:
if op == "push":
st.push(values[val_idx])
val_idx += 1
elif op == "pop":
print(f"Popped Element - {st.pop()}")
elif op == "top":
print(f"Top Element - {st.top()}")
else:
raise InvalidStackOpError(f"Operation {op} is invalid")
operations = ["push", "push", "pop", "pop", "push", "top"]
values = [20, 10, 30]
perform_stackops(operations, values)
Is this the right way to define and raise user-defined exceptions in python? Can I improve this even further?
Answer: "Is this the right way in Python?"
Is this the right way to define and raise user-defined exceptions in python? | {
"domain": "codereview.stackexchange",
"id": 44842,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, exception",
"url": null
} |
python, exception
Is this the right way to define and raise user-defined exceptions in python?
The exception definitions are technically correct.
when writing docstrings, it's recommended to enclose in """...""" instead of "...".
It would be good to add some tests that exercise the exceptions, because that's how you can really know that they are doing their job.
For more resources on using exceptions correctly I recommend:
The Python docs on the subject: 8. Errors and Exceptions (easy enough to find with web search for "python exceptions")
The Python style guide: PEP-8
Stack implementation
Class names should be PascalCase, so Stack would be more appropriate.
The attribute s is too short to be descriptive, stack would be better.
When initializing an empty list [] is recommended instead of list().
Instead of:
if not len(self.s):
The recommended writing style is simply:
if not self.s:
In this code:
popped = self.s.pop()
return popped
I don't think the popped variable adds much value, I would simply inline it (return self.s.pop()).
Write unit tests
It would be good to write unit tests that verify the stack works correctly, including the raising of exceptions.
Drop perform_stackops and InvalidStackOpError
I don't see much purpose for these elements.
I think they just add unnecessary complexity in the program. | {
"domain": "codereview.stackexchange",
"id": 44842,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, exception",
"url": null
} |
python, object-oriented
Title: A Python class for handling mortality (and lapse) probabilities
Question: I'm developing a model in Python which produces IFRS and SII balance sheets for a hypothetical life insurance company. To value the hypothetical company's insurance liabilities, I need to project the probability of a policy being redeemed in a given year.
Policies may be redeemed in two possible ways:
The policy holder dies
The policy lapses (the policy-holder voluntarily chooses to redeem it)
The function relied upon most heavily in this module is prob_death() which gives the probability that a policy holder dies in a given year. Since they must die eventually, the sum of these probabilities will be 1.0.
The csv file 'mortality_data.csv' contains probabilities that a person who is currently alive and aged x will survive to age x+1.
This is the code:
# Import external libraries
import pandas as pd
import numpy as np
class Mortality:
def __init__(self, lapse_rate=0.0, mortality_stress=None):
if type(lapse_rate) == list:
self.lapse_rate = np.array(lapse_rate)
else:
self.lapse_rate = lapse_rate
self.mortality_stress = mortality_stress
# Read in mortality data and set age as index
self.mort_data = pd.read_csv('inputs/mortality_data.csv', index_col='Age')
# Apply mortality stress if applicable
self.mort_data = apply_stress(self.mort_data, mortality_stress)
def q(self, x):
return self.mort_data.loc[x, 'Death Prob']
def prob_in_force(self):
qx_curve = model.mort_data['Death Prob'].to_list()
df_qx = pd.DataFrame([[0] + qx_curve[i:] + [0] * i for i in range(0, len(qx_curve))],
index=[x for x in range(17, 121)])
if type(self.lapse_rate) == np.ndarray:
lapse_rate = np.insert(self.lapse_rate, 0, 0.0)[:-1]
else:
lapse_rate = self.lapse_rate | {
"domain": "codereview.stackexchange",
"id": 44843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
decr_probs = (df_qx + lapse_rate - df_qx * lapse_rate).clip(0, 1)
cond_if_probs = (1 - decr_probs)
if_probs = cond_if_probs.cumprod(axis=1)
return if_probs
def prob_death(self):
# Get the probabilities of lives of each possible age being inforce at each point in time
df_prob_in_force = self.prob_in_force()
# Get the qx values for all possible ages of interest
qx_curve = (self.q([x for x in range(17, 121)])).to_list()
# Construct a DataFrame whose (i, j)th entry is q(i+j)
# TODO: Refactor
df_qx = pd.DataFrame([qx_curve[i:] + [0] * (i+1) for i in range(0, len(qx_curve))], index=[x for x in range(17, 121)])
decr_probs = (df_qx + self.lapse_rate - df_qx * self.lapse_rate).clip(0, 1)
# Multiply the probability inforce at each time by the probability of dying during that year
df_prob_death = decr_probs * df_prob_in_force
# Increment columns by 1 and return the result
df_prob_death.columns += 1
return df_prob_death
def simulate_mortality(self, policy_data):
# Simulate a random number between 0 and 1 for each in-force policy
np_test_stats = np.random.uniform(size=policy_data.shape[0])
# Get the qx value for each policy
qx = self.q(policy_data['Age'])
# Flag each policy as still in-force if and only if the simulated random value is greater than the qx
# probability for that policy
np_pol_if_flags = (np_test_stats > qx).to_numpy()
# Return only the policies from the inputted policy data whose in-force flag is true
return policy_data[np_pol_if_flags]
def apply_stress(base_mortality_curve, stress):
if type(stress) == str:
# Read in the multiplicative stress factors for each stress
mort_stress_factors = pd.read_csv('inputs/mortality_stress_factors.csv', index_col='Stress') | {
"domain": "codereview.stackexchange",
"id": 44843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
# Multiply the original qx probabilities by the multiplicative stress factor for the chosen stress
base_mortality_curve['Death Prob'] *= mort_stress_factors.loc[stress, 'Factor']
if type(stress) == float:
base_mortality_curve['Death Prob'] *= 1 + stress
# Subject all qx probabilities to a cap of 1 and a floor of 0 and return the result
return base_mortality_curve.clip(0, 1)
if __name__ == '__main__':
model = Mortality([0.08] * 5 + [0.01] * 100)
foo = model.prob_death()
print(foo)
To run this code without need for the .csv file, simply replace the line
self.mort_data = pd.read_csv('inputs/mortality_data.csv', index_col='Age')
with
self.mort_data = pd.DataFrame([0.0006, 0.000594, 0.000587, 0.000582, 0.000577, 0.000572, 0.000569, 0.000567, 0.000566, 0.000567, 0.00057, 0.000574, 0.00058, 0.00059, 0.000602, 0.000617, 0.000636, 0.00066, 0.000689, 0.000724, 0.000765, 0.000813, 0.00087, 0.000937, 0.001014, 0.001104, 0.001208, 0.001327, 0.001465, 0.001622, 0.001802, 0.002008, 0.002241, 0.002508, 0.002809, 0.003152, 0.003539, 0.003976, 0.004469, 0.005025, 0.00565, 0.006352, 0.00714, 0.008022, 0.009009, 0.010112, 0.011344, 0.012716, 0.014243, 0.01594, 0.017824, 0.019913, 0.022226, 0.024783, 0.027606, 0.030718, 0.034144, 0.037911, 0.042046, 0.046578, 0.051538, 0.056956, 0.062867, 0.069303, 0.0763, 0.083893, 0.092117, 0.101007, 0.1106, 0.120929, 0.132028, 0.143929, 0.15666, 0.170247, 0.184714, 0.200079, 0.216354, 0.233548, 0.251662, 0.270688, 0.290613, 0.311414, 0.333058, 0.355505, 0.378702, 0.402588, 0.42709, 0.452127, 0.477608, 0.503432, 0.529493, 0.555674, 0.581857, 0.607918, 0.633731, 0.659171, 0.684114, 0.708442, 0.732042, 0.754809, 0.776648, 0.797477, 0.817225, 1.0], index=range(17, 121), columns=['Death Prob']) | {
"domain": "codereview.stackexchange",
"id": 44843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
python, object-oriented
Answer: The function names are not always very intuitive unless perhaps one works in the same field as you. But since they are small it could make sense to gather the comments into one single docstring declaration at the top, so that the purpose is explained in one simple paragraph.
There seems to be a problem of structure. At first glance, the indentation suggests that the function apply_stress does not belong here. But since you are calling that function within your class (in your __init__ method) it really is part of it and needs to be embedded as well. It could qualify as static method.
The init does too many things. It should just "set up" the class but not run anything that is not strictly necessary for its instantiation. It should be possible to pass some arguments, such as the data source before the class goes on to perform the heavy work. Hardcoding file names is not a good idea. In its current form, the class cannot be reused easily without making changes to its code.
The handling of variables is problematic. Expecting a variable in different possible types (str, float) suggests that there is a lack of control (or quality control) on the data. This is quite dangerous and will likely cause runtime bugs if the variable type is allowed to change along the process.
The reasons are obvious. Depending on variable type, the applicable functions and methods will be different. Normalize the data so that it is delivered to your functions in a predictable and consistent format.
Type hinting would help here. Explicitly declaring the expected type will serve as a visual guide, and keep you focused on providing what the function expects from you. | {
"domain": "codereview.stackexchange",
"id": 44843,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, object-oriented",
"url": null
} |
c++, julia
Title: Write Julia struct to a C++ struct
Question: For the following Julia code:
mutable struct MutationWeights
mutate_constant::Float64
optimize::Float64
end
const mutations = [fieldnames(MutationWeights)...]
@generated function MutationWeights(;
mutate_constant=0.048,
optimize=0.0,
)
return :(MutationWeights($(mutations...)))
end
"""Convert MutationWeights to a vector."""
@generated function Base.convert(
::Type{Vector}, weightings::MutationWeights
)::Vector{Float64}
fields = [:(weightings.$(mut)) for mut in mutations]
return :([$(fields...)])
end
I wrote the following C++ alternative:
struct MutationWeights {
float mutate_constant = 0.048;
float optimize = 0.0;
};
const auto mutations = std::vector<std::string>{"mutate_constant", "optimize"};
template <typename... Args>
MutationWeights createMutationWeights(Args&&... args) {
return {std::forward<Args>(args)...};
}
std::vector<double> convertMutationWeightsToVector(const MutationWeights& weightings) {
return {weightings.mutate_constant,
weightings.optimize};
}
Is this the most sensible way of doing it, or would you suggest something different?
Answer: Precision
float is usually a 32-bit floating point type. Perhaps you meant double? With C++23, you can use std::float64_t.
Aggregates
There is aggregate initialization that removes the need for createMutationWeights. Note that if narrowing conversion should be allowed, then createMutationWeights does not help with it.
(Implicit) conversion functions
If the conversion into std::vector<double> is often needed, I would implement a conversion function and make it explicit (will require a cast like static_cast to be used) if needed.
struct MutationWeights {
float mutate_constant = 0.048;
float optimize = 0.0;
operator std::vector<double>() {
return { mutate_constant, optimize };
}
}; | {
"domain": "codereview.stackexchange",
"id": 44844,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, julia",
"url": null
} |
c++, julia
operator std::vector<double>() {
return { mutate_constant, optimize };
}
};
Reconsider the interface
I would recommend returning std::span<float> or even std::span<float, 2> (i.e. statically sized). One could also try std::array<float, 2> to avoid some lifetime issues. | {
"domain": "codereview.stackexchange",
"id": 44844,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, julia",
"url": null
} |
c#, beginner
Title: Write a method which computes the first twenty Fibonacci numbers
Question: It's a task from a C#-course I'm currently taking.
The task is to write a method, which returns the first twenty Fibonacci-numbers.
I have done it the following way.
using System;
namespace CrashCourse
{
public class Fibonacci
{
// ... The actual method
public static List<int> GetNumbers() {
var numbs = new List<int> { 1, 1 }; // Provided. Not by myself.
for (var i = 2; i < 20; i++) {
var prev2 = numbs[i - 2];
var prev1 = numbs[i - 1];
numbs.Add(prev1 + prev2);
}
return numbs;
}
}
}
// Usage
var numbs = Fibonacci.GetNumbers();
foreach(var numb in numbs) {
Console.WriteLine(numb);
}
What's your opinion about my coding concerning naming, style and algorithm?
What should I do differently and why?
Answer: Welcome to CR.
The Good: Your indentation and spacing is decent enough. You separate the tasks of gathering the numbers and displaying the numbers into 2 different methods.
The Bad: The first comment // ... The actual method is utterly useless. The method GetNumbers() would be better suited to be named GetFirst20Numbers() as it is hardcoded to do just that.
In C#, the convention is to put the opening brace on a new line.
While your solution, most likely for homework or training, is very specific, I would suggest it is too specific. The more flexible and reusable solution would be to create a method that produces Fibonacci numbers, and let a calling method determine how many that should be. This could be done 1 of 2 ways: one would be to pass in an integer of the desired count, e.g. GetNumbers(20). The other would be to use an enumeration to produce the next Fibonacci number in a sequence. Each subsequent call would return 1 value. | {
"domain": "codereview.stackexchange",
"id": 44845,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner",
"url": null
} |
performance, bash, checksum
Title: Generate a checksum for this input
Question: I am inputting a file of uniq -c | sort -nr and I need to
take the string from the file,
generate a unique id of the string and then
Output a pipe separated value of cksum|$string | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
The code below works, but I definitely feel like it could be improved. Perhaps removing the tr or not using xargs since I can parallelize it anyways.
Input
3671184 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: {.job_code} Failed to add JDBC connection to the connection pool, connection pool is full..
3195403 Execution error for request {.request_id}. Reason: Transfered zip file failed validation
1118052 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: BIP job failed
190220 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: javax.xml.ws.WebServiceException
163155 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: oracle.xdo.servlet.CreateException
136588 Execution error for request {.request_id}. Reason: Atleast One of the Child requests ended in error or Warning
85080 Execution error for request {.request_id}. Reason: Could not update entity indexing state for entity with uuid: '{.uuid}' in meta model version with uuid '{.uuid}': method [PUT], host
75707 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: Failure during Schedule Item Import job..
69138 Execution error for request {.request_id}. Reason: Spawned job for request {.request_id} produced the business error exit code: BIZ_ERROR | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
57302 Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: Returning a business error. Do not re-try. | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
Code
head uniq.txt | sed -E 's/[0-9]+ (.*)/\1/g' |
tr '\n' '\0' |
xargs -0 -n 1 sh -e -c ' echo "${1}" | cksum | cut -d" " -f1 && echo "${1}"' _ |
tr '\n' '\0' |
xargs -0 -n 2 printf "%d|%s\n" | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
The switching between \n and \0 is because the line I am feeding to xargs has spaces and new lines in it, and xargs will treat those as token separators.
Output
3839440388|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: {.job_code} Failed to add JDBC connection to the connection pool, connection pool is full..
1495326131|Execution error for request {.request_id}. Reason: Transfered zip file failed validation
126216303|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: BIP job failed
2952592408|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: javax.xml.ws.WebServiceException
719205600|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: oracle.xdo.servlet.CreateException
437977472|Execution error for request {.request_id}. Reason: Atleast One of the Child requests ended in error or Warning
2503345575|Execution error for request {.request_id}. Reason: Could not update entity indexing state for entity with uuid: '{.uuid}' in meta model version with uuid '{.uuid}': method [PUT], host
2651334677|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a system error occurred while executing an asynchronous java job for request {.request_id}. Job error is: Failure during Schedule Item Import job..
3069376900|Execution error for request {.request_id}. Reason: Spawned job for request {.request_id} produced the business error exit code: BIZ_ERROR | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
3790403139|Execution error for request {.request_id}. Reason: {.ess_code} Job logic indicated a business error occurred while executing an asynchronous java job for request {.request_id}. Job error is: Returning a business error. Do not re-try. | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
performance, bash, checksum
Answer: Minimize program executions per loop iteration
Executing programs has an overhead, and when doing that in a loop, it quickly becomes noticeable.
For each line in the input, many programs will be executed, namely sh, cksum, cut.
With the given input example, the following produces the same output, executing only cksum:
head uniq.txt | while read count line; do
read s _ < <(cksum <<< "$line")
echo "$s|$line"
done
Another strategy could be to generate an output of all the checksums, and then paste that with the original lines:
head uniq.txt | sed -E 's/[0-9]+ (.*)/\1/g' > lines.txt
paste -d'|' <(while read line; do cksum <<< "$line"; done < lines.txt | cut -f1 -d' ') lines.txt
No need to convert \n to \0
It seems the only reason to convert \n to \0 is because the subshell outputs 2 lines for 1 line of input. It would be simpler to make the subshell output a single line, and then you won't need the conversion:
head uniq.txt | sed -E 's/[0-9]+ (.*)/\1/g' |
xargs -d '\n' -n 1 sh -e -c 'echo "$1" | cksum | cut -d" " -f1 && echo "$1"' _ |
xargs -d '\n' -n 2 printf "%d|%s\n"
Prefer simpler regexes
If the purpose of sed -E 's/[0-9]+ (.*)/\1/g' is to remove the numeric prefix of the lines, then it's simpler to write:
... | sed -E 's/^[0-9]+ //' | {
"domain": "codereview.stackexchange",
"id": 44846,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "performance, bash, checksum",
"url": null
} |
html, css, sh, script, blog
Title: Blog site generator written in shell script
Question: Since I am not a fan of having using large web-frameworks and libraries just to setup a simple blog, I decided to write my own static blog site generator in pure shell script.
The script uses pandoc, to convert markdown files to html files.
To test the script, check out the μblog repository.
It contains documentation + some example blog files.
The output should look like this:
I would like to know, what I can improve. Especially the part about sorting the posts, and extracting information seems still a bit to convoluted for my liking.
mublog.sh
#!/bin/bash
declare -A post_info
declare -a posts
dst_root_dir="dst"
dst_posts_dir="${dst_root_dir}/posts"
dst_css_dir="${dst_root_dir}/css"
dst_assets_dir="${dst_root_dir}/assets"
src_root_dir="src"
src_posts_dir="${src_root_dir}/posts"
src_css_dir="${src_root_dir}/css"
src_assets_dir="${src_root_dir}/assets"
post_ignore_delim="_"
footer_copyright="Copyright © 2023 John Doe :)"
author_mail="johndoe@mail.com"
# Description:
# Removes old build artefacts, and generates the build directories
# The /dst directory is the root directory of the blog
# The /dst/posts directory contains all the blog post files
# The /dst/assets directory stores images, videos etc of posts
# The /dst/css directory contains the style sheets of the blog
initialize_directories() {
rm -rf "$dst_root_dir"
# Create output directories
if mkdir -p "$dst_root_dir" &&
mkdir -p "$dst_posts_dir" &&
mkdir -p "$dst_css_dir" &&
mkdir -p "$dst_assets_dir" &&
cp "$src_css_dir"/*.css "$dst_css_dir" &&
cp -r "$src_assets_dir/." "$dst_assets_dir/"; then
echo "Build directories initialized."
else
echo "Failed to create build directories. Aborting."
exit 1
fi
} | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
# Description:
# Verifies presence and validity of header fields line by line.
# If a field is not present, or its value is not valid, the variables
# will be set to empty. Leading and trailing whitespaces will be stripped,
# if present, except or the markers, where only trailing whitespace is stripped.
# Parameters:
# $1: The path to the src post file to validate
function validate_header() {
echo "Validating post $1 ..."
# Line 1: Check for --- start-marker
marker1=$(sed -n '1p' "$1" | sed 's/^---[[:space:]]*$/---/; t; s/.*//')
# Line 2: Check for title-field
title=$(sed -n '2p' "$1" | sed -n 's/^title:\s*\(.*\)\s*$/\1/p')
# Line 3: Check for description-field
description=$(sed -n '3p' "$1" | sed -n 's/^description:\s*\(.*\)\s*$/\1/p')
# Line 4: Check for date-field with valid date in YYYY-MM-DD format
date=$(sed -n '4p' "$1" | sed -n 's/^date:\s*\(.*\)\s*$/\1/p')
regex='^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$'
date=$(echo "$date" | grep -P "$regex" | awk '{print $1}')
# Line 5: Check for tags-field
tags=$(sed -n '5p' "$1" | sed -n 's/^tags:\s*\(.*\)\s*$/\1/p')
# Line 6: Check for --- end-marker
marker2=$(sed -n '6p' "$1" | sed 's/^---[[:space:]]*$/---/; t; s/.*//')
# Check if the header is invalid (aka, non-empty fields)
if [ -z "$marker1" ]; then
echo "Invalid Header: Starting markers missing or incorrect" && exit 1
elif [ -z "$title" ]; then
echo "Invalid Header: Title field missing or incorrect" && exit 1
elif [ -z "$description" ]; then
echo "Invalid Header: Description field missing or incorrect" && exit 1
elif [ -z "$date" ]; then
echo "Invalid Header: Date field missing, incorrect or in wrong format." && exit 1
elif [ -z "$tags" ]; then
echo "Invalid Header: Tags field missing or incorrect" && exit 1
elif [ -z "$marker2" ]; then
echo "Invalid Header: Ending marker missing or incorrect" && exit 1
fi
} | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
# Description:
# Converts the markdown post or page into html format using pandoc.
# During this process, the header is prepended and the footer appended to the post.
# Parameters:
# $1: The source path to the markdown post/page file
# $2: The destination path where the converted html file will be saved.
build_pages() {
local header="
<html>
<meta charset="utf-8">
<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">
<link rel=\"stylesheet\" href=\"/css/normalize.css\" type=\"text/css\" media=\"all\">
<link rel=\"stylesheet\" href=\"/css/style.css\" type=\"text/css\" media=\"all\">
<nav>
<a href=\"/index.html\">home</a>
<a href=\"/articles.html\">articles</a>
<a href=\"mailto:$author_mail\">mail</a>
<a href=\"/about.html\">about</a>
</nav>
<hr>"
local footer="
</main>
<footer>
<hr>
<p>
$footer_copyright
<br/>
</p>
</footer>
</body>
</html>"
pandoc "$1" -f markdown -t html | { echo -e "$header"; cat; echo -e "$footer"; } > "$2"
}
# Description:
# Iterate through all source post files, and extract values stored in their headers
# such as date, title, but also stores source path and destination path.
# Parameters:
# $1: The path to the source directory of the posts
process_files() {
local src_posts_dir="$1"
# Find all .md posts in the post directory and extract info from the headers
while IFS= read -r -d '' src_post_path; do
if validate_header "$src_post_path"; then
local date=$(grep -oP "(?<=date: ).*" "$src_post_path")
local title=$(grep -oP "(?<=title: ).*" "$src_post_path")
base_name=$(basename "$src_post_path")
local dst_post_path="${dst_posts_dir}/${base_name%.md}.html"
posts+=("$date|$title|$src_post_path|$dst_post_path")
fi
done < <(find "$src_posts_dir" -name "*.md" -print0)
} | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
# Description:
# Sorts posts in reverse chronological order, based on the extracted date
sort_posts() {
IFS=$'\n' sorted_posts=($(sort -r <<<"${posts[*]}"))
unset IFS
}
initialize_directories
build_pages "$src_root_dir/about.md" "$dst_root_dir/about.html"
build_pages "$src_root_dir/index.md" "$dst_root_dir/index.html"
build_pages "$src_root_dir/articles.md" "$dst_root_dir/articles.html"
process_files "$src_posts_dir"
sort_posts
posts_processed=0
posts_skipped=0
article_list="<ul class=\"articles\">"
for post_info in "${sorted_posts[@]}"; do
date=$(cut -d '|' -f 1 <<<"$post_info")
title=$(cut -d '|' -f 2 <<<"$post_info")
src=$(cut -d '|' -f 3 <<<"$post_info")
dst=$(cut -d '|' -f 4 <<<"$post_info")
dst_link=${dst#*/}
echo "Processing post: $src"
echo " title: $title"
echo " date: $date"
echo " output: $dst"
echo " dst_link: $dst_link"
# Check if the file should be ignored (if it starts with the ignore delimter)
filename=$(basename "$src")
if [[ $filename == $post_ignore_delim* ]]; then
posts_skipped=$(($posts_skipped+1))
continue
else
# Build article list
article_item="<li><b style=\"color: #14263b;\">"[${date}]"</b> <a href="\"/${dst_link}\"">${title}</a></li>"
article_list=$article_list$article_item
# Build post file
build_pages "$src" "$dst"
posts_processed=$(($posts_processed+1))
fi
done
article_list=$article_list"</ul>"
echo "Generating article listing ..."
# Replace article tags in the article.html file with the generated article list
sed -i -e '/<article>/ {
N
s|<article>\(.*\)</article>|<article>\1\n'"$(sed 's/[&/\]/\\&/g' <<< "$article_list")"'\n</article>|
}' "$dst_root_dir/articles.html"
echo "Finished! (built: $posts_processed, skipped: $posts_skipped)"
Answer: #! /bin/bash | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
echo "Finished! (built: $posts_processed, skipped: $posts_skipped)"
Answer: #! /bin/bash
That's where it's located on your system.
But for some folks it might be in /usr/bin or /usr/local/bin.
When publishing a portable script,
consider using this shebang:
#! /usr/bin/env bash
The env
utility is not exactly what you'd call feature rich.
It has been there since the dawn of time,
or at least the 70's.
It is soooo boring that even during the great Unix Wars
no one thought to mess with it or move it.
The big thing that it brings to this party
is it obeys ${PATH}, so it will find
the interpreter in whichever of the popular
locations it happened to land on this particular host.
BTW, I really like your
CSS reset.
It's reminiscent of the one offered by
Y!UI.
Putting all browsers on equal footing is really important
for being able to test once and have confidence the test
result translates to other browsers.
I personally find it's a bit of a challenge to author good Bourne code,
since there are so many places that values
can get expanded and re-globbed,
erasing the difference between $@ and $*.
Before submitting code for review,
it's pretty important to use
ruff *.py,
cc -Wall -Wextra -Wpendantic *.c,
or whatever the relevant linter would be.
Here, either you didn't or you chose to ignore the advice
without writing any # comment about that decision.
I will just reproduce the output below without comment.
$ shellcheck mublog.sh
In mublog.sh line 92:
<meta charset="utf-8">
^---^ SC2140 (warning): Word is of the form "A"B"C" (B indicated). Did you mean "ABC" or "A\"B\"C"?
In mublog.sh line 129:
local date=$(grep -oP "(?<=date: ).*" "$src_post_path")
^--^ SC2155 (warning): Declare and assign separately to avoid masking return values.
In mublog.sh line 130:
local title=$(grep -oP "(?<=title: ).*" "$src_post_path")
^---^ SC2155 (warning): Declare and assign separately to avoid masking return values. | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
In mublog.sh line 143:
IFS=$'\n' sorted_posts=($(sort -r <<<"${posts[*]}"))
^-------------------------^ SC2207 (warning): Prefer mapfile or read -a to split command output (or quote to avoid splitting).
In mublog.sh line 173:
posts_skipped=$(($posts_skipped+1))
^------------^ SC2004 (style): $/${} is unnecessary on arithmetic variables.
In mublog.sh line 182:
posts_processed=$(($posts_processed+1))
^--------------^ SC2004 (style): $/${} is unnecessary on arithmetic variables.
For more information:
https://www.shellcheck.net/wiki/SC2140 -- Word is of the form "A"B"C" (B in...
https://www.shellcheck.net/wiki/SC2155 -- Declare and assign separately to ...
https://www.shellcheck.net/wiki/SC2207 -- Prefer mapfile or read -a to spli...
footer_copyright="Copyright © 2023 John Doe :)"
No.
Please elide the smiley.
You're trying to offer legal advice to your users.
Offer good advice.
The © glyph isn't exactly bad.
But I recommend you elide it.
The USPTO describes certain notice benefits and offers some
advice:
A copyright notice consists of three elements:
• The copyright symbol © ..., the word “Copyright,” or the abbreviation “Copr.”;
• The year of first publication of the work ...; and
• The name of the copyright owner....
I don't recommend using that ancient "Copr." abbreviation.
And I don't recommend saying saying the same same thing twice twice.
Use the C-in-a-circle glyph, or the word. Not both.
Let's switch gears slightly.
Your users probably want folks to make copies of their work.
Consider encouraging them to license their copyrighted
work, perhaps using Creative Commons'
CC attribution no-derivatives.
Adding a line of boilerplate is all it would take.
author_mail="johndoe@mail.com" | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
author_mail="johndoe@mail.com"
Best practice here is to use a domain of
example.com.
I see this greeting ATM when I start sending mail to that address:
220 mail.com (mxgmxus007) Nemesis ESMTP Service ready
It's a sad fact of life that if x@y.com appears in a document,
MTAs will wind up processing a non-zero number of messages
for that address.
I like initialize_directories().
Consider putting set -e, for early bailout,
at the very top of the script -- it will
still be compatible with the && clauses.
And if you do that, go all the way: set -e -o pipefail
Probably worth adding set -u, too,
since we don't expect any unset variables.
These are just belt-and-suspender approaches,
something we routinely put on top of presumably correct code
that strictly shouldn't need it.
function validate_header() {
Ok, you lost me a little bit, there.
It's unclear which porting setup you are targeting.
The function keyword is perfectly nice.
Recommend you uniformly use it everywhere,
or else use it nowhere.
The various checks seem nice enough.
My offhand impression is that, as a user, a blog author,
they are maybe not very diagnostic errors.
That is, upon viewing an error, I might understand
what went wrong and what I should fix.
I'm just not yet confident of that.
Sorry, don't have any specific advice here,
it's just a matter of testing the system with users,
looking over their shoulder,
and seeing what speedbumps they actually stumble over in production.
That takes time and bugreports to work out.
build_pages() {
local header= ...
The proliferation of \ backwhacked " quotes seems tedious.
Consider using the syntax of a << HERE document to make writing
and reading HTML quotes a little more pleasant.
pandoc ... | { echo -e "$header"; cat; echo -e "$footer"; } > "$2" | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
Kudos, that is really nicely phrased.
It calls the reader's attention to the "hard" part, pandoc with its args,
and it does a great job of showing off the parallel structure
of the {header, text, footer} sandwich. I like it.
process_files() {
...
while IFS= read ...
It's worth adding a comment that IFS= lets us parse NUL delimited records.
posts+=("$date|$title|$src_post_path|$dst_post_path")
Up in validate_header() we never checked whether the title
contains prohibited characters such as | pipe.
That's kind of a problem, here.
sort_posts() {
IFS=$'\n' sorted_posts=($(sort -r <<<"${posts[*]}"))
unset IFS
I find the IFS thing non-obvious, and I feel it warrants a # comment.
Ok, now I understand it, having looked at this pair of identical examples,
with BASH_VERSION='3.2.57(1)-release' on MacOS:
$ echo one $'\n' two
one
two
$
$ echo -e one '\n' two
one
two
The unset is weird, avoid doing that.
Kudos on this mainline code:
initialize_directories
build_pages ...
build_pages ...
build_pages ...
process_files ...
sort_posts
Nicely organized.
Including how we validate at just the right point in the pipeline.
Maybe put these few lines in a function called main() ?
process_files "$src_posts_dir"
Let me lean on that line, which relies on a find.
My concern is that after some dozens of blog articles have been published,
we wind up
taking a "long" time running pandoc on unchanged inputs, and
we essentially touch *.html, changing webserver HTTP timestamp headers.
Consider using a technique like make
so you only update HTML files that need it.
posts_processed=0
...
for post_info in ...
This stuff wants to be in a named function. Just sayin'.
Also, we see a bunch of cut invocations that
operate on field 1 .. 4.
Consider extracting that into a tiny helper function.
Similarly you really need a replace_article_tags() helper.
And it would be lovely if it had an automated unit test,
so I could better see just what it does. | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
html, css, sh, script, blog
Based on what I read,
it is unclear to me what platform(s) you intend for this to
be portable to.
CentOS? Cygwin? MacOS? FreeBSD? Certainly debian linux.
The version of bash plus coreutils really matters.
Consider bailing out with a fatal diagnostic
if the target host's versions are out-of-whack
with the one or more systems that you have tested on.
Whatever automated tests you write,
definitely publish them so as to invite
contributors to run them as part of submitting PRs.
This codebase achieves its design goals.
I would be willing to delegate or accept maintenance tasks on it. | {
"domain": "codereview.stackexchange",
"id": 44847,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "html, css, sh, script, blog",
"url": null
} |
javascript, html, css
Title: Calorie Calculator
Question: I have developed a calorie-tracker webpage and would appreciate some feedback on it. I'm particularly interested in optimizing performance, improving code readability, and ensuring best practices are followed. | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
<!DOCTYPE html>
<html lang='eng'>
<head>
<title>FITIFY | Fitness Tracker</title>
<!--CSS Styling-->
<style>
h1{
color: gold;
font-family: 'Open Sans', sans-serif;
font-weight: bolder;
}
h2, h3{
color: white;
margin: 6%;
text-align: center;
font-family: 'Instrument Sans', sans-serif;
font-size: 40px;
font-weight: bold;
}
h5{
background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
a{
text-decoration: none;
color: white;
margin: 3%;
}
.nav-brand{
margin: 1%;
color: white;
}
.btn{
background-color: #19376D;
}
.btn:hover{
background-color: green;
font-weight: bold;
}
.nav-links{
width: 40%;
margin-right: 0%;
}
.dropdown{
display: inline-block;
}
.main-box{
background: linear-gradient(to bottom right,#3d97ce 0%,#12debb 100%);
width: 100%;
height: 90vh;
border-bottom: solid black 3px;
margin-top: 6%;
position: relative;
}
.main-text-box{
float: left;
width: 50%;
height: 100%;
}
#main-para{
color: white;
text-align: left;
margin: 2% 2% 2% 10%;
font-size: 22px;
visibility: hidden;
font-weight: 400;
}
.main-image-box{
float: right;
width: 50%;
height: 100%;
}
#main-img{
width: 80%;
height: 80%; | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
}
#main-img{
width: 80%;
height: 80%;
margin: 5%;
border:white solid 3px;
}
#to-features{
background-color: black;
color: white;
border: solid 2.5px;
border-image-slice: 1;
border-image-source: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
width: 10%;
height: 10%;
position: absolute;
margin: 0% 40% 0% 20%;
bottom: 10%;
font-family: 'Instrument Sans', sans-serif;
font-size: 20px;
font-weight: bold;
}
.feature-box{
background: linear-gradient(to top right,#3d97ce 0%,#12debb 100%);
background-size: cover;
height: auto;
}
.card{
color: black;
background-color: white;
width: 21%;
height: 250px;
margin: 14% 2% 10% 2%;
}
.row{
margin-right: 0%;
}
.cards-btn{
background-color: black;
color: white;
border: solid 3px;
border-image-slice: 1;
border-image-source: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
padding: 2%;
margin: 50px 10% 2% 20%;
font-family: 'Instrument Sans', sans-serif;
font-size: 13px;
font-weight: bold;
}
.cards-btn:hover{
color: green;
} | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
@media screen and (max-width: 1200px) {
h1{
font-size: 4rem;
}
h2{
font-size: 5rem;
}
a{
margin: 3%;
font-size: 2.5vw;
}
.nav-links{
margin: 0%;
width: 70%;
}
.btn{
font-size: 2.5vw;
margin-right: 1%;
}
.main-box{
margin-top: 8%;
height: 100vh;
}
.main-text-box{
width: 100%;
}
#main-para{
font-size: 6vw;
}
.main-image-box{
display: none;
}
#to-features{
width: 30%;
height: 5%;
padding: 1%;
margin: 0% 20% 15% 35%;
font-size: 2rem;
font-weight: bolder;
}
.card{
width: 35%;
height: 30%;
margin: 15% 10% 5% 35%;
font-size: 1.4rem;
}
.cards-btn{
margin: 5% 5% 2% 30%;
}
#goal-btn{
margin-left: 25%;
}
}
@media screen and (min-width: 1800px) and (max-width: 2600px) { /* 4k */
h1{
font-size: 6rem;
}
h2{
font-size: 5rem;
font-weight: bolder;
}
a{
margin: 5%;
font-size: 3rem;
}
.nav-links{
margin: 0%;
width: 55%;
}
.btn{
font-size: 3rem;
margin-right: 10%;
}
.main-box{
margin-top: 6%;
height: 100vh;
}
#main-para{ | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
margin-top: 6%;
height: 100vh;
}
#main-para{
font-size: 60px;
}
#to-features{
width: 20%;
height: 9%;
padding: 1%;
font-size: 40px;
margin: 10% 0% 0% 15%;
}
.card{
width: 20%;
height: 250px;
margin: 15% 3% 10% 2%;
}
#goal-btn{
margin-left: 10%;
}
}
</style>
</head>
<body>
<header>
<nav class="navbar bg-dark fixed-top" data-bs-theme="dark">
<div class="nav-brand">
<h1>FITIFY</h1>
</div>
<div class="nav-links">
<a href="./index.html">HOME</a>
<div class="dropdown">
<button class="btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
FEATURES
</button>
<ul class="dropdown-menu gap-1 p-2 rounded-3 mx-0 shadow w-220px" data-bs-theme="light">
<li><a class="dropdown-item rounded-2" href="./bmi.html">BMI CALCULATOR</a></li>
<li><a class="dropdown-item rounded-2" href="./calories.html">TRACK CALORIES</a></li>
<li><a class="dropdown-item rounded-2" href="./goal.html">KNOW YOUR GOAL</a></li>
<li><a class="dropdown-item rounded-2" href="./basic_redirect.html">STORE YOUR DETAILS</a></li>
</ul>
</div>
<a href="./about.html">ABOUT US</a>
<a href="./contacts.html">CONTACT US</a>
</div>
</nav>
</header>
<main>
<div class="main-box">
<div class="main-text-box"> | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
<main>
<div class="main-box">
<div class="main-text-box">
<h2>Transform yourself today.</h2>
<p id="main-para">"Welcome to Fitify, your ultimate fitness companion! We are dedicated to helping you on your fitness journey by providing powerful tools to track your progress. With our user-friendly interface achieving your health and fitness goals has never been easier. Join our community today and take the first step towards a healthier, fitter you!"</p>
<button id="to-features">GET FIT</button>
</div>
<div class="main-image-box">
<img src="./nutri.webp" id="main-img" alt="Display Image">
</div>
</div>
<div class="feature-box">
<div class="row">
<div class="card">
<i class="fa-sharp fa-solid fa-dumbbell"></i>
<div class="card-body">
<h5 class="card-title">CALCULATE YOUR BMI</h5>
<p class="card-text">Calculate your Body Mass Index (BMI) to know your health status right away.</p><br>
<a href="./bmi.html" class="cards-btn">CALCULATE</a>
</div>
</div>
<div class="card">
<i class="fa-solid fa-utensils"></i>
<div class="card-body">
<h5 class="card-title">TRACK YOUR CALORIES</h5>
<p class="card-text">Track your calories for the day and know how much you consumed today.</p>
<a href="./calories.html" class="cards-btn">TRACK NOW</a>
</div>
</div>
<div class="card">
<i class="fa-solid fa-person-dress"></i>
<div class="card-body">
<h5 class="card-title">YOUR IDEAL WEIGHT</h5> | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
<h5 class="card-title">YOUR IDEAL WEIGHT</h5>
<p class="card-text">Calculate your ideal weight by entering your measurements.</p><br>
<a href="./goal.html" class="cards-btn" id="goal-btn">KNOW YOUR GOAL</a>
</div>
</div>
<div class="card">
<i class="fa-solid fa-info"></i>
<div class="card-body">
<h5 class="card-title">STORE YOUR BASIC DETAILS</h5>
<p class="card-text">Keep a log of your basic information in our secure database.</p>
<a href="./basic_redirect.html" class="cards-btn">STORE DETAILS</a>
</div>
</div>
</div>
</div>
</main>
<script>
const button = document.getElementById('to-features');
window.onload = function() {
var para = document.getElementById("main-para");
var para_text = para.innerHTML;
var speed = 15;
var i = 0;
para.innerHTML = "";
function typeWriter_para() {
if (i< para_text.length) {
para.innerHTML += para_text.charAt(i);
i++;
setTimeout(typeWriter_para, speed);
}
}
setTimeout(typeWriter_para, 100); // Delay before starting the paragraph animation
para.style.visibility = "visible"; // Make the paragraph visible
};
const feature_box = document.querySelector('.feature-box');
button.addEventListener('click', function(){
feature_box.scrollIntoView();
});
</script>
</body>
</html> | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
LIVE SITE URL: Click Here
Please feel free to provide any feedback, suggestions, or improvements you think would enhance the code quality and maintainability of my project. Thank you in advance for your time and valuable insights! | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
Answer: 1 General Issues
1.1 Markup Validation
As the comments state, eng is not a valid value for the lang attribute. W3C Validation Service will flag with a red flag.
1.2 Indents
Your idents differ. Sometimes you use 2 spaces for indents and on other parts, you sued 4 spaces for indents. YOu should use the tab only and decide between 2 or 4 but do not mix them.
1.3 Loigcal Gaps
You used no logical gaps which hurt readability. your code reads similar to a book with no paragraphs but all text in one block and without any punctuation.
Use logical gaps to spread elements apart and give a visual difference between elements that do not directly belong to each other. This allows developers to read more easily and recognize specific modules or element groups. As an example, you could have split the single cards from each other.
1.4 Linebreaks
You used no linebreak which also makes text hard to read. Split text within a paragraph to a new line to fit even a smaller screen. Right now any developer has to horizontally scroll to read the text.
1.5 Comments
You only used one COmment and the above style tag to show that CSS follows. The comment there is redundant. Anyone who will read the code knows that a style tag contains CSS.
You could use a comment as a headline if you use more then one CSS to headline a logical code block but it is unnecessary in your case.
2 Head Element
2.1 Character Set
While it is still valid not to declare a character set, I would recommend you always use <meta charset="utf-8"> to ensure that the same character set is used as you programmed in.
2.2 Styling
You chose head-style for your CSS. This overall does the job but will hurt both performance and readability.
2.2.1 Performance | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
2.2.1 Performance
Since you have a single file and HTML as well as CSS and JS are single-threaded, everything will run and read synchronously. That means, that first the style is read before the document can even start to render the document. The rendering of the document with that is delayed.
A performant solution would be to push the CSS into its own CSS file and load the CSS file as an external file. That way, the CSS can even be cached which will improve loading times at the second request.
2.2.2 Readability
As for readability, a dedicated external file will always win. It is easier to read the CSS in a different file where I explicitly expect it to be CSS. On the other hand, I do not have to check where the CSS start and where it ends. Which also makes the HTML code shorter.
2.2.3 Best Practice
The best practice when developing with an RWD (Responsive Web Design) approach is to start mobile first and then use styles for higher and higher screens that will overwrite previous stylings.
You sued 2 media queries one for 1200px or below and one for between 1800 and 2600px. You have no queries for between 1200-1800px and none to address screens higher the 2600px. That is harder to read and is confusing as any developer will search for the missing queries and/or will have to scroll between the entire CSS to see which style would apply on a certain width.
2.3 JavaScript
2.3.1 Performance
Same as with the CSS you should move the JS to an external file and allow the usage of running it into a second thread independent from the HTML. You should then declare it within the head element so it will be read already during the start and reduce the time it needs to execute the script.
window.onload()
This issue only matters if you keep the script at the end of the body. That event trigger is redundant or useless. A script at the end of the body will only execute when the entire document is already read and parsed. There is no need to wait for the onload event anymore. | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
2.3.2 Readability
As said before, you miss logical gaps which make your code harder to read. You also miss sufficient commenting to explain what you trying to do.
the next issue is following code fragment:
var i = 0;
para.innerHTML = "";
function typeWriter_para() {
if (i< para_text.length) {
i++;
setTimeout(typeWriter_para, speed);
}
} | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
in the if condition you are referencing a variable called i. As a quick sidenote in that configuration, the variable i is not readable. On the other hand, you use a function to create and copy the behavior of a for loop.
2.3.3 innerHTML
You should not use innerHTML anymore. It has 2 issues, for one it is slow as it needs the DOM to prepare and on the other hand, it poses a security risk (XSS injection).
Since you only try to get text, use textContent instead.
2.3.4 Conventions
Conventions are a good way to increase readability and to work with other developers as well as maintenance.
2.3.4.1 Constants and variables
You should differentiate constants and variables from each other by writing const NAMES as capital.
Declare constants at the very top of the document or if you use an onload event at the top within the onload event. Your const feature_box is declared somewhere in the mid-end.
Use a constant when you expect something not to change within your script. Noticeably in the variable var para = document.getElementById("main-para"); I would expect that the element does not change and as such a constant would have been more appropriate.
2.3.4.2 Naming
You should use names that are self-explaining. Names are used to be self-explaining to developers and as such must be readable. At no point should they be chosen for efficiency to save a few bytes. The word para is an actual word coming from Latin and means "side". It is not the best choice to choose a short word for a paragraph.
2.3.5 Best Practice
2.3.5.1 let vs var
You have to choices to declare a variable either let or var. In modern JS I would recommend always using let unless you understand the difference and explicitly need the options that var would give you.
2.3.5.2 onload
In modern JS you do not use event triggers such as onload or onlick (all events starting with on). The issue here is, that you can only have one event and will always overwrite the previous event. | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
The modern practice is to append events by using addEventListener.
As such you should change:
window.onload = function() {
// your function
} | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
javascript, html, css
to this modern approach:
window.addEventListener('DOMContentLoaded', function() {
// your function
})
3 Body
3.1 Navbar
<div class="nav-brand">
<h1>FITIFY</h1>
</div>
That is not an element I would expect within a navbar as it has no navigational purpose. More appropriate would be the placement within the header element outside of the navbar.
As such your container <div class="nav-links"> will be obsolete as nav as a container can take over the task.
It is not incorrect to use ul as a container for a list of links but IMHO it would be more appropriate for menu which behaves the same. The reason why it is not incorrect in technical terms is conflicting documentation between Mozilla (official documentation and WHATWG founder) with the WHATWG specifications. Those conflicts are caused because HTML5 and CSS3 are not officially specified in technical terms by the W3C but are proposed in the form of recommendations by WHATWG.
3.2 Main
You contain your content within the main element by pushing them into logical containers by using div. A section would be more appropriate as a semantic container than a div | {
"domain": "codereview.stackexchange",
"id": 44848,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, html, css",
"url": null
} |
c#, .net, asynchronous, http, stream
Title: Seekable HTTP response stream wrapper
Question: I created this wrapper to use together with HttpClient streams and ZipArchive. ZipArchive reads .zip index once from the end of the archive, so this wrapper caches last 4MiB of the stream. Also the wrapper avoids pointless seeks until the first read.
I am interested if there any issues with this approach, and whether this can be improved.
namespace Playground
{
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
public class SeekableHttpStream : Stream
{
private long _position;
private long _underlyingStreamOffset;
private Stream _underlyingStream;
private bool _forceRequest;
internal SeekableHttpStream(
HttpClient client,
HttpResponseMessage response,
HttpRequestMessage request)
{
Client = client;
Response = response;
Request = request;
var headers = response.Headers;
var acceptRanges = headers?.AcceptRanges;
if (acceptRanges == null || !acceptRanges.Contains("bytes"))
{
throw new ArgumentException("server does not support HTTP range requests", nameof(request));
}
var contentHeaders = response.Content?.Headers;
if (contentHeaders.ContentLength != null)
{
Length = contentHeaders.ContentLength.Value;
}
else if (contentHeaders.ContentRange != null)
{
if (contentHeaders.ContentRange.Length == null)
{
throw new ArgumentException("missing Content-Range length", nameof(request));
} | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
Length = contentHeaders.ContentRange.Length.Value;
}
else
{
throw new ArgumentException("failed to determine stream length", nameof(request));
}
}
public HttpClient Client { get; }
public HttpResponseMessage Response { get; }
public HttpRequestMessage Request { get; }
public override bool CanRead => _position < Length;
public override bool CanSeek => true;
public override bool CanWrite => false;
public override long Length { get; }
public override long Position
{
get => _position;
set => Seek(value, SeekOrigin.Begin);
}
public override void Flush()
{
}
public override int Read(byte[] buffer, int offset, int count)
{
EnsureStreamOpen().GetAwaiter().GetResult();
int read = _underlyingStream.Read(buffer, offset, count);
_position += read;
return read;
}
public override int Read(Span<byte> buffer)
{
EnsureStreamOpen().GetAwaiter().GetResult();
int read = _underlyingStream.Read(buffer);
_position += read;
return read;
}
public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
await EnsureStreamOpen(cancellationToken).ConfigureAwait(false);
int read = await _underlyingStream.ReadAsync(buffer, offset, count, cancellationToken)
.ConfigureAwait(false);
_position += read;
return read;
}
public override int ReadByte()
{
EnsureStreamOpen().GetAwaiter().GetResult();
var value = _underlyingStream.ReadByte();
++_position;
return value;
} | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
return value;
}
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
await EnsureStreamOpen(cancellationToken).ConfigureAwait(false);
int read = await _underlyingStream.ReadAsync(buffer, cancellationToken)
.ConfigureAwait(false);
_position += read;
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
return SeekAsync(offset, origin).GetAwaiter().GetResult();
}
private ValueTask EnsureStreamOpen(CancellationToken cancellationToken = default)
{
if (_underlyingStream == null)
{
_forceRequest = true;
return new ValueTask(SeekAsync(0, SeekOrigin.Current, cancellationToken));
}
return default;
}
public async Task<long> SeekAsync(long offset, SeekOrigin origin, CancellationToken cancellationToken = default)
{
const long SeekThreshold = 1024 * 1024;
long newPosition = origin switch
{
SeekOrigin.Begin => offset,
SeekOrigin.Current => _position + offset,
SeekOrigin.End => Length + offset,
_ => throw new ArgumentOutOfRangeException(nameof(origin)),
};
if (newPosition < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset));
}
if (newPosition > Length)
{
throw new NotSupportedException("seeking beyond the length of the stream is not supported");
} | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
long delta = newPosition - _position;
if (_underlyingStream == null)
{
if (_forceRequest)
{
await OpenUnderlyingStream(newPosition, cancellationToken)
.ConfigureAwait(false);
}
_position = newPosition;
}
else if (_underlyingStream.CanSeek && newPosition >= _underlyingStreamOffset && newPosition <= _underlyingStreamOffset + _underlyingStream.Length)
{
_underlyingStream.Position = newPosition - _underlyingStreamOffset;
_position = newPosition;
}
else if (delta < 0 || delta > SeekThreshold)
{
await OpenUnderlyingStream(newPosition, cancellationToken)
.ConfigureAwait(false);
}
else if (delta > 0)
{
var buffer = new byte[delta];
await ReadAsync(buffer, 0, (int)delta, cancellationToken);
}
return _position;
}
private async Task<HttpRequestMessage> CopyHttpRequest()
{
var clone = new HttpRequestMessage(Request.Method, Request.RequestUri);
if (Request.Content != null)
{
var bytes = await Request.Content.ReadAsByteArrayAsync()
.ConfigureAwait(false);
clone.Content = new ByteArrayContent(bytes);
if (Request.Content.Headers != null)
foreach (var h in Request.Content.Headers)
clone.Content.Headers.Add(h.Key, h.Value);
}
clone.Version = Request.Version;
foreach (var prop in Request.Properties)
{
clone.Properties.Add(prop);
} | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
foreach (var header in Request.Headers)
{
clone.Headers.TryAddWithoutValidation(header.Key, header.Value);
}
return clone;
}
private async Task OpenUnderlyingStream(long position, CancellationToken cancellationToken = default)
{
const long UseBufferedStreamThreshold = 4 * 1024 * 1024;
if (position < 0)
{
throw new ArgumentOutOfRangeException(nameof(position));
}
using var newRequest = await CopyHttpRequest()
.ConfigureAwait(false);
if (position > 0)
{
var responseHeaders = Response.Headers;
var contentHeaders = Response.Content.Headers;
if (responseHeaders.ETag != null)
{
newRequest.Headers.IfRange = new RangeConditionHeaderValue(responseHeaders.ETag);
}
else if (contentHeaders.LastModified != null)
{
newRequest.Headers.IfRange = new RangeConditionHeaderValue(contentHeaders.LastModified.Value);
}
newRequest.Headers.Range = new RangeHeaderValue(position, null);
}
long remainingLength = Length - position;
var response = await Client.SendAsync(
newRequest,
remainingLength <= UseBufferedStreamThreshold ? HttpCompletionOption.ResponseContentRead : HttpCompletionOption.ResponseHeadersRead,
cancellationToken
).ConfigureAwait(false); | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
if (!response.IsSuccessStatusCode)
{
response.EnsureSuccessStatusCode();
}
else if (position > 0 && response.StatusCode != HttpStatusCode.PartialContent)
{
response.Dispose();
throw new InvalidOperationException("range request not supported or content has changed since last request");
}
else
{
try
{
var stream = await response.Content.ReadAsStreamAsync()
.ConfigureAwait(false);
if (_underlyingStream != null)
{
await _underlyingStream.DisposeAsync()
.ConfigureAwait(false);
}
_underlyingStream = stream;
_underlyingStreamOffset = position;
_forceRequest = false;
_position = position;
}
catch
{
response.Dispose();
throw;
}
}
}
protected override void Dispose(bool disposing)
{
_underlyingStream?.Dispose();
Response.Dispose();
Request.Dispose();
base.Dispose(disposing);
}
#region Unsupported write methods
public override void SetLength(long value)
{
throw new NotSupportedException();
}
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state)
{
throw new NotSupportedException();
}
public override void EndWrite(IAsyncResult asyncResult) => throw new NotSupportedException(); | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
public override void Write(ReadOnlySpan<byte> buffer) => throw new NotSupportedException();
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
{
throw new NotSupportedException();
}
public override void WriteByte(byte value)
{
throw new NotSupportedException();
}
public override int WriteTimeout
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
#endregion Unsupported write methods
}
public static class HttpClientExtensions
{
public static async Task<SeekableHttpStream> GetSeekableStreamAsync(this HttpClient client, string requestUri)
{
using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
return await SendSeekableStreamAsync(client, request)
.ConfigureAwait(false);
}
public static async Task<SeekableHttpStream> GetSeekableStreamAsync(this HttpClient client, Uri requestUri)
{
using var request = new HttpRequestMessage(HttpMethod.Get, requestUri);
return await SendSeekableStreamAsync(client, request)
.ConfigureAwait(false);
}
public static async Task<SeekableHttpStream> SendSeekableStreamAsync(this HttpClient client, HttpRequestMessage request)
{
HttpMethod method = request.Method;
try
{
request.Method = HttpMethod.Head;
var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead)
.ConfigureAwait(false);
response.EnsureSuccessStatusCode(); | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
c#, .net, asynchronous, http, stream
try
{
return new SeekableHttpStream(client, response, request);
}
catch
{
response.Dispose();
throw;
}
}
finally
{
request.Method = method;
}
}
}
}
Answer: else if (delta > 0)
{
var buffer = new byte[delta];
await ReadAsync(buffer, 0, (int)delta, cancellationToken);
}
This code has a fairly nasty bug: ReadAsync is not required to read as much data as you're requesting, it can read less. You either need to use the .Net 7 method ReadExactlyAsync, or you need to read in a loop, until the right number of bytes has been read. | {
"domain": "codereview.stackexchange",
"id": 44849,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, .net, asynchronous, http, stream",
"url": null
} |
python, sqlite, connection-pool
Title: Simple Connection Pool for SQLite in Python
Question: When I talk to people regarding connection pooling in SQLite most of them always laugh and say "You don't know about SQLite", "It is not a client server DB, and only overhead in creating new connection is opening a file connection".
I agree but connection pooling helps in SQLite if we want to make use of PRAGMA cache_size. This cache works at sqlite connection level and if we close connection the cache will be discarded (it is also discarded when database file changes).
So in order to make use of cache_size when set with higher values it is better to pool connections.
Here is my simple implementation in python
import queue
import sqlite3
from contextlib import contextmanager
class ConnectionPool:
def __init__(self, max_connections, database):
self.max_connections = max_connections
self.database = database
self.pool = queue.Queue(maxsize=max_connections)
for _ in range(max_connections):
conn = self.create_connection()
self.pool.put(conn)
def create_connection(self):
return sqlite3.connect(self.database)
def get_connection(self, timeout):
try:
return self.pool.get(timeout=timeout)
except queue.Empty:
raise RuntimeError("Timeout: No available pool in the pool.")
def release_connection(self, conn):
self.pool.put(conn)
@contextmanager
def connection(self, timeout=10):
conn = self.get_connection(timeout)
try:
yield conn
finally:
self.release_connection(conn)
if __name__ == "__main__":
pool = ConnectionPool(5, 'cp.db')
with pool.connection() as connection:
cursor = connection.cursor()
cursor.execute('SELECT 1')
result = cursor.fetchall()
print(result)
Please feel free to give feedbacks and suggestion for improving above connection pool implementation | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
python, sqlite, connection-pool
Please feel free to give feedbacks and suggestion for improving above connection pool implementation
Answer: I would make a few suggestions. The last two, listed separately, may be of marginal value to you and do increase the complexity of the code considerably. I have included a sample implementation that incorporates these two ideas mostly for my future reference and use. Ironically, I could now use somebody to review this for me!
I would prepend to your class's attribute names a '_' signifying that they are "private."
If a client uses the context manager method connection to obtain a connection, there is a default timeout argument value. However, the same is not true if the client wants to explicitly call get_connection and release_connection. But if these two methods are not meant to be called by the client, then rename these methods so that they have a leading '_'. Otherwise, you can have defaults for both styles of acquisition with that default value specified only once for consistency:
def get_connection(self, timeout=None):
if timeout is None:
timeout = 10
... # rest of code omitted
@contextmanager
def connection(self, timeout=None):
conn = self.get_connection(timeout)
... # rest of code omitted | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
python, sqlite, connection-pool
You might wish to implement a close method that closes all the connections. This method should only be called when it is known that all the connections have been returned to the pool for good.
I have updated the signature on the __init__ method so that the client can add additional parameters the call to sqlite3.connect.
If you timeout during acquisition, the RuntimeError message should be changed to "Timeout: No available connection in the pool."
A connection pool is just a special case of a more general "resource" pool where the resource in question is a reusable connection. Consider creating an abstract base class, ResourcePool, that can be used to allocate any type of resource. This class would have an abstract method, allocate_resource, that is overridden in a subclass (e.g. your ConectionPool class) and creates an instance of a specific type of resource. Thus, ResourcePool class would have method names such as allocate_resource instead of create_connection, get_resource instead of get_connection, etc. Your ConnectionPool subclass can define, for example, a get_connection method that simply delegates to the base class get_resource method so that the client can use connection-specific method names.
If you want to be slightly more efficient at the cost of additional complexity, then: | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
python, sqlite, connection-pool
If you want to be slightly more efficient at the cost of additional complexity, then:
You might wish to lazily create connections. Store as attributes the maximum number of connections to create, the number of connections created and the number of connections currently in the pool, i.e. the Queue instance, that are immediately available for allocation. As long as there are unused connections in the queue, you can simply get the next available one. But if the queue is empty, then if the number of connections that have been created is less than the maximum number of connections permitted, you simply create another connection, update the count of created connections and return the new connection. This logic is a critical section that needs to be serialized under control of a threading.Lock instance. Lazy allocation will save you something if the maximum number of concurrent connections in use at one time is considerably less than your pool size and if creating a connection uses a lot of resources. This is probably not your situation.
If a connection is returned to the pool with uncommitted updates, it would be wise to perform a rollback on the connection.
You might also wish to use a collections.deque instance instead of a queue.Queue, since it would be a bit faster. But your code also becomes a bit more complicated. | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
python, sqlite, connection-pool
Update
Your implementation, which used a queue.Queue instance to implement the pool (as well as my previous sample implementation) assumes that the connections would be obtained by threads running concurrently for if it were only a single thread running, what would be the point of that thread obtaining multiple connections to the same database? You would then really only need a pool size of 1. But in this case, you would still be better off just implementing a singleton connection and forget about using a pool.
So the problem now become this: A sqlite3 connection can only be used on the thread that created it (at least that is the case for my Python 3.8.5). So such a pool is really not suitable for a multithreading environment.
My conclusion is that such a pool needs to be using instead asyncio and thus your original implementation needs to be using a asyncio.Queue instance. So my new sample implementation would be:
Sample asyncio Implementation Using a deque and Lazy Connection Creation
import asyncio
from abc import ABC, abstractmethod
from collections import deque
from contextlib import asynccontextmanager
class ResourcePool(ABC):
def __init__(self, max_resources):
if max_resources < 1:
raise ValueError(f'Invalid max_resources argument: {max_resources}')
self._max_resources = max_resources
self._request_lock = asyncio.Lock()
self._resource_returned = asyncio.Condition()
self._pool = deque()
self._n_resources_created = 0
self._is_hashable_resource = self.is_hashable_resource()
self._in_use = set()
async def close(self):
"""Close all resources."""
async with self._request_lock:
while self._pool:
res = self._pool.popleft()
await self.close_resource(res)
while self._in_use:
res = self._in_use.pop()
await self.close_resource(res) | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
python, sqlite, connection-pool
async def close_resource(self, res):
"""Subclasses should override this method if the resource does
not implement a close method."""
await res.close()
def is_hashable_resource(self):
"""Override this function and return False if the resource cannot be
added to a set. Otherwise, we can do some additional error checking and
ensure that all resources are closed when method close is called."""
return True
@abstractmethod
async def create_resource(self):
pass
async def get_resource(self, timeout=None):
if timeout is None:
timeout = 10
while True:
async with self._request_lock:
if self._pool:
res = self._pool.popleft()
if self._is_hashable_resource:
self._in_use.add(res)
return res
# Can we create another resource?
if self._n_resources_created < self._max_resources:
self._n_resources_created += 1
res = await self.create_resource()
if self._is_hashable_resource:
self._in_use.add(res)
return res
# We must wait for a resource to be returned
async def wait_for_resource():
async with self._resource_returned:
await self._resource_returned.wait()
try:
await asyncio.wait_for(wait_for_resource(), timeout=timeout)
# The pool now has at least one resource available and
# we will succeed on next iteration.
except asyncio.TimeoutError:
raise RuntimeError("Timeout: No available resource in the pool.") | {
"domain": "codereview.stackexchange",
"id": 44850,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, sqlite, connection-pool",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.