text
stringlengths
1
2.12k
source
dict
php, validation, laravel Questions: Is there any redundancy in my code? Do you see any security issues? Answer: Is there any redundancy in my code? There is some redundancy between $rules and $messages This may not be an orthodox idea by many Laravel programmers but $rules could be generated on the fly by iterating over the keys of $messages - Something like: $rules = array_reduce(array_keys($messages), function($carry, $messageKey) { [$field] = explode('.', $messageKey); if (str_contains($field, 'theme')) { return $carry + [$field => 'required']; } $type = str_contains($field, 'email') ? 'email' : 'string'; return $carry + [$field => "required|$type|max:190"]; }, []); The update method repeatedly calls $request->get() That method calls $request->get() ten times. Many of those could be called in a loop - e.g. which iterates over the fields from $messages. As I explained in this answer a subclass of form request could be created to encapsulate all of the validation logic and simplify the setting of validated fields in the model. If such a form request was made, then most all of those lines calling $request()->get() could be replaced with a single call to $request->validated() using the update() method. Do you see any security issues? Can any user update update the settings? If not, then perhaps a role should be checked on the user. Another benefit of form requests is that they can help with authorization - e.g. the authorize() method can be defined and have it return false for any user that should not be able to submit such a request.
{ "domain": "codereview.stackexchange", "id": 44393, "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": "php, validation, laravel", "url": null }
beginner, physics, fortran Title: Simulating the orbits of the Earth, Moon and Sun together in Fortran Question: This has been racking my brain for hours now. I will try to explain as much as I can. I'm aware this code is horrendously ungraceful, but I'm new to Fortran and making things more efficient is not easy for me. I am trying to simulate the celestial motion I've specified in the title. I am going to have (before moving to the co-moving frame) the Sun at the origin of coordinates, the Earth at x = 149597870d+3meters away (the mean distance from the Sun to the Earth I believe), y = 0. For the moon, I'm having it at the distance from the Moon to Earth (384400d+3 meters) plus the distance from the Earth to the Sun, so that we essentially have a situation where all planets are situated on the y = 0 line, with the Earth an astronomical unit away in the x-axis, and the moon a further distance away equal to the distance between the Earth and the moon. I've attempted to illustrate the situation, as well as the free body diagrams, in the following two images. From there, I've defined a 12 dimensional array, sol, which holds the x and y positions and velocities of each body such that sol = (x1,y1,x2,y2,x3,y3,dx1/dt,dy1/dt,dx2/dt,dy2/dt,dx3/dt,dy3/dt). I then initialized the array: the sun will have no initial velocities, the Earth will have an initial y velocity equal to its mean orbital velocity around the sun with no initial x velocity, and the moon will have an initial y velocity equal to its mean orbital velocity around the earth and no initial x velocity. inits(1:2) = 0d0 inits(3) = distE inits(4) = 0d0 inits(5) = distE+distM inits(6:9) = 0d0 inits(10) = vE inits(11) = 0d0 inits(12) = vM sol = inits I then attempt to bring everything to a co-moving frame based off the following equation:
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran I then attempt to bring everything to a co-moving frame based off the following equation: mf = 0 Mtot = mSun + mEarth + mMoon mf(1:2) = mSun/(Mtot) * mf(1:2) + mEarth/(Mtot) * sol(3:4) + mMoon/(Mtot) * sol(5:6) mf(3:4) = mEarth/(Mtot) * mf(3:4) + mSun/(Mtot) * sol(1:2) + mMoon/(Mtot) * sol(5:6) mf(5:6) = mMoon/(Mtot) * mf(5:6) + mSun/(Mtot) * sol(1:2) + mEarth/(Mtot) * sol(3:4) mf(7:8) = mSun/(Mtot) * mf(7:8) + mEarth/(Mtot) * sol(9:10) + mMoon/(Mtot) * sol(11:12) mf(9:10) = mEarth/(Mtot) * mf(9:10) + mSun/(Mtot) * sol(7:8) + mMoon/(Mtot) * sol(11:12) mf(11:12) = mMoon/(Mtot) * mf(11:12) + mSun/(Mtot) * sol(7:8) + mEarth/(Mtot) * sol(9:10) sol = inits - mf I then use a varied timestep for my calculations based off the equation: real*8 function fun_tstepq8(arr) use importants implicit none real*8,dimension(12), intent(in) :: arr real*8::alp,part1,part2,part3,distEtoS,distEtoM,distStoM real*8 :: distEdottoMdot,distEdottoSdot,distSdottoMdot alp = 1d-4 distEtoS = SQRT((sol(3)-sol(1))**2 + (sol(4)-sol(2))**2)**3 distEtoM = SQRT((sol(5)-sol(3))**2 + (sol(6)-sol(4))**2)**3 distStoM = SQRT((sol(5)-sol(1))**2 + (sol(6)-sol(2))**2)**3 distEdottoSdot = SQRT((sol(9)-sol(7))**2 + (sol(10)-sol(8))**2) distEdottoMdot = SQRT((sol(11)-sol(9))**2 + (sol(12)-sol(10))**2) distSdottoMdot = SQRT((sol(11)-sol(7))**2 + (sol(12)-sol(8))**2) part1= distEtoS/distEdottoSdot part2= distEtoM/distEdottoMdot part3= distStoM/distSdottoMdot fun_tstepq8 = alp * MIN(part1,part2,part3) end function
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran Putting that all together, I use a Forward Euler method and calculate the function f from y0 = y0 + hf using the subroutine: subroutine q8RHS(sol) use importants, ONLY: mSun, mEarth,mMoon, F, G implicit none real*8 :: distEtoS,distEtoM,distStoM real*8,dimension(12) :: sol integer :: i distEtoS = SQRT((sol(3)-sol(1))**2 + (sol(4)-sol(2))**2)**3 distEtoM = SQRT((sol(5)-sol(3))**2 + (sol(6)-sol(4))**2)**3 distStoM = SQRT((sol(5)-sol(1))**2 + (sol(6)-sol(2))**2)**3 do i = 1,12 if (i < 7) then F(i) = sol(i+6) elseif (i < 9) then F(i) = G * (mEarth * (sol(i-4) - sol(i-6))/distEtoS + mMoon * (sol(i-2) - sol(i-6))/distStoM) elseif (i < 11) then F(i) = G * mSun * (sol(i-6) - sol(i-8))/distEtoS - mMoon * G *(sol(i-4) - sol(i-6))/distEtoM else F(i) = -G * mSun * (sol(i-6) - sol(i-10))/distStoM -G*mEarth * (sol(i-6) - sol(i-8))/distEtoM endif enddo end subroutine In terms of deriving the q8RHS subroutine, I started with: And then this is my work to derive mechanics for one of the planets. Note I use the Euler method here, and derive suitable functions to use for f(x,t) = dx/dt form needed for the Euler method. Note I couldn't use the denominator I derived as at some point x2 = x1 in my simulation if I use this, hence the issue I talked about with the timestep getting tiny enough where the simulation grinds to a halt.
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran Overall, my program looks like this: module importants implicit none integer,parameter::Ndim = 3 integer:: N,N2 real*8, parameter :: G = 6.67408e-11 integer,parameter :: Nbodies = 2 integer::specific_Nbodies = 2*Nbodies real*8,dimension(12) :: inits,sol,F real*8 :: d_j = 778.547200d+9 real*8 :: v_j = 13.1d+3 integer :: rank = Nbodies * Ndim * 2 real*8 :: mSun = 1.989d+30 real*8, dimension(12) :: mf real*8 :: mJup = 1.89819d+27 real*8, parameter :: pi= DACOS(-1.d0) real*8 :: a,P,FF real*8 :: pJ = 374080032d0 real*8, dimension(2) :: QEcompare,QLcompare,QPcompare real*8 :: mEarth = 5.9722d+24 real*8 :: mMoon = 7.34767309d+22 real*8 :: distE = 149597870d+3 ! Dist from sun to earth real*8 :: distM = 384400d+3 ! Dist from earth to moon real*8 :: distMS = 152d+9 real*8 :: vE = 29.78d+3 real*8 :: vM = 1.022d+3 end module program exercise3 use importants implicit none print*,'two' !call solve() !call q3() !call q4() !call q5() !call q5circ() !call q6ecc() !call q6pt2() !call q7() call q8() end program
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran subroutine q8() use importants implicit none !real*8,external :: Epot,Ekin, L real*8,external :: fun_tstepq8 real*8 :: tstep,time,tracker,Mtot,t !real*8,dimension(2) :: Etot,L1,L2 !real*8, dimension(3,2) :: r2 integer :: j,i print*, 'Starting Q8. -------------------------------------------------------' inits(1:2) = 0d0 inits(3) = distE inits(4) = 0d0 inits(5) = distE+distM inits(6:9) = 0d0 inits(10) = vE inits(11) = 0d0 inits(12) = vM sol = inits mf = 0 Mtot = mSun + mEarth + mMoon mf(1:2) = mSun/(Mtot) * mf(1:2) + mEarth/(Mtot) * sol(3:4) + mMoon/(Mtot) * sol(5:6) mf(3:4) = mEarth/(Mtot) * mf(3:4) + mSun/(Mtot) * sol(1:2) + mMoon/(Mtot) * sol(5:6) mf(5:6) = mMoon/(Mtot) * mf(5:6) + mSun/(Mtot) * sol(1:2) + mEarth/(Mtot) * sol(3:4) mf(7:8) = mSun/(Mtot) * mf(7:8) + mEarth/(Mtot) * sol(9:10) + mMoon/(Mtot) * sol(11:12) mf(9:10) = mEarth/(Mtot) * mf(9:10) + mSun/(Mtot) * sol(7:8) + mMoon/(Mtot) * sol(11:12) mf(11:12) = mMoon/(Mtot) * mf(11:12) + mSun/(Mtot) * sol(7:8) + mEarth/(Mtot) * sol(9:10) sol = inits - mf print*, '---------------------------------------------------------------------' print*, 'Beginning fixed t timestep. ' t = 0d0 P = 3.154d+7 time=0 tracker=0 print*, 'P understood as :', P open(70,file='q8.dat') time=0 tracker=0 write(70,*) sol(1),sol(2),sol(3),sol(4),sol(5),sol(6) do while(time.le.P) call q8RHS(sol) tstep=fun_tstepq8(sol) time=time+tstep tracker=tracker+1 print*, tstep do i=1,12 sol(i) = sol(i) + tstep * F(i) enddo write(70,*) sol(1),sol(2),sol(3),sol(4),sol(5),sol(6) enddo end subroutine
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran I know there are a bunch of variables that are not used here, but were used for other subroutines, as this is a bit, ungainly beast of a program I've made. I just know that the previous subroutines and all of their related variables have run fine, and I have no issue with them and they don't interfere with the code I have in mind. The motions of the bodies look like this: I'm not sure if the Earth and Moon are behaving properly with regards to each other. Zooming in, the moon does seem to oscillate to the left and right of the Sun's trajectory, so if the z axis was viewable this might make more sense, but it also might not. The behavior above of the Moon's path moving to the left and right of the Earth's repeats constantly, but I'm not sure if this is still necessarily physically sensible. Answer: This question is an oldie but goodie. Nice work! It really deserves some love. An edit bumped it recently to the front page, and that got me interested in how I’d refactor the program. The Modern Conveniences You declare your variables in the style of Fortran-77, which is fine. Twenty-first-century Fortran has some new syntax that will improve your quality of life by letting you write structured code instead of labels, simplify your array declarations, and (in theory) have full standardized portability for your code. For example, the declaration of the masses of the celestial bodies, currently three mutable variables, might become the array: real(real64),parameter :: masses(nBodies) = [ 1.989d+30, 5.9722d+24, 7.34767309d+22 ]
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran Don’t Let Anything Modify Your Data that Doesn’t Need to The more places in your code can modify a piece of data, the harder it is to figure out where a modification came from. The compiler will also be able to optimize better, especially when compiling a loop that calls a function or subroutine, if it knows nothing could have changed a variable behind its back. One corollary of this is that you should declare parameter data wherever you can. The code currently does this for some vonstants, such as G, but not others. Another aspect of this is that it makes sense to factor your program into small functions and subroutines that each declare only the local data they need. There are fewer things to keep track of and fewer variables you could mix up by mistake. Use Multidimensional Arrays Currently, you do most of your work on flat arrays that you access by index, with expressions such as: mf(7:8) = mSun/(Mtot) * mf(7:8) + mEarth/(Mtot) * sol(9:10) + mMoon/(Mtot) * sol(11:12) This is confusing. You already declare Ndim and Nbodies as integer parameters. You could instead declare your arrays as, for example real(real64) :: positions(nBodies,nDim) real(real64) :: velocities(nBodies,nDim)
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran If you then remember that each column holds the data for a celestial body, in order of decreasing mass, and each row holds the coordinates for an individual body, it becomes easy to see that velocity(i,1) is the x-coordinate of celestial body i. You can still define parameter constants for the indices of the sun, earth and moon if you like. (But I advise hardcoding those into your program logic; I’ll come back to this later.) Use Array Operations These are not only very easy to write and to read, they optimize very well. Let’s suppose we have multidimensional arrays holding the component-wise positions, velocities and accelerations of each vector. A simple subroutine, using only first-year calculus, to update these arrays, would look like this: subroutine update_system( dt, ps, vs, as ) use importants implicit none real(real64) ,intent(in) :: dt real(real64) :: ps(nBodies,nDim) real(real64) :: vs(nBodies,nDim) real(real64),intent(in) :: as(nBodies,nDim) ps = ps + dt*(vs + dt*0.5*as) vs = vs + dt*as end subroutine
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran ps = ps + dt*(vs + dt*0.5*as) vs = vs + dt*as end subroutine On a modern compiler with optimizations enabled (such as ICX), this will auto-vectorize.. Make Your Algorithm More General, if Possible Currently, you’re hardcoding a set of formulas that assume you are working with only the sun, earth and moon, and flat arrays mf and sol laid out in a particular order. Now, a lot of the time, when I say something like, “You might later want to switch between the two-dimensional and three-dimensional cases based on the inclination of the orbits from the ecliptic, or work with a different number of bodies,” you should say, YAGNI: You Ain’t Gonna Need It. Here, though, I think the code becomes a lot more readable and maintainable if you roll the algorithm up into a loop that works for any number of bodies. Here’s a very simple function—using only high-school physics—that calculates each component of acceleration for each body from the current positions and masses of the bodies. All inputs and outputs are arrays with dimension (nBodies, nDim). The elementary round-trip polar conversion only supports two dimensions, but it allows an arbitrary number of bodies, without assumptions about their names or ordering. pure function accelerations(ps) result(as) use importants implicit none real(real64),intent(in) :: ps(nBodies,nDim) real(real64) :: as(nBodies,nDim) real(real64) :: rsquared real(real64) :: angles(nBodies,nBodies) real(real64) :: forces(nBodies,nBodies) integer :: i, j real(real64) :: components(nDim) ! Not needed in theory, but makes the behavior more deterministic. do i = 1, nBodies do j = 1, nBodies angles(i,j) = 0.0 forces(i,j) = 0.0 end do end do
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran ! For all i > j, set forces(i,j) to the gravitational force exerted on ! body i by body j, and angles(i,j) to the direction of that vector. do i = 1, nBodies do j = 1, i-1 rsquared = (ps(j,1)-ps(i,1))**2 + (ps(j,2)-ps(i,2))**2 angles(i,j) = atan2(ps(j,2)-ps(i,2), ps(j,1)-ps(i,1)) forces(i,j) = G*masses(i)*masses(j)/rsquared end do end do do i = 1, nBodies components = [0.0, 0.0] do j = 1, i-1 components(1) = components(1) + (forces(i,j) * cos(angles(i,j))) components(2) = components(2) + (forces(i,j) * sin(angles(i,j))) end do ! Take advantage of the symmetry of the problem: the force exerted by j ! on i is equal and opposite to the force exerted by i on j. do j = i+1, nBodies components(1) = components(1) - (forces(j,i) * cos(angles(j,i))) components(2) = components(2) - (forces(j,i) * sin(angles(j,i))) end do as(i,1) = components(1) / masses(i) as(i,2) = components(2) / masses(i) end do end function
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran I make no claim that this is a good implementation. The error is much higher than with a Runge–Kutta method like the one you used. It’s also very plausible there’s a bug in there that I haven’t caught. It seems to behave reasonably with real-world initial conditions for about a month. Document the Code You currently have short, often-cryptic names, such as sol(9:10), and very few comments. This makes it very hard for someone else (or myself a year or two later when I’ve done that) to figure out what the code is doing or whether you’re actually using the right slices of sol and mf. It would be better to put at least some of thee explanation of your algorithm that you currently have as scans of your handwritten notes in the post, as comments in the code itself, or at minimum a URL. A Minor Issue on Types You declare most of your variables REAL*8. I don’t know of any compiler in actual use that rejects that but accepts the formal standard, but in principle, the language defines the constant real64 in the module ISO_FORTRAN_ENV as the kind of a 64-bit REAL. I therefore write real(real64), but many programmers abbreviate it. Aliasing this to something like real(realKind) instead would make it easier to change the precision. Putting it All Together Here’s what I finally came up with. module importants use iso_fortran_env, only:real64 implicit none integer,parameter :: nDim = 2 ! All columns of bodies are in the order [Sun, Earth, Moon]. integer,parameter :: nBodies = 3 real(real64),parameter :: masses(nBodies) = [ 1.989d+30, 5.9722d+24, 7.34767309d+22 ] real(real64),parameter :: G = 6.67408e-11 end module module interfaces interface subroutine update_system( dt, ps, vs, as ) use importants real(real64),intent(in) :: dt real(real64) :: ps(nBodies,nDim) real(real64) :: vs(nBodies,nDim) real(real64),intent(in) :: as(nBodies,nDim) end subroutine
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran pure function accelerations(ps) result(as) use importants real(real64),intent(in) :: ps(nBodies,nDim) real(real64) :: as(nBodies,nDim) end function end interface end module ! Given a time increment and component-wise position, velocity and ! acceleration vectors of the same shape, advances the position and velocity. subroutine update_system( dt, ps, vs, as ) use importants implicit none real(real64) ,intent(in) :: dt real(real64) :: ps(nBodies,nDim) real(real64) :: vs(nBodies,nDim) real(real64),intent(in) :: as(nBodies,nDim) ps = ps + dt*(vs + dt*0.5*as) vs = vs + dt*as end subroutine ! Returns the component-wise acceleration based on the arrays of the coord- ! inates and masses of the bodies. pure function accelerations(ps) result(as) use importants implicit none real(real64),intent(in) :: ps(nBodies,nDim) real(real64) :: as(nBodies,nDim) real(real64) :: rsquared real(real64) :: angles(nBodies,nBodies) real(real64) :: forces(nBodies,nBodies) integer :: i, j real(real64) :: components(nDim) ! Not needed in theory, but makes the behavior more deterministic. do i = 1, nBodies do j = 1, nBodies angles(i,j) = 0.0 forces(i,j) = 0.0 end do end do ! For all i > j, set forces(i,j) to the gravitational force exerted on ! body i by body j, and angles(i,j) to the direction of that vector. do i = 1, nBodies do j = 1, i-1 rsquared = (ps(j,1)-ps(i,1))**2 + (ps(j,2)-ps(i,2))**2 angles(i,j) = atan2(ps(j,2)-ps(i,2), ps(j,1)-ps(i,1)) forces(i,j) = G*masses(i)*masses(j)/rsquared end do end do do i = 1, nBodies components = [0.0, 0.0] do j = 1, i-1 components(1) = components(1) + (forces(i,j) * cos(angles(i,j))) components(2) = components(2) + (forces(i,j) * sin(angles(i,j))) end do
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
beginner, physics, fortran ! Take advantage of the symmetry of the problem: the force exerted by j ! on i is equal and opposite to the force exerted by i on j. do j = i+1, nBodies components(1) = components(1) - (forces(j,i) * cos(angles(j,i))) components(2) = components(2) - (forces(j,i) * sin(angles(j,i))) end do as(i,1) = components(1) / masses(i) as(i,2) = components(2) / masses(i) end do end function program threebody use importants use interfaces implicit none real(real64),parameter :: tn = 60.d0*60*24*28 real(real64),parameter :: deltat = 1 real(real64) :: t = 0 real(real64) :: positions(nBodies,nDim) real(real64) :: velocities(nBodies,nDim) ! Set the initial conditions in column-major order. positions = reshape(([0.d0, 1.47095d+11, 1.47095d+11 + 4.055d+8, 0.d0, 0.d0, 0.d0]), shape(positions)) velocities = reshape(([0.d0, 0.d0, 0.d0, 0.d0, 2.978d+3, 2.978d+3 + 970.d0]), shape(velocities)) print *, positions(1:1, :), positions(2:2, :), positions(3:3, :) print *, sqrt((positions(2,1)-positions(1,1))**2 + (positions(2,2)-positions(1,2))**2), sqrt((positions(3,1)-positions(2,1))**2 + (positions(3,2)-positions(2,2))**2) do while (t < tn) call update_system( deltat, positions, velocities, accelerations(positions) ) !print *, positions(1:1, :), positions(2:2, :), positions(3:3, :) t = t + deltat end do print *, positions(1:1, :), positions(2:2, :), positions(3:3, :) print *, sqrt((positions(2,1)-positions(1,1))**2 + (positions(2,2)-positions(1,2))**2), sqrt((positions(3,1)-positions(2,1))**2 + (positions(3,2)-positions(2,2))**2) end program I’m certain you can improve on the algorithm. The general structure here, and in particular using arrays with the same intuitive shape, and passing them to and returning them from functions, is a strategy you and others can use.
{ "domain": "codereview.stackexchange", "id": 44394, "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": "beginner, physics, fortran", "url": null }
performance, algorithm, rust, steganography Title: Text to image steganography Question: This simple implementation hides text secrets (S) in images by manipulating the least significant bits (lsb) on Pixels. How it works When encrypting I take a three pixel "chunk" for each byte. Each bit of the byte is hidden in the RGB (lsb) values of the pixels. The last blue value in the last pixel of each chunk is an exception, it stores a termination flag, more characters need to be encrypted sets this flag to 1 otherwise to 0. Decryption reverts the above method, by constructing a byte from each three pixel chunk and putting it back to a string. Implementation The encrypt function: /// Hides a secret string in the target image. /// /// # Arguments /// /// * `src_img` - Target image the secret will be written to. /// * `secret` - Secret string which will be hidden in the target image. /// pub fn encode_secret(src_img: &mut DynamicImage, secret: String) { let secret_bytes = secret.into_bytes(); // Iterate over each byte in the secret for (byte_idx, byte) in secret_bytes.iter().enumerate() { // Index of the first (of three) Pixel let n_rgb = byte_idx as u32 * 3; // Get bits for current byte let bit_buffer = byte.to_bit_buffer(); // Iterate over chunks of three bits for (bit_chunk_idx, bit_chunk) in bit_buffer.chunks(3).enumerate() { // Calculate (image) row and column of the current pixel let n: u32 = n_rgb + bit_chunk_idx as u32; let col_idx = n / src_img.width(); let row_idx = n % src_img.width(); // Replace the least signbificant bits for R and G values of the Pixel. let o_pixel = src_img.get_pixel(row_idx, col_idx); let r_out = o_pixel[0].set_lsb(bit_chunk[0]); let g_out = o_pixel[1].set_lsb(bit_chunk[1]);
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
performance, algorithm, rust, steganography let b_out: u8 = if bit_chunk.len() > 2 { // More than 2 bits in chunk, not the last chunk. We expect more chunks to come o_pixel[2].set_lsb(bit_chunk[2]) } else if byte_idx + 1 == secret_bytes.len() { // This is the last secret char, we set the last byte to be even. o_pixel[2].set_lsb(false) } else { o_pixel[2].set_lsb(true) // Last chunk but not the last secret char, we set the last byte to be odd. }; // Write pixel back to image src_img.put_pixel( row_idx, col_idx, image::Rgba([r_out, g_out, b_out, o_pixel[3]]), ); } } } The decrypt function: /// Returns a secret string retrieved from the provided image if it exists. /// /// # Arguments /// /// * `img` - Image from which a secret will be retrieved. /// pub fn decode_secret(img: &DynamicImage) -> Option<String> { let mut result: String = String::new(); let mut byte_array = vec![]; let pixels: Vec<_> = img.pixels().collect(); // Iterate chunks of three pixels for pixel_chunk in pixels.chunks(3) { let mut byte: u8 = 0; // Construct a byte from three pixels byte = byte.set_bit(0, pixel_chunk[0].2 .0[0].get_lsb()); byte = byte.set_bit(1, pixel_chunk[0].2 .0[1].get_lsb()); byte = byte.set_bit(2, pixel_chunk[0].2 .0[2].get_lsb()); byte = byte.set_bit(3, pixel_chunk[1].2 .0[0].get_lsb()); byte = byte.set_bit(4, pixel_chunk[1].2 .0[1].get_lsb()); byte = byte.set_bit(5, pixel_chunk[1].2 .0[2].get_lsb()); byte = byte.set_bit(6, pixel_chunk[2].2 .0[0].get_lsb()); byte = byte.set_bit(7, pixel_chunk[2].2 .0[1].get_lsb()); byte_array.push(byte);
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
performance, algorithm, rust, steganography byte_array.push(byte); // Last byte (blue) value of the last pixel in the chunk is even. This is the termination flag. if pixel_chunk[2].2 .0[2] % 2 == 0 { break; } } // Try convert the byte array to (secret) string match String::from_utf8(byte_array) { Ok(res) => result = format!("{}{}", result, res), Err(_err) => return None, } if result.is_empty() { return None; } Some(result) } For the bit operations I use some helper functions: pub trait BitBuffer { fn to_bit_buffer(&self) -> Vec<bool>; } impl BitBuffer for u8 { /// Returns a vector of bools representing the single bits of self. /// fn to_bit_buffer(&self) -> Vec<bool> { let mut result = vec![]; for i in 0..=7 { result.push(self.get_bit(i).unwrap()); } result } } pub trait BitOps { /// Sets the least significant bit of a number according to the passed value. /// fn set_lsb(&self, value: bool) -> Self; /// Returns the bit on the specified position. /// fn get_bit(&self, n: u8) -> Option<bool>; /// Sets a bit on the specified position. /// fn set_bit(&self, n: usize, value: bool) -> u8; /// Returns the least significant bit. /// fn get_lsb(&self) -> bool; } impl BitOps for u8 { fn get_bit(&self, n: u8) -> Option<bool> { if n > 7 { return None; } let result = *self >> n & 1; if result == 1 { return Some(true); } else if result == 0 { return Some(false); } panic!(); } fn set_bit(&self, n: usize, value: bool) -> u8 { let mut result = *self; if n > 7 { panic!(); } if value { result |= 1 << n; } else { result &= !(1 << n); } result }
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
performance, algorithm, rust, steganography fn set_lsb(&self, value: bool) -> u8 { let mut result = *self; if value { result |= 0b0000_0001; return result; } result &= 0b1111_1110; result } fn get_lsb(&self) -> bool { self % 2 != 0 } } In order to run the above implementation you will need the image crate in your project. Load an image and pass the required parameters to the functions above. Because of the nature of the implementation, your image will need to have a pixel amount which is at least three times the character amount. What am I (not) looking for in a review It is not my goal to implement a highly sophisticated algorithm, just a simple one. Am I doing things the rustacean way? Especially in the encode_secret function I have a feeling, that I should/could have used more iter magic. Still after browsing the docs I ended up using nested loops. How is the overall code style? Is there any room for performance optimization? Answer: There might be more crustacean ways to express this cast: let n_rgb = byte_idx as u32 * 3; Giving an explicit type with n_rgb: u32 = ... , or even just writing the factor 3 first, may improve the readability a bit. Thank you for the valuable comment about indexing the first (of three) pixels. Consider deleting redundant comments such as // Iterate over each byte in the secret ... // Get bits for current byte Your code is wonderfully clear already. We use comments to explain why, and code to explain what is happening. I feel the code that assigns r_out and g_out is fine the way it is. But a purist might ask for MANIFEST_CONSTANTS indicating that we're indexing the red and green pixels, and then the very helpful comment would become redundant.
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
performance, algorithm, rust, steganography Consider replacing the outer for loop with a zip that also iterates through secret bits. The function is not yet "too" long, but nonetheless you might push some of its logic into a write_lsb(secret_byte, bit_chunk) helper. Suppose we hid a short message in a very large image. When recovering the message, does img.pixels().collect() eagerly do a lot more work than necessary? We would prefer to lazily evaluate, so pixels at the end are never even touched. The decode for loop offers the perfect opportunity to introduce a construct_byte(pixel_chunk) helper. And if the helper could produce the sequence of indexes being visited, a single loop could keep assigning byte * 2 + ... lsb. This is a slightly unusual expression: if pixel_chunk[2].2 .0[2] % 2 == 0 { There's many ways to phrase it. But having adopted an idiom, stick with it. Here, .get_lsb() is how you've been recovering those bits, so it would be appropriate to also use it here, showing parallel structure. I am reading the get_bit helper. Sorry, I don't understand why it's useful for the return value to be optional. Shouldn't we throw fatal error if caller offers n too large, as we see in set_bit ? Also, given *self >> n, I am sad that we can't just mask against 1 and that's the end of it. I am reading set_bit. Consider renaming it to assign_bit, as "set" / "clear" in this context suggests assigning 1 / 0. Similarly for assign_lsb. The logic is perfectly clear. It does frustrate Intel's branch prediction. If you ever profile this code and find that you want it to go faster, consider using a branchless expression. Simplest approach is to unconditionally clear, then merge in the bit: let mask = !(1 << n); result &= mask; result |= value << n; Similarly for the lsb helper: result &= 0b1111_1110; result |= value; You might instead obtain these helpers from a crate. If you ever want to shoot for a more sophisticated algorithm:
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
performance, algorithm, rust, steganography If you ever want to shoot for a more sophisticated algorithm: Consider pre-processing secret with checksum or compression, so you can verify that it round tripped correctly. Consider searching for a "good" image location to alter, as adding low-bit noise to a wash or constant background is more apparent than adding it to images of vegetation or people. Overall? This code is maintainable by others, and it achieves its design goals. LGTM. Ship it!
{ "domain": "codereview.stackexchange", "id": 44395, "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, algorithm, rust, steganography", "url": null }
vba, excel Title: Copy and Paste Macro Containing For Loop Question: The macro below loops through column E in Sheet2 and finds matches in column Z of Sheet1. If a match is found it copies the value on the same row contained in column AA. It works ok but hangs when it runs. There are usually a few thousand values in column E but less than 30 in column Z. I've run it on a few PCs with decent specs but always have the same issue. Are there any ways to optimise it? Example Data: Sheet1, column Z: Z 42039505 40642035 40191591 23239795 38593074 Sheet1, column AA: AA 0 1 R E 8 Sheet2, column E E 42039505 40642035 40191591 23239795 38593074 42039505 40642035 40191591 23239795 38593074 42039505 40642035 40191591 23239795 38593074 Sub CopyResult() Dim WS1 As Worksheet Dim WS2 As Worksheet Dim Rng1 As Range Dim Rng2 As Range Dim c As Range Application.ScreenUpdating = False Set WS1 = ThisWorkbook.Sheets("Sheet2") Set WS2 = ThisWorkbook.Sheets("Sheet1") Set Rng1 = WS1.Range(WS1.Range("E2"), WS1.Range("E" & Rows.Count).End(xlUp)) Set Rng2 = WS2.Range(WS2.Range("Z5"), WS2.Range("Z" & Rows.Count).End(xlUp)) For Each c In Rng1 On Error Resume Next Rng2.Find(What:=c).Offset(, 1).Copy Destination:=c.Offset(, 19) Err.Clear Next c Set WS1 = Nothing Set WS2 = Nothing Set Rng1 = Nothing Set Rng2 = Nothing Application.ScreenUpdating = True End Sub Answer: A Classic VBA Lookup Pros First of all, congratulations, the code compiles which could indicate that you understand the importance of Option Explicit. Mostly you understand the importance of qualifying objects which includes qualifying the worksheets which you do with ThisWorkbook, the workbook containing this code. You are correctly looping through column E of the destination worksheet Sheet2 that has a ton of duplicates, to lookup values in column Z of the source worksheet Sheet1 that should have unique (distinct) values. You are not lazy to use Next without the control variable c. Cons
{ "domain": "codereview.stackexchange", "id": 44396, "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 Cons Using variables like WS1 and WS2 is bad practice i.e. already in a day or two, it won't be so easy to determine which one is the source and which one the destination worksheet not to mention the additional confusion you introduced by using WS1 for Sheet2 and WS2 for Sheet1. There is no room for On Error Resume Next when using the Find method. Also, the prescribed way to use it is: On Error Resume Next Whatever On Error Goto 0 Adding another variable and testing it against Nothing is the way to go. Also, copying by assignment is faster then using the Copy method. Dim sCell As Range For Each c In Rng1.Cells Set sCell = Rng2.Find(...) If Not sCell Is Nothing Then c.Offset(...).Value = sCell.Offset(...).Value End If Next What are you looping through? Through cells. So use ... In Rng1.Cells. Using offset in this way is bad practice. Sure, everyone immediately knows the column adjacent to the right of column Z but I don't think that anyone will instantly know that 19 columns to the right of column E is column X. The Find method has many more arguments so you should utilize them, in this case especially the 4th argument, the LookAt argument with the parameter xlWhole or xlPart which is saved each time the Find method is used. The series of lines Set Whatever = Nothing are totally redundant and they gotta go. Nit Picking You are not using constants. You have put the variable declarations at the beginning, far from the action. I prefer to have them closer, and since there will be more than a dozen of them in my code, I wouldn't want that wall of variables at the beginning of my code. I prefer to use a variable for the workbook even if it is ThisWorkbook so in the case I would want to use a different workbook, I would have to change it only in one place. I would put Application.ScreenUpdating = False right before the loop indicating that this is where the action begins. You haven't qualified the Rows in Rows.Count e.g.: WS1.Rows.Count.
{ "domain": "codereview.stackexchange", "id": 44396, "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 Status The bottleneck is that you're looping through tens of thousands of cells in the destination lookup column. You can't turn off enough settings for it to not take forever to finish. The use of Application.Match instead of the Find method would increase efficiency a bit but I won't go down that road since it won't make enough of a difference. The Plan In the source worksheet (Sheet1), write the values from the lookup column (Z) and the corresponding values, the values in the same row, from the return column (AA) to arrays, loop through the arrays and write the lookup values to the keys, and the return values to the items of a dictionary. Erase the arrays. In the destination worksheet (Sheet2), write the values from the lookup column (E) to another array and use yet another array of the same size to write the matches to it. Then write the matches to the return column (X). Use a message box to not wonder if the code has run or not since it is 'lightning' fast. The Main Procedure Option Explicit Sub LookupData() Const SRC_NAME As String = "Sheet1" Const SRC_FIRST_LOOKUP_CELL As String = "Z5" Const SRC_RETURN_COL As String = "AA" Const DST_NAME As String = "Sheet2" Const DST_FIRST_LOOKUP_CELL As String = "E2" Const DST_RETURN_COL As String = "X"
{ "domain": "codereview.stackexchange", "id": 44396, "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 Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code Dim sws As Worksheet: Set sws = wb.Sheets(SRC_NAME) ' The `Find` or the `End` method would fail if the worksheet were filtered. If sws.FilterMode Then sws.ShowAllData Dim sfCell As Range: Set sfCell = sws.Range(SRC_FIRST_LOOKUP_CELL) Dim slrg As Range: Set slrg = RefColumn(sfCell) If slrg Is Nothing Then Exit Sub ' no data in column range Dim slData(): slData = GetSingleColumnRange(slrg) Dim srrg As Range: Set srrg = slrg.EntireRow.Columns(SRC_RETURN_COL) Dim srData(): srData = GetSingleColumnRange(srrg) Dim dict As Object: Set dict = DictTwoSingleColumns(slData, srData) If dict Is Nothing Then Exit Sub ' only error values and blanks Erase slData Erase srData Dim dws As Worksheet: Set dws = wb.Sheets(DST_NAME) ' The `Find` or the `End` method would fail if the worksheet were filtered. If dws.FilterMode Then dws.ShowAllData Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_LOOKUP_CELL) Dim dlrg As Range: Set dlrg = RefColumn(dfCell) If dlrg Is Nothing Then Exit Sub ' no data in column range Dim dlData(): dlData = GetSingleColumnRange(dlrg) Dim drData(): drData = GetLookedUpColumnInDict(dlData, dict) Dim drrg As Range: Set drrg = dlrg.EntireRow.Columns(DST_RETURN_COL) drrg.Value = drData MsgBox "Data looked up.", vbInformation End Sub The Help Note that the last two procedures aren't as flexible as the first two i.e. their parameters are restricted to 2D single-column column arrays while the last is additionally restricted to a one-based array. The keys of the dictionary are values converted to strings and in the last procedure, the lookup values are converted to strings.
{ "domain": "codereview.stackexchange", "id": 44396, "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 Reference a Single Column Range '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Purpose: References the range from a given cell to the bottom-most ' non-empty cell in same column. ' Remarks: It will fail if the worksheet is filtered. ' It will not fail if the worksheet has hidden rows or columns. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function RefColumn( _ ByVal FirstCell As Range) _ As Range Dim rg As Range With FirstCell.Cells(1) Set rg = .Resize(.Worksheet.Rows.Count - .Row + 1) _ .Find("*", , xlFormulas, , , xlPrevious) If Not rg Is Nothing Then Set rg = .Resize(rg.Row - .Row + 1) End With If Not rg Is Nothing Then Set RefColumn = rg End Function Single Column Range To Array '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Purpose: Returns the values of a given column of a range ' in a 2D one-based single-column array. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GetSingleColumnRange( _ ByVal rg As Range, _ Optional ByVal ColumnNumber As Long = 1) _ As Variant If ColumnNumber < 1 Then Exit Function If ColumnNumber > rg.Columns.Count Then Exit Function Dim Data() With rg.Areas(1).Columns(ColumnNumber) Dim rCount As Long: rCount = .Rows.Count If rCount = 1 Then ReDim Data(1 To 1, 1 To 1): Data(1, 1) = .Value Else Data = .Value End If End With GetSingleColumnRange = Data End Function
{ "domain": "codereview.stackexchange", "id": 44396, "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 Source Lookup and Return Values To Dictionary '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Purpose: Returns the unique values from a given 2D one-based ' single-column array, converted to strings, in the 'keys', ' and the corresponding values, the values in the same rows ' of another given same sized array, not converted to strings, ' in the 'items' of a dictionary. ' Remarks: Error values and blanks are excluded. '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function DictTwoSingleColumns( _ DataKeys() As Variant, _ DataItems() As Variant) _ As Object Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary") dict.CompareMode = vbTextCompare ' case-insensitive Dim Key As Variant Dim r As Long For r = LBound(DataKeys, 1) To UBound(DataKeys, 1) Key = DataKeys(r, 1) If Not IsError(Key) Then ' exclude error values If Len(CStr(Key)) > 0 Then ' exclude blanks dict(CStr(Key)) = DataItems(r, 1) End If End If Next r If dict.Count = 0 Then Exit Function ' only error values and blanks Set DictTwoSingleColumns = dict End Function
{ "domain": "codereview.stackexchange", "id": 44396, "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 End Function Return Values From Dictionary To Array '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ' Purpose: From a given dictionary, returns the corresponding looked up ' values, converted to strings, of a given 2D one-based ' single-column array, in another same-sized array. ' Remarks: The 'keys' of the dictionary need also to be strings while ' the 'items' can be simple variants (not objects or arrays). '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Function GetLookedUpColumnInDict( _ Data() As Variant, _ ByVal dict As Object) _ As Variant() Dim dData(): ReDim dData(1 To UBound(Data, 1), 1 To 1) Dim r As Long, rString As String For r = 1 To UBound(Data, 1) rString = CStr(Data(r, 1)) If Len(rString) > 0 Then If dict.Exists(rString) Then dData(r, 1) = dict(rString) End If Next r GetLookedUpColumnInDict = dData End Function
{ "domain": "codereview.stackexchange", "id": 44396, "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 }
c++, game, console, makefile Title: Command-line Tower of Hanoi game Question: This code has been revised. See (Rev. 2) Command-line Tower of Hanoi game Compiled with g++ 9.4.0. makefile included. Any criticism welcome. main.cpp /* Author: Jared Thomas Date: Tuesday, August 4, 2020 */ #include <iostream> #include <string> #include <vector> #include <cstdlib> #include <cstring> #include <cmath> #include "parse.h" #include "move_parser.h" #include "help.h" #include "Tower.h" #include "TowerDrawer.h" unsigned leastPossible(size_t num_disks) { return pow(2, num_disks) - 1; } double getScore(size_t num_disks, unsigned moves) { return round(100.0 * leastPossible(num_disks) / moves); } void printResults(size_t num_disks, unsigned moves) { std::cout << "You finished in " << moves << " moves\n"; std::cout << "Best possible is "\ << leastPossible(num_disks) << " moves\n"; std::cout << "Your score: " << getScore(num_disks, moves) << "%"; } void drawTowers(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer) { system("clear"); towerDrawer.draw(towers); } void printStatus(const std::string& statusMessage) { std::cout << "\n"; std::cout << statusMessage << "\n"; std::cout << "\n"; } void askQuestion(const std::string& question) { std::cout << question; } enum INPUT_TYPE { INVALID_INPUT, MOVE, COMMAND, EMPTY_INPUT }; INPUT_TYPE parseInput(const std::vector<std::string>& input) { /* If there are two tokens, then treat the input as valid syntax for a move. XXX XXXX If there is only one token in the input, then treat it as a command. XXXXXXX If there are no tokens, then this is empty input. If there are more than two tokens, then the input is invalid. XXX XXXX XX */ switch(input.size()) { case 0: return EMPTY_INPUT; case 1: return COMMAND; case 2: return MOVE; default: return INVALID_INPUT; } }
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile enum COMMAND_TYPE { REQUEST_QUIT, REQUEST_RESET, INVALID_COMMAND, REQUEST_HELP }; COMMAND_TYPE parseCommand(const std::vector<std::string>& input) { std::string command(input.front()); if(command == "quit") return REQUEST_QUIT; if(command == "reset") return REQUEST_RESET; if(command == "help") return REQUEST_HELP; return INVALID_COMMAND; } bool checkForGameWon(const Tower& goalTower, int totalDisks) { return goalTower.num_disks() == totalDisks; } void resetTowers(std::vector<Tower>& towers, int totalDisks) { towers.clear(); towers.push_back(Tower(totalDisks)); towers.push_back(Tower()); towers.push_back(Tower()); } void resetGame(std::vector<Tower>& towers, int numDisks, int& moves, std::string& statusMessage, std::string& prompt) { resetTowers(towers, numDisks); moves = 0; statusMessage = "Type \"help\" at any time for instructions. Good luck!"; prompt = "What's your first move? "; } bool askPlayAgain() { char inputChar; do { std::cout << "Do you want to play again? (y/n): "; std::cin >> inputChar; } while(!(inputChar == 'y' || inputChar == 'n')); return inputChar == 'y'; } int main(int argc, char* argv[]) { const int NUM_DISKS = (argc == 2) ? std::stoi(argv[1]) : 3; const int NUM_TUTORIAL_DISKS = 3; const int TUTORIAL_ROD_HEIGHT = NUM_TUTORIAL_DISKS + 2; const int GOAL_TOWER_VECTOR_INDEX = 2; std::vector<Tower> towers; // Actual game rods TowerDrawer tower_drawer(NUM_DISKS + 3); resetTowers(towers, NUM_DISKS); std::vector<Tower> tutorialTowers; // Appears on the help text TowerDrawer tutorialTowerDrawer(TUTORIAL_ROD_HEIGHT); resetTowers(tutorialTowers, NUM_TUTORIAL_DISKS);
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile int moves = 0; bool requestQuit = false; bool gameOver = false; std::string status, question, rawInput; status = "Type \"help\" at any time for instructions. Good luck!"; question = "What's your first move? "; while(!(requestQuit || gameOver)) { drawTowers(towers, tower_drawer); printStatus(status); askQuestion(question); std::string rawInput = getRawInput(); std::vector<std::string> tokens = tokenize(rawInput); switch(parseInput(tokens)) { case MOVE: break; case EMPTY_INPUT: continue; case COMMAND: { switch(parseCommand(tokens)) { case REQUEST_QUIT: { requestQuit = true; continue; } case REQUEST_RESET: { resetGame(towers, NUM_DISKS, moves, status, question); continue; } case REQUEST_HELP: { system("clear"); showHelpText(tutorialTowers, tutorialTowerDrawer); std::cout << "\n\n"; std::cout << "Press \"Enter\" for the list of commands..."; getRawInput(); system("clear"); showCommandsHelp(); std::cout << "\n\n"; std::cout << "Press \"Enter\" to go back to the game..."; getRawInput(); continue; } case INVALID_COMMAND: { status = "No such command..."; continue; } } } case INVALID_INPUT: { status = "Huh?"; continue; } }
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile TOWER_MOVE towerMove = parseMove(tokens, towers); switch(towerMove.moveType) { case VALID_MOVE: { doMove(towerMove, towers); moves++; if(checkForGameWon(towers.at(GOAL_TOWER_VECTOR_INDEX), NUM_DISKS)) { drawTowers(towers, tower_drawer); printStatus("You win!"); printResults(NUM_DISKS, moves); std::cout << "\n\n"; gameOver = !askPlayAgain(); if(!gameOver) { resetGame(towers, NUM_DISKS, moves, status, question); } continue; } status = ""; question = "What's your next move? "; break; } case DISKLESS_TOWER: { status = "Nothing on that tower..."; break; } case LARGER_ON_SMALLER: { status = "Can't place a larger disk on a smaller disk..."; break; } case INVALID_MOVE_SYNTAX: { status = "Can't do that..."; break; } } } return 0; } parse.h /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides string processing and parsing utilities. */ #ifndef PARSE_H #define PARSE_H #include <vector> #include <string> // Retrieves input from the console and returns the result as a string std::string getRawInput(); // Splits the string on the space (' ') character. Ignores leading spaces. // Returns a vector containing the tokens. std::vector<std::string> tokenize(const std::string& s); enum PARSE_LONG_RESULT { INVALID_STRING, UNDERFLOW, OVERFLOW, SUCCESS }; // The input will not have leading or trailing spaces. PARSE_LONG_RESULT parseLong(const char* s, long* result); #endif
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile #endif parse.cpp /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides string processing and parsing utilities. */ #include <iostream> #include <vector> #include <string> #include <cstring> #include <climits> #include "parse.h" // Retrieves input from the console and returns the result as a string std::string getRawInput() { std::string input; std::getline(std::cin, input); return input; } // Splits the string on the space (' ') character. Ignores leading spaces. // Returns a vector containing the tokens. std::vector<std::string> tokenize(const std::string& s) { // Create an intermediate string buffer const std::size_t BUFFER_LENGTH = s.length() + 1; char* buffer = new char[BUFFER_LENGTH]; memset(buffer, 0, BUFFER_LENGTH); // Copy the string into the buffer s.copy(buffer, s.length()); // Tokenize std::vector<std::string> result; char* token = strtok(buffer, " "); while(token) { result.push_back(std::string(token)); token = strtok(nullptr, " "); } delete[] buffer; return result; } // The input will not have leading or trailing spaces. PARSE_LONG_RESULT parseLong(const char* s, long* result) { const char* afterTheNumber = s + strlen(s); char* endPtr = nullptr; int previousErrno = errno; errno = 0; long int longValue = strtol(s, &endPtr, 10); if(endPtr != afterTheNumber) { errno = previousErrno; return INVALID_STRING; } if(longValue == LONG_MIN && errno == ERANGE) { errno = previousErrno; return UNDERFLOW; } if(longValue == LONG_MAX && errno == ERANGE) { errno = previousErrno; return OVERFLOW; } errno = previousErrno; *result = longValue; return SUCCESS; } move_parser.h /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides higher-order parsing for Towers moves. */
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile This module provides higher-order parsing for Towers moves. */ #ifndef MOVE_PARSER_H #define MOVE_PARSER_H #include <vector> #include <string> #include "Tower.h" /* DISKLESS_TOWER - Attempt to take a disk from a rod with no disks. LARGER_ON_SMALLER - Attempt to place a larger disk on a smaller disk. INVALID_MOVE_SYNTAX - The input could not be processed due to one or more of the following reasons: 1. Some input couldn't be converted to a numerical type 2. Some numerical identifier would be out of range */ enum MOVE_TYPE { VALID_MOVE, DISKLESS_TOWER, LARGER_ON_SMALLER, INVALID_MOVE_SYNTAX }; struct TOWER_MOVE { long int from; long int to; enum MOVE_TYPE moveType; }; /* Parses tokens and produces a tower move record. */ TOWER_MOVE parseMove(const std::vector<std::string>& tokens, const std::vector<Tower>& towers); /* Executes the towers move. The move type must not be INVALID_MOVE_SYNTAX or DISKLESS_TOWER. Move type LARGER_ON_SMALLER is allowed, but violates the traditional rules of the game. */ void doMove(TOWER_MOVE move, std::vector<Tower>& towers); #endif move_parser.cpp /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides higher-order parsing for Towers moves. */ #include <vector> #include <string> #include "move_parser.h" #include "parse.h" #include "Tower.h" TOWER_MOVE parseMove(const std::vector<std::string>& tokens, const std::vector<Tower>& towers) { long int from, to; PARSE_LONG_RESULT fromResult = parseLong(tokens.at(0).c_str(), &from); PARSE_LONG_RESULT toResult = parseLong(tokens.at(1).c_str(), &to); // Return this when processing the move would result in a fatal error. const TOWER_MOVE PROBLEM_MOVE = { 0, 0, INVALID_MOVE_SYNTAX };
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile if(!(fromResult == SUCCESS && toResult == SUCCESS)) { return PROBLEM_MOVE; } if((from < 1) || (from > 3)) { return PROBLEM_MOVE; } if((to < 1) || (to > 3)) { return PROBLEM_MOVE; } from--; to--; const Tower& towerFrom = towers.at(from); const Tower& towerTo = towers.at(to); if(towerFrom.is_diskless()) { TOWER_MOVE result = { from, to, DISKLESS_TOWER }; return result; } if(!towerTo.is_diskless() && (towerFrom.size_of_top() > towerTo.size_of_top())) { TOWER_MOVE result = { from, to, LARGER_ON_SMALLER }; return result; } TOWER_MOVE result = { from, to, VALID_MOVE }; return result; } void doMove(const TOWER_MOVE move, std::vector<Tower>& towers) { Tower& towerFrom = towers.at(move.from); Tower& towerTo = towers.at(move.to); towerFrom.top_to_top(towerTo); } help.h /* Author: Jared Thomas Date: Monday, January 23, 2023 This module provides the help command handler. */ #ifndef HELP_H #define HELP_H #include <vector> #include "Tower.h" #include "TowerDrawer.h" // Clears the terminal and prints the help text explaining the rules and goal // of the game. // // The passed in towers will be shown as a demonstration in the help text. void showHelpText(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer); void showCommandsHelp(); #endif help.cpp /* Author: Jared Thomas Date: Monday, January 23, 2023 This module provides the help command handler. */ #include "help.h" #include <vector> #include <cstdlib> #include <iostream> #include "Tower.h" #include "TowerDrawer.h"
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile #include "Tower.h" #include "TowerDrawer.h" // Clears the terminal and prints the help text explaining the rules and goal // of the game. // // The passed in towers will be shown as a demonstration in the help text. void showHelpText(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer) { std::cout << "Towers, an adaptation of the game \"Tower of Hanoi\"\n"; std::cout << "Nexus Game Studios, 2023\n"; std::cout << "Programming, Jared Thomas\n"; std::cout << "\n"; std::cout << "The goal of Towers is to move all the disks from the leftmost rod to the rightmost rod.\n"; std::cout << "Sounds easy, right? But not so fast!\n"; std::cout << "You can only move the topmost disk from any tower.\n"; std::cout << "On top of that, you can't put a larger disk on top of a smaller one!\n"; towerDrawer.draw(towers); std::cout << "\n"; std::cout << "To move a disk from one rod to another, type the rod number you want to\n"; std::cout << "move from, then the rod number to move to, separated by a space. Like this:\n"; std::cout << "\n"; std::cout << "1 2\n"; std::cout << "\n"; std::cout << "This would move the topmost disk from the left rod to the middle rod.\n"; std::cout << "If you can move all the disks to the rightmost rod, you win!"; } // Prints the commands help text. void showCommandsHelp() { std::cout << "Commands\n"; std::cout << "\n"; std::cout << "quit Quit the game\n"; std::cout << "help Show the game explanation, rules, and commands\n"; std::cout << "reset Start the game over again"; } Disk.h #pragma once struct Disk { // size > 0 Disk(const int size); void draw() const; int size() const; private: int size_; }; void draw_solid_style(const Disk); void draw_slash_bracket_style(const Disk); Disk.cpp #include "Disk.h" #include <cassert> #include <iostream> using namespace std;
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile Disk.cpp #include "Disk.h" #include <cassert> #include <iostream> using namespace std; Disk::Disk(const int size): size_(size) { assert(size_ > 0); } void Disk::draw() const { for(int i = 0; i < (2 * size() + 1); i++) { cout << '+'; } } int Disk::size() const { return size_; } void draw_solid_style(const Disk d) { cout << '['; int j = 2 * d.size() + 1; if(d.size() >= 10 && d.size() <= 99) j--; for(int i = 0; i < j; i++) { if(i == (2 * d.size() + 1) / 2) cout << d.size(); else cout << ' '; } cout << ']'; } void draw_slash_bracket_style(const Disk d) { cout << '['; int j = 2 * d.size() + 1; if(d.size() >= 10 && d.size() <= 99) j--; for(int i = 0; i < j; i++) { if(i == (2 * d.size() + 1) / 2) cout << d.size(); else if(i == ((2 * d.size() + 1) / 2) - 1) cout << ' '; else if(i == ((2 * d.size() + 1) / 2) + 1) cout << ' '; else cout << '/'; } cout << ']'; } Tower.h #pragma once #include "Disk.h" #include <vector> class Tower { public: Tower(); Tower(size_t num_disks); size_t num_disks() const; int size_of_top() const; int size_of_largest_disk() const; int size_of_disk_at(size_t place) const; bool is_diskless() const; bool are_strictly_decreasing() const; const Disk& disk_at(size_t index) const; void top_to_top(Tower& dest_tower); bool compare(const Tower&) const; private: std::vector<Disk> disks_; }; size_t highestTower(const std::vector<Tower>& towers); Tower.cpp #include "Tower.h" #include "Disk.h" #include <cassert> #include <iostream> using namespace std; Tower::Tower() { } Tower::Tower(size_t num_disks) { assert(num_disks >= 0); for(int i = num_disks; i > 0; i--) { disks_.push_back(Disk(i)); } } size_t Tower::num_disks() const { return disks_.size(); } int Tower::size_of_top() const { assert(!is_diskless()); return disks_.back().size(); }
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile int Tower::size_of_top() const { assert(!is_diskless()); return disks_.back().size(); } int Tower::size_of_largest_disk() const { assert(!is_diskless()); int largest = 0; for(size_t u = 0; u < num_disks(); u++) { if(size_of_disk_at(u) > largest) largest = size_of_disk_at(u); } return largest; } int Tower::size_of_disk_at(size_t place) const { assert(!is_diskless()); return disks_.at(place).size(); } bool Tower::is_diskless() const { return num_disks() == 0; } bool Tower::are_strictly_decreasing() const { assert(!is_diskless()); size_t expected = num_disks(); for(size_t j = 0; j < num_disks(); j++) { if(size_of_disk_at(j) != expected) return false; expected--; } return true; } const Disk& Tower::disk_at(size_t i) const { assert(!is_diskless()); return disks_.at(i); } void Tower::top_to_top(Tower& dest_tower) { assert(!is_diskless()); Disk diskToMove = disks_.back(); disks_.pop_back(); dest_tower.disks_.push_back(diskToMove); } bool Tower::compare(const Tower& T) const { if(T.num_disks() != num_disks()) return false; if(T.is_diskless() && is_diskless()) return true; for(size_t disk = 0; disk < num_disks(); disk++) { if(T.disk_at(disk).size() != disk_at(disk).size()) return false; } return true; } // Returns the number of disks on the tower in the vector with the most disks size_t highestTower(const std::vector<Tower>& towers) { assert(!towers.empty()); size_t highest = 0; for(size_t i = 0; i < towers.size(); i++) { if(towers.at(i).num_disks() > highest) { highest = towers.at(i).num_disks(); } } return highest; } TowerDrawer.h #pragma once #include <cstddef> #include <vector> class Tower; class TowerDrawer { public: TowerDrawer(int pole_height); int pole_height() const; size_t draw(const Tower&) const; size_t draw(const std::vector<Tower>&) const;
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile private: void draw_spaces(const int num_spaces = 1) const; int num_slashes(const int disk_size) const; int num_chars(const int disk_size) const; int center_of(const int disk_size) const; void draw_disk_row(const int disk_index, const Tower&) const; void draw_rod_row(const Tower&) const; void draw_rod_top(const Tower&) const; void draw_tower_row(int row, const Tower&) const; int pole_height_; }; TowerDrawer.cpp #include "TowerDrawer.h" #include "Tower.h" #include <cassert> #include <iostream> #include <climits> using namespace std; TowerDrawer::TowerDrawer(int pole_height): pole_height_(pole_height) {} int TowerDrawer::pole_height() const { return pole_height_; } size_t TowerDrawer::draw(const Tower& T) const { std::vector<Tower> tempTowerVector; tempTowerVector.push_back(T); return draw(tempTowerVector); } size_t TowerDrawer::draw(const std::vector<Tower>& towers) const { if(towers.empty()) return 0; assert(pole_height_ > highestTower(towers)); for(int i = pole_height_; i >= 0; i--) { for(size_t t = 0; t < towers.size(); t++) { draw_tower_row(i, towers.at(t)); draw_spaces(12); } cout << endl; } return towers.size(); } int to_signed(const unsigned x) { if(x <= INT_MAX) return static_cast<int>(x); if(x >= INT_MIN) return static_cast<int>(x - INT_MIN) + INT_MIN; throw x; // Or whatever else you like } void TowerDrawer::draw_spaces(const int N) const { assert(N >= 0); for(int i = 0; i < N; i++) cout << ' '; } int TowerDrawer::num_slashes(const int disk_size) const { return disk_size * 2 + 1; } int TowerDrawer::num_chars(const int disk_size) const { return 2 + num_slashes(disk_size); } int TowerDrawer::center_of(const int disk_size) const { return (num_chars(disk_size) - 1) / 2; }
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile int TowerDrawer::center_of(const int disk_size) const { return (num_chars(disk_size) - 1) / 2; } void TowerDrawer::draw_disk_row(const int disk_index, const Tower& t) const { draw_spaces(center_of(t.size_of_largest_disk()) - center_of(t.size_of_disk_at(disk_index))); if(!(t.size_of_disk_at(disk_index) & 1)) draw_slash_bracket_style(t.disk_at(disk_index)); else draw_slash_bracket_style(t.disk_at(disk_index)); draw_spaces(center_of(t.size_of_largest_disk()) - center_of(t.size_of_disk_at(disk_index))); } void TowerDrawer::draw_rod_row(const Tower& t) const { if(t.is_diskless()) { draw_spaces(); cout << "|_|"; draw_spaces(); return; } draw_spaces(center_of(t.size_of_largest_disk()) - 1); cout << "|_|"; draw_spaces(center_of(t.size_of_largest_disk()) - 1); } void TowerDrawer::draw_rod_top(const Tower& t) const { if(t.is_diskless()) { draw_spaces(2); cout << '_'; draw_spaces(2); return; } draw_spaces(center_of(t.size_of_largest_disk())); cout << '_'; draw_spaces(center_of(t.size_of_largest_disk())); } // todo: draws funnily when tower.num_disks() == tower.height() void TowerDrawer::draw_tower_row(int row, const Tower& tower) const { assert(row <= pole_height_); if(row == pole_height_) draw_rod_top(tower); else if(row >= tower.num_disks()) draw_rod_row(tower); else draw_disk_row(row, tower); } makefile all: towers debug: main.cpp parse.cpp move_parser.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp g++ -std=c++17 main.cpp parse.cpp move_parser.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp -o towers -g towers: main.cpp parse.cpp move_parser.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp g++ -std=c++17 main.cpp parse.cpp move_parser.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp -o towers clean: rm towers
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile clean: rm towers Answer: General Observations Interesting! Decent job of coding. The partitioning of the code seems pretty good, but it can be improved. In the display of towers, the towers should be numbered so that the user knows what to input. What might also be helpful to the user is a prompt the indicates the proper format of a move. What's your next move? [Two integers between 1 and 3] There should be a -h command line argument that would print the proper usage. Since in the future there may be more arguments on the command line, there should be a command line parser as well. The game could also prompt for the number of disks at runtime if there are no command line arguments. Be consistent in all of the programming, more on this below. wc -Llwc *.h *.cpp 15 28 238 42 Disk.h 25 52 577 54 Tower.h 27 72 708 65 TowerDrawer.h 25 71 533 84 help.h 48 163 1267 95 move_parser.h 27 90 710 78 parse.h 47 198 1036 64 Disk.cpp 105 235 2177 77 Tower.cpp 121 276 2928 96 TowerDrawer.cpp 49 276 1868 109 help.cpp 248 648 6691 117 main.cpp 57 180 1613 94 move_parser.cpp 69 225 1869 74 parse.cpp 863 2514 22215 117 total Allow the compiler to check the code for you, there are some warning messages on the code if you add the proper compiler switches: -Wall -Wextra -pedantic -Werror Line 23 in main.cpp: warning: 'return': conversion from 'double' to 'unsigned int', possible loss of data Line 19 in Tower.cpp warning: 'initializing': conversion from 'size_t' to 'int', possible loss of data Line 23 in main.cpp : return pow(2, num_disks) - 1; The call to pow() returns a double. Line 19 in Tower.cpp: for (int i = num_disks; i > 0; i--) {
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile Since num_disks is size_t it might be better of i is size_t as well. Rather than creating a Makefile you might want to use CMake instead. The current Makefile is ignoring dependencies that it should not be ignoring (the header files). CMake will handle these dependencies for you. Be Consistent! There are multiple places where the code is inconsistent, one is the use of include guards in some header files and #pragma once in other header files. Both are legitimate, include guards are older technology and a little more portable. The important thing is to pick one and use it through out the project. Other people might have to maintain the code and consistency is very important in that case. Use int or unsigned int consistently. There is no clear need for integers on any of the code since most of the values can never go negative. The function getScore() should probably return either an unsigned int or size_t. Many/most of the files use the names spaces, but Tower.cpp has using namespace std;. Avoid using namespace std; If you are coding professionally you probably should get out of the habit of using the using namespace std; statement. The code will more clearly define where cout and other identifiers are coming from (std::cin, std::cout). As you start using namespaces in your code it is better to identify where each function comes from because there may be function name collisions from different namespaces. The identifiercout you may override within your own classes, and you may override the operator << in your own classes as well. This stack overflow question discusses this in more detail. Partitioning of Functionality
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile Partitioning of Functionality While the code does a fair job of partitioning functionality, the main.cpp still contains code for parsing the commands, all of the parsing related functions should be in parse.cpp with prototypes in parse.h. The point of partitioning the code should be to remove as many dependencies as possible, only global entry points should be listed as prototypes in header files. All of the parsing related enums should be declared in parse.h if they need to be global or parse.cpp if the can be made local. The function resetTowers() probably belongs in either Tower.h or TowerDrawer.h. integers Versus size_t Check the value of argv[1] if it is on the command line, it should never be negative, report a user error if it is and exit the program. That way the code can use just unsigned int or size_t rather than using integers and needing conversions from unsigned to int. Switching back and forth between unsigned and signed can be a cause of bugs. Line 18 in Tower.cpp is meaningless, since size_t is unsigned num_disks can never be less than zero. assert(num_disks >= 0);
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
c++, game, console, makefile Complexity Some measures of complexity are the number of lines in a function or a section of code and the number of levels of indentation. One of the best practices in coding is that a function should be completely viewable in a single scree (on my computer that is 58 lines of code or less). The main() function in main.cpp is 112 lines of code, this is almost 2 full screens on most computers. The reason that one screen max per function is a best practice is that it is very difficult for someone reading, writing or maintaining the code to keep track of everything the function is doing. The function main() is too complex (does too much). As programs grow in size the use of main() should be limited to calling functions that parse the command line, calling functions that set up for processing, calling functions that execute the desired function of the program, and calling functions to clean up after the main portion of the program. There is also a programming principle called the Single Responsibility Principle that applies here. The Single Responsibility Principle states: that every module, class, or function should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by that module, class or function. The code in the while (!(requestQuit || gameOver)) loop belongs in its own function, in fact it might be broken up into multiple functions. If I was writing the code I might have a Game class that had a play() function. The instantiation of the Game object would handle most of the setup (hint pass the number of disks into the game constructor). The includes for parse.h, move_parser.h, Tower.h and TowerDrawer.h would move from main.cpp to Game.cpp.
{ "domain": "codereview.stackexchange", "id": 44397, "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++, game, console, makefile", "url": null }
performance, r Title: Group uncorrelated variables into subsets using correlation matrix Question: I am trying to group uncorrelated variables into subsets. So, using the correlation matrix, I check each variable to see the correlation. If correlation is more then a threshold I will create a new list, else I will add it to the current list. At the end, in each subset the variables are not correlated. I have written the below code and it works fine. However, when the number of variables are high (> 20,000), it takes more than two hours to run. Is there any suggestion to make it faster? or do some operations in parallel? corr <- matrix(c(1,0.9,0,0.83,0.9,0.9,1,0.2,0.9,0.1,0,0.2,1,0.1,0.9,0.83,0.9,0.1,1,0.9,0.9,0.1,0.9,0.9,1), 5,5, byrow = T) rownames(corr) <- colnames(corr) <- LETTERS[1:5] #corr <- cor(t(dataset)) %>% abs() vars <- rownames(corr) list_data[[1]] <- vars[1] for(i in 2:length(vars)){ message(vars[i]) added <- 1 for(j in 1:length(list_data)){ cur_list <- list_data[[j]] flag <- 1 for(k in 1:length(cur_list)){ corr_data <- corr[vars[i], cur_list[k]] if(corr_data >= 0.8){ flag <- 0 break } } if(flag == 0) next else { list_data[[j]] <- c(cur_list, vars[i]) added <- 0 break } } if(added == 1) list_data[[j+1]] <- vars[i] } I have added an example input data including five variables. In my data, the number of variables are around 21,000, which makes the code really slow. Answer: rownames(corr) <- colnames(corr) <- 1:ncol(corr) vars <- rownames(corr) vars <- as.integer(vars) list_data2 <- list() list_data2[[1]] <- vars[1]
{ "domain": "codereview.stackexchange", "id": 44398, "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, r", "url": null }
performance, r list_data2 <- list() list_data2[[1]] <- vars[1] t1 <- proc.time() for (i in 2:length(vars)) { added <- 1L corr2 <- corr[vars[i], ] for (j in 1:length(list_data2)) { cur_list <- list_data2[[j]] flag <- 1L for (k in 1:length(cur_list)) { corr_data <- corr2[cur_list[k]] if (corr_data >= 0.8) { flag <- 0L break } } if (flag == 0L) next else { list_data2[[j]] <- c(cur_list, vars[i]) added <- 0L break } } if (added == 1L) list_data2[[j + 1L]] <- vars[i] } don't use col/row names to subset matrix, use integers (positions of cols/rows) we can subset row in outer loop (line: corr2 <- corr[vars[i], ]) afterwards we can get names from indexes, if needed: your_names <- paste0('v', 1:n) # example name_list <- lapply(list_data2, function(x) your_names[x]) Update Another huge improvement is to do your comparison outside loop & remove names of resulting matrix, because of that matrix/vectors subsetting is much faster. vars <- 1:ncol(corr) list_data3 <- list() list_data3[[1]] <- vars[1] t1 <- proc.time() compar <- unname(corr) >= 0.8 # do comparison outside loop for (i in 2:length(vars)) { added <- 1L corr2 <- compar[vars[i], ] for (j in 1:length(list_data3)) { cur_list <- list_data3[[j]] flag <- 1L for (k in seq_along(cur_list)) { # little bit faster corr_data <- corr2[cur_list[k]] if (corr_data) { flag <- 0L break } } if (flag == 0L) next else { list_data3[[j]] <- c(cur_list, vars[i]) added <- 0L break } } if (added == 1L) list_data3[[j + 1L]] <- vars[i] } t2 <- proc.time() (t2 - t1)[3] # ~10 sec for 20k*20k symmetric matrix
{ "domain": "codereview.stackexchange", "id": 44398, "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, r", "url": null }
javascript, functional-programming, ecmascript-6, factors Title: Abundant number implementation Question: I have implementted a simple JavaScript function to find the list of abundant numbers and print them on the screen. an abundant number is a number for which the sum of its proper divisors is greater than the number The function printAbundantNumbers(), takes an argument, which is a range that tells the function how many abundant numbers that it should find and print out on the screen. The function also includes several smaller functions to ensure the readability of the code - so that each functionality will be performed with no conflicts to the other code. I think the code is quite long. Is there a way to shorten it? Here is the code: function printAbundantNumbers(num) { const concatAbundantNumbers = function(){ const finalArray = collectAbundantNumbers().map(arr=>arr[1]*arr[arr.length-1]); return finalArray; // Return the final array. } // Collects all abundant numbers. const collectAbundantNumbers = function (){ let listOfFactors = collectFactorsForEachNumbers(num).filter(e=>addArray(e)>(e[1]*e[e.length-1])); // Find all the factors and loop through them. If the sum of these factors is greater than the number, then assign them to a variable. return listOfFactors; } // Collect factors for each number. const collectFactorsForEachNumbers = function (num){ let listOfIndividualElementFactors = []; for(let i=2;i<=num;i++) { let factors = findFactor(i); // find factors. listOfIndividualElementFactors.push([...factors]); // Making a 2-d array out of this and assign to the variable. } return listOfIndividualElementFactors; }
{ "domain": "codereview.stackexchange", "id": 44399, "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, functional-programming, ecmascript-6, factors", "url": null }
javascript, functional-programming, ecmascript-6, factors // find factors. const findFactor = function (num){ let listOfFactors = []; for(let i=1; i<num;i++) { if(num%i===0)listOfFactors.push(i); } return listOfFactors; } // add arrays const addArray = function(arr){ let sum=0; arr.forEach(e=>sum+=e); // loop through the array and them. return sum; } concatAbundantNumbers().forEach(e=>console.log(e+"\n")); // writes the abundant to the screen. } printAbundantNumbers(200); Answer: Is there a way to shorten it? I'll do you one better: make it shorter overall and more efficient. You need the sum of (proper) divisors of each number that is being tested. It seems to make sense to compute the divisors and then sum them.. but number theory being number theory, there is a shortcut. Using the shortcut, we save some code, and at the same time make it more efficient. The shortcut uses the prime factorization of the number. That seems as difficult as listing the divisors, but it is usually easier: there are typically many more divisors than prime factors, and listing the prime factors in a simple way is significantly more efficient than listing the divisors in a simple way (the difference can be reduced by, you may have guessed it, generating the divisors from the prime factorization). A core difference is that we only need to iterate trial-division up to the square root of n, in the worst case, and in better cases we can divide n by each factor that is found, decreasing the loop bound as we go. A sum-of-divisors function based on the prime factorization p can be based on this formula:
{ "domain": "codereview.stackexchange", "id": 44399, "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, functional-programming, ecmascript-6, factors", "url": null }
javascript, functional-programming, ecmascript-6, factors Where p[i] is the i'th prime factor and a[i] is its corresponding exponent. The x in this function will be 1 for our purposes, different values of x create different kinds of divisor function. With x = 1 this calculates the sum of divisors, to turn it into the sum of proper divisors we just subtract n later on. To summarize what's happening in that formula: suppose we find a find factor p of our number n, with exponent a, then we want the sum of all powers of p from 0 to a inclusive. Do that for all factors, and take the product of those sums. Here is one attempt in Javascript, evaluating that sigma formula while finding prime factors: (your software engineering instinct may tell you to separate all the things, that would just add complication here) function sumOfDivisors(n) { var s = 1; for (var p = 2; p * p <= n; p++) { var inner_sum = 1; var power_of_p = 1; while (n % p === 0) { n /= p; power_of_p *= p; inner_sum += power_of_p; } s *= inner_sum; } if (n > 1) s *= (1 + n); return s; } Admittedly that function is somewhat long, but now the rest can be much simpler, with no need to sum anything from this point on or to reconstruct numbers from their divisors: function printAbundantNumbers(n) { var abundantNumbers = [...Array(n + 1).keys()].filter(i => i && sumOfDivisors(i) - i > i); abundantNumbers.forEach(e => console.log(e)); } Where [...Array(n + 1).keys()] is a trick to get the numbers 0 .. n (inclusive) in an array, and the filter condition includes i && to remove zero. By the way I only wrote it that way because I thought that might fit your style. I like that this spells out the condition sumOfDivisors(i) - i > i as opposed to addArray(e)>(e[1]*e[e.length-1]) which is equivalent but more mysterious. As for efficiency, this implementation can easily list the abundant numbers up to a million.
{ "domain": "codereview.stackexchange", "id": 44399, "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, functional-programming, ecmascript-6, factors", "url": null }
python, algorithm, interval Title: Finding missing numbers in ranges Question: I have a list of (potentially overlapping) ranges, e.g [(3, 9), (8, 10), (1, 18), (1, 1000000)]. I need to process them in order and for each range calculate how many numbers from the range have not been seen so far (i.e. not present in previous ranges). For example, for the above list the result would be [7, 1, 10, 999982]. A simple solution using a set: def get_missing(ranges): seen = set() result = [] for start, end in ranges: missing = 0 for n in range(start, end+1): if n not in seen: missing += 1 seen.add(n) result.append(missing) return result How can I improve the performance of this solution (i.e. do it without looping through each number of each range)? Answer: The primary problem with your current approach. As you know from previous answers and comments, the limitation of your current approach is that it falters when faced with very large intervals, which cause the inner loop to balloon in size. A little bit of progress can be made by taking fuller advantage of sets to perform the intersection logic (as shown below in the benchmarks). But that improvement is only modest: the sets eliminate the inner loop in your own code, but behind the scenes the Python sets are doing iteration of their own. Some infrastructure. Let's create a simple dataclass to make the code more readable, a utility function to generate intervals to our specifications (many or few, big or small), and a utility function to benchmark the various approaches to the problem. We will compare your code (slight modified to handle the new dataclass), a set-based alternative similar to the one in another answer, and a much faster approach using an IntervalUnion (to be discussed below). import sys import time from dataclasses import dataclass from random import randint
{ "domain": "codereview.stackexchange", "id": 44400, "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, algorithm, interval", "url": null }
python, algorithm, interval def main(args): intervals = tuple(create_intervals( n = 1000, start_limit = 100000000, max_size = 100000, )) funcs = ( get_missing_orig, get_missing_sets, get_missing_interval_union, ) exp = None for func in funcs: got, dur = measure(func, intervals) if exp is None: exp = got print(func.__name__, dur, got == exp) @dataclass(frozen = True, order = True) class Interval: start: int end: int def create_intervals(n, start_limit, max_size): for _ in range(n): start = randint(0, start_limit) end = start + randint(0, max_size) yield Interval(start, end) def measure(func, intervals): t1 = time.time() got = func(intervals) return (got, time.time() - t1) def get_missing_orig(ranges): # Your original implementation, slightly adjusted. seen = set() result = [] for x in ranges: missing = 0 for n in range(x.start, x.end + 1): if n not in seen: missing += 1 seen.add(n) result.append(missing) return result def get_missing_sets(intervals): # A set-based approach. counts = [] seen = set() for x in intervals: s = set(range(x.start, x.end + 1)) - seen counts.append(len(s)) seen.update(s) return counts def get_missing_interval_union(intervals): # An approach that just stores intervals, as few as possible. iu = IntervalUnion() return [iu.add(x) for x in intervals] if __name__ == '__main__': main(sys.argv[1:])
{ "domain": "codereview.stackexchange", "id": 44400, "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, algorithm, interval", "url": null }
python, algorithm, interval if __name__ == '__main__': main(sys.argv[1:]) The intuition behind IntervalUnion. We're trying to avoid two problems. First, we want to process and store only the intervals, not all of their implied values. Second, we don't want to end up having to make passes over an ever-growing collection of intervals. Instead, we would rather merge intervals whenever they overlap. If we can keep the size of the data universe in check, our computation will also be quick. For starters we need a couple of utility functions: one to tell us whether two intervals can be merged and, if so, how many of their values are overlapping; and another that can merge two intervals into one. def overlapping(x, y): # Takes two intervals. Returns a (CAN_MERGE, N_OVERLAPPING) tuple. # Intervals can be merged if they overlap or abut. # N of overlapping values is 1 + min-end - max-start. n = 1 + min(x.end, y.end) - max(x.start, y.start) if n >= 0: return (True, n) else: return (False, 0) def merge(x, y): # Takes two overlapping intervals and returns their merger. return Interval( min(x.start, y.start), max(x.end, y.end), ) The data structure of an IntervalUnion. A IntervalUnion holds a SortedList of Interval instances. The SortedList provides the ability to add and remove intervals without having to keep the list sorted ourselves. The SortedList will do that work efficiently for us, and the various add/remove operations will operate on the order of O(logN) rather than O(N) or O(NlogN). The add() method orchestrates those details, which are explained in the code comments, and returns the number that you need -- namely, how many distinct values are represented by the interval we just added. from sortedcontainers import SortedList class IntervalUnion: def __init__(self): self.intervals = SortedList()
{ "domain": "codereview.stackexchange", "id": 44400, "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, algorithm, interval", "url": null }
python, algorithm, interval class IntervalUnion: def __init__(self): self.intervals = SortedList() def add(self, x): # Setup and initialization: # - The N of values in the initial interval x. # - N of overlaps observed as we add/merge x into the IntervalUnion. # - Convenience variable for the SortedList of existing intervals. # - Existing intervals to be removed as a result of those mergers. n_vals = x.end - x.start + 1 n_overlaps = 0 xs = self.intervals removals = [] # Get the index where interval x would be added in the SortedList. # From that location we will look leftward and rightward to find # nearby intervals that can be merged with x. To the left, we # just need to check the immediate neighbor. To the right, we # must keep checking until no more merges are possible. i = xs.bisect_left(x) for j in range(max(0, i - 1), len(xs)): y = self.intervals[j] can_merge, n = overlapping(x, y) if can_merge: # If we can merge, do it. Then add y to the list of intervals # to be removed, and increment the tally of overlaps. x = merge(x, y) removals.append(y) n_overlaps += n elif j >= i: # Stop on the first rightward inability to merge. break # Remove and add. for y in removals: xs.remove(y) xs.add(x) # Return the distinct new values added to the IntervalUnion. return n_vals - n_overlaps
{ "domain": "codereview.stackexchange", "id": 44400, "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, algorithm, interval", "url": null }
python, algorithm, interval Benchmarks. In terms of space, the IntervalUnion is quite efficient: it stores only intervals and it merges them whenever possible. At one extreme (all of the intervals overlap), the space used is O(1) because the IntervalUnion never contains more than one interval. At the other extreme (no overlap), the space used is O(N), where N represents the number of intervals. In terms of time, the IntervalUnion becomes faster than the other approaches when the interval sizes reach about 300 (at least in my limited number of experiments). When the intervals get even bigger, the advantages of the IntervalUnion are substantial. For example: # max_size = 300 get_missing_orig 0.027595043182373047 True get_missing_sets 0.01658797264099121 True get_missing_interval_union 0.013303995132446289 True # max_size = 1000 get_missing_orig 0.10612797737121582 True get_missing_sets 0.054525136947631836 True get_missing_interval_union 0.013611078262329102 True # max_size = 10000 get_missing_orig 1.1063508987426758 True get_missing_sets 0.5742030143737793 True get_missing_interval_union 0.013240814208984375 True # max_size = 100000 get_missing_orig 9.316476106643677 True get_missing_sets 6.468451023101807 True get_missing_interval_union 0.016165733337402344 True
{ "domain": "codereview.stackexchange", "id": 44400, "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, algorithm, interval", "url": null }
vba, pointers, reflection, rubberduck, com Title: Low Level VBA Hacking - making Private functions Public Question: NEW: Download demo files Not sure what to title this - essentially, inspired by RubberDuck's unit test engine, I've created a way to call private methods of standard modules in VBA. It also lets you pass around modules as though they were objects. So, you can do something like this: '''Module Foo Option Private Module Private Sub Hi(ByVal who As String) Debug.Print "Hello hello "; who End Sub ''' '''Module Bar (far away) Dim fooModule as Object Set fooModule = GetFancyAccessor("Foo") fooModule.Hi "world" 'Call Private Hi method of module Foo - prints "Hello hello world" as expected 'NOTE: Private method, Option Private Module, password locked VBA project etc. all fine ''' Or in the editor: If that sounds esoteric (a.k.a. why??) it's because it is, and really this project is more a proof-of-concept of a capability which others may find an application for, as well as a place to consolidate several techniques for dealing with function pointers, memory manipulation and COM/OLE Automation machinery that I've picked up which are quite fiddly to get to grips with. I will still go over some applications at the end. Summary - How it works This code does 3 things: First, it borrows a trick from RubberDuck for reading the secret library of VBA projects to get access to the standard modules of a project in object form. Secondly, it borrows another trick from RubberDuck to locate the secret type information that describes the layout of these module objects in memory (including the bits declared as private!). These 2 tricks are used by RD to execute its unit tests in any host without Application.Run - thanks RD team for the open source! That said, it's tricky to translate C# to VBA so this wasn't completely easy.
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Thirdly, it creates a FancyAccessor (real name) to tape together the module object (1) and supplementary information (2), and which has some specific COM machinery overwritten to allow you to call the methods of the module using Dot.Notation(). Code Now for some code, and I can expand on each of those things in turn: [0. References] There are 3 main references (other than Scripting.Dictionary): MemoryTools.xlam - This is an addin which wraps cristianbuse/VBA-MemoryTools which I'm using to read/write memory e.g. MemByte(address As LongPtr) = value because it is both performant and has a really nice API design in my opinion. This dependency has been removed (see update at end of post)TLBINF32.dll - This is a nice wrapper library for dealing with ITypeLib and ITypeInfo reflection* interfaces. However, it has some drawbacks: On 64-bit VBA it needs to be wrapped in a "COM+ server" since it is only a 32-bit library (install instructions). It is no longer shipped with Windows so has to be obtained from dodgy sites (download). More importantly, it cannot process the full ITypeInfo and filters out only the public members. As you will see this restricted the usage of this dll (and I'm going to eliminate the dependency in future). COMTools.xlam - This is an addin I wrote myself for this project and contains all the types and library functions to make working with COM possible in VBA. In particular: VTables** for IUnknown, IDispatch and the other various interfaces that crop up Standard methods like ObjectFromObjPtr and QueryInterface for dealing with interfaces Methods CallFunction, CallCOMObjectVTableEntry & CallVBAFuncPtr which wrap DispCallFunc and allow you to invoke function pointers
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Edit: I've made all these files, as well as the demo workbook, available for download here. Update: since removing TLI it is now easy to use these; just copy the 3 .xlam files to all be in the correct folder C:/ProgramData/Temp/VBAHack and the demo should just work TM *Reflection in OLE Automation (that's the whole framework, derived from COM, which VBA is built on under the hood) is most familiar to us when talking about "Late-Bound" code - i.e. when you declare class variables As Object (as opposed to "Early-Bound" As Class1). The way VBA works out what functions different method calls refer to in Late-Bound code is by a special interface called IDispatch (As Object is an alias for As IDispatch). This interface has the job of translating string versions of methods (the names of methods) into actual function pointers - things we can execute. The way IDispatch does that is by looking up those strings in ITypeInfo structures, that map names onto pointers. An ITypeLib is a library containing multiple ITypeInfos; each VBA project/addin defines an ITypeLib and the classes & standard modules are each described by an ITypeInfo. **VTables or virtual tables are another bit of COM terminology. A class in a COM based language like VBA has some methods. The VTable is nothing more than an array of pointers to those methods in a well defined order - each class/ interface defines its own VTable layout. An instance of a class meanwhile is a chunk of memory for the class variables unique to each instance, where the first bit of that memory stores a pointer to the VTable Array shared between all instances of that class. The VTables are interesting, I define them in COMTools.xlam like this: Public Type IUnknownVTable QueryInterface As LongPtr AddRef As LongPtr ReleaseRef As LongPtr End Type: Public IUnknownVTable As IUnknownVTable
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Type IDispatchVTable IUnknown As IUnknownVTable GetTypeInfoCount As LongPtr GetTypeInfo As LongPtr GetIDsOfNames As LongPtr Invoke As LongPtr End Type: Public IDispatchVTable As IDispatchVTable Public Property Get IUnknownVTableOffset(ByRef member As LongPtr) As LongPtr IUnknownVTableOffset = VarPtr(member) - VarPtr(IUnknownVTable) End Property Public Property Get IDispatchVTableOffset(ByRef member As LongPtr) As LongPtr IDispatchVTableOffset = VarPtr(member) - VarPtr(IDispatchVTable) End Property The Property Gets + Public instances together let me obtain the offset (in bytes) of a certain function pointer relative to the start of the VTable array - e.g. IDispatchVTableOffset(IDispatchVTable.GetIDsOfNames) returns 40 meaning the GetIDsOfNames function is 40 bytes from the start of the IDispatch VTable*. I've been trying to keep my code more modular by referencing external addins where possible. I'm writing a package manager so that distributing these samples will hopefully be easier soon... *This makes sense - IUnknown has 3 methods VTableIndex[0,1,2] and IDispatch extends IUnknown with 4 more VTableIndex[3,4,5,6]. IDispatch::GetIDsofNames is the 3rd member of the IDispatch interface, therefore 5 steps from the start of the VTable (which is IUnknown::QueryInterface for all COM objects). ByteOffset = VTableIndex*FUNC_PTR_SIZE = 5*8(64-bit) = 40 1. Getting the secret module objects This is the first bit of trickery taken from RubberDuck's source code. It's a bit complex and the code speaks for itself, but I'll try to summarise.
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Use Application.VBE.ActiveVBProject.References to get a pointer to the VBEReferencesObj structure. Use VBEReferencesObj.typeLib to get a pointer to the VBETypeLibObj structure. VBETypeLibObj forms a doubly linked list of pointers to prev and next typelib - use these to create an iterable for all the typelibs in the project. At this point, I diverge a little from what RD does; RD declares some wrappers for the the raw ITypeLibs, and uses them to filter typelibs by name etc to get the Typelnfo of the module of interest containing the function to be invoked. I do a similar thing with the TLBINF32.DLL to filter typelibs by name, then navigating to get to the child TypeInfoWrapper. Extract raw ITypeInfo pointer from TypeInfoWrapper for module of interest. Call COMTools.QueryInterface on that pointer with an Interface ID of Guid("DDD557E1-D96F-11CD-9570-00AA0051E5D4") to get the object's undocumented IVBEComponent interface. Call IVBEComponent::GetStdModAccessor() As IDispatch method. Finally, this should give me the IDispatch interface to StdModAccessor for the module I'm after, which can be used in C# with an IDispatchHelper, but for VBA is just a late-bound Object that I could call with CallByName or moduleAccessor.MethodToCall() since IDispatch is supported natively. Also keep the ITypeLib pointers from step 4 handy as that will give us access to the less restricted ITypeInfo. Here's all that in code: Module VBETypeLib Responsible for following the breadcrumbs to get to the IVBEComponent::GetStdModAccessor - along the way generating a project ITypeLib which contains all the public and private members. '@Folder "TypeInfoInvoker" Option Explicit Option Private Module Public Type VBEReferencesObj vTable1 As LongPtr 'To _References vtable vTable2 As LongPtr vTable3 As LongPtr object1 As LongPtr object2 As LongPtr typeLib As LongPtr placeholder1 As LongPtr placeholder2 As LongPtr RefCount As LongPtr End Type
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Type VBETypeLibObj vTable1 As LongPtr 'To ITypeLib vtable vTable2 As LongPtr vTable3 As LongPtr Prev As LongPtr '@Ignore KeywordsUsedAsMember: Looks nice, sorry ThunderFrame Next As LongPtr End Type Public Function StdModuleAccessor(ByVal moduleName As String, ByVal project As String, Optional ByRef outModuleTypeInfo As TypeInfo, Optional ByRef outITypeLib As LongPtr) As Object Dim referencesInstancePtr As LongPtr referencesInstancePtr = ObjPtr(Application.VBE.ActiveVBProject.References) Debug.Assert referencesInstancePtr <> 0 'The references object instance looks like this, and has a raw pointer contained within it to the typelibs it uses Dim refData As VBEReferencesObj MemoryTools.CopyMemory refData, ByVal referencesInstancePtr, LenB(refData) Debug.Assert refData.vTable1 = memlongptr(referencesInstancePtr) Dim typeLibInstanceTable As VBETypeLibObj MemoryTools.CopyMemory typeLibInstanceTable, ByVal refData.typeLib, LenB(typeLibInstanceTable) 'Create a class to iterate over the doubly linked list Dim typeLibPtrs As New TypeLibIterator typeLibPtrs.baseTypeLib = refData.typeLib Dim projectTypeLib As TypeLibInfo Dim found As Boolean
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Do While typeLibPtrs.TryGetNext(projectTypeLib) Debug.Assert typeLibPtrs.tryGetCurrentRawITypeLibPtr(outITypeLib) Debug.Print "[LOG] "; "Discovered: "; projectTypeLib.name If projectTypeLib.name = project Then 'we have found the project typelib, check for the correct module within it Dim moduleTI As TypeInfo If TryGetTypeInfo(projectTypeLib, moduleName, outTI:=moduleTI) Then found = True Exit Do Else Err.Raise vbObjectError + 5, Description:="Module with name '" & moduleName & "' not found in project " & project End If End If Loop If Not found Then Err.Raise vbObjectError + 5, Description:="No project found with that name" 'Cast to IVBEComponent Guid("DDD557E1-D96F-11CD-9570-00AA0051E5D4") ' In RD this is done via Aggregation ' Meaning an object is made by merging the COM interface with a managed C# interface ' We don't have to worry about this, it is just to avoid some bug with C# reflection I think Dim IVBEComponent As LongPtr IVBEComponent = COMTools.QueryInterface(moduleTI.ITypeInfo, InterfacesDict("IVBEComponent")) 'Call Function IVBEComponent::GetStdModAccessor() As IDispatch Dim stdModAccessor As Object Set stdModAccessor = GetStdModAccessor(IVBEComponent) 'ERROR: Failed to call VTable method. DispCallFunc HRESULT: 0x80004001 - E_NOTIMPL 'return result Set StdModuleAccessor = stdModAccessor Set outModuleTypeInfo = moduleTI End Function Private Function TryGetTypeInfo(ByVal typeLib As TypeLibInfo, ByVal moduleName As String, ByRef outTI As TypeInfo) As Boolean On Error Resume Next Set outTI = typeLib.GetTypeInfo(moduleName) TryGetTypeInfo = Err.Number = 0 On Error GoTo 0 End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com ... which references a class for doing the iteration over the doubly linked list of VBETypeLibObj: Class TypeLibIterator '@Folder "TypeInfoInvoker" Option Explicit Private Type TIterator currentTL As VBETypeLibObj pCurrentTL As LongPtr End Type Private this As TIterator Public Property Let baseTypeLib(ByVal rawptr As LongPtr) currentTL = rawptr ResetIteration End Property Private Property Let currentTL(ByVal rawptr As LongPtr) this.pCurrentTL = rawptr CopyMemory this.currentTL, ByVal rawptr, LenB(this.currentTL) End Property Public Sub ResetIteration() Do While this.currentTL.Prev <> 0 currentTL = this.currentTL.Prev Loop End Sub Private Function NextTypeLib() As LongPtr If this.currentTL.Next = 0 Then Err.Raise 5, Description:="We've reached the end of the line" NextTypeLib = this.currentTL.Next currentTL = this.currentTL.Next 'move the iterator along End Function '@Description("Gets type library com objects from list") Public Function TryGetNext(ByRef outTypeLib As TypeLibInfo) As Boolean On Error GoTo cleanFail Dim tlPtr As LongPtr tlPtr = NextTypeLib Set outTypeLib = TLI.TypeLibInfoFromITypeLib(ObjectFromObjPtr(tlPtr)) TryGetNext = True cleanExit: Exit Function cleanFail: TryGetNext = False Set outTypeLib = Nothing Resume cleanExit End Function '@Description("Returns the raw ITypeLib interface; this is because TLI.TypeLibInfo is a slightly more restricted view than the pointer here and hides private members") Public Function tryGetCurrentRawITypeLibPtr(ByRef outITypeLib As LongPtr) As Boolean If this.pCurrentTL <= 0 Then Exit Function outITypeLib = this.pCurrentTL tryGetCurrentRawITypeLibPtr = True End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com ... and this module deals with the IVBEComponent interface. We can't just write our own IVBEComponent interface and cast to that, as VBA does not let you specify the GUID like you can in C#, so this is where the VTables and function pointer invocations really come in: Module TypeInfoExtensions '@Folder "TypeInfoInvoker" Option Private Module Option Explicit ''' FROM RubberDuck '<Summary> An internal interface exposed by VBA for all components (modules, class modules, etc) '<remarks> This internal interface is known to be supported since the very earliest version of VBA6 '[ComImport(), Guid("DDD557E1-D96F-11CD-9570-00AA0051E5D4")] '[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] 'Public Enum IVBEComponentVTableOffsets '+3 for the IUnknown ' CompileComponentOffset = 12 + 3 'void CompileComponent(); ' GetStdModAccessorOffset = 14 + 3 'IDispatch GetStdModAccessor(); ' GetSomeRelatedTypeInfoPtrsOffset = 34 + 3 'void GetSomeRelatedTypeInfoPtrs(out IntPtr a, out IntPtr b); // returns 2 TypeInfos, seemingly related to this ITypeInfo, but slightly different. 'End Enum Public Type IVBEComponentVTable 'undocumented structure for accessing the module object IUnknown As COMTools.IUnknownVTable placeholder(1 To 12) As LongPtr CompileComponent As LongPtr placeholder2(1 To 1) As LongPtr GetStdModAccessor As LongPtr placeholder3(1 To 19) As LongPtr GetSomeRelatedTypeInfoPtrs As LongPtr End Type: Public IVBEComponentVTable As IVBEComponentVTable Public Property Get IVBEComponentVTableOffset(ByRef member As LongPtr) As LongPtr IVBEComponentVTableOffset = VarPtr(member) - VarPtr(IVBEComponentVTable) End Property
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com '@Description("Invoke IVBEComponent::GetStdModAccessor - re-raise error codes as VBA errors") Public Function GetStdModAccessor(ByVal pIVBEComponent As LongPtr) As Object Dim hresult As hResultCode hresult = COMTools.CallFunction(pIVBEComponent, IVBEComponentVTableOffset(IVBEComponentVTable.GetStdModAccessor), CR_HRESULT, CC_STDCALL, VarPtr(GetStdModAccessor)) If hresult = S_OK Then Exit Function Err.Raise hresult, "GetStdModAccessor", "Function did not succeed. IVBEComponent::GetStdModAccessor HRESULT: 0x" & Hex$(hresult) End Function 2. Getting the extended type information Now we have a StdModAccessor and ITypeInfo for each module in a project, RD has a second trick. The StdModAccessor nominally only lets you call public methods. However calling a method happens in 2 stages: IDispatch::GetIDsOfNames takes the string name of the function (and arguments) and converts them to dispatch ids (DISPIDS). This function only works with names of public methods. IDispatch::Invoke takes a DISPID (and any parameters of the method) and calls whatever function happens to be associated with that DISPID public or private
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Therefore, rather than using IDispatch::GetIDsOfNames to generate a DISPID given a method name, we instead get the DISPID from the module's type info which has all the methods. This module is responsible for navigating the ITypeInfo which is challenging as for some stupid reason stdole2.tlb defines but forbids the usage of many of the important types and interfaces becuse they are not "automation compatible", so I have written them again in COMTools.xlam. Module TypeInfoHelper NOTE: right now this returns a dictionary of {methodName: DISPID} but could be expanded with named arguments and other useful data for reflection '@Folder "TLI" Option Explicit Option Private Module 'Created by JAAFAR 'Src: https://www.vbforums.com/showthread.php?846947-RESOLVED-Ideas-Wanted-ITypeInfo-like-Solution&p=5449985&viewfull=1#post5449985 'Modified by wqweto 2020 (clean up) 'Modified by Greedo 2022 (refactor) '@ModuleDescription("ITypeInfo parsing/navigation without TLBINF32.dll. We don't want that because (1) It's no longer included in Windows, and (2) It ignores the type info marked as 'private', which we want to see") '@Description("Returns a map of funcName:dispid given a certain ITypeInfo without TLBINF32.dll") Public Function GetFuncDispidFromTypeInfo(ByVal ITypeInfo As IUnknown) As Scripting.Dictionary Dim attrs As TYPEATTR attrs = getAttrs(ITypeInfo)
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Dim result As Scripting.Dictionary Set result = New Scripting.Dictionary result.CompareMode = TextCompare 'so we can look names up in a case insensitive manner Dim funcIndex As Long For funcIndex = 0 To attrs.cFuncs - 1 Dim funcDescriptior As FUNCDESC funcDescriptior = getFuncDesc(ITypeInfo, funcIndex) Dim funcName As String funcName = getFuncNameFromDescriptor(ITypeInfo, funcDescriptior) With funcDescriptior Debug.Print "[INFO] "; funcName & vbTab & Switch( _ .INVOKEKIND = INVOKE_METHOD, "VbMethod", _ .INVOKEKIND = INVOKE_PROPERTYGET, "VbGet", _ .INVOKEKIND = INVOKE_PROPERTYPUT, "VbLet", _ .INVOKEKIND = INVOKE_PROPERTYPUTREF, "VbSet" _ ) & "@" & .memid 'property get/set all have the same dispid so only need to be here once If Not result.Exists(funcName) Then result.Add funcName, .memid ElseIf result(funcName) <> .memid Then Err.Raise 5, Description:=funcName & "is already associated with another dispid" Else Debug.Assert .INVOKEKIND <> INVOKE_METHOD 'this method & dispid should not appear twice End If End With funcName = vbNullString Next Set GetFuncDispidFromTypeInfo = result End Function Public Function getFuncNameFromDescriptor(ByVal ITypeInfo As IUnknown, ByRef inFuncDescriptor As FUNCDESC) As String getFuncNameFromDescriptor = getDocumentation(ITypeInfo, inFuncDescriptor.memid) End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Function getModName(ByVal ITypeInfo As IUnknown) As String getModName = getDocumentation(ITypeInfo, KnownMemberIDs.MEMBERID_NIL) End Function Private Function getDocumentation(ByVal ITypeInfo As IUnknown, ByVal memid As dispid) As String 'HRESULT GetDocumentation( [in] MEMBERID memid, [out] BSTR *pBstrName, [out] BSTR *pBstrDocString, [out] DWORD *pdwHelpContext, [out] BSTR *pBstrHelpFile) Dim hresult As hResultCode hresult = COMTools.CallCOMObjectVTableEntry(ITypeInfo, ITypeInfoVTableOffset(ITypeInfoVTable.getDocumentation), CR_HRESULT, memid, VarPtr(getDocumentation), NULL_PTR, NULL_PTR, NULL_PTR) If hresult <> S_OK Then Err.Raise hresult End Function Public Function getAttrs(ByVal ITypeInfo As IUnknown) As TYPEATTR 'HRESULT GetTypeAttr([out] TYPEATTR **ppTypeAttr ) Dim hresult As hResultCode Dim pTypeAttr As LongPtr hresult = COMTools.CallCOMObjectVTableEntry(ITypeInfo, ITypeInfoVTableOffset(ITypeInfoVTable.GetTypeAttr), CR_HRESULT, VarPtr(pTypeAttr)) If hresult <> S_OK Then Err.Raise hresult 'make a local copy of the data so we can safely release the reference to the type attrs object 'TODO Is it safe? Does this make the info in the attrs structure invalid? CopyMemory getAttrs, ByVal pTypeAttr, LenB(getAttrs) 'void ITypeInfo::ReleaseTypeAttr( [in] TYPEATTR *pTypeAttr) COMTools.CallCOMObjectVTableEntry ITypeInfo, ITypeInfoVTableOffset(ITypeInfoVTable.ReleaseTypeAttr), CR_None, pTypeAttr pTypeAttr = NULL_PTR 'good practice to null released pointers so we don't accidentally use them End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Function getFuncDesc(ByVal ITypeInfo As IUnknown, ByVal index As Long) As FUNCDESC 'HRESULT GetFuncDesc([in] UINT index, [out] FUNCDESC **ppFuncDesc) Dim hresult As hResultCode Dim pFuncDesc As LongPtr hresult = COMTools.CallCOMObjectVTableEntry(ITypeInfo, ITypeInfoVTableOffset(ITypeInfoVTable.getFuncDesc), CR_HRESULT, index, VarPtr(pFuncDesc)) If hresult <> S_OK Then Err.Raise hresult 'logic same as in tryGetAttrs CopyMemory getFuncDesc, ByVal pFuncDesc, LenB(getFuncDesc) 'void ReleaseFuncDesc( [in] FUNCDESC *pFuncDesc) COMTools.CallCOMObjectVTableEntry ITypeInfo, ITypeInfoVTableOffset(ITypeInfoVTable.ReleaseFuncDesc), CR_None, pFuncDesc pFuncDesc = NULL_PTR End Function 3. Creating the FancyAccessor This is the final bit linking everything together. At this point, RD just uses: IDispatchHelper.Invoke(staticModule, func.memid, DISPATCH_METHOD, args) However, I don't like that user interface. What I really want is something like this with dot notation: Public Function Shout(arg1, arg2) ... Private Function Whisper(arg1, arg2) ... Set mod As Object = StdModAccessor() result1 = mod.Shout(1,2) 'fine result2 = mod.Whisper(1,2) 'fails - private method Set mod = FancyAccessor() result1 = mod.Shout(1,2) 'fine result2 = mod.Hi(1,2) 'succeeds - ITypeInfo lets us call private methods But that means creating an object returned by the FancyAccessor function which can have arbitrary methods you can dot.Invoke(). So how can you overload what the dot operator does for FancyAccessor objects? Again, the implementation of this is quite complex, but the principle is pretty simple. All I do is this:
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Make some class in VBA (I called it SwapClass). Overwrite the IDispatch::GetIDsOfNames and IDispatch::Invoke entries in that class's VTable (remember - calling a late bound method on an object equates to calling those two methods, so if we change them we can get a different thing to happen when VBA tries to make a late bound call on the object). Replace SwapClass/IDispatch::GetIDsOfNames with a custom method that looks up the name in our {name:DISPID} map based on the extended ITypeInfo from section (2) - this will return ids of public and private methods. Replace SwapClass/IDispatch::Invoke with a custom method that forwards the call onto StdModAccessor/IDispatch::Invoke Return the SwapClass instance As Object - i.e. late bound so VBA has to use the (now overloaded) IDispatch interface. Here is the slightly complex implementation of that: Interface IDispatchVB As you can see, this interface defines the IDispatch methods we want to overload. They will be used to swap with the default existing IDispatch VTable. Implementing an interface is not strictly necessary, as SwapClass' default instance could define them without implementing this interface. However using an interface means the location of these custom overloads is well defined in the VTable, making the swap easier to execute. '@Folder "TypeInfoInvoker.DispatchWrapper" Option Explicit '@Interface 'IDispatch:: GetIDsOfNames method 'IDispatch:: GetTypeInfo method 'IDispatch:: GetTypeInfoCount method 'IDispatch:: invoke method Public Sub GetIDsOfNamesVB( _ ByVal riid As LongPtr, _ ByVal namesArray As LongPtr, _ ByVal cNames As Long, _ ByVal lcid As Long, _ ByVal dispidArray As LongPtr _ ) 'HRESULT GetIDsOfNames( ' [in] REFIID riid, ' [in] LPOLESTR *rgszNames, ' [in] UINT cNames, ' [in] LCID lcid, ' [out] dispid * rgDispId '); End Sub
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Sub InvokeVB( _ ByVal dispIDMember As Long, _ ByVal riid As LongPtr, _ ByVal lcid As Long, _ ByVal wFlags As Integer, _ ByVal pDispParams As LongPtr, _ ByVal pVarResult As LongPtr, _ ByVal pExcepInfo As LongPtr, _ ByVal puArgErr As LongPtr _ ) 'HRESULT Invoke( ' [in] DISPID dispIdMember, ' [in] REFIID riid, ' [in] LCID lcid, ' [in] WORD wFlags, ' [in, out] DISPPARAMS *pDispParams, ' [out] VARIANT *pVarResult, ' [out] EXCEPINFO *pExcepInfo, ' [out] UINT * puArgErr '); End Sub Helper Module DispatchVBTypes This defines the layout of IDispatchVBVTable based on the above interface. This will allow us to locate the pointers of our custom overloads so we can replace the default IDispatch functions. '@Folder "TypeInfoInvoker.DispatchWrapper" Option Private Module Option Explicit 'https://github.com/wine-mirror/wine/blob/master/include/winerror.h 'TODO move to COMtools Public Enum DISPGetIDsOfNamesErrors DISP_E_UNKNOWNNAME = &H80020006 DISP_E_UNKNOWNLCID = &H8002000C End Enum Public Type IDispatchVBVTable IDispatch As IDispatchVTable GetIDsOfNamesVB As LongPtr InvokeVB As LongPtr End Type: Public IDispatchVBVTable As IDispatchVBVTable Public Property Get IDispatchVBVTableOffset(ByRef member As LongPtr) As LongPtr IDispatchVBVTableOffset = VarPtr(member) - VarPtr(IDispatchVBVTable) End Property Class SwapClass Here's where the magic happens. In Class_Initialize() we copy the VTable items at index 7 & 8 of the IDispatchVB interface's VTable to index 5 & 6 respectively, swapping whatever is in the default IDispatch implementation with our custom overloads. The change persists a long time after the class goes out of scope, so Class_Initialize is used to avoid cache invalidation. '@Folder "TypeInfoInvoker.DispatchWrapper" Option Explicit
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Implements IDispatchVB 'For the VTable swap Implements IModuleInfo 'Easy access to additional methods Private Declare PtrSafe Function SysReAllocString Lib "oleaut32.dll" (ByVal pBSTR As LongPtr, Optional ByVal pszStrPtr As LongPtr) As Long Public accessor As Object Public ITypeInfo As IUnknown Private Sub Class_Initialize() Dim asDisp As IDispatchVB Set asDisp = Me Dim pAsDispVT As LongPtr pAsDispVT = memlongptr(ObjPtr(asDisp)) Dim pInvokeVB As LongPtr, pInvokeOriginal As LongPtr pInvokeVB = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.InvokeVB) pInvokeOriginal = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.IDispatch.Invoke) Dim pGetIDsOfNamesVB As LongPtr, pGetIDsOfNamesOriginal As LongPtr pGetIDsOfNamesVB = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.GetIDsOfNamesVB) pGetIDsOfNamesOriginal = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.IDispatch.GetIDsOfNames) 'swap the vtable entries memlongptr(pGetIDsOfNamesOriginal) = memlongptr(pGetIDsOfNamesVB) memlongptr(pInvokeOriginal) = memlongptr(pInvokeVB) End Sub Private Property Get funcs() 'NOTE cached assuming you cannot modify typeinfo at all at runtime (i.e. you cannot edit a module while vba is running) 'TODO Check if this holds True for VBComponents.Add Static result As Dictionary If result Is Nothing Then Set result = TypeInfoHelper.GetFuncDispidFromTypeInfo(ITypeInfo) Set funcs = result End Property
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Private Sub IDispatchVB_GetIDsOfNamesVB(ByVal riid As LongLong, ByVal namesArray As LongLong, ByVal cNames As Long, ByVal lcid As Long, ByVal dispidArray As LongLong) 'Debug.Assert cNames = 1 Debug.Assert Not ITypeInfo Is Nothing Debug.Assert Not accessor Is Nothing Dim i As Long For i = 0 To cNames - 1 Dim name As String name = GetStrFromPtrW(memlongptr(namesArray + PTR_SIZE * i)) If funcs.Exists(name) Then MemLong(dispidArray + PTR_SIZE * i) = CLng(funcs(name)) Else MemLong(dispidArray + PTR_SIZE * i) = -1 'unrecognised 'REVIEW: SetLastError DISPGetIDsOfNamesErrors.DISP_E_UNKNOWNNAME ? Err.Raise DISPGetIDsOfNamesErrors.DISP_E_UNKNOWNNAME End If Next i End Sub Private Sub IDispatchVB_InvokeVB(ByVal dispIDMember As Long, ByVal riid As LongLong, ByVal lcid As Long, ByVal wFlags As Integer, ByVal pDispParams As LongLong, ByVal pVarResult As LongLong, ByVal pExcepInfo As LongLong, ByVal puArgErr As LongLong) Debug.Assert Not accessor Is Nothing Dim hresult As hResultCode hresult = COMTools.CallCOMObjectVTableEntry( _ accessor, IDispatchVTableOffset(IDispatchVTable.Invoke), _ CR_LONG, _ dispIDMember, _ riid, lcid, wFlags, _ pDispParams, _ pVarResult, pExcepInfo, puArgErr _ ) End Sub Private Property Get IModuleInfo_ExtendedITypeInfo() As IUnknown Set IModuleInfo_ExtendedITypeInfo = ITypeInfo End Property Private Property Get IModuleInfo_ModuleFuncInfoMap() As Dictionary Set IModuleInfo_ModuleFuncInfoMap = funcs End Property Private Property Get IModuleInfo_PublicOnlyModuleAccessor() As Object Set IModuleInfo_PublicOnlyModuleAccessor = accessor End Property
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Private Property Get IModuleInfo_ExtendedModuleAccessor() As Object Dim dipatchInterface As IDispatchVB 'need to cast me to the correct interface as only IDispatchVB is overloaded Set dipatchInterface = Me Set IModuleInfo_ExtendedModuleAccessor = dipatchInterface End Property 'Returns a copy of a null-terminated Unicode string (LPWSTR/LPCWSTR) from the given pointer Private Function GetStrFromPtrW(ByVal Ptr As LongPtr) As String SysReAllocString VarPtr(GetStrFromPtrW), Ptr End Function NOTE: Only the IDispatchVB interface of the class has its IDispatch overloaded, other interfaces of the class (IModuleInfo, default SwapClass, etc.) are not overloaded. Therefore, I've added a method IModuleInfo_ExtendedModuleAccessor that returns the IDispatchVB cast As Object; this is our fancy module accessor! The IModuleInfo interface also facilitates access to the other bits of data about the module. '@Folder "TypeInfoInvoker.DispatchWrapper" '@Exposed Option Explicit '@Description("The Extended ITypeInfo interface for the module this accessor refers to") Public Property Get ExtendedITypeInfo() As IUnknown End Property '@Description("Parsed map of ProcedureName:Info for methods of the extended module accessor (public/private)") Public Property Get ModuleFuncInfoMap() As Dictionary End Property '@Description("Base accessor for accessing public members of a module using standard late binding") Public Property Get PublicOnlyModuleAccessor() As Object End Property '@Description("Rich accessor for accessing public and private members of any module based on extended ITypeInfo") Public Property Get ExtendedModuleAccessor() As Object End Property
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Overloading the SwapClass functions like this will leave SwapClass itself as a broken class whose IDispatch implementation does not make sense at all (so we can't let users instantiate SwapClass or cast to that interface). However it will produce a new, better module accessor object that has the power of RD's clever approach with the simplicity of normal late bound VBA code. An advantage of this is that VBA is now responsible for coercing arguments into a DISPARAMS structure, which means things like Property Let/ Set which are usually quite difficult to implement (RD has not got round to it yet), we get free of charge. In fact, the only thing missing right now is named function arguments. Finally... This is the entry point module, that just calls the 3 steps to assemble an accessor for a given module and return it. The interface returned is the overloaded IDispatch of SwapClass (although the consumer will never know that; it is an implementation detail). What they can do is cast to the IModuleInfo interface which will give them access to the raw type info and accessors for maximum flexibility. Module API '@Folder("TypeInfoInvoker") Option Explicit '@EntryPoint Public Function GetFancyAccessor(Optional ByVal moduleName As String = "ExampleModule", Optional ByVal projectName As Variant) As Object Dim project As String project = IIf(IsMissing(projectName), Application.VBE.ActiveVBProject.name, projectName) Dim moduleTypeInfo As TypeInfo Dim accessor As Object Dim pITypeLib As LongPtr Set accessor = StdModuleAccessor(moduleName, project, moduleTypeInfo, pITypeLib) 'not sure why but not the same as moduleTypeInfo.ITypeInfo - different objects Dim moduleITypeInfo As IUnknown Set moduleITypeInfo = getITypeInfo(moduleName, pITypeLib) 'calling ITypeInfo::GetIDsOfNames, DispGetIDsOfNames etc. does not work Set GetFancyAccessor = tryMakeFancyAccessor(accessor, moduleITypeInfo).ExtendedModuleAccessor End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com End Function 'The IModuleInfo interface gives simplified access to the accessor IDispatch interface Private Function tryMakeFancyAccessor(ByVal baseAccessor As IUnknown, ByVal ITypeInfo As IUnknown) As IModuleInfo Dim result As SwapClass Set result = New SwapClass Set result.accessor = baseAccessor Set result.ITypeInfo = ITypeInfo Set tryMakeFancyAccessor = result End Function Private Function getITypeInfo(ByVal moduleName As String, ByVal pITypeLib As LongPtr) As IUnknown 'HRESULT FindName( ' [in, out] LPOLESTR szNameBuf, ' [in] ULONG lHashVal, ' [out] ITypeInfo **ppTInfo, ' [out] MEMBERID *rgMemId, ' [in, out] USHORT * pcFound '); Dim hresult As hResultCode Dim pModuleITypeInfoArray(1 To 1) As LongPtr Dim memberIDArray(1 To 1) As Long '@Ignore IntegerDataType Dim pcFound As Integer 'number of matches pcFound = 1 'call ITypeLib::FindName to get the module specific type info hresult = COMTools.CallFunction( _ pITypeLib, ITypeLibVTableOffset(ITypeLibVTable.FindName), _ CR_HRESULT, CC_STDCALL, _ StrPtr(moduleName), _ 0&, _ VarPtr(pModuleITypeInfoArray(1)), _ VarPtr(memberIDArray(1)), _ VarPtr(pcFound)) If hresult <> S_OK Then Err.Raise hresult Set getITypeInfo = ObjectFromObjPtr(pModuleITypeInfoArray(1)) End Function Here's my folder structure: Project file structure with files with numbers corresponding to step 1, 2 and 3 of this post Applications A couple of ideas:
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Applications A couple of ideas: Passing a module as an argument to a late bound function - makes duck-typed code easier. Find and execute all methods in a module or project called xxx_Test If projectB.xlsm references projectA.xlam, ordinarily projectA is not aware of this. However now, projectA has the ability to see what other projects are loaded, and even call their methods. You could make projectA a code profiling addin that automatically detects and profiles whatever projects reference it - like python's timeit OK I'm going to stop typing now;) Update I tried removing the dependency on TLI (TLBINF32.dll) and it actually wasn't too tricky, just add the following classes as a drop in replacement (for the bits I was using, a tiny subset) Module TypeLibHelper Does the COM calls on ITypeLib interface to help navigate it '@Folder "TLI" Option Explicit Public Function getITypeInfoByIndex(ByVal ITypeLib As IUnknown, ByVal index As Long) As IUnknown '4 HRESULT GetTypeInfo( ' /* [in] */ UINT index, ' /* [out] */ __RPC__deref_out_opt ITypeInfo **ppTInfo) = 0; Dim hresult As hResultCode Dim pITypeInfo As LongPtr hresult = COMTools.CallCOMObjectVTableEntry(ITypeLib, ITypeLibVTableOffset(ITypeLibVTable.getTypeInfo), CR_HRESULT, index, VarPtr(pITypeInfo)) If hresult <> S_OK Then Err.Raise hresult Set getITypeInfoByIndex = COMTools.ObjectFromObjPtr(pITypeInfo) End Function Public Function getTypeInfoCount(ByVal ITypeLib As IUnknown) As Long '3 UINT GetTypeInfoCount( void) = 0; 'TODO: assert not nothing getTypeInfoCount = COMTools.CallCOMObjectVTableEntry(ITypeLib, ITypeLibVTableOffset(ITypeLibVTable.getTypeInfoCount), CR_LONG) End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Public Function getProjName(ByVal ITypeLib As IUnknown) As String getProjName = getDocumentation(ITypeLib, KnownMemberIDs.MEMBERID_NIL) End Function Private Function getDocumentation(ByVal ITypeLib As IUnknown, ByVal memid As dispid) As String ' virtual /* [local] */ HRESULT STDMETHODCALLTYPE GetDocumentation( ' /* [in] */ INT index, ' /* [annotation][out] */ ' _Outptr_opt_ BSTR *pBstrName, ' /* [annotation][out] */ ' _Outptr_opt_ BSTR *pBstrDocString, ' /* [out] */ DWORD *pdwHelpContext, ' /* [annotation][out] */ ' _Outptr_opt_ BSTR *pBstrHelpFile) = 0; Dim hresult As hResultCode hresult = COMTools.CallCOMObjectVTableEntry(ITypeLib, ITypeLibVTableOffset(ITypeLibVTable.getDocumentation), CR_HRESULT, memid, VarPtr(getDocumentation), NULL_PTR, NULL_PTR, NULL_PTR) If hresult <> S_OK Then Err.Raise hresult End Function ... which is wrapped by a class for convenience: Wrapper Class TypeLibInfo '@Folder("TLI") Option Explicit Private Type TTypeLibInfo ITypeLib As IUnknown typeInfos As TypeInfoCollection End Type Private this As TTypeLibInfo Public Property Get name() As String name = TypeLibHelper.getProjName(ITypeLib) End Property Public Property Get ITypeLib() As IUnknown Debug.Assert Not this.ITypeLib Is Nothing Set ITypeLib = this.ITypeLib End Property Public Property Set ITypeLib(ByVal RHS As IUnknown) Set this.ITypeLib = RHS Set this.typeInfos = TypeInfoCollection.Create(ITypeLib) End Property Public Function getTypeInfoByName(ByVal name As String) As ModuleReflection.TypeInfo Set getTypeInfoByName = this.typeInfos.Find(name) End Function
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com That TypeLibInfo class generates a collection of the ITypeInfos each wrapped in a TypeInfo wrapper for ease of access and all held in a TypeInfoCollection which allows TypeInfos to be filtered by name: Predeclared Class TypeInfoCollection '@PredeclaredId '@Folder("TLI") Option Explicit Private Type TTypeInfoCollection ITypeLib As IUnknown typeInfos As New Dictionary count As Long End Type Private this As TTypeInfoCollection Public Property Get ITypeLib() As IUnknown Debug.Assert Not this.ITypeLib Is Nothing Set ITypeLib = this.ITypeLib End Property Public Property Set ITypeLib(ByVal RHS As IUnknown) Set this.ITypeLib = RHS this.count = TypeLibHelper.getTypeInfoCount(ITypeLib) End Property Private Function tryGenerateNext(ByRef outITypeInfo As TypeInfo) As Boolean Static i As Long 'zero indexed If i >= this.count Then Exit Function On Error Resume Next Dim rawITypeInfo As IUnknown Set rawITypeInfo = TypeLibHelper.getITypeInfoByIndex(ITypeLib, i) i = i + 1 Dim noErrors As Boolean noErrors = Err.Number = 0 On Error GoTo 0 If noErrors Then Set outITypeInfo = New TypeInfo Set outITypeInfo.ITypeInfo = rawITypeInfo tryGenerateNext = True End If End Function Public Function Create(ByVal wrappedITypeLib As IUnknown) As TypeInfoCollection Dim result As New TypeInfoCollection Set result.ITypeLib = wrappedITypeLib Set Create = result End Function Public Function Find(ByVal name As String) As TypeInfo Do While Not this.typeInfos.Exists(name) Dim wrappedTI As TypeInfo If Not tryGenerateNext(wrappedTI) Then Err.Raise 5, Description:="That name can't be found" this.typeInfos.Add wrappedTI.name, wrappedTI Loop Set Find = this.typeInfos.Item(name) End Function Wrapper Class TypeInfo '@Folder("TLI") Option Explicit Private Type TTypeInfo ITypeInfo As IUnknown End Type
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Private Type TTypeInfo ITypeInfo As IUnknown End Type Private this As TTypeInfo Public Property Get ITypeInfo() As IUnknown Debug.Assert Not this.ITypeInfo Is Nothing Set ITypeInfo = this.ITypeInfo End Property Public Property Set ITypeInfo(ByVal RHS As IUnknown) Set this.ITypeInfo = RHS End Property Public Property Get name() As String name = getModName(ITypeInfo) End Property Private Function attrs() As COMTools.TYPEATTR Static result As TYPEATTR 'check if already set If result.aGUID.data1 = 0 Then result = TypeInfoHelper.getAttrs(ITypeInfo) attrs = result End Function Finally, the methods are called from a module Module TLI '@Folder("TLI") Option Explicit Public Const NULL_PTR As LongPtr = 0 Public Enum KnownMemberIDs MEMBERID_NIL = -1 End Enum Public Function TypeLibInfoFromITypeLib(ByVal ITypeLib As IUnknown) As TypeLibInfo Dim result As New TypeLibInfo Set result.ITypeLib = ITypeLib Set TypeLibInfoFromITypeLib = result End Function The download links have been updated accordingly. Answer: Private Function NextTypeLib() As LongPtr If this.currentTL.Next = 0 Then Err.Raise 5, Description:="We've reached the end of the line" NextTypeLib = this.currentTL.Next currentTL = this.currentTL.Next 'move the iterator along End Function '@Description("Gets type library com objects from list") Public Function TryGetNext(ByRef outTypeLib As TypeLibInfo) As Boolean On Error GoTo cleanFail Dim tlPtr As LongPtr tlPtr = NextTypeLib Set outTypeLib = TLI.TypeLibInfoFromITypeLib(ObjectFromObjPtr(tlPtr)) TryGetNext = True
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com This is an off-by-one error; after the Reset to the first element of the list of typelibs, the first call to TryGetNext calls NextTypeLib = this.currentTL.Next meaning the first item returned is actually the second typelib. The first typelib is always skipped - this breaks the technique for all unsaved 64 bit projects, and unsaved or saved 32 bit projects with no other references. Easy fix is to call .Next after assigning the return value to avoid skipping the first one, being careful not to dereference memory beyond the end of the list. SwapClass Private Sub Class_Initialize() Dim asDisp As IDispatchVB Set asDisp = Me Dim pAsDispVT As LongPtr pAsDispVT = memlongptr(ObjPtr(asDisp)) Dim pInvokeVB As LongPtr, pInvokeOriginal As LongPtr pInvokeVB = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.InvokeVB) pInvokeOriginal = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.IDispatch.Invoke) Dim pGetIDsOfNamesVB As LongPtr, pGetIDsOfNamesOriginal As LongPtr pGetIDsOfNamesVB = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.GetIDsOfNamesVB) pGetIDsOfNamesOriginal = pAsDispVT + IDispatchVBVTableOffset(IDispatchVBVTable.IDispatch.GetIDsOfNames) 'swap the vtable entries memlongptr(pGetIDsOfNamesOriginal) = memlongptr(pGetIDsOfNamesVB) memlongptr(pInvokeOriginal) = memlongptr(pInvokeVB) End Sub Swapping the VTable of the IDispatchVB interface only overloads that interface. If I do something like: Dim fancyAccessor As Object Set fancyAccessor = GetFancyAccessor("myModule") 'late bound IDispatchVB interface with overloaded VTable Dim unkInterface As IUnknown Set unkInterface = FancyAccessor 'IUnknown::QueryInterface(IID_IUNKNOWN) Dim accessorAfterQI As Object Set accessorAfterQI = unkInterface 'IUnknown::QueryInterface(IID_IDISPATCH)
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
vba, pointers, reflection, rubberduck, com Debug.Assert ObjPtr(accessorAfterQI) = ObjPtr(fancyAccessor) 'fails ... 'This makes sense because IID_IDISPATCHVB <> IID_IDISPATCH, ' so we can expect 2 different interface pointers and you don't break COM/IUnknown rules. 'But because you only overloaded the IDispatchVB's IDispatch vtable not the root vtable, ' the overloaded implementation won't be called which is bad UX and does break COM's rules on IDispatch, ' specifically that the IUnknown & IDispatch implementations of each of the dual interfaces of an object ' should all do the same thing The two variables declared "As Object" should point to the same (overloaded) IDispatch instance. But they don't. This is because the second one points to the root IDispatch interface, which is not the same one. Easy fix is to overload the IDispatch implementation of the default interface, meaning whenever the client asks for IID_IDISPATCH, they always get the overloaded version. Downside is this means the VTable layout is dependent on the order the SwapClass is written in VBA which is less robust and predictable than implementing a custom interface. Both these changes have been implemented when I ported the code to twinBASIC https://github.com/Greedquest/vbInvoke
{ "domain": "codereview.stackexchange", "id": 44401, "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, pointers, reflection, rubberduck, com", "url": null }
javascript, stream Title: Stream Implementation In JavaScript Question: I usually do not create Streams, but it seems that JavaScript doesn't have a built-in one and I figured I would do it for a personal project I am working on. This code seems to work as intended and does what I want just fine, but I have concerns mainly about how often I am checking my buffer. I am mainly looking for a recommendation about how often I should check to see if any data has been written to my buffer. If there are any other improvements/suggestions, I am open to hearing them! Edit: After thinking about this more, I realized I could do this as event-driven instead and let the system/browser handle the blocking. I left both functions in so people can weigh in on either one. However, I would still like input on the first approach for general knowledge. const StreamPrototype = { _data: [], _callbacks: [], readAsync: async function* () { while(await sleep(25)) { let data; while((data = this._data.pop())) yield data; } }, onData: function(callback) { if (callback instanceof Function) this._callbacks.push(callback); }, push: function(data) { if (data) { this._pushOntoStack(data); } }, _pushOntoStack: async function(data) { return new Promise(resolve => { this._data.push(data); // Uses Sleeps this._callbacks.forEach(item => { // Pushes data out using event-driven item(data); }); }); } }; // This was just copied from the internet const sleep = time => new Promise(res => setTimeout(res, time, "done sleeping")); Answer: This doesn't look like a nice approach. For one, you don't really need that 25ms waiting like polling. So assuming that you're working with WebSockets like // Create WebSocket connection. const socket = new WebSocket('ws://localhost:8080');
{ "domain": "codereview.stackexchange", "id": 44402, "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, stream", "url": null }
javascript, stream // Listen for messages socket.addEventListener('message', (event) => { console.log('Message from server ', event.data); }); You may merge the async "message" event listener and others like "error", "open", "close" etc, under one async iterable and consume with for await of loop as follows. Note that we don't need to use an async generator here since we are yielding promises. function wsMessageStream(url){ let _v, // previous resolve _x, // previous reject p = new Promise((v,x) => (_v = v, _x = x)), ws = new WebSocket(url); function* emitterGen(ws){ ws.addEventListener( "open" , _ => ( _v({data: `Esatablished WebSocket connection for ${url}.`}) , p = new Promise((v,x) => (_v = v, _x = x)) ) ); ws.addEventListener( "close" , _ => ( _v({data: `Closed WebSocket connection for ${url}.`}) , _v = null , _x = null ) ); ws.addEventListener( "message" , m => ( _v(m) , p = new Promise((v,x) => (_v = v, _x = x)) ) ); ws.addEventListener( "error" , e => ( _x(e) , p = new Promise((v,x) => (_v = v, _x = x)) ) ); while (_v || _x){ try{ yield p; } catch(e){ console.log(e); } } return Promise.resolve(null); // finalize the iterable } return { stream: emitterGen(ws) , socket: ws }; } let {stream,socket} = wsMessageStream('wss://ws.postman-echo.com/raw'), counter = 0; setTimeout(_ => socket.close(), 5000); (async function(){
{ "domain": "codereview.stackexchange", "id": 44402, "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, stream", "url": null }
javascript, stream (async function(){ for await (let msg of stream){ console.log(`Message received: ${msg.data}`); // run msg handlers here socket.readyState === 1 && socket.send(`Thank you. ${counter++}`); } })();
{ "domain": "codereview.stackexchange", "id": 44402, "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, stream", "url": null }
python, linked-list, memory-management, complexity Title: Doubly linked list first fit free list malloc/free in Python Question: As an exercise I've implemented malloc and free in Python as a first fit free list as described here. This tracks which blocks are free in a doubly linked list that is sorted by the address of the first byte of the block. It also keeps track of the size of each allocated block in a dictionary. The time complexity is \$O(N)\$ for both malloc and free, where \$N\$ is the number of free blocks. from typing import Optional class Block(): def __init__(self, size: int, address: int): self.address: int = address self.size = size self.prev: Optional[Block] = None self.next: Optional[Block] = None def __str__(self): return f"(start {self.address}, size {self.size})" def __repr__(self): return f"(start {self.address}, size {self.size})" class Heap(): def __init__(self, size: int): self.size = size self.head: Optional[Block] = Block(size, 0) self.allocation_headers: dict[int, int] = {} def num_free_blocks(self) -> int: block = self.head total = 0 while block: total += 1 block = block.next return total def free_size(self) -> int: block = self.head total = 0 while block: total += block.size block = block.next return total def total_size(self) -> int: free = self.free_size() allocated = sum(self.allocation_headers.values()) return allocated + free
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
python, linked-list, memory-management, complexity def malloc(self, size: int) -> int: if size <= 0: raise Exception # Sort the linked list by address block = self.head while block: if block.size >= size: self.allocation_headers[block.address] = size return_address = block.address if block.size == size: # remove the block if block.prev: block.prev.next = block.next if block.next: block.next.prev = block.prev if self.head == block: self.head = block.next else: # make the block smaller block.address += size block.size -= size return return_address block = block.next raise Exception def free(self, ptr: int): """ Take an address pointer ptr and free it. All we need to do to free is to add an element to the free list. """ free_size = self.allocation_headers[ptr] del self.allocation_headers[ptr] prev = None block = self.head while block and block.address < ptr: prev = block block = block.next new_block = Block(free_size, ptr) if not self.head: self.head = new_block if prev: prev.next = new_block new_block.prev = prev if block: block.prev = new_block new_block.next = block if self.head == block: self.head = new_block
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
python, linked-list, memory-management, complexity # coalesce next if new_block.next and new_block.next.address == (new_block.address + new_block.size): new_block.size += new_block.next.size new_block.next = new_block.next.next if new_block.next: new_block.next.prev = new_block # coalesce prev if new_block.prev and new_block.address == (new_block.prev.address + new_block.prev.size): new_block.prev.size += new_block.size new_block.prev.next = new_block.next if new_block.prev.next: new_block.prev.next.prev = new_block.prev Example usage: def test_case_1(): heap = Heap(1000) assert (heap.total_size() == 1000) assert (heap.num_free_blocks() == 1) assert (heap.free_size() == 1000) a = heap.malloc(100) assert (heap.num_free_blocks() == 1) assert (heap.free_size() == 900) assert (a == 0) b = heap.malloc(500) assert (heap.num_free_blocks() == 1) assert (heap.free_size() == 400) assert (b == 100) try: heap.malloc(950) except: pass heap.free(b) assert (heap.num_free_blocks() == 1) assert (heap.free_size() == 900) heap.free(a) try: heap.free(a) except: pass heap.malloc(950) print("Test case 1 succeeded!")
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
python, linked-list, memory-management, complexity I believe this implementation is correct as I've fuzzed it with hundreds of millions of random inputs and all of these conditions were maintained: def perform_checks(self): forward_blocks: list[Block] = [] forward_addresses: list[int] = [] reverse_blocks: list[Block] = [] reverse_addresses: list[int] = [] tail = None block = self.head forward_length = 0 forward_free = 0 last_address = -1 while block: # zoom to the end assert (block.address > last_address) forward_addresses.append(block.address) forward_blocks.append(block) forward_length += 1 forward_free += block.size if not block.next: tail = block last_address = block.address block = block.next reverse_length = 0 reverse_free = 0 last_address = 1000000000 if self.head is not None: assert (tail is not None) while tail: assert (tail.address < last_address) reverse_blocks.append(tail) reverse_addresses.append(tail.address) reverse_length += 1 reverse_free += tail.size last_address = tail.address tail = tail.prev assert ( forward_length == reverse_length ), f"Forward length of {forward_length}, Reverse length of {reverse_length}" reverse_blocks.reverse() assert (forward_blocks == reverse_blocks) assert (forward_free == reverse_free) assert (self.total_size() == self.size ), f"Total size {self.total_size()}, size {self.size}" assert (forward_length == len(forward_addresses))
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
python, linked-list, memory-management, complexity However, I would like suggestions on improving the simplicity of the code. The time complexity and block fragmentation could be improved by switching to a best-fit red/black tree, but let's ignore that. Assuming a flat left-to-right heap, how can we improve this and maintain the \$O(N)\$ time complexity? Could the code be dramatically cleaned up by using a Python built-in data structure? Answer: Trivial DRY: __repr__() should simply return __str__(). If in future they diverge, then so be it. Type hint nit: self.address: int = address Maybe we don't need the int hint? Since address very helpfully offers it. And yes, definitely keep the hint in the signature. It is most visible and most helpful there. In general, I am loving your optional type hints, keep it up! I imagine mypy would be happy with such an input file. If I could criticize the whole Optional[Block] thing for a moment. Maybe have your machinery always allocate a 1-byte block? So there is always something in there? (Yeah, I know, we leaked one byte of storage. We'll get over it.) self.allocation_headers: dict[int, int] = {} I confess I do not understand the meaning of that identifier. It seems to me that self.allocation would be the natural name for such a mapping. I have no idea what the usage patterns on num_free_blocks() and free_size() are. If, in some realistic workload, profiling reveals they are called "a lot", consider making them take O(1) constant time. That is, we might choose to have the mutators maintain statistics which could be immediately returned. But let's return to the current O(n) linear implementation. The two functions are nearly identical. I am a little bit sad that we don't have some convenient iterator or other helper that they could rely on. I am reading malloc. if size <= 0: I am reading the spec If the size of the space requested is 0, the behavior is implementation-defined: the value returned shall be either a null pointer or a unique pointer.
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
python, linked-list, memory-management, complexity Recommend you name your function something other than malloc if you're not keen to support malloc semantics. Also, we can do much better than raising a generic Exception. Go to the trouble of subclassing it so caller will see a diagnostic error specific to your module. In particular, caller's try clause should be able to focus on just an AllocationError. This is correct: if block.size == size: # remove the block But consider relaxing that equality criterion. Suppose that caller is creating random strings with length between 10 and 20 characters that must be allocated. If we discretize allocations to, say, multiple of 4, then the if would find more opportunities to remove a block. In deployed systems, discretizing to logarithmic boundaries tends to be more practical. In free there is a while loop and several ifs. Please push them down into a helper function which computes prev and block and does some mutation. Thank you for providing automated unit tests. Please express the +inf constant as 1_000_000_000 or int(1e9). Please improve PEP-8 readability, perhaps by running the source through black. I've fuzzed it with various random inputs Potential off by one errors abound. Consider making hypothesis part of your test suite. Certainly it has taught me amazing things I never would have believed before. Overall? This is good code that achieves its design goals. I would be happy to accept or delegate maintenance tasks for it. Coalescing allocated chunks, at logarithmic granularity, seems the biggest opportunity for combating the somewhat ugly O(n) "linear cost with size of free list" overhead. There is a rich literature describing slab, buddy, and related allocators, likely far beyond the interests of this project. Pick an example workload, benchmark these library functions, describe the results, and see where you'd like to go from there!
{ "domain": "codereview.stackexchange", "id": 44403, "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, linked-list, memory-management, complexity", "url": null }
javascript Title: Adding classes from a given array or an object Question: I want to add classes to elements based on a source array or object. For example, it can be: classesArr = ["class1", "class2", "class3"]; or classesObj = {class1: "class1", class2: "class2", class3: "class3"}; the way I currently do it is: // for arrays element = document.getElementById("myelement"); classesArr.forEach(className => { element.classList.add(className); }); or // for objects element = document.getElementById("myelement"); for (const [key, className] of Object.entries(classesObj) { element.classList.add(className) } But perhaps there are some JavaScript tricks that can do it simpler (maybe even in 1 line?) Answer: You’re not using the keys of the returned 2D array of Object.entries, so you could use the flat Object.values instead. More importantly, the DOMTokenList.add method takes a list as its argument already, so there is no need to explicitly iterate as you can just spread the array for it (element.classList.add(...classesArr)). As a function, you could have the element being worked on be the argument so there wouldn’t be those loosely floating references to elements.
{ "domain": "codereview.stackexchange", "id": 44404, "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", "url": null }
c++, sorting, c++20 Title: Find steps to sort unsorted string list Question: Let's say that we have a list of strings and we want to find the steps (pair representing swaps to be made) to sort it. Here is my current implementation: #include <algorithm> #include <unordered_map> #include <vector> auto is_lexicographically_ordered = [](const std::string &s1, const std::string &s2) { return std::lexicographical_compare(s1.begin(), s1.end(), s2.begin(), s2.end()); }; std::vector<std::pair<std::string, std::string>> find_unsorted(const std::vector<std::string> &list) { std::vector<std::string> cpy(list); std::vector<std::string> sorted(list); std::vector<std::pair<std::string, std::string>> result; std::sort(sorted.begin(), sorted.end(), is_lexicographically_ordered); // Cache indices for faster retrieval in loop auto index_in_cpy = std::unordered_map<std::string, int>(); for (int i = 0; i < cpy.size(); ++i) index_in_cpy.insert({cpy.at(i), i}); // Find mistmatched between sorted and current list auto it = std::mismatch(cpy.begin(), cpy.end(), sorted.begin()); while (it.first != cpy.end()) { result.push_back(std::make_pair(*it.first, *it.second)); auto new_it = cpy.begin() + index_in_cpy.at(*it.second); std::iter_swap(it.first, new_it); it = std::mismatch(++it.first, cpy.end(), ++it.second); } // Merging paths because for { c, a, b, d }, we would get { c, a }, { c, b } and { c, d } // but we only need to move c after d auto u = std::unique(result.rbegin(), result.rend(), [](const auto &p1, const auto &p2) { return p1.first == p2.first; }); result.erase(result.begin(), u.base()); return result; } and here is an example on how to run it: int main(int argc, char const *argv[]) { for (auto &item : find_unsorted({ "a", "c", "b", "d" })) { std::cout << "(" << item.first << ", " << item.second << ")" << std::endl; } return 0; }
{ "domain": "codereview.stackexchange", "id": 44405, "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++, sorting, c++20", "url": null }
c++, sorting, c++20 Any feedback on how to improve runtime or storage space is welcome. Also, if you have more modern way of writing this (eg: range, etc.), feel free to recommend. Answer: Avoid copies of complex/big objects, especially if it involves a heap-allocation or anything similarly expensive. Just sort a list of indices. Use views (std::span) instead of constant references. It results in a more flexible interface without additional cost. Are you sure you want to return copies of pairs of objects, instead of indices?
{ "domain": "codereview.stackexchange", "id": 44405, "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++, sorting, c++20", "url": null }
javascript, security, html5 Title: sanitize untrusted input for templates Question: Attempting to populate HTML string-templates from untrusted input. function sanitizer(str, i, list){ return str + (this[i] ?? '').toString() .replace(/&/g, '&#x26;') .replace(/</g, '&#x3C;') .replace(/>/g, '&#x3E;') .replace(/'/g, '&#x27;') .replace(/"/g, '&#x22;') ; } function sanitize(str, ...input){ return str.map(sanitizer, input).join(''); } function template(data){ return sanitize`<div>${ data }</div>`; } ref: https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html#Output_Encoding_Rules_Summary Calling template('1<23') should render a HTMLDivElement with Text '1﹤23'. notable development since posting: https://developer.mozilla.org/en-US/docs/Web/API/Sanitizer https://developer.mozilla.org/en-US/docs/Web/API/HTML_Sanitizer_API previously this substituted for look-alike characters which works well generally, except for copy+paste, in which case a convert-back would solve for, and potentially avoids double-escaping/encoding problems: function sanitizer(str, i, list){ return str + (this[i] ?? '').toString() .replace(/&/g, '&') .replace(/</g, '﹤') .replace(/>/g, '﹥') .replace(/'/g, '’') .replace(/"/g, '”') .replace(/\//g, '/') ; }
{ "domain": "codereview.stackexchange", "id": 44406, "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, security, html5", "url": null }
javascript, security, html5 Answer: approach You are striking out in your own direction, preferring custom code over an upstream library that's been battle tested by a large community. This can be made to work. But using a supported library with a good track record would instill greater confidence that the real-world security goals have been achieved. security Do these functions correctly implement the cited OWASP advice? Yes, they do. Presenting unit tests with the code would yield a stronger security argument, and automated browser-specific Selenium system tests would be stronger still. This code attempts to alter DOM semantics without altering the rendered appearance. If you have use cases that could tolerate some corruption of user-supplied text, such as deliberately deleting certain characters, then again we would have a stronger security argument. Why would this be of interest? I can imagine future browser bugs where double rendering manages to undo your sanitizer transformation. Consider simplifying the sanitizer signature so it just accepts a single string, putting responsibility for catenating strings on the caller. In software engineering, simplicity is a virtue. Doubly so for security-critical code. performance sanitizer() processes a string of arbitrary length, and makes half a dozen scans of the string, looking for half a dozen dangerous characters. This works. Rather than making repeated scans, consider making just a single scan where you examine each character, and append it or its sanitized substitute to an output string.
{ "domain": "codereview.stackexchange", "id": 44406, "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, security, html5", "url": null }
c#, game, collision, monogame Title: Intersecting rectangles on a torus Question: Description Imagine a space like the arcade game Asteroids where everything wraps around right to left and bottom to top - effectively coordinates on a flat torus. The diagram shows an example of two intersecting rectangles. The red rectangle at bottom right is wrapping around so that portions off screen are shown on the top and left, likewise with the blue. Code The code takes in coordinates and width and height of two rectangles and the domain for x and y, and it returns whether they are intersecting given that they wrap around within the domain. I've included some test cases. Asking for thoughts on improvements, optimisations, simplifications, bugs? etc... // Preconditions: x1, w1, y1, h1, x2, w2, y2, h2 are between 0 and domain exclusive bool IntersectsOnTorus(int x1, int w1, int y1, int h1, int x2, int w2, int y2, int h2, int domain) { int r1 = x1 + w1; int r2 = x2 + w2; if (r1 < domain || r2 < domain) { r1 -= r1 >= domain ? domain : 0; r2 -= r2 >= domain ? domain : 0; if (x1 >= r2 && x2 >= r1 || x1 <= r1 && x2 <= r2 && (x1 >= r2 || x2 >= r1)) return false; } int b1 = y1 + h1; int b2 = y2 + h2; if (b1 < domain || b2 < domain) { b1 -= b1 >= domain ? domain : 0; b2 -= b2 >= domain ? domain : 0; if (y1 >= b2 && y2 >= b1 || y1 <= b1 && y2 <= b2 && (y1 >= b2 || y2 >= b1)) return false; } return true; } Test(5, 10, 5, 20, 20, 10, 20, 10, 50, false); Test(5, 15, 5, 20, 20, 10, 20, 10, 50, false); Test(5, 17, 5, 20, 20, 10, 20, 10, 50, true); Test(5, 25, 5, 20, 20, 10, 20, 10, 50, true); Test(5, 28, 5, 20, 20, 10, 20, 10, 50, true); Test(5, 48, 5, 20, 20, 10, 20, 10, 50, true); Test(25, 28, 5, 20, 20, 10, 20, 10, 50, true); Test(30, 28, 5, 20, 20, 10, 20, 10, 50, false); Test(30, 45, 5, 20, 20, 10, 20, 10, 50, true);
{ "domain": "codereview.stackexchange", "id": 44407, "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#, game, collision, monogame", "url": null }
c#, game, collision, monogame void Test(int x1, int w1, int y1, int h1, int x2, int w2, int y2, int h2, int domain, bool expected) { bool result1 = IntersectsOnTorus(x1, w1, y1, h1, x2, w2, y2, h2, domain); bool result2 = IntersectsOnTorus(x2, w2, y2, h2, x1, w1, y1, h1, domain); bool result3 = IntersectsOnTorus(y1, h1, x1, w1, y2, h2, x2, w2, domain); bool result4 = IntersectsOnTorus(y2, h2, x2, w2, y1, h1, x1, w1, domain); bool success = result1 == result2 && result2 == result3 && result3 == result4 && result1 == expected; Console.WriteLine($"""{result1}, {result2}, {result3}, {result4}, {(success ? "Success" : "Fail")}"""); Console.WriteLine(); } Answer: bool IntersectsOnTorus(int x1, int w1, int y1, int h1, int x2, int w2, int y2, int h2, int domain) Choosing to phrase it as (x, w, y, h) instead of (x, y, w, h) seems a bit odd, but OK, we can go with it. int r1 = x1 + w1; int r2 = x2 + w2; if (r1 < domain || r2 < domain) { r1 -= r1 >= domain ? domain : 0; r2 -= r2 >= domain ? domain : 0; Didn't we want r1 >= domain rather than < ? Is there some reason % modulo is not suitable here? If so, it's worth documenting in a // comment. If it's due to some timing measurement, include a URL that describes details. if (x1 >= r2 && x2 >= r1 || x1 <= r1 && x2 <= r2 && (x1 >= r2 || x2 >= r1)) I imagine this is mostly correct. It would be helpful to name some of those sub-expressions, perhaps with identifiers like x1_wrapped. Let's talk about some adjacent unit squares, with UL LR coords of (0, 1) (1, 0) and (1, 1) (2, 0). Now, are they "overlapping"? I'm inclined to think the answer is "no". I recommend using lo <= x < hi half-open intervals. The current approach uses lo <= x <= hi. DRY. The "bottom" calculations are essentially identical to the "right" calculations. Consider rephrasing (x, y) as a single location. Then we could Extract Helper and pass in 0 for the "right" comparison and pass in 1 for the "bottom" comparison.
{ "domain": "codereview.stackexchange", "id": 44407, "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#, game, collision, monogame", "url": null }
c#, game, collision, monogame Wow, I really like the symmetries exposed by Test(), good job!
{ "domain": "codereview.stackexchange", "id": 44407, "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#, game, collision, monogame", "url": null }
php Title: Sorting an array by given hierarchy Question: I have a known hierarchy of the organization units, by descending order: $hierarchy = [ "a" => "organization", "b" => "company", "c" => "group", "d" => "unit", "e" => "sub_unit", "f" => "team" ]; I am then given an input key-value array which can consist of any of the units, but not necessarily all of them, and not always in the correct order: $array = [ "team" => "team1", "organization" => "organization1", "group" => "group1" ]; I want to sort it in the correct order, so for the example input array above, the result should be: $array = [ "organization" => "organization1", "group" => "group1" "team" => "team1" ]; The way I did it seem too complicated for what it's supposed to do, so maybe there is a better/more efficient way: public function sort_custom(&$array) { // set the known hierarchy ordered alphabetically by the keys $hierarchy = [ "a" => "organization", "b" => "company", "c" => "group", "d" => "unit", "e" => "sub_unit", "f" => "team" ]; // fill temp array with the key-value pair from the matching input array $tmp_array = []; foreach ($array as $key => $value) { $match = array_search($key, $hierarchy); $tmp_array[$match] = $key; } // sort the temp array ksort($tmp_array); // assign the values from the original array to the temp array foreach ($tmp_array as $key => $val) { $tmp_array[$val] = $array[$val]; unset($tmp_array[$key]); } // finally copy the sorted temp array to the original array $array = $tmp_array; } Answer: It is more optimal with this method. function sort_custom(&$array) { // set the known hierarchy ordered alphabetically by the keys $hierarchy = [ "organization", "company", "group", "unit", "sub_unit", "team" ];
{ "domain": "codereview.stackexchange", "id": 44408, "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": "php", "url": null }
php $array = array_merge( array_intersect_key(array_flip($hierarchy), $array), $array ); } In this situation, it is not necessary to use an associative array, because with the array_flip function, the values will be replaced with keys.
{ "domain": "codereview.stackexchange", "id": 44408, "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": "php", "url": null }
python Title: 3 dimensional renderer Question: I’m trying to make a 3d renderer but I can only get at most 20fps on idle. I tried using @functools.lru_cache(maxsize=None) on project_and_rotate() and got it up to 40fps on idle. Is there any way I could make this any faster? I’m using a long math formula I found a few month ago but it seems to be to slow for the map in projected_des. from math import * import pygame import numpy from functools import lru_cache @lru_cache(maxsize=None) def project_and_rotate(x, y, z,rotx,roty,rotz,posx,posy,posz,cx,cy,cz,scale,render_distance): x,y,z=x-posx,y-posy,z-posz if abs(x)>render_distance or abs(z)>render_distance:return None px = (((x * cos(rotz) - sin(rotz) * y) * cos(roty) - z * sin(roty)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cx py = (((y * cos(rotz) + x * sin(rotz)) * cos(rotx) - (z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * sin(rotx)) * (315 / ((((z * cos(roty) + (x * cos(rotz) - sin(rotz) * y) * sin(roty)) * cos(rotx) + (y * cos(rotz) + x * sin(rotz)) * sin(rotx)) + 5) + cz))) * scale + cy return [round(px),round(py)]
{ "domain": "codereview.stackexchange", "id": 44409, "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", "url": null }