text
stringlengths
1
2.12k
source
dict
python class coordinate: def __init__(self,x,y,z): self.x=x self.y=y self.z=z class verticies_structure: def __init__(self): self._verts=[] def add_vert(self,x,y,z): self._verts.append(coordinate(x,y,z)) def get_coords(self,indexes): return self._verts[indexes[0]:indexes[1]] class camera: def __init__(self,w,h,render_distance,fov=45): self.fov=360-fov self.w=w self.h=h self.x=0 self.rx=0 self.cx=0 self.y=0 self.ry=0 self.cy=0 self.z=0 self.rz=0 self.cz=0 self.render_distance=render_distance def false(f,value): if value==f: value=f+0.01 return value def inf360(value): if value>359:value=0 if value<0:value=359 return value class mesh(object): def __init__(self,file_obj,cam): self.cam=cam self.verts=verticies_structure() self.source=file_obj self.read_object_file() self.verts=verticies_structure() size=100 for x in range(size): for z in range(size): self.verts.add_vert(x-size//2,0,z-size//2) self.w2s_vect=numpy.vectorize(self.w2s) self.array_verts=numpy.array(self.verts._verts) def w2s(self,coord): cam=self.cam return project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance)
{ "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 }
python def projected_des(self,cam): #return self.w2s_vect(self.array_verts).tolist() return map( lambda coord:project_and_rotate(coord.x,coord.y,coord.z,cam.ry,cam.rx,cam.rz,cam.x,cam.y,cam.z,cam.cx,cam.cy,cam.cz,10,cam.render_distance),self.verts.get_coords([0,-1])) def read_object_file(self): self.verts=verticies_structure() import re reComp = re.compile("(?<=^)(v |vn |vt |f )(.*)(?=$)", re.MULTILINE) with open(self.source) as f: data = [txt.group() for txt in reComp.finditer(f.read())] v_arr, vn_arr, vt_arr, f_arr = [], [], [], [] for line in data: tokens = line.split(' ') if tokens[0] == 'v': v_arr.append([float(c) for c in tokens[1:]]) elif tokens[0] == 'vn': vn_arr.append([float(c) for c in tokens[1:]]) elif tokens[0] == 'vt': vn_arr.append([float(c) for c in tokens[1:]]) elif tokens[0] == 'f': f_arr.append([[int(i) if len(i) else 0 for i in c.split('/')] for c in tokens[1:]]) vertices, normals = [], [] for face in f_arr: for tp in face: self.verts.add_vert(*v_arr[tp[0]-1]) self.array_verts=numpy.array(self.verts._verts) class draw: class frame: class pygame_uitl: def grid(rowx,rowy,px,color=(255,255,255)): display=pygame.display.get_surface() for r in range(rowx): r+=1 pygame.draw.line(display,color,(0,(display.get_height()/(rowx+1))*r),(display.get_width(),(display.get_height()/(rowx+1))*r),px) for r in range(rowy): r+=1 pygame.draw.line(display,color,((display.get_width()/(rowy+1))*r,0),((display.get_width()/(rowy+1))*r,display.get_height()),px)
{ "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 }
python class system: class pygame_util: def get_orientation(): inf=pygame.display.Info() w,h=inf.current_w,inf.current_h if w>h: return 1 else: return 0
{ "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 }
python class Drivers: class Pygame: DEFAULT="PG-default" SDL2="PG-sdl2" class master: class scene: def __init__(self,wh:list,display_driver:str,render_distance:int,fps:int): self._model={ "class 1":[], "class 2":[], "class 3":[], "class 4":[]} self._fps=fps self._window_wh=wh self._driver=display_driver self._camera=camera(*wh,render_distance) self._mode="mesh" self._super_ls=0 if display_driver==Drivers.Pygame.DEFAULT: self._render_pygame_def_setup() def add_model(self,file): model=mesh(file,self._camera) vertexes=len(model.verts._verts) if vertexes>100: self._model["class 4"].append(model) elif vertexes>50: self._model["class 3"].append(model) elif vertexes>25: self._model["class 2"].append(model) else: self._model["class 1"].append(model) def regulate_camera(self): self._camera.rx,self._camera.ry,self._camera.rz=false(0,self._camera.rx),false(0,self._camera.ry),false(0,self._camera.rz) self._camera.cx,self._camera.cy,self._camera.cz=false(0,self._camera.cx),false(0,self._camera.cy),false(0,self._camera.cz) def correct_camera(self,orient=1): self._orient=orient if orient: self._camera.cx=self._window_wh[1]//2 self._camera.cy=self._window_wh[0] self._camera.ry=0.4 else: self._camera.cx=self._window_wh[0]//2 self._camera.cy=self._window_wh[1] self._camera.ry=0.2 def auto_render_distance(self): if self._driver==Drivers.Pygame.DEFAULT:
{ "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 }
python def auto_render_distance(self): if self._driver==Drivers.Pygame.DEFAULT: if self._pygame_clock.get_fps()+5>self._fps: self._camera.render_distance+=1 else: self._camera.render_distance-=1
{ "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 }
python def landscape_super(self): self._super_ls=1 self._lss_hdri_file_jpg_surf=pygame.Surface([self._window_wh[0],self._window_wh[1]//2.01]) self._lss_hdri_file_jpg_surf.fill((200,220,255)) def _render_pygame_def_setup(self): self._pygame_clock=pygame.time.Clock() self._pygame_screen=pygame.display.set_mode((self._camera.w,self._camera.h),pygame.DOUBLEBUF|pygame.HWACCEL|pygame.HWSURFACE) def _render_pygame_def_update(self): self._pygame_screen.fill((0,70,0)) self.regulate_camera() for idx,vclass in self._model.items(): for model in vclass: for point in model.projected_des(self._camera): if point!=None: try:self._pygame_screen.set_at(point,(255,255,255)) except:pass if self._super_ls: self._pygame_screen.blit(self._lss_hdri_file_jpg_surf,(0,0)) def _render_pygame_def_finish(self): pygame.display.flip() self._pygame_clock.tick(self._fps) scene=master.scene([2176,1080],Drivers.Pygame.DEFAULT,render_distance=25,fps=60) scene.add_model("plane.obj") scene.correct_camera(0) scene.landscape_super() #make the sky mapped to edge of render pygame.font.init() while 1: rx,ry=pygame.mouse.get_rel() scene._camera.rx+=rx/200 scene._render_pygame_def_update() #scene.auto_render_distance() scene._pygame_screen.blit(pygame.font.SysFont(None,60).render(str(scene._pygame_clock.get_fps()),None,(255,0,0)),(0,0)) scene._render_pygame_def_finish()
{ "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 }
python plane.obj # Exported OBJ from Prisma3D Exporter v2018 g Plane v 10 0 -10 v 10 0 10 v -10 0 10 v -10 0 -10 vn 0 0.07053456 0 vn 0 0.07053456 0 vn 0 0.07053456 0 vn 0 0.07053456 0 vt 0 0 vt 0 1 vt 1 1 vt 1 0 usemtl Material f 3/3/3 2/2/2 1/1/1 f 3/3/3 1/1/1 4/4/4 Answer: One problem is that you apply project_and_rotate to every point and recompute lots of sin and cos every time, even though the rot-values do not change. Try rewriting project_and_rotate to pass sin(rotx), cos(rotx), etc to the function, instead of the angles rotx, rot,y, rotz. This will be reflected in the call from project_des. Old code: def projected_des(self, cam): #return self.w2s_vect(self.array_verts).tolist() prj_n_rot = lambda coord: project_and_rotate( coord.x, coord.y, coord.z, cam.ry, cam.rx, cam.rz, cam.x, cam.y, cam.z, cam.cx, cam.cy, cam.cz, 10, cam.render_distance) return map(prj_n_rot, self.verts.get_coords([0,-1])) new code def projected_des(self, cam): #return self.w2s_vect(self.array_verts).tolist() sin_cam_ry = sin(cam.ry) cos_cam_ry = cos(cam.ry) sin_cam_rx = sin(cam.rx) cos_cam_rx = cos(cam.rx) sin_cam_rz = sin(cam.rz) cos_cam_rz = cos(cam.rz) prj_n_rot = lambda coord: project_and_rotate( coord.x, coord.y, coord.z, sin_cam_ry, cos_cam_ry, sin_cam_rx, cos_cam_rx, sin_cam_rz, cos_cam_rz, cam.x, cam.y, cam.z, cam.cx, cam.cy, cam.cz, 10, cam.render_distance) return map(prj_n_rot, self.verts.get_coords([0,-1]))
{ "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 }
c, array, vectors Title: C generic typesafe dynamic array (vector) try 2 Question: The previous generic dynamic array I asked a review for here was written using only the preprocessor and so while the array itself was type-safe, all the manipulating macros where not. In this try I wrote a dynamic array that stores the element size, and then a macro interface that hides it as an implementation detail. I also took advice from the previous review and removed the arrayMap(array,callback) macro and replaced it with VEC_FOREACH(index_variable_name, vec) which is simply a wrapper around a for loop. A note on memory allocation: as I'm still testing this array, I didn't add any code to gracefully handle memory allocation errors yet. The code is currently in a single file, and isn't ready yet to be included by other files yet. #include <stdint.h> #include <stdlib.h> #include <stddef.h> // offsetof #include <assert.h> typedef struct vec_header { uint32_t used; uint32_t capacity; uint32_t element_size; char data[]; } VecHeader; union align { int i; long l; long *lp; void *p; void (*fp)(void); float f; double d; long double ld; }; union header { VecHeader h; union align a; }; VecHeader *_vec_make_header(uint32_t element_size, uint32_t capacity) { VecHeader *h = calloc(1, element_size * capacity + sizeof(union header)); assert(h); h->capacity = capacity; h->element_size = element_size; return h; } static inline VecHeader *_vec_to_header(void *vec) { assert(vec); return vec - offsetof(VecHeader, data); } void _vec_free_header(VecHeader *h) { free(h); } void _vec_ensure_capacity(void **vec, uint32_t capacity) { assert(vec && *vec); VecHeader *h = _vec_to_header(*vec); if(h->used >= capacity) { return; } h->capacity = capacity; h = realloc(h, h->element_size * h->capacity +sizeof(union header)); assert(h); *vec = (void *)h->data; }
{ "domain": "codereview.stackexchange", "id": 44410, "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, array, vectors", "url": null }
c, array, vectors void *_vec_prepare_push(void **vec) { assert(vec && *vec); VecHeader *h = _vec_to_header(*vec); if(h->used + 1 > h->capacity) { h->capacity *= 2; h = realloc(h, h->element_size * h->capacity + sizeof(union header)); assert(h); } h->used++; *vec = (void *)h->data; return h->data + (h->used - 1) * h->element_size; } void *_vec_pop(VecHeader *h) { assert(h && h->used > 0); h->used--; return h->data + h->used * h->element_size; } void *_vec_get(VecHeader *h, uint32_t index) { assert(h && index < h->used); return h->data + index * h->element_size; } void _vec_copy(void **dest_vec, VecHeader *src) { assert(dest_vec && *dest_vec && src); VecHeader *dest = _vec_to_header(*dest_vec); assert(dest->element_size == src->element_size); dest->used = 0; // clear the destination vec. _vec_ensure_capacity(dest_vec, src->capacity); dest = _vec_to_header(*dest_vec); // needed in case of reallocation in above call. // both loops can be replaced with 'memcpy(dest->data, src->data, i * src->element_size); for(uint32_t i = 0; i < src->used; ++i) { for(uint32_t j = 0; j < src->element_size; ++j) { dest->data[i * dest->element_size + j] = src->data[i * src->element_size + j]; } } _vec_to_header(*dest_vec)->used = src->used; } void _vec_reverse(void *vec) { assert(vec); VecHeader *h = _vec_to_header(vec); // The division below might result in a float in which // case it will be rounded down which is what we want. for(uint32_t i = 0; i < h->used / 2; ++i) { for(uint32_t j = 0; j < h->element_size; ++j) { char tmp = h->data[i * h->element_size + j]; h->data[i * h->element_size + j] = h->data[(h->used - i - 1) * h->element_size + j]; h->data[(h->used - i - 1) * h->element_size + j] = tmp; } } } #define VEC_INITIAL_SIZE 8
{ "domain": "codereview.stackexchange", "id": 44410, "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, array, vectors", "url": null }
c, array, vectors #define VEC_INITIAL_SIZE 8 #define VEC_NEW(type) ((type *)(_vec_make_header(sizeof(type), VEC_INITIAL_SIZE)->data)) #define VEC_FREE(vec) (_vec_free_header(_vec_to_header((void *)vec))) #define VEC_CAPACITY(vec) (_vec_to_header((void *)vec)->capacity) #define VEC_LENGTH(vec) (_vec_to_header((void *)vec)->used) #define VEC_PUSH(vec, value) (*(typeof(vec))(_vec_prepare_push((void **)&(vec))) = (value)) #define VEC_POP(vec) (*(typeof(vec))_vec_pop(_vec_to_header((void *)vec))) #define VEC_GET(vec, index) (*(typeof(vec))_vec_get(_vec_to_header((void *)vec), index)) #define VEC_COPY(dest, src) (_vec_copy((void **)&(dest), _vec_to_header((void *)src))) #define VEC_CLEAR(vec) ((void)(_vec_to_header((void *)vec)->used = 0)) #define VEC_REVERSE(vec) (_vec_reverse((void *)(vec))) #define VEC_FOREACH(index_var_name, vec) for(uint32_t index_var_name = 0; index_var_name < VEC_LENGTH(vec); ++index_var_name) // Note: [vec] is referenced multiple times. #define VEC_ITERATE(iter_var_name, vec) for(typeof(*vec) *iter_var_name = (vec); iter_var_name - (vec) < VEC_LENGTH(vec); ++iter_var_name) An example usage: #include <stdio.h> int main(void) { int *nums = VEC_NEW(int); VEC_PUSH(nums, 42); VEC_PUSH(nums, 123); VEC_FOREACH(i, nums) { printf("nums[%u] = %d\n", i, nums[i]); // VEC_GET(nums, i) checks bounds. } int *nums2 = VEC_NEW(int); VEC_COPY(nums2, nums); printf("len: %u, cap: %u, nums2[len] = %d\n", VEC_LENGTH(nums2), VEC_CAPACITY(nums2), VEC_POP(nums2)); VEC_CLEAR(nums2); VEC_FREE(nums2); VEC_FREE(nums); return 0; }
{ "domain": "codereview.stackexchange", "id": 44410, "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, array, vectors", "url": null }
c, array, vectors Answer: Should vec_header.data be a uint8_t instead of a char? VEC_NEW asserts and fails on an allocation error. It could return NULL and let the caller decide how to handle out-of-memory errors. Why does _vec_ensure_capacity test that h->used is greater than the desired capacity, rather than h->capacity? This means you may reallocate when the destination is large enough, but not full. And when used is bigger than the new capacity, you don't reallocate - leaving around the old values with no way to access them. _vec_prepare_push could call _vec_ensure_capacity to avoid having two very similar blocks of code that call realloc. The last line of _vec_copy shouldn't need another call to _vec_to_header: dest already has that value. Technically, the division in _vec_reverse won't result in a float, but it will be rounded toward zero as you state. In _vec_reverse, I might use two local variables for the repeated index calculations: uint32_t front = i * h->element_size + j; rear = (h->used - i - 1) * h->element_size + j;
{ "domain": "codereview.stackexchange", "id": 44410, "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, array, vectors", "url": null }
c#, .net, logging, asp.net-core Title: Serilog logging extension methods Question: I've been using this extension in almost all of my projects. What's your opinion? Do you think there is something else to add or to be improved? The idea is to ignore all default ASP.NET messages that are there by default and if optionally to override stuff via configuration. I actually override Microsoft.AspNetCore.Hosting.Diagnostics and Microsoft.AspNetCore.Routing.EndpointMiddleware via appsettings. public static class LoggingExtensions { private const string SectionName = "Serilog"; public static IHostBuilder AddCustomLogging( this IHostBuilder builder, IConfiguration configuration, LogEventLevel minLevelLocal = LogEventLevel.Information) { const string outputTemplate = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"; Log.Logger = new LoggerConfiguration() .MinimumLevel.Is(minLevelLocal) .MinimumLevel.Override("System", LogEventLevel.Error) .MinimumLevel.Override("Microsoft", LogEventLevel.Error) .ReadFrom.Configuration(configuration, SectionName) .Enrich.FromLogContext() .Enrich.WithMachineName() .Enrich.WithProcessName() .Enrich.WithMemoryUsage() .WriteTo.Console(outputTemplate: outputTemplate) .CreateLogger(); return builder.UseSerilog(); } } { "Serilog": { "MinimumLevel": { "Default": "Information", "Override": { "Microsoft.AspNetCore.Hosting.Diagnostics": "Debug", "Microsoft.AspNetCore.Routing.EndpointMiddleware": "Debug" } } } }
{ "domain": "codereview.stackexchange", "id": 44411, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, logging, asp.net-core", "url": null }
c#, .net, logging, asp.net-core <ItemGroup> <PackageReference Include="Serilog.Extensions.Hosting" Version="5.0.1" /> <PackageReference Include="Serilog.Sinks.Console" Version="4.1.0" /> <PackageReference Include="Serilog.Settings.Configuration" Version="3.4.0" /> <PackageReference Include="Serilog.Enrichers.Environment" Version="2.2.0" /> <PackageReference Include="Serilog.Enrichers.Memory" Version="1.0.4" /> <PackageReference Include="Serilog.Enrichers.Process" Version="2.0.2" /> </ItemGroup> Answer: constants of LoggingExtensions I don't know why did you declare SectionName on class level whereas the outputTemplate inside the AddCustomLogging method I think both could be defined on class level const string SectionName = "Serilog"; const string OutputTemplate = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj} {Properties:j}{NewLine}{Exception}"; AddCustomLogging's parameters As I stated earlier I don't think the configuration parameter is necessary since you can reach it through the builder parameter For me this minLevelLocal name seems a bit weird What does local mean in this context? Allowing the user to specify the default log level seems odd to me Either allow to specify all three log levels Or do not allow any of them, since you can set them via the json config UseSerilog It seems a really strict restriction to use only serilog In order to allow flexibility I would suggest to add an other method which would register serilog as one of the log providers (AddSerilog) public static IHostBuilder RegisterSerilogCustomLogging(this IHostBuilder builder, IConfiguration configuration) public static IHostBuilder AddSerilogCustomLogging(this IHostBuilder builder, IConfiguration configuration) Enrichers, Filters or sinks Your current design does not allow the user to add something to the predefined setup If you want to allow that flexibility then you can do the following:
{ "domain": "codereview.stackexchange", "id": 44411, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, logging, asp.net-core", "url": null }
c#, .net, logging, asp.net-core public static IHostBuilder RegisterSerilogCustomLogging( this IHostBuilder builder, IConfiguration configuration, Action<LoggerConfiguration>? configureLogger = null) { ... var loggerConfig = new LoggerConfiguration() ... .WriteTo.Console(outputTemplate: outputTemplate); configureLogger?.Invoke(loggerConfig); Log.Logger = loggerConfig.CreateLogger(); builder.UseSerilog(); }
{ "domain": "codereview.stackexchange", "id": 44411, "lm_label": null, "lm_name": null, "lm_q1_score": null, "lm_q1q2_score": null, "lm_q2_score": null, "openwebmath_perplexity": null, "openwebmath_score": null, "tags": "c#, .net, logging, asp.net-core", "url": null }
python, pygame, physics Title: Planetary simulation in python Question: I have created a program in python that calculates forces between bodies (i.e earth, moon and a hypothetical moon) and make them move according to the changes in velocity and forces. This is the code for the program: from math import sin,cos,sqrt,atan2,pi import pygame pygame.init()
{ "domain": "codereview.stackexchange", "id": 44412, "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, pygame, physics", "url": null }
python, pygame, physics class Planet: dt = 1/100 G = 6.67428e-11 #G constant scale = 1/(1409466.667) #1 m = 1/1409466.667 pixlar def __init__(self,x=0,y=0,radius=0,color=(0,0,0),mass=0,vx=0,vy=0): self.x = x #x-coordinate pygame-window self.y = y #y-coordinate pygame-window self.radius = radius self.color = color self.mass = mass self.vx = vx #velocity in the x axis self.vy = vy #velocity in the y axis def draw(self,screen): pygame.draw.circle(screen, self.color, (self.x, self.y), self.radius) def orbit(self,trace): pygame.draw.rect(trace, self.color, (self.x, self.y, 2, 2)) def update_vel(self,Fnx,Fny): ax = Fnx/self.mass #Calculates acceleration in x- and y-axis for body 1. ay = Fny/self.mass self.vx -= ((ax * Planet.dt)/Planet.scale) self.vy -= ((ay * Planet.dt)/Planet.scale) self.update_pos() def update_pos(self): self.x += ((self.vx * Planet.dt)) #changes position considering each body's velocity. self.y += ((self.vy * Planet.dt)) def move(self,body): dx = (self.x - body.x) #Calculates difference in x- and y-axis between the bodies dy = (self.y - body.y) r = (sqrt((dy**2)+(dx**2))) #Calculates the distance between the bodies angle = atan2(dy, dx) #Calculates the angle between the bodies with atan2! if r < self.radius: #Checks if the distance between the bodies is less than the radius of the bodies. Uses then Gauss gravitational law to calculate force. F = 4/3 * pi * r Fx = cos(angle) * F Fy = sin(angle) * F else: F = (Planet.G*self.mass*body.mass)/((r/Planet.scale)**2) #Newtons gravitational formula. Fx = cos(angle) * F Fy = sin(angle) * F return Fx,Fy
{ "domain": "codereview.stackexchange", "id": 44412, "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, pygame, physics", "url": null }
python, pygame, physics def motion(): for i in range(0,len(bodies)): Fnx = 0 #net force Fny = 0 for j in range(0,len(bodies)): if bodies[i] != bodies[j]: Fnx += (bodies[i].move(bodies[j]))[0] Fny += (bodies[i].move(bodies[j]))[1] elif bodies[i] == bodies[j]: continue bodies[i].update_vel(Fnx,Fny) bodies[i].draw(screen) bodies[i].orbit(trace) Fnx,Fny=0,0 screen = pygame.display.set_mode([900,650]) #width - height trace = pygame.Surface((900, 650)) pygame.display.set_caption("Moon simulation") FPS = 60 #how quickly/frames per second our game should update. Change? earth = Planet(450,325,30,(0,0,255),5.97219*10**(24),-24.947719394204714/2) #450= xpos,325=ypos,30=radius luna = Planet(450,(575/11),10,(128,128,128),7.349*10**(22),1023) moon = Planet() #the second moon bodies = [earth,luna] running = True clock = pygame.time.Clock() while running: #if user clicks close window clock.tick(FPS) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((0,0,0)) pygame.Surface.blit(screen, trace, (0, 0)) motion() pygame.display.flip() #update? flip? pygame.quit()
{ "domain": "codereview.stackexchange", "id": 44412, "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, pygame, physics", "url": null }
python, pygame, physics pygame.display.flip() #update? flip? pygame.quit() The code works and I get the moon to orbit around earth. However since I am an amateur in such an area I wonder if it can be improved on. Do the calculations look alright? Can I make some improvements? I am trying to make my simulation realistic and thus I have a scaling factor that I use to convert pixels to meters and vice versa. Here for example: Is it correct to divide by the scaling factor or should I multiply it (so I don't mix pixels with meters): def update_vel(self,Fnx,Fny): ax = Fnx/self.mass #Calculates acceleration in x- and y-axis for body 1. ay = Fny/self.mass self.vx -= ((ax * Planet.dt)/Planet.scale) self.vy -= ((ay * Planet.dt)/Planet.scale) self.update_pos() Thankful for any suggestions or thoughts on my code and/or the physics involved in it! Answer: Use a vector type to store positions, velocities and forces Instead of writing out all the calculations for the x and y direction separately, consider using a library that provides you with vector types, like for example PyGLM. This allows you to write simpler expressions, and there will be less chance of accidental mistakes. Using glm.vec2, you can write code like: def __init__(self, pos=glm.vec2(0, 0), …, vel=glm.vec2(0, 0)): self.pos = pos … self.vel = vel def update_vel(self, Fn): a = Fnx / self.mass self.vel -= (a * Planet.dt) / Planet.scale self.update_pos() def update_pos(self): self.pos += self.vel * Planet.dt
{ "domain": "codereview.stackexchange", "id": 44412, "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, pygame, physics", "url": null }
python, pygame, physics def update_pos(self): self.pos += self.vel * Planet.dt Use the velocity Verlet method You are using a rather straightforward but naive way to calculate the next position given the current velocity and acceleration, which is also known as the semi-implicit Euler method. While this is already better than the forward Euler method, it's just a first-order approximation, and if the time step is too large it might result in an unstable system. There are various ways to improve on this. A very commonly used method to discretely integrate the equations of motion is the velocity Verlet method; it is a second order approximation, and results in a much more stable system, but it's still very simple to implement and very efficient. Avoid using trigonometric functions You can calculate the force vectors without using atan(), cos() and sin(). Consider that cos(angle) is just dx / r and sin(angle) is dy / r. Scaling It would indeed be very nice if you put in all the values in SI units like kilograms, meters, seconds and so on. You can find distances between the Sun, planets and moons on Wikipedia. Try to fill in the values for our solar system. You'll notice that the time step should then be quite large, for example if you set it to 1 hour, then it will take about 24 * 365 = 8760 steps for the Earth to revolve around the Sun once. That's about 2 minutes if your simulation runs at 60 frames per second. You also have to convert from meters to pixels in such a way that the distance to the outermost planet is slightly less than half the width and height of the window, so everything fits in it. This scaling factor should be global, the same value should be used for all objects you want to show. It should be applied inside draw(), not while updating the positions and velocities: keep all the physics in SI units, and only convert to pixels when it's time to draw.
{ "domain": "codereview.stackexchange", "id": 44412, "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, pygame, physics", "url": null }
javascript, beginner, google-apps-script Title: Pulling Data from an Email and Pasting it into a Google Spreadsheet
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script Question: Background The reason why I'm doing this is because at my company, we get emails a lot from different locations that have relevant data we need for other processes. The problem is that this data is always in a CSV or excel file format, and downloading the file, then copying all of the data, then pasting it in the proper location takes away time that people could be using on other relevant business-related tasks. To mitigate the above issue, I've been working on a Google App Script library for my company that simplifies a lot of the functions that we use on a regular basis inside of app script. Because I'm still fairly new to JS and how function overloading works, I realized I can concatenate some of the functions currently in the library more succinctly, so they're more readable. Below is an example of what 4 internal functions looked like inside another function, and then with some fiddling what I was able to decrease it to.
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script What the code does is fairly simple, a user specifies an emailSubject and a targetSheet. These two parameters must always be specified. What this does is it looks into the user's Gmail and finds the first email that matches user-specified emailSubject. Once it finds that email, it will take the first attachment (currently only if it is an excel or CSV file), takes the data from that attachment, and then pastes it onto a google spreadsheet, specifically on the sheet that the user specified as targetSheet. The other parameters are attachmentNumber, row, and column. attachmentNumber is used in the case that an email has multiple attachments, but the user only wants to pull a specific attachment that is not the first one. attachmentNumber will NOT correspond to the index in the attachments array in the emailAttachmentRetrieval function, as that is already taken into account. (So if the attachment is the fifth attachment in an email, the user just needs to enter 5 and not worry about index number of the attachments array). row and column are the index of both the row and column on the targetSheet data is initially pasted to that the user specified if they don't want the data to be pasted starting at row 1, column 1. I call the functions function1, function2, etc., because that was the way that I found it online, but if there is a different naming convention that would be superior, I am also open to hearing it. My Request I'm not a fan of just using if-else statements, as I know that there are other, better ways of doing this that I am currently not aware of. I tried using switch-case, but couldn't figure out how that could be an implemented properly, or even if it was an improvement. I think one of the issues is that attachmentNumber is causing issues as a parameter in functions 2 and 3. Any advice would be appreciated, and I can provide further details as necessary My Code function emailAttachment() { var function1 = function(emailSubject, targetSheet){
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script My Code function emailAttachment() { var function1 = function(emailSubject, targetSheet){ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) let data = emailAttachmentRetrieval(emailSubject, 1) ss.getRange(1, 1, data.length, data[0].length).clear().setValues(data) }
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script var function2 = function(emailSubject, targetSheet, attachmentNumber){ if(attachmentNumber < 1){ throw new Error('Attachment number cannot be less than 1') } else{ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) let data = emailAttachmentRetrieval(emailSubject, attachmentNumber) ss.getRange(1, 1, data.length, data[0].length).clear().setValues(data) } } var function3 = function(emailSubject, targetSheet, row, column){ if(row < 1 || column < 1){ throw new Error('Row and column number cannot be less than 1') } else{ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) let data = emailAttachmentRetrieval(emailSubject, 1) ss.getRange(row, column, data.length, data[0].length).clear().setValues(data) } } var function4 = function(emailSubject, targetSheet, attachmentNumber, row, column){ if(attachmentNumber < 1){ throw new Error('Attachment number cannot be less than 1') } else if(row < 1 || column < 1){ throw new Error('Row and column number cannot be less than 1') } else{ let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) let data = emailAttachmentRetrieval(emailSubject, attachmentNumber) ss.getRange(row, column, data.length, data[0].length).clear().setValues(data) } try{ if(arguments.length === 2){ function1(arguments[0], arguments[1]) } else if(arguments.length === 3){ function2(arguments[0], arguments[1], arguments[2]) } else if(arguments.length === 4){ function3(arguments[0], arguments[1], arguments[2], arguments[3]) } else if(arguments.length === 5){ function4(arguments[0], arguments[1], arguments[2], arguments[3], arguments[4]) } } catch(e){ Logger.log(e) } }
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script My Attempt at Improving It: function emailAttachment1(emailSubject, targetSheet, attachmentNumber, row, column) { let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(targetSheet) if(attachmentNumber === null && row === null && column === null){ let data = emailAttachmentRetrieval(emailSubject, 1) ss.getRange(1,1,data.length, data[0].length).clear().setValues(data) } else if(row === null && column === null){ if(attachmentNumber < 1){ attachmentError() } else{ let data = emailAttachmentRetrieval(emailSubject, attachmentNumber) ss.getRange(1,1,data.length,data[0].length).clear().setValues(data) } } else if(attachmentNumber === null){ if(row < 1 || column < 1){ rowColumnError() } else{ let data = emailAttachmentRetrieval(emailSubject, 1) ss.getRange(row, column, data.length, data[0].length).clear().setValues(data) } } else{ if(attachmentNumber < 1){ attachmentError() } else if(row < 1 && column < 1){ rowColumnError() } else{ let data = emailAttachmentRetrieval(emailSubject, attachmentNumber) ss.getRange(row, column, data.length, data[0].length).clear().setValues(data) } } } Other Relevant Code: function emailAttachmentRetrieval(emailSubject, attachmentNumber){ var msgs = GmailApp.getMessagesForThreads(GmailApp.search('subject: ' + emailSubject,0,1)) for (var i = 0 ; i < msgs.length; i++) { for (var j = 0; j < msgs[i].length; j++) { var attachments = msgs[i][j].getAttachments() } } if(attachmentNumber < attachments.length){ throw new Error('attachment number is outside the scope of the attachments array') } else{ var convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, attachments[attachmentNumber-1]).id var data = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0].getDataRange().getValues() Drive.Files.remove(convertedSpreadsheetId) } return data }
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script function attachmentError(){ throw new Error('Attachment number cannot be less than 1') } function rowColumnError(){ throw new Error('Row and column number cannot be less than 1') } Answer: This is what I came up with so far that I felt helped concatenate all my code. I used a similar methodology from this question that I also asked: Sending Email Through App Script. Anyone is welcome to improve it further if they believe that there is room for improvement. What I Changed Because this specificemailAttachmentRetrieval() function will only be used by the emailAttachment() function, I decided to include it within the function itself rather than leave it floating in case there is another function that would use the same name. (I don't think I will, but you never know). Because emailSubject and targetSheet will always be included within the function parameters, I created an object that I will pull the necessary properties I need from it when I need to If there are 3 or 5+ parameters, attachmentNumber is added as the third property Because there can be 4 or 5 parameters when calling the function, there is check to see how many there are. If there are 4, row is added to the options object as the third property, and column is added as the fourth. If there are 5 parameters, then row is added as the fourth property and column is added as the fifth Added a bunch of ternary operators, specifically in the data variable and calling the functions that paste the data copied from the email into the spreadsheet. Currently inside those ternary operators, if the value in the options object does exist and is greater than 1, then it is pulled from the options object and used in the execution, otherwise 1 is used.
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script Those are all of the things that I have currently done to improve the emailAttachment() function as it currently stands, however if someone else finds this question in the future and believes they can improve it further, please feel free to do so. function emailAttachment(){ try{ const options = { emailSubject: arguments[0], targetSheet: arguments[1], } //Both options have the 3rd argument as the attachment number arguments.length === 3 || arguments.length >= 5 ? options.attachmentNumber = arguments[2] : null if(arguments.length >= 4){ /* For 4 arguments, get the 3rd and 4th arguments For 5 arguments, get the 4th and 5th arguments */ let index = arguments.length === 4 ? 2 : 3 options.row = arguments[index] options.column = arguments[index + 1] } let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(options.targetSheet) let data = emailAttachmentRetrieval(options.emailSubject, (options.attachmentNumber && options.attachmentNumber > 1 ? options.attachmentNumber : 1)) ss.getRange( (options.row && options.row > 1 ? options.row : 1), (options.column && options.column > 1 ? options.column : 1), data.length, data[0].length).clear().setValues(data) } catch(e){ Logger.log(e) }
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
javascript, beginner, google-apps-script //Function used in all the emailAttachment functions; Used for retrieving data from emails function emailAttachmentRetrieval(emailSubject, attachmentNumber){ let msgs = GmailApp.getMessagesForThreads(GmailApp.search('subject: ' + emailSubject,0,1)) for (let i = 0 ; i < msgs.length; i++) { for (let j = 0; j < msgs[i].length; j++) { let attachments = msgs[i][j].getAttachments() } } if(attachmentNumber < attachments.length){ throw new Error('attachment number is outside the scope of the attachments array') } else{ let convertedSpreadsheetId = Drive.Files.insert({mimeType: MimeType.GOOGLE_SHEETS}, attachments[attachmentNumber-1]).id let data = SpreadsheetApp.openById(convertedSpreadsheetId).getSheets()[0].getDataRange().getValues() Drive.Files.remove(convertedSpreadsheetId) } return data } }
{ "domain": "codereview.stackexchange", "id": 44413, "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, beginner, google-apps-script", "url": null }
php, database, laravel, eloquent Title: Laravel Eager Loading tickets from DB Question: So I have the following relationship in my Model: Events Model: class Events extends Model { use CrudTrait; use HasFactory; use Sluggable; /** * The attributes that are mass assignable. * * @var array */ protected $fillable = [ 'title', 'url', 'start', 'end', 'category', 'level', 'bookable', 'additional_info', 'repeats', 'duration', ]; /** * The attributes that should be cast to native types. * * @var array */ protected $casts = [ 'id' => 'integer', 'start' => 'datetime', 'end' => 'datetime', 'category' => 'string', 'level' => 'integer', 'boookable' => 'boolean', 'repeats' => 'integer', 'duration' => 'integer', ]; public function tickets() { return $this->hasMany(Tickets::class, 'event_id'); } } the function public function tickets() above is what I am talking about. Tickets Model: class Tickets extends Model { use CrudTrait; use HasFactory; public $fillable = [ 'title', 'price', 'min', 'max', 'students', 'event_id' ]; } then I show the ticket pricings on the frontend in a blade: @foreach($events as $event) <div class="group-hover:hidden"> {{ $event->tickets->count() > 1 ? 'Starting at:' : '' }} @if ($event->tickets->min(fn($row) => $row->price) === '0.00') Free @else ($event->tickets->min(fn($row) => $row->price) !== 0) {{$event->tickets->min(fn($row) => $row->price)}} € @endif </div> @endforeach
{ "domain": "codereview.stackexchange", "id": 44414, "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, database, laravel, eloquent", "url": null }
php, database, laravel, eloquent Controller: public function showEvents($course) { // function for the /events/{$course} pages [$view, $id] = match ($course) { default => ['error', 'error'], // URL Request from ($course) then the set the $view and $id 'loremimpsum' => ['pages.course.loremimpsum', '2'], 'impsumlorem' => ['pages.course.impsumlorem', '3'], 'loremlorem' => ['pages.course.loremlorem', '4'], 'impsumimpsum' => ['pages.course.impsumimpsum', '5'], 'looremloorem' => ['pages.course.looremloorem', '6'], 'impsimps' => ['pages.course.impsimps', '7'], 'loremloremlorem' => ['pages.course.loremloremlorem', '8'], }; try { return view($view, [ 'events' => Events::query() ->orderBy('title') ->orderBy('start') ->where('category', $id) ->where('start', '>', now()) ->get() ]); } catch (InvalidArgumentException) { return Redirect::route('all-events')->with('error', 'You were redirected! This event was not found.'); } } Route: Route::get('/events/{course}', [EventsController::class, 'showEvents']); first I check if there are more than two tickets on one event, then it will show Starting at. Then I check if the price on the ticket is 0, if this is the case I set the text on the button to Free. After that I check if the price is not 0 and whow the real price from the DB. The question: How would one Eager Load these tickets and are there further optimizations? There are several thousand tickets in the DB. The documentation from Laravel for Eager Loading only show an example with belongsTo not with hasMany. And StackOverflow has no answers with hasMany and a foreignKey
{ "domain": "codereview.stackexchange", "id": 44414, "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, database, laravel, eloquent", "url": null }
php, database, laravel, eloquent Answer: Review Readability is good though model naming could be better As someone who has used laravel for many years the code is simple to read. One critique would be that typically models are named in a singular fashion - e.g. Event instead of Events, even though the database table name may be named in a plural manner. Template likely has a flaw There appears to be a mistake in the template: @else ($event->tickets->min(fn($row) => $row->price) !== 0) Shouldn't that be an elseif? Question Response How would one Eager Load these tickets and are there further optimizations? There are several thousand tickets in the DB. The section in the documentation above the Section Eager loading is Aggregating Related Models discusses eager loading aggregates for the hasMany relations. The One to Many section sets up the comments relationship for the Post model: <?php namespace App\Models; use Illuminate\Database\Eloquent\Model; class Post extends Model { /** * Get the comments for the blog post. */ public function comments() { return $this->hasMany(Comment::class); } } 1 The first section about aggregating models demonstrates getting the count of comments: Counting Related Models Sometimes you may want to count the number of related models for a given relationship without actually loading the models. To accomplish this, you may use the withCount method. The withCount method will place a {relation}_count attribute on the resulting models: use App\Models\Post; $posts = Post::withCount('comments')->get(); foreach ($posts as $post) { echo $post->comments_count; }
{ "domain": "codereview.stackexchange", "id": 44414, "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, database, laravel, eloquent", "url": null }
php, database, laravel, eloquent 2 So to get the count of tickets the withCount() method can be used. Also, the call to query() can be removed since methods like that as well as Model::where() and Model::orderBy() return an instance of \Illuminate\Database\Query\Builder: Events::withCount('tickets') ->orderBy('title') ->orderBy('start') ->where('category', $id) ->where('start', '>', now()) ->get() Then each Event model will have an attribute tickets_count that can be used to get the count of tickets instead of $event->tickets->count(). The Other Aggregate Functions section mentions the withMin method. In addition to the withCount method, Eloquent provides withMin, withMax, withAvg, withSum, and withExists methods. These methods will place a {relation}_{function}_{column} attribute on your resulting models: use App\Models\Post; $posts = Post::withSum('comments', 'votes')->get(); foreach ($posts as $post) { echo $post->comments_sum_votes; } So to get the minimum price of the tickets for each event a call to withMin() can be added: Events::withCount('tickets') ->withMin('tickets', 'price') ->orderBy('title') ->orderBy('start') ->where('category', $id) ->where('start', '>', now()) ->get() Then each Event model should have an attribute tickets_min_price that can be used instead of $event->tickets->min(fn($row) => $row->price). Thus instead of a query to get the events plus one query for each event, there is a single query like: select "events".*, (select count(*) from "tickets" where "events"."id" = "tickets"."event_id") as "tickets_count", (select min("tickets"."price") from "tickets" where "events"."id" = "tickets"."event_id") as "tickets_min_price" from "events" where "category" = '7' and "start" > '2024-01-09 23:55:23' order by "title" asc, "start" asc
{ "domain": "codereview.stackexchange", "id": 44414, "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, database, laravel, eloquent", "url": null }
performance, c Title: Logistic regression using gradient descent Question: My code seems to work fine, but I'm interested in how I can make it faster. I really just want to reduce any wasteful computation (for instance eta_m = eta / (double)m reduces coef[j] -= eta * gradient_coef[j] / (double)m to coef[j] -= eta_m * gradient_coef[j]). I realize a good BLAS implementation would probably be useful, but I've found that complicates usage on other systems (unless there's some generalized implementation out there). I've tried to take advantage of some linear properties (where able) to reduce the number of loops performed, though the initial loop that sets coefficients and gradients to 0.0 could probably be wrapped into the main loops using if statements. The alpha and beta declarations are vestigial from using BLAS but can't imagine they're very impactful. Anything glaringly inefficient that I'm missing here? #include <stdlib.h> #include <math.h> // Compute z = w * x + b double dlc( unsigned long n, double *X, double *coef, double intercept ) { double z = intercept; for ( unsigned long j = 0; j < n; j++ ) { z += X[j] * coef[j]; } return z; } // Compute y_hat = 1 / (1 + e^(-z)) double dsigmoid( unsigned long n, double alpha, double *X, double *coef, double beta, double intercept ) { //double z = intercept; //bli_ddotxv( BLIS_NO_CONJUGATE, BLIS_NO_CONJUGATE, n, &alpha, X, 1, coef, 1, &beta, &z ); double z = dlc(n, X, coef, intercept); if ( z >= 0) { return 1.0 / (1.0 + exp(-z)); } else { return exp(z) / (1.0 + exp(z)); } } // Gradient descent void dgd( unsigned long m, unsigned long n, double *X, double *y, double *coef, double *intercept, double eta, int max_iter, int fit_intercept ) { double alpha = 1.0, beta = 1.0, gradient_intercept = 0.0, eta_m;
{ "domain": "codereview.stackexchange", "id": 44415, "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, c", "url": null }
performance, c double *y_pred = (double *) malloc (m * sizeof(double)); double *resid = (double *) malloc (m * sizeof(double)); double *gradient_coef = (double *) malloc (n * sizeof(double)); for ( unsigned long j = 0; j < n; j++ ) { coef[j] = 0.0; gradient_coef[j] = 0.0; } *intercept = 0.0; eta_m = eta / (double)m; for ( int epoch = 0; epoch < max_iter; epoch++ ) { // Compute y_hat and gradients for ( unsigned long i = 0; i < m; i++ ) { y_pred[i] = dsigmoid( n, alpha, &X[n*i], coef, beta, *intercept ); resid[i] = y[i] - y_pred[i]; for ( unsigned long j = 0; j < n; j++ ) { gradient_coef[j] -= (X[n*i + j] * resid[i]); } if ( fit_intercept == 1 ) { gradient_intercept -= resid[i]; } } // Adjust weights for ( unsigned long j = 0; j < n; j++ ) { coef[j] -= eta_m * gradient_coef[j]; gradient_coef[j] = 0.0; } if ( fit_intercept == 1 ) { *intercept -= eta_m * gradient_intercept; gradient_intercept = 0.0; } } free(y_pred); free(resid); free(gradient_coef); } Edit: added code for checking speed of execution. int main(void) { double *X, *y, *coef, *y_preds; double intercept, eta = 0.5; double alpha = 1.0, beta = 1.0; unsigned long m = 100000; unsigned long n = 20; int max_iter = 250; int class_0 = (unsigned long)(3.0 / 4.0 * (double)m); double pct_class_1 = 0.0; clock_t test_start; clock_t test_end; double test_time; printf("Constructing variables...\n"); X = (double *) malloc (m * n * sizeof(double)); y = (double *) malloc (m * sizeof(double)); y_preds = (double *) malloc (m * sizeof(double)); coef = (double *) malloc (n * sizeof(double));
{ "domain": "codereview.stackexchange", "id": 44415, "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, c", "url": null }
performance, c // Initialize classes for ( unsigned long i = 0; i < m; i++ ) { if (i < class_0) { y[i] = 0.0; } else { y[i] = 1.0; } /* // Troubleshooting print if (i < 10 || i > m - 10) { //printf("%f\n", y[i]); } */ } // Initialize observation features for ( unsigned long i = 0; i < m; i++ ) { if (i < class_0) { X[n*i] = 1.0 / (double)m; } else { X[n*i] = (double)i / (double)m; } X[n*i + 1] = (double)i / (double)m; for ( unsigned long j = 2; j < n; j++ ) { X[n*i + j] = (double)rand() / (double)RAND_MAX; } /* // Troubleshooting print if (i < 10) { //printf("%f\t%f\n", X[n*i], X[n*i+1]); } */ } // Fit weights printf("Running GD/SGD...\n"); test_start = clock(); dgd( m, n, X, y, coef, &intercept, eta, max_iter, 1 ); test_end = clock(); test_time = (double)(test_end - test_start) / CLOCKS_PER_SEC; printf("Time taken: %f\n", test_time); // Compute y_hat and share of observations predicted as class 1 printf("Making predictions...\n"); for ( unsigned long i = 0; i < m; i++ ) { y_preds[i] = dsigmoid( n, alpha, &X[i*n], coef, beta, intercept ); }
{ "domain": "codereview.stackexchange", "id": 44415, "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, c", "url": null }
performance, c printf("Printing results...\n"); for ( unsigned long i = 0; i < m; i++ ) { //printf("%f\n", y_pred[i]); if (y_preds[i] > 0.5) { pct_class_1 += 1.0; } // Troubleshooting print if (i < 10 || i > m - 10) { printf("%g\n", y_preds[i]); } } /* // Troubleshooting print printf("Intercept: %f\n", intercept); printf("Coefficients:\n"); for ( unsigned long i = 0; i < n; i++ ) { printf("%f\n", coef[i]); } */ printf("Total observations: %ld\n", m); printf("Percent class 1: %f\n", pct_class_1 / (double)m); return 0; } Answer: how I can make it faster (?) At this time, I see no big O() improvements. 2x faster?: Use float If the range and precision requirements are not so high, many implementations have 2x (or more) fast float functions. This inner computation loops would benefit most with this change. e.g. float z; // float type return expf(z) / (1.0f + expf(z)); // float constant, function Of course this is highly dependent on OP's compiler and machine. Modest: Moved repeated test Test fit_intercept == 1 once. if (fit_intercept == 1) { for (size_t i = 0; i < m; i++ ) { y_pred[i] = dsigmoid( n, alpha, &X[n*i], coef, beta, *intercept ); resid[i] = y[i] - y_pred[i]; for (size_t j = 0; j < n; j++ ) { gradient_coef[j] -= (X[n*i + j] * resid[i]); } gradient_intercept -= resid[i]; } } else { for (size_t i = 0; i < m; i++ ) { y_pred[i] = dsigmoid( n, alpha, &X[n*i], coef, beta, *intercept ); resid[i] = y[i] - y_pred[i]; for (size_t j = 0; j < n; j++ ) { gradient_coef[j] -= (X[n*i + j] * resid[i]); } } }
{ "domain": "codereview.stackexchange", "id": 44415, "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, c", "url": null }
performance, c Minor: Use the right size type for array indexing size_t is the right size for all array indexing. unsigned long may be too big (or possibly too small). // double dlc( unsigned long n, double *X, double *coef, double intercept ) double dlc(size_t n, double *X, double *coef, double intercept) Same for dsigmoid(), dgd(). Minor: Use const for unchanging referenced data Performance: Lessor compilers will benefit. Good compiler will already know referenced data is not changed. Functionality: by using const, code may be called with const arrays. // double dlc( unsigned long n, double *X, double *coef, double intercept ) // double dlc(unsigned long n, const double *X, const double *coef, double intercept) Same for dsigmoid(), dgd(). Tip Avoid allocate errors (none were noted here). Allocate to the size of the referenced object and avoid getting the type wrong. // y_pred = (double *) malloc (m * sizeof(double)); // Correct even if `y_red` later changed to a `float *`. y_pred = malloc (sizeof y_pred[0] * m);
{ "domain": "codereview.stackexchange", "id": 44415, "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, c", "url": null }
xaml Title: Avalonia user control with design time XAML property setter Question: I am trying to make an AvaloniaUI user control. I want to be able to set a property at design time from inside my XAML files and see the result in the designer in Rider, such as the "Hello World!" text below. The approach I have taken is to add a property to the control that gets and sets the Text property of a TextBlock that is defined in the XAML. public partial class SectionHeader : UserControl { public string Caption { get { return this.FindControl<TextBlock>("CaptionText").Text; } set { this.FindControl<TextBlock>("CaptionText").Text = value; } } public SectionHeader() { InitializeComponent(); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } } <UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:viewModels="clr-namespace:BasicMvvmSample.ViewModels" mc:Ignorable="d" d:DesignWidth="800" d:DesignHeight="450" x:Class="AvTest.Controls.SectionHeader"> <Design.DataContext> <viewModels:MyViewModel /> </Design.DataContext> <TextBlock Background="#c71e32" Foreground="White" Padding="2,3" FontWeight="Bold" Margin="2" Height="25" Name="CaptionText" > </TextBlock> </UserControl> This approach works, but it does not use the patterns described in the documentation that rely on AvaloniaProperty. I am new to both Avalonia and XAML and wonder if my approach is sensible, or if there is a better and more "XAML way" to achieve this.
{ "domain": "codereview.stackexchange", "id": 44416, "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": "xaml", "url": null }
xaml Answer: By 'default' the preference is to use a StyledProperty, as these can be bound or styled. If you don't need that, then you get away with something simpler, but if you really don't need anything more, then perhaps consider using a TextBlock with a class (e.g. Classes="SectionHeader") and styling to go with it. Custom controls are mostly useful for providing new behaviours; if you just want to keep the styling clean, then use styles. To set up a StyledProperty in the class (which I'd suggest doing, because binding gives you so much power (e.g. to bind to a localisable resource key for globalisation)) you'd generally add something like public static readonly StyledProperty<string> CaptionProperty = AvaloniaProperty.Register<SectionHeader, string>(nameof(Caption)); public string Caption { get => this.GetValue(CaptionProperty); set => this.SetValue(CaptionProperty, value); } as you can find in the documentation you've linked, and then bind this property in your XAML for the control (so that the above property is reflected in the control interface), for the TextBlock*: Text="{Binding $parent[UserControl].Caption}" and when using SectionHeader: <controls:SectionHeader Caption="Hello, World!" /> <controls:SectionHeader Caption="{Binding Whatever.SectionCaption}" /> <controls:SectionHeader Caption="{DynamicResource LocalisedSectionCaption}" />
{ "domain": "codereview.stackexchange", "id": 44416, "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": "xaml", "url": null }
xaml Again, you're not using any of the power of a UserControl, but I'd say there's nothing wrong with using one here. When accessing named controls, consider adding a reference to XamlNameReferenceGenerator: if you're using .NET7+ it'll use a source-generator to generate fields for your named controls, so you don't have to find them by name (this makes the code cleaner, quicker to write and harder to get wrong or later break) * $parent[UserControl] is one way to access the properties of the UserControl, rather than it's DataContext: see https://docs.avaloniaui.net/docs/data-binding/binding-to-controls for more information
{ "domain": "codereview.stackexchange", "id": 44416, "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": "xaml", "url": null }
c++, error-handling, c++20, constrained-templates Title: Basic scoped timer struct design Question: I have written the following simple scoped timer struct in order to help me measure the execution time of arbitrary scopes. Here is the code (live): #include <chrono> #include <thread> #include <cstdio> #include <fmt/core.h> #include <fmt/chrono.h> template < class Time = std::chrono::microseconds, class Clock = std::chrono::steady_clock > requires ( std::chrono::is_clock_v<Clock> ) struct ScopedTimer { const std::chrono::time_point< Clock > m_start { Clock::now( ) }; std::chrono::time_point< Clock > m_end; std::FILE* m_stream; ScopedTimer( std::FILE* const stream = stderr ) noexcept( noexcept( Clock::now( ) ) ) : m_stream { stream } { } ~ScopedTimer( ) { m_end = Clock::now( ); fmt::print( m_stream, "\nTimer took {}\n", std::chrono::duration_cast<Time>( m_end - m_start ) ); } ScopedTimer( const ScopedTimer& ) = delete; ScopedTimer& operator=( const ScopedTimer& ) = delete; }; int main( ) { // default instantiation ScopedTimer timer; // another instantiation // ScopedTimer<std::chrono::milliseconds, std::chrono::system_clock> timer; using std::chrono_literals::operator""ms; std::this_thread::sleep_for( 500ms ); } Now I have a few question regarding its design:
{ "domain": "codereview.stackexchange", "id": 44417, "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++, error-handling, c++20, constrained-templates", "url": null }
c++, error-handling, c++20, constrained-templates Now I have a few question regarding its design: How do I put constraints on the template parameter Time just like I have done for Clock inside the requires clause? Because something like std::chrono::is_duration_v<Time> doesn't exist in the standard library. Should it only allow clock types that are trivial (i.e. satisfy the requirements of TrivialClock) or is it fine if it allows non-trivial ones too? If it should then how can I implement the constraint? Regarding the exception safety of the ctor and the dtor, for a given trivial clock, its now() method does not throw unlike a non-trivial clock. So in case I allow non-trivial clock types, then how should I make the ctor and dtor noexcept? My current idea is to use noexcept( noexcept( Clock::now() ) ) as can be seen in the above code snippet. And what should I do for the dtor since exceptions should not escape the dtor? Speaking of access specifiers, should the three member variables be public or private? I consider public as a better option since it allows the client code to access them using the dot operator (obj._member) without the need for getters or setters. Could any standard attributes (e.g. [[maybe_unused]]) be used to further enhance the correctness of the above struct? Any other suggestions are welcome. Answer: Answers to your questions How do I put constraints on the template parameter Time just like I have done for Clock inside the requires clause? Because something like std::chrono::is_duration_v<Time> doesn't exist in the standard library. You can create a concept yourself, for example: template<typename Clock, typename Duration> concept can_yield_duration = requires(Clock::time_point t) { std::chrono::duration_cast<Duration>(t - t); }; template < class Time = std::chrono::milliseconds, class Clock = std::chrono::steady_clock > requires ( std::chrono::is_clock_v<Clock> && can_yield_duration<Clock, Time> ) struct ScopedTimer …
{ "domain": "codereview.stackexchange", "id": 44417, "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++, error-handling, c++20, constrained-templates", "url": null }
c++, error-handling, c++20, constrained-templates Should it only allow clock types that are trivial (i.e. satisfy the requirements of TrivialClock) or is it fine if it allows non-trivial ones too? If it should then how can I implement the constraint? Don't restrict things unnecessarily. Even if you cannot see the usefulness, someone else might. If you are sure using any non-trivial clock type would cause the template to fail to instantiate or would cause it to do the wrong thing, then it might make sense to constrain it. Regarding the exception safety of the ctor and the dtor, for a given trivial clock, its now() method does not throw unlike a non-trivial clock. So in case I allow non-trivial clock types, then how should I make the ctor and dtor noexcept? My current idea is to use noexcept( noexcept( Clock::now() ) ) as can be seen in the above code snippet. And what should I do for the dtor since exceptions should not escape the dtor? The noexcept specifier you wrote for the constructor looks fine to me. As for the destructor, you can use a noexcept specifier for it as well. But would it be useful? Would anyone catch it? I would either just not specify it, then it will implicitly be noexcept(true), and then any exception thrown inside the destructor will cause the program to abort. Alternatively, you could catch any exception in the destructor and then just print an error message, although fmt::print() can throw as well. Speaking of access specifiers, should the three member variables be public or private? I consider public as a better option since it allows the client code to access them using the dot operator (obj._member) without the need for getters or setters. I don't see any reason for client code to modify those member variables. The more you make public, the less chance you have of making changes to your code would braking backwards compatibility. Could any standard attributes (e.g. [[maybe_unused]]) be used to further enhance the correctness of the above struct?
{ "domain": "codereview.stackexchange", "id": 44417, "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++, error-handling, c++20, constrained-templates", "url": null }
c++, error-handling, c++20, constrained-templates I don't think so. Your class has side effects, so [[maybe_unused]] is not necessary. I also don't think any other attribute applies. Simpler way to write types Instead of writing std::chrono::time_point<Clock>, you can write Clock::time_point. If you are going to write the same long type name multiple times, you could also consider creating an alias for it: using time_point = typename Clock::time_point; const time_point m_start = { Clock::now(); }; Avoid declaring unnecessary member variables The variable m_end is only used inside the destructor, so there is no need to make this a member variable, just make it a local function variable. Don't use C I/O in a C++ program Why use FILE* in a C++ program? You should pass a reference to a std::ostream instead: std::ostream& m_stream; ScopedTimer( std::ostream& stream = std::cerr ) noexcept(…) : m_stream { stream } { } What if you don't want to print the elapsed time? If all you care about is that the elapsed time is printed to some stream, this is fine. But what if you want to do something else? You could consider passing a callback function instead of passing a stream to the constructor, and have it call that function in the destructor, so you can write something like: ScopedTimer timer( [] ( auto duration ) { fmt::print( std::cerr, "Timer took {}\n", duration.count() ); }); This removes responsibility from the ScopedTimer class, and while it does less, it is now much more flexible. I would then also not have Time as a template parameter, but just have the result of the subtraction passed directly to the callback function, which can then decide if it wants to do a duration cast or not. To pass a function to the constructor and to store it until the timer is destructed, use std::function: #include <chrono> #include <fmt/core.h> #include <fmt/ostream.h> #include <functional> #include <iostream>
{ "domain": "codereview.stackexchange", "id": 44417, "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++, error-handling, c++20, constrained-templates", "url": null }
c++, error-handling, c++20, constrained-templates template < class Clock = std::chrono::steady_clock > requires ( std::chrono::is_clock_v< Clock > ) class ScopedTimer { using TimePoint = typename Clock::time_point; using Duration = typename Clock::duration; using Callback = std::function< void( Duration ) >; Callback m_callback; TimePoint m_start{ Clock::now() }; static void default_callback( Duration duration ) { fmt::print( std::cerr, "Timer took {}\n", duration.count() ); } public: ScopedTimer( Callback callback = default_callback ) : m_callback { callback } { } ~ScopedTimer() { TimePoint end{ Clock::now() }; m_callback( end - m_start ); } }; For demonstration purposes I've also shown how you can still have a default value for the callback parameter, however I would not include it, as it introduces a dependency on both <fmt/*.h> and <iostream>.
{ "domain": "codereview.stackexchange", "id": 44417, "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++, error-handling, c++20, constrained-templates", "url": null }
parsing, lexical-analysis, antlr Title: ANTLR4 grammar for Conventional Commits spec Question: I would like to create a grammar for the Conventional Commits spec and I would love to hear any feedback for what I wrote. The spec has some ambiguities, I think, hence my usage of "island grammars" to avoid writing predicates and such, which would limit the parser to a certain language target. An example of a conventional commit message the parser should be able to handle fix(some_module): this is a commit description Some more in-depth description of what was fixed. This can be a multi-line text, not only a one-liner. Signed-off: john.doe@some.domain.com Another-Key: another value Some-Other-Key: some other value The lexer: lexer grammar ConventionalCommitLexer; options { caseInsensitive = true; } tokens { TEXT } WS: [ \t]+ -> skip; NEWLINE: ('\r')? '\n'; LPAREN: '(' -> mode(Scope); RPAREN: ')'; SEMICOLON: ':' WS*-> mode(Description); OTHER: 'other'; FEAT: 'feat'; FIX: 'fix'; DOCS: 'docs'; STYLE: 'style'; REFACTOR: 'refactor'; PERF: 'perf'; TEST: 'test'; CHORE: 'chore'; BUILD: 'build'; CI: 'ci'; BREAKING: 'breaking'; SECURITY: 'security'; REVERT: 'revert'; CONFIG: 'config'; UPGRADE: 'upgrade'; DOWNGRADE: 'downgrade'; PIN: 'pin'; IDENTIFIER: [a-z][a-z0-9_-]*; mode Scope; WS_SCOPE: [ \t] -> skip; SCOPE: IDENTIFIER -> type(IDENTIFIER); END_OF_SCOPE: RPAREN -> type(RPAREN), mode(DEFAULT_MODE); mode Description; DESCRIPTION: ~[\n]+ -> type(TEXT); END_OF_TEXT: (WS | NEWLINE)+ -> mode(Body), type(NEWLINE); mode Body; END_OF_BODY: (WS | NEWLINE)+ -> mode(Footer), type(NEWLINE); BODY: (SINGLE_LINE | MULTI_LINE) -> type(TEXT); SINGLE_LINE : ~[\n]+ ; MULTI_LINE : (SINGLE_LINE | (~[\n]+ NEWLINE))+ -> mode(Footer) ; mode Footer; WS_FOOTER: ' ' -> skip; KEY: IDENTIFIER -> type(IDENTIFIER); SEPARATOR: WS_FOOTER* SEMICOLON WS_FOOTER* -> type(SEMICOLON), mode(FooterValue); mode FooterValue; NEWLINE_FOOTER: NEWLINE -> type(NEWLINE), mode(Footer); VALUE: ~[\n]+ -> type(TEXT);
{ "domain": "codereview.stackexchange", "id": 44418, "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": "parsing, lexical-analysis, antlr", "url": null }
parsing, lexical-analysis, antlr The parser: parser grammar ConventionalCommitParser; options { tokenVocab = ConventionalCommitLexer; } type: (OTHER | FEAT | FIX | DOCS | STYLE | REFACTOR | PERF | TEST | CHORE | BUILD | CI | BREAKING | SECURITY | REVERT | CONFIG | UPGRADE | DOWNGRADE | PIN) #RecognizedType | IDENTIFIER #OtherType ; footerKeyValue: key = IDENTIFIER SEMICOLON value = TEXT NEWLINE?; commitMessage: type LPAREN scope = IDENTIFIER RPAREN SEMICOLON description = TEXT (NEWLINE body = TEXT)? (NEWLINE values += footerKeyValue+)? EOF; Answer: Nice idea. Obtaining conformant commit messages will be easier if much of a project's developer community installs a validating .git/hooks/pre-commit script. I think a giant regex could handle the task, but this is far more readable! SEMICOLON: ':' WS*-> mode(Description); nit: Whitespace around the -> arrow, please, for readability. Bigger item: Surely this is a COLON token, no? {FEAT, FIX} are canonical, and then there are multiple vocabularies that a project could choose to adopt, such as Angular's {BUILD, CHORE, ...}. For such words, I feel you should Separate them out with a blank line. Cite the URL of your reference (as you nicely did in this question). Maybe alphabetize, even if (as here) the cited reference does not. What we're shooting for is traceability, and ease of editing when the upstream reference inevitably changes the list of words. For the same reason, consider putting BREAKING right after {FEAT, FIX}, to match the cited reference. WS_SCOPE: [ \t] -> skip; I am slightly sad that we didn't manage to recycle WS from above. Whatever. I get the sense that you feel CRLF could potentially be a Problem. DESCRIPTION: ~[\n]+ -> type(TEXT);
{ "domain": "codereview.stackexchange", "id": 44418, "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": "parsing, lexical-analysis, antlr", "url": null }
parsing, lexical-analysis, antlr Soooo, that's going to lump \r CR in with the TEXT, right? Is that OK? Both SINGLE_LINE & MULTI_LINE wrestle with the same detail. Oh, wait. Could DESCRIPTION take advantage of SINGLE_LINE ? Maybe we'd be better off insisting that a "strip all CRs!" preprocessing step shall happen before lexing? END_OF_TEXT: (WS | NEWLINE)+ -> mode(Body), type(NEWLINE); Pair of tiny nits: WS or NEWLINE is kind of funny, it is whitespace. But yeah, I get it. Consider using the name BLANK for WS? To free up the name for this expression? I would find these slightly easier to read and compare if we consistently mentioned type / mode in the same order. WS_FOOTER: ' ' -> skip; Pretty sure you wanted to handle TABs, as well. Maybe we could reuse WS? | PIN) #RecognizedType | IDENTIFIER #OtherType I found the first comment helpful, thank you. The second produced some cognitive dissonance with OTHER, sigh! footerKeyValue: key = IDENTIFIER SEMICOLON value = TEXT NEWLINE?; The NEWLINE? feels like it's possibly trouble. Imagine that an annoying commit message mentioned Another-Key: aaa Looks-Like-A-Header: bbb ccc on a single line. I'm concerned that TEXT would pick up just aaa. It doesn't seem hard to accidentally stumble upon, perhaps with Priority: time to implement: soon. Or even with a URL. Again, insisting on a preprocessing step, in this case one which appends \n so we're sure the document ends with NEWLINE, seems fairly prudent. commitMessage: type LPAREN scope = IDENTIFIER RPAREN SEMICOLON description = TEXT (NEWLINE body = TEXT)? (NEWLINE values += footerKeyValue+)? EOF; Wrap this at 80 chars, please, to improve readability. Overall? All issues are minor. Looks fine to ship and get some testing feedback from real-world inputs.
{ "domain": "codereview.stackexchange", "id": 44418, "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": "parsing, lexical-analysis, antlr", "url": null }
python, python-3.x, aws-cdk Title: Python boto3 code to get the matrics from aws cloudwatch Question: I am working on a boto3 library and getting some metrics from aws cloud service cloud watch and that works perfectly fine, however, I am placing this question just in anticipation to get a review and guidelines form the python experts to make this code more explicit and distinct for readers so I can also get the opportunity to improve going forward. import boto3 import os import json from datetime import datetime, timedelta from boto3.dynamodb.conditions import Key from botocore.exceptions import ClientError # Clients should be created outside of the request handler fsx = boto3.client('fsx') cloudwatch = boto3.client('cloudwatch') ses = boto3.client('ses') region_name = os.environ['AWS_REGION'] dynamodb = boto3.resource('dynamodb', region_name=region_name) # Lambda handler function def lambda_handler(event, context): now = datetime.utcnow() start_time = (now - timedelta(minutes=5)).strftime('%Y-%m-%dT%H:%M:%SZ') end_time = now.strftime('%Y-%m-%dT%H:%M:%SZ') filesystem_ids = [] result = [] next_token = None # get all filesystem_ids while True: if next_token: response = fsx.describe_file_systems(NextToken=next_token) else: response = fsx.describe_file_systems() for filesystem in response.get('FileSystems'): filesystem_id = filesystem.get('FileSystemId') filesystem_ids.append(filesystem_id) next_token = response.get('NextToken') if not next_token: break
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk try: # Create the DynamoDB table if it does not exist # Don't keep `dbtable` outside the as it will through an error like "local variable 'dbtable' referenced before assignment"! dbtable = dynamodb.Table('hwde-fsxn-fs-monitoring') dbtable = dynamodb.create_table( TableName='hwde-fsxn-fs-monitoring', KeySchema=[ { 'AttributeName': 'filesystem_id', 'KeyType': 'HASH' } ], AttributeDefinitions=[ { 'AttributeName': 'filesystem_id', 'AttributeType': 'S' } ], ProvisionedThroughput={ 'ReadCapacityUnits': 10, 'WriteCapacityUnits': 10 } ) # Wait for the table to be created dbtable.meta.client.get_waiter( 'table_exists').wait(TableName='hwde-fsxn-fs-monitoring') except ClientError as e: if e.response['Error']['Code'] != 'ResourceInUseException': raise
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk # Code to retrieve metric data and check if alert needs to be sent for filesystem_id in filesystem_ids: response = cloudwatch.get_metric_data( MetricDataQueries=[ { 'Id': 'm1', 'MetricStat': { 'Metric': { 'Namespace': 'AWS/FSx', 'MetricName': 'StorageCapacity', 'Dimensions': [ { 'Name': 'FileSystemId', 'Value': filesystem_id }, { 'Name': 'StorageTier', 'Value': 'SSD' }, { 'Name': 'DataType', 'Value': 'All' } ] }, 'Period': 60, 'Stat': 'Sum' }, 'ReturnData': True }, { 'Id': 'm2', 'MetricStat': { 'Metric': { 'Namespace': 'AWS/FSx', 'MetricName': 'StorageUsed', 'Dimensions': [ { 'Name': 'FileSystemId', 'Value': filesystem_id }, { 'Name': 'StorageTier', 'Value': 'SSD' }, { 'Name': 'DataType', 'Value': 'All' } ] }, 'Period': 60, 'Stat': 'Sum' }, 'ReturnData': True } ], StartTime=start_time, EndTime=end_time ) storage_capacity = response['MetricDataResults'][0]['Values'] storage_used = response['MetricDataResults'][1]['Values']
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk if storage_capacity: storage_capacity = storage_capacity[0] else: storage_capacity = None if storage_used: storage_used = storage_used[0] else: storage_used = None if storage_capacity and storage_used: percent_used = (storage_used / storage_capacity) * 100 else: percent_used = None ###################################################################### #### Check if an alert has already been sent for this filesystem_id ### ####################################################################### _dbQuery = dbtable.get_item(Key={'filesystem_id': filesystem_id}) if 'Item' in _dbQuery: alert_sent = _dbQuery['Item']['alert_sent'] print("E-mail has been sent for the filesystem {}:".format(filesystem_id)) else: alert_sent = False print("E-mail has not been sent for the filesystem {}:".format(filesystem_id)) # Send an alert if storage usage exceeds the threshold and no alert has been sent yet if percent_used > 85 and not alert_sent: result.append({'filesystem_id': filesystem_id, 'percent_used': percent_used}) if result: header = f''' Dear Team,<br><br> Please find the FSx ONTAP filesystem(SSD Tier) threshold breached report below for the {region_name} region, Kindly check the alert and increase the filesystem if required or act accordingly. <br></br> <table> <tr> <th style='text-align: left'>FileSystemId</th> <th style='text-align: right'>Used %</th> </tr> ''' body = ""
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk for fs in result: body += f''' <tr> <td style='text-align: left'>{fs['filesystem_id']}</td> <td style='text-align: right; color:red;'>{str(round(fs['percent_used'], 2))}%</td> </tr> ''' footer = f'''</table> <br></br> Sincerely,<br> Storage CIS Team. ''' email_body = header + body + footer if not alert_sent: ses.send_email( Source='botoassist@example.com', Destination={ 'ToAddresses': ['some-email@example.com'] }, Message={ 'Subject': { 'Data': "FSx ONTAP filesystem alert report for {} region.".format(region_name) }, 'Body': { 'Html': { 'Data': email_body } } } ) for fs in result: filesystem_id = fs['filesystem_id'] dbtable.put_item( Item = { 'filesystem_id': filesystem_id, 'alert_sent': True } ) return { 'statusCode': 200, 'body': json.dumps('Email sent!') } Thank you so much in advanced and a very happy new year!
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk Thank you so much in advanced and a very happy new year! Answer: In general, remember that one function (or class), one responsibility is a good rule of thumb when designing software. Furthermore, in general, variables should be declared as late as possible and as close to their site of use as possible: if a variable like result is declared at the beginning of a function and used only tens of lines later, that's a code smell and not only hurts readability but also makes it susceptible to errors. The first tip in Best practices for working with AWS Lambda functions is to separate the Lambda handler from your core logic. Indeed, I get a strong urge to find logical pieces of your current solution and break it down to smaller pieces that are individually testable and usable. You could look at the lambda handler as doing (at least) these steps: Get filesystem IDs. Build a DynamoDB table. For each filesystem ID, get corresponding CloudWatch metric data. Build a list of alerts to notify the users. Prepare and format an email to be sent. Send an email and do logging. All this in a single lambda handler is very difficult to read and reason about. Start by cutting out pieces of logic from your lambda handler. I recommend you approach this with test-driven development in mind. So for each, write a unit test and a function that gathers all FSx filesystem IDs, and a function that, given a filesystem id, gets the corresponding CloudWatch metric data.
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
python, python-3.x, aws-cdk You can further use a helper function that prepares the metric data query. After this, I would keep going and write a function that receives the required parameters, and prepares an email body to be sent. I would also consider if the lambda function really needs to create the DynamoDB table: could you create this somewhere outside the lambda function completely and let the lambda handler just use it? Here, remember that it's best practice to pass details such as table names to a lambda via environment variables (again, see the link provided). I hope this gets you going, it sounds like a fun exercise to implement all this and refactor the handler so that it's more readable, maintainable and testable.
{ "domain": "codereview.stackexchange", "id": 44419, "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, python-3.x, aws-cdk", "url": null }
c, collections, library, vectors, macros Title: C macro based dynamic array library Question: This library is a fork of eteran/c-vector. It is macro based, so that it is generic, without void pointers and additional functions. This of course means that it has the downsides of macros in C. The repository for the project is hosted here. It is still in its early stages, in the future I will upload the unit tests for the library, documentation, a readme and more C goodies. It passes all the tests (which are written with MinUnit), but we have found and fixed 2-3 sneaky bugs that the tests did in fact miss. What I'm looking to get from this code review is feedback about the quality of the code, adherence to convetions, usage of C idioms and so on. A discussion of a potential implementation of the library using functions instead of macros is also welcome. Lastly, if this library is up to standard, feel free to use in your own projects, I hope that it saves you time (after all a list is very useful usually). Here is the code: #ifndef LIB_DYNAMIC_ARRAY_H #define LIB_DYNAMIC_ARRAY_H #ifndef DYNAMIC_ARRAY_malloc #define DYNAMIC_ARRAY_malloc malloc #endif #ifndef DYNAMIC_ARRAY_realloc #define DYNAMIC_ARRAY_realloc realloc #endif #ifndef DYNAMIC_ARRAY_free #define DYNAMIC_ARRAY_free free #endif #ifndef DYNAMIC_ARRAY_GROWTH_FACTOR #define DYNAMIC_ARRAY_GROWTH_FACTOR 1.5 #endif #ifndef DYNAMIC_ARRAY_INITIAL_CAPACITY #define DYNAMIC_ARRAY_INITIAL_CAPACITY 2 #endif #include <stddef.h> #include <assert.h> #include <stdlib.h> #ifdef NDEBUG #define CHECK(_pointer) \ do { \ if (!(_pointer)) \ { \ exit(EXIT_FAILURE); \ } \ } while (0) #else #include <stdio.h> #include <errno.h> #include <string.h>
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #else #include <stdio.h> #include <errno.h> #include <string.h> #define CHECK(_pointer) \ do { \ if (!(_pointer)) \ { \ fprintf(stderr, "errno: %d\n%s\n", errno, strerror(errno)); \ exit(EXIT_FAILURE); \ } \ } while (0) #endif #define DYNAMIC_ARRAY_SIZE(dynamic_array) \ ((dynamic_array) ? ((size_t *)(dynamic_array))[-2] : (size_t)0) #define DYNAMIC_ARRAY_CAPACITY(dynamic_array) \ ((dynamic_array) ? ((size_t *)(dynamic_array))[-1] : (size_t)0) #define DYNAMIC_ARRAY_EMPTY(dynamic_array) \ (DYNAMIC_ARRAY_SIZE(dynamic_array) == 0) #define DYNAMIC_ARRAY_PEEK(dynamic_array) \ (dynamic_array)[DYNAMIC_ARRAY_SIZE(dynamic_array) - 1]
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_ALLOCATE(dynamic_array, requested_capacity) \ do { \ assert((requested_capacity) > 0); \ const size_t _total_capacity = (requested_capacity) * sizeof(*(dynamic_array)) + (sizeof(size_t) * 2); \ if (!(dynamic_array)) \ { \ const size_t * _dynamic_array_pointer = DYNAMIC_ARRAY_malloc(_total_capacity); \ CHECK(_dynamic_array_pointer); \ (dynamic_array) = (void *)(&_dynamic_array_pointer[2]); \ ((size_t *)(dynamic_array))[-1] = (requested_capacity); \ ((size_t *)(dynamic_array))[-2] = 0; \ } \ else \ { \ const size_t * _dynamic_array_pointer = DYNAMIC_ARRAY_realloc(&((size_t *)(dynamic_array))[-2], _total_capacity); \
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros CHECK(_dynamic_array_pointer); \ (dynamic_array) = (void *)(&_dynamic_array_pointer[2]); \ ((size_t *)(dynamic_array))[-1] = (requested_capacity); \ if ((requested_capacity) < DYNAMIC_ARRAY_SIZE(dynamic_array)) \ { \ ((size_t *)(dynamic_array))[-2] = (requested_capacity); \ } \ } \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_FREE(dynamic_array) \ do { \ assert(dynamic_array); \ free(&((size_t *)(dynamic_array))[-2]); \ (dynamic_array) = NULL; \ } while (0) #define DYNAMIC_ARRAY_RESERVE(dynamic_array, requested_capacity) \ do { \ assert((requested_capacity) > 0); \ if ((requested_capacity) > DYNAMIC_ARRAY_CAPACITY(dynamic_array)) \ { \ DYNAMIC_ARRAY_ALLOCATE(dynamic_array, requested_capacity); \ } \ } while (0) #define DYNAMIC_ARRAY_FIT(dynamic_array) \ do { \ assert(dynamic_array); \ if(!DYNAMIC_ARRAY_EMPTY(dynamic_array)) \ { \ DYNAMIC_ARRAY_ALLOCATE(dynamic_array, DYNAMIC_ARRAY_SIZE(dynamic_array)); \ } \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_PUSH_BACK(dynamic_array, value) \ do { \ const size_t _capacity_ = DYNAMIC_ARRAY_CAPACITY(dynamic_array), _size_ = DYNAMIC_ARRAY_SIZE(dynamic_array); \ if (_capacity_ == _size_) \ { \ DYNAMIC_ARRAY_ALLOCATE((dynamic_array), !_capacity_ ? DYNAMIC_ARRAY_INITIAL_CAPACITY : (size_t)(_capacity_ * DYNAMIC_ARRAY_GROWTH_FACTOR)); \ } \ (dynamic_array)[_size_] = (value); \ ((size_t *)(dynamic_array))[-2] = _size_ + 1; \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_REMOVE_BACK(dynamic_array) \ do { \ assert((dynamic_array) && DYNAMIC_ARRAY_SIZE(dynamic_array) > 0); \ ((size_t *)(dynamic_array))[-2] = ((size_t *)(dynamic_array))[-2] - 1; \ if (DYNAMIC_ARRAY_SIZE(dynamic_array) == (size_t)(DYNAMIC_ARRAY_CAPACITY(dynamic_array) / DYNAMIC_ARRAY_GROWTH_FACTOR)) \ { \ DYNAMIC_ARRAY_FIT(dynamic_array); \ } \ } while (0) #define DYNAMIC_ARRAY_POP_BACK(dynamic_array, destination) \ do { \ assert((dynamic_array) && DYNAMIC_ARRAY_SIZE(dynamic_array) > 0); \ (destination) = DYNAMIC_ARRAY_PEEK(dynamic_array); \ DYNAMIC_ARRAY_REMOVE_BACK(dynamic_array); \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_INSERT(dynamic_array, value, index) \ do { \ const long _size = DYNAMIC_ARRAY_SIZE(dynamic_array), _move = (_size - 1 - (index)); \ assert((index) >= 0 && (index) <= _size); \ if (_move) \ { \ DYNAMIC_ARRAY_PUSH_BACK(dynamic_array, (dynamic_array)[_size - 1]); \ memmove(&(dynamic_array)[index + 1], &(dynamic_array)[index], _move * sizeof(*(dynamic_array))); \ (dynamic_array)[index] = (value); \ } \ else \ { \ DYNAMIC_ARRAY_PUSH_BACK(dynamic_array, value); \ } \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_REMOVE(dynamic_array, index) \ do { \ const size_t _size = DYNAMIC_ARRAY_SIZE(dynamic_array); \ assert((dynamic_array) && (index) >= 0 && (index) <= _size - 1); \ memmove(&(dynamic_array)[index], &(dynamic_array)[index + 1], (_size - 1 - (index)) * sizeof(*(dynamic_array))); \ DYNAMIC_ARRAY_REMOVE_BACK(dynamic_array); \ } while (0) #define DYNAMIC_ARRAY_ERASE(dynamic_array, index, destination) \ do { \ assert((dynamic_array) && (index) >= 0 && (index) < DYNAMIC_ARRAY_SIZE(dynamic_array)); \ (destination) = (dynamic_array)[index]; \ DYNAMIC_ARRAY_REMOVE(dynamic_array, index); \ } while (0) #define DYNAMIC_ARRAY_TRUNCATE(dynamic_array, requested_size) \ do { \ assert((dynamic_array) && (requested_size) < DYNAMIC_ARRAY_SIZE(dynamic_array)); \ ((size_t *)(dynamic_array))[-2] = (requested_size); \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_EXTEND(dynamic_array, requested_size, value) \ do { \ assert((requested_size) > DYNAMIC_ARRAY_SIZE(dynamic_array)); \ while (DYNAMIC_ARRAY_SIZE(dynamic_array) < (requested_size)) \ { \ DYNAMIC_ARRAY_PUSH_BACK(dynamic_array, value); \ } \ } while (0) #define DYNAMIC_ARRAY_RESIZE(dynamic_array, requested_size, value) \ do { \ assert((requested_size) >= 0 && (requested_size) != DYNAMIC_ARRAY_SIZE(dynamic_array)); \ if (DYNAMIC_ARRAY_SIZE(dynamic_array) > (requested_size)) \ { \ DYNAMIC_ARRAY_TRUNCATE(dynamic_array, requested_size); \ } \ else \ { \ DYNAMIC_ARRAY_EXTEND(dynamic_array, requested_size, value); \ } \ } while (0) #define DYNAMIC_ARRAY_CLEAR(dynamic_array) \ do { \ assert(!DYNAMIC_ARRAY_EMPTY(dynamic_array)); \ ((size_t *)(dynamic_array))[-2] = 0; \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_COPY(destination, source) \ do { \ assert(!DYNAMIC_ARRAY_EMPTY(source)); \ DYNAMIC_ARRAY_ALLOCATE(destination, DYNAMIC_ARRAY_SIZE(source)); \ memcpy(&((size_t *)(destination))[-2], &((size_t *)(source))[-2], DYNAMIC_ARRAY_SIZE(source) * sizeof(*(source)) + 2 * sizeof(size_t)); \ } while (0)
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #define DYNAMIC_ARRAY_CONCATENATE(destination, source) \ do { \ assert(source); \ if(DYNAMIC_ARRAY_EMPTY(destination)) \ { \ DYNAMIC_ARRAY_COPY(destination, source); \ } \ else \ { \ DYNAMIC_ARRAY_ALLOCATE(destination, DYNAMIC_ARRAY_SIZE(destination) + DYNAMIC_ARRAY_SIZE(source)); \ memcpy(&(destination)[DYNAMIC_ARRAY_SIZE(destination)], source, DYNAMIC_ARRAY_SIZE(source) * sizeof(*(source))); \ ((size_t *)(destination))[-2] = DYNAMIC_ARRAY_SIZE(source) + DYNAMIC_ARRAY_SIZE(destination); \ } \ } while (0) #endif Notes:
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros #endif Notes: The reason I have defined macros for malloc(), calloc() and realloc() is that there is a possibility that alternative memory allocators may be used to improve performance, such as jemalloc. Many macros access the size and capacity properties of the dynamic array, sometimes through the relevant macros, other do so directly. One of the two methods will be used for the sake of consistency, the functionality should be the same though. The rule of thumb, in order to optimize for speed, was that if something is to fail internally, it should be checked explicitly. If the user makes an error in using a macro with inappropriate arguments, assertions are in place to assist in the debugging process, but no checks are in place. I am aware that if people use this library they will shoot themselves in the foot one way or another, is my approach acceptable? The API provided is similar to C++'s std::vector, as well as eteran/c-vector, but the aim is for it to feel familiar, not to be exactly the same. Answer: Consider alphabetizing each little stanza of includes. It's a way of communicating to the reader that they don't depend on one another, plus it can reduce merge conflicts during maintenance when multiple developers add new includes. #define DYNAMIC_ARRAY_SIZE(dynamic_array) Kudos for being descriptive. But maybe abbreviate such parameter names? Whatever. #define DYNAMIC_ARRAY_SIZE(array) (Or maybe you want to minimize diffs from upstream. That's cool.) The DYNAMIC_ARRAY_COPY(destination, source) and DYNAMIC_ARRAY_CONCATENATE signatures are very nice.
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros We use this expression for capacity: ((size_t *)(dynamic_array))[-1]. I get what's going on here. I'm just slightly surprised that it is valid portable C. I'm also concerned that various code checking tools will spuriously flag an out-of-bounds reference. Maybe introduce a helper function that backs up to the true start-of-allocation, and de-references using a positive offset? (If this is "too slow", at least document the benchmark result in the source code.) Same item for "size", of course. Also, prepending some bookkeeping fields makes me concerned about cache-line alignment. If the app-level developer was trying to use strides that match cache-line size, being slightly offset might invalidate such reasoning. Maybe pad the bookkeeping with a few bytes? At least when the allocation is "large"? Do we want to arrange for DYNAMIC_ARRAY_PEEK to fail when it attempts to peek an empty array? Looks like it could return the capacity, as currently written. #define DYNAMIC_ARRAY_ALLOCATE(dynamic_array, requested_capacity) \ ... ((size_t *)(dynamic_array))[-1] = (requested_capacity); \ ((size_t *)(dynamic_array))[-2] = 0; \ This is pretty ordinary code, there's nothing especially wrong with it. And you graciously explained the _SIZE & _CAPACITY immediately above it. But the magic numbers do make me a little sad, plus there's the whole cache-line thing. Consider defining manifest constants for -1 & -2. Or, better, make a macro that can be used in both getter and setter macros such as seen here. One of the two methods will be used for the sake of consistency Oh, I see, it's on the TODO list already. Cool. _total_capacity = (requested_capacity) * sizeof(*(dynamic_array)) + ...
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros I find that calling both of these a "capacity" makes it hard to reason about them, since "total" has units of bytes. Maybe call it _total_bytes ? For example, that naming approach didn't make it any easier for me to figure out what was going on in this test: if ((requested_capacity) < DYNAMIC_ARRAY_SIZE(dynamic_array)) \ Consider adding a comment which explains the need for the conditional. Consider adding a comment that explains to app developers the value-add offered by DYNAMIC_ARRAY_RESERVE over DYNAMIC_ARRAY_ALLOCATE. It's not obvious to me why DYNAMIC_ARRAY_FIT should skip an empty array. Put these two on separate lines for readability, please. const size_t _capacity_ = DYNAMIC_ARRAY_CAPACITY(dynamic_array), _size_ = DYNAMIC_ARRAY_SIZE(dynamic_array); \ Similarly in DYNAMIC_ARRAY_INSERT. #define DYNAMIC_ARRAY_REMOVE_BACK(dynamic_array) \ ... if (DYNAMIC_ARRAY_SIZE(dynamic_array) == (size_t)(DYNAMIC_ARRAY_CAPACITY(dynamic_array) / DYNAMIC_ARRAY_GROWTH_FACTOR)) \ The / division seems slightly more expensive than folks might want. Maybe cache the result in a third bookkeeping slot? Maybe offer a variant REMOVE macro that won't auto FIT, for an app developer who knows about the app's memory pattern? It's not obvious to me why wanting to DYNAMIC_ARRAY_COPY an empty source array would be Bad. I would expect an empty destination array as a result. Aha! The COPY macro is starting to spell out why the ALLOCATE macro was making size comparisons. This needs to be much better documented. Consider defining "private" macro(s) for your use that you don't expect an app developer to use.
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c, collections, library, vectors, macros Suppose I have a pair of arrays: a of float, and b of double. And then I try a crazy operation like trying to COPY or CONCATENATE them. I was in error when I tried that, right? Would the current implementation notice the difference in sizeof ? Do we expect it to report failure? if people use this library they will shoot themselves in the foot one way or another, is my approach acceptable? Sure, that's C for you, life in the big city. There's already pretty explicit debug support, which affects both assert and whether stderr receives an "I'm melting!" message upon fatal exit. Consider adding sentinel support, before and after the app-level array. So allocate some additonal padding at the end, and write 0xdeadbeef or whatever at both start and end. If the application ever overwrites the sentinel you can check and report it, in the debug version. In a similar vein, consider rolling some constant MAGIC_NUMBER and writing that as the initial portion of your bookkeeping bytes. And verify that it never changes. The ISC BIND9 consistently performs such checks, and it has been a big help for fault isolation. Looking forward to those unit tests! Please distinguish between public tests that do what you feel an app developer should do, and private tests which might use private macros. It was clear to me that an app developer should not be accessing [-2] for size directly, but it wasn't clear if all macros would be fair game for app-level use. Overall, here are the big items to focus on: Get around to that [-1], [-2] TODO item. Distinguish public from private macros, if you want any private ones. Better document the public macros, or for unchanged semantics you might cite upstream documentation. Document or improve app-level interaction with cache lines. Then ship it!
{ "domain": "codereview.stackexchange", "id": 44420, "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, collections, library, vectors, macros", "url": null }
c++, game, console, makefile Title: (Rev. 2) Command-line Tower of Hanoi game Question: This is a follow-up from Command-line Tower of Hanoi game -- many thanks to those whose reviwed it. By request, the project is also available on GitHub. Forks and bug reports are welcomed. Compiled with g++ 9.4.0. makefile included. Issues addressed The disks are further differentiated between even and odd by styling, even disks are solid. All include guards are now #ifndef/#define. int and size_t data is now unsigned whereever it makes sense. Deleted all using namespace std. Left only main-related code in main(). Replaced entering number of disks at the command-line with asking the player at run-time. Removed some useless assertions. Increased modularity of functions/modules. Game variables wrapped into a struct for easy distribution into functions. Improved documentation throughout. Issues not addressed system() for clearing the screen As much as I would like to find a safe and portable alternative for system(), I have done some researching, and it seems there is no clean cut solution for this. Workarounds range from using external libraries to abstract low-level differences (want to avoid dependencies like this), to using ANSI escape codes (which I have tried and does not seem to work on Windows). Until I find a better way to do this, the best I can do is passing system() the correct command for the appropriate operating system. main.cpp /* Author: Jared Thomas Date: Tuesday, August 4, 2020 */ #include "game.h" #include "screen.h" int main() { clearScreen(); game(askNumDisks()); return 0; } game.h /* Author: Jared Thomas Date: Thursday, February 2, 2023 This module contains the core game loop */ #ifndef GAME_H #define GAME_H /* Asks the player for the number of disks they want to play with. Blocks program flow until the player enters valid input, where valid input is a number between 1 and 8 inclusive.
{ "domain": "codereview.stackexchange", "id": 44421, "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 Returns the number of disks the player entered. */ unsigned askNumDisks(); /* Starts the game with an initial number of disks */ void game(unsigned initialDisks); #endif game.cpp /* Author: Jared Thomas Date: Thursday, February 2, 2023 This module contains the core game loop */ #include <vector> #include <string> #include <cmath> #include <iostream> #include <cassert> #include "Tower.h" #include "TowerDrawer.h" #include "screen.h" #include "game.h" #include "game_parser.h" #include "parse.h" #include "help.h" struct GameState { GameState(unsigned initialDisks); ~GameState(); std::vector<std::string> tokens; bool requestQuit; bool gameOver; std::vector<Tower> towers; TowerDrawer towerDrawer; unsigned numDisks; // Total number of game disks unsigned moves; // Number of valid moves that the player has made std::string status; // Message that prints every frame std::string question; }; GameState::GameState(unsigned initialDisks): tokens(), requestQuit(false), gameOver(false), towers(), towerDrawer(initialDisks + 3), numDisks(initialDisks), moves(0), status(), question() { } GameState::~GameState() { } static unsigned inputState(GameState& gameState); static void moveState(GameState& gameState); const unsigned GOAL_TOWER_VECTOR_INDEX = 2; /* Returns the least possible number of moves required to win a game (perfect game). This is (2^d - 1), where d is the number of disks. */ unsigned leastPossible(unsigned numDisks) { return (1U << numDisks) - 1; } /* Calculates and returns the game score as the number of moves the player made out of the minimum moves required to win */ unsigned getScore(unsigned numDisks, unsigned moves) { return (unsigned)(round(100.0 * leastPossible(numDisks) / moves)); }
{ "domain": "codereview.stackexchange", "id": 44421, "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 /* Prints the player's game statistics after the game has been won. The statistics are the number of moves made, minimum moves required, and the final score */ void printResults(unsigned numDisks, unsigned moves) { std::cout << "You finished in " << moves << " moves\n"; std::cout << "Best possible is "\ << leastPossible(numDisks) << " moves\n"; std::cout << "Your score: " << getScore(numDisks, moves) << "%"; } /* Clears the screen and draws the towers vector using a tower drawer */ void drawTowers(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer) { clearScreen(); towerDrawer.draw(towers); } /* Prints the status message after drawing the 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; } /* Returns true if the winning condition has been reached, returns false otherwise */ bool checkForGameWon(const Tower& goalTower, unsigned totalDisks) { return goalTower.num_disks() == totalDisks; } /* Puts the towers back in their initial state */ void resetTowers(std::vector<Tower>& towers, unsigned totalDisks) { towers.clear(); towers.push_back(Tower(totalDisks)); towers.push_back(Tower()); towers.push_back(Tower()); } /* Puts the entire game back in its initial state; this includes resetting the towers and all state variables */ void resetGame(GameState& gameState) { resetTowers(gameState.towers, gameState.numDisks); gameState.moves = 0; gameState.status = "Type \"help\" at any time for instructions. Good luck!"; gameState.question = "What's your first move? "; } /* Asks the player if they want to play again. Blocks program flow until the player enters valid input.
{ "domain": "codereview.stackexchange", "id": 44421, "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 Returns true if the player requests to play again, returns false if they don't. */ bool askPlayAgain() { std::string input; do { std::cout << "Do you want to play again? (y/n): "; input = getRawInput(); } while(!(input == "y" || input == "n")); return input == "y"; } /* Asks the player for the number of disks they want to play with. Blocks program flow until the player enters valid input, where valid input is a number between 1 and 8 inclusive. Returns the number of disks the player entered. */ unsigned askNumDisks() { std::string input; long numDisks; do { input.clear(); numDisks = 0; do { std::cout << "How many disks do you want to play with? (1=Easiest, 8=Hardest): "; input = getRawInput(); } while(parseLong(input.c_str(), &numDisks) != SUCCESS); } while((numDisks < 1) || (numDisks > 8)); return (unsigned)numDisks; } void game(unsigned initialDisks) { GameState gameState(initialDisks); resetTowers(gameState.towers, gameState.numDisks); std::string rawInput; gameState.status = "Type \"help\" at any time for instructions. Good luck!"; gameState.question = "What's your first move? "; while(!(gameState.requestQuit || gameState.gameOver)) { drawTowers(gameState.towers, gameState.towerDrawer); printStatus(gameState.status); askQuestion(gameState.question); std::string rawInput = getRawInput(); gameState.tokens = tokenize(rawInput); if(inputState(gameState)) continue; moveState(gameState); } } /* Performs input processing and command handling of tokens. Returns 0 if the input is a tower move and should be passed on to the move parser.
{ "domain": "codereview.stackexchange", "id": 44421, "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 Returns 0 if the input is a tower move and should be passed on to the move parser. Returns 1 if the flow should return to the beginning of the game loop. */ static unsigned inputState(GameState& gameState) { const unsigned NUM_TUTORIAL_DISKS = 3; const unsigned TUTORIAL_ROD_HEIGHT = NUM_TUTORIAL_DISKS + 2; std::vector<Tower> tutorialTowers; // Appears on the help text TowerDrawer tutorialTowerDrawer(TUTORIAL_ROD_HEIGHT); resetTowers(tutorialTowers, NUM_TUTORIAL_DISKS); switch(parseInput(gameState.tokens)) { case MOVE: return 0; case EMPTY_INPUT: return 1; case COMMAND: { switch(parseCommand(gameState.tokens.front())) { case REQUEST_QUIT: { gameState.requestQuit = true; return 1; } case REQUEST_RESET: { gameState.numDisks = askNumDisks(); gameState.towerDrawer.set_pole_height(gameState.numDisks + 3); resetGame(gameState); return 1; } case REQUEST_HELP: { showHelpText(tutorialTowers, tutorialTowerDrawer); return 1; } case INVALID_COMMAND: { gameState.status = "No such command..."; return 1; } } break; // This only pacifies the compiler; it cannot really be reached. } case INVALID_INPUT: { gameState.status = "Huh?"; return 1; } } assert(0); // Impossible to get here return 0; }
{ "domain": "codereview.stackexchange", "id": 44421, "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 /* Takes in tokens from the input stage and attempts to process them as tower moves. */ static void moveState(GameState& gameState) { TOWER_MOVE towerMove = parseMove(gameState.tokens, gameState.towers); switch(towerMove.moveType) { case VALID_MOVE: { doMove(towerMove, gameState.towers); gameState.moves++; if(checkForGameWon(gameState.towers.at(GOAL_TOWER_VECTOR_INDEX), gameState.numDisks)) { drawTowers(gameState.towers, gameState.towerDrawer); printStatus("You win!"); printResults(gameState.numDisks, gameState.moves); std::cout << "\n\n"; gameState.gameOver = !askPlayAgain(); if(!gameState.gameOver) { gameState.numDisks = askNumDisks(); gameState.towerDrawer.set_pole_height(gameState.numDisks + 3); resetGame(gameState); } return; } gameState.status = ""; gameState.question = "What's your next move? "; return; } case DISKLESS_TOWER: { gameState.status = "Nothing on that tower..."; return; } case LARGER_ON_SMALLER: { gameState.status = "Can't place a larger disk on a smaller disk..."; return; } case INVALID_MOVE_SYNTAX: { gameState.status = "Can't do that..."; } } } screen.h /* Author: Jared Thomas Date: Sunday, January 29, 2023 This module provides the platform-dependent clear screen command. */ #ifndef SCREEN_H #define SCREEN_H /* Clears the terminal. The actual system call used is platform-dependent. */ void clearScreen(); #endif screen.cpp /* Author: Jared Thomas Date: Sunday, January 29, 2023 This module provides the platform-dependent clear screen command. */ #include "screen.h"
{ "domain": "codereview.stackexchange", "id": 44421, "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 the platform-dependent clear screen command. */ #include "screen.h" #ifdef PLATFORM_LINUX #define CLEAR_SCREEN_COMMAND "clear" #endif #ifdef PLATFORM_WINDOWS #define CLEAR_SCREEN_COMMAND "cls" #endif #include <cstdlib> void clearScreen() { system(CLEAR_SCREEN_COMMAND); } parse.h /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides general-purpose 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. Blocks program flow until a newline character is encountered. */ std::string getRawInput(); /* Splits the string on the space (' ') character, ignoring any leading and trailing 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 }; /* Attempts to interpret the input string as a base 10 integer. If successful, the interpreted value is stored at the location pointed to by result. The input should not have leading or trailing spaces. If the conversion was successful, SUCCESS is returned. If the conversion was successful and the interpreted value would be smaller than the minimum value for a (long), UNDERFLOW is returned. If the conversion was successful and the interpreted value would be larger than the maximum value for a (long), OVERFLOW is returned. If the string could not interpreted as a base-10 integer, INVALID_STRING is returned. */ PARSE_LONG_RESULT parseLong(const char* s, long* result); #endif parse.cpp /* Author: Jared Thomas Date: Sunday, January 22, 2023 This module provides general-purpose string processing and parsing utilities. */
{ "domain": "codereview.stackexchange", "id": 44421, "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 general-purpose string processing and parsing utilities. */ #include <iostream> #include <vector> #include <string> #include <cstring> #include <climits> #include "parse.h" std::string getRawInput() { std::string input; std::getline(std::cin, input); return input; } 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; } 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; } game_parser.h /* Author: Jared Thomas Date: Wednesday, February 1, 2023 This module provides game-specific parsing functions. */ #ifndef GAME_PARSER_H #define GAME_PARSER_H #include <vector> #include <string> #include "Tower.h" enum INPUT_TYPE { INVALID_INPUT, MOVE, COMMAND, EMPTY_INPUT }; /* Low-level parser that returns the type of input the tokens represent.
{ "domain": "codereview.stackexchange", "id": 44421, "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 /* Low-level parser that returns the type of input the tokens represent. If the input is a towers move, MOVE is returned. If the input is a game command, COMMAND is returned. If the input is an empty string, EMPTY_INPUT is returned. If the input was none of the above, INVALID_INPUT is returned. */ INPUT_TYPE parseInput(const std::vector<std::string>& tokens); enum COMMAND_TYPE { REQUEST_QUIT, REQUEST_RESET, INVALID_COMMAND, REQUEST_HELP }; /* Mid-level parser that accepts a command string, and returns the requested operation */ COMMAND_TYPE parseCommand(const std::string& command); 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; }; /* High-level parser that accepts a string representing a tower move and a vector of towers the moves should be done on. Returns a tower move record which contains information about the resulting move. The record can be later executed if the move is valid. If the semantics of the input are bad (negative or out-of-range tower number, etc.), then the returned record will have INVALID_MOVE_SYNTAX as a move type, and the from-to fields will be 0. If the input string would attempt to take a disk from a rod with no disks, then the returned record will have DISKLESS_TOWER as a move type, and the from-to fields will be populated with the appropriate tower indices (zero-indexed). If the input string would attempt to place a larger disk on top of a smaller disk, then the returned record will have LARGER_ON_SMALLER as a move type, and the from-to fields will be populated with the appropriate tower indices (zero-indexed). If none of the above cases occurred, then the returned record will have VALID_MOVE as a move type, and the from-to fields will be populated with the appropriate tower indices (zero-indexed).
{ "domain": "codereview.stackexchange", "id": 44421, "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 parseMove(const std::vector<std::string>& tokens, const std::vector<Tower>& towers); /* Executes a tower move record on the input vector of towers. 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 game_parser.cpp /* Author: Jared Thomas Date: Wednesday, February 1, 2023 This module provides game-specific parsing functions. */ #include <vector> #include <string> #include "game_parser.h" #include "parse.h" #include "Tower.h" 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; } } COMMAND_TYPE parseCommand(const std::string& command) { if(command == "quit") return REQUEST_QUIT; if(command == "reset") return REQUEST_RESET; if(command == "help") return REQUEST_HELP; return INVALID_COMMAND; } 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": 44421, "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 screen and starts the help texts which come in two screens. The passed in towers will be shown as a demonstration in the explanation. */ void showHelpText(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer); /* Shows part 1/2 of the help text which is the game objective, rules, and inputs explanation */ void showExpanation(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer); /* Shows part 2/2 of the help text which is the list of game commands */ 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" #include "screen.h" #include "parse.h"
{ "domain": "codereview.stackexchange", "id": 44421, "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" #include "screen.h" #include "parse.h" void showHelpText(const std::vector<Tower>& towers, const TowerDrawer& towerDrawer) { clearScreen(); showExpanation(towers, towerDrawer); std::cout << "\n\n"; std::cout << "Press \"Enter\" for the list of commands..."; getRawInput(); clearScreen(); showCommandsHelp(); std::cout << "\n\n"; std::cout << "Press \"Enter\" to go back to the game..."; getRawInput(); } void showExpanation(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!"; } 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 #ifndef DISK_H #define DISK_H struct Disk { /* Constructs a disk with a size
{ "domain": "codereview.stackexchange", "id": 44421, "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.h #ifndef DISK_H #define DISK_H struct Disk { /* Constructs a disk with a size size > 0 */ Disk(unsigned size); /* Draws the disk to standard output */ void draw() const; /* Returns the size of the disk */ unsigned size() const; private: unsigned size_; }; void draw_solid_style(Disk); void draw_slash_bracket_style(Disk); #endif Disk.cpp #include "Disk.h" #include <cassert> #include <iostream> Disk::Disk(unsigned size): size_(size) { assert(size_ > 0); } void Disk::draw() const { for(unsigned i = 0; i < (2 * size() + 1); i++) { std::cout << '+'; } } unsigned Disk::size() const { return size_; } void draw_solid_style(const Disk d) { std::cout << '['; // Left edge of the disk unsigned j = 2 * d.size() + 1; if(d.size() >= 10 && d.size() <= 99) j--; for(unsigned i = 0; i < j; i++) { const unsigned DISK_CENTER = (2 * d.size() + 1) / 2; if(i == DISK_CENTER) std::cout << d.size(); else std::cout << ' '; } std::cout << ']'; // Right edge of the disk } void draw_slash_bracket_style(const Disk d) { std::cout << '['; // Left edge of the disk unsigned j = 2 * d.size() + 1; if(d.size() >= 10 && d.size() <= 99) j--; for(unsigned i = 0; i < j; i++) { const unsigned DISK_CENTER = (2 * d.size() + 1) / 2; if(i == DISK_CENTER) std::cout << d.size(); else if(i == (DISK_CENTER - 1)) std::cout << ' '; else if(i == (DISK_CENTER + 1)) std::cout << ' '; else std::cout << '/'; } std::cout << ']'; // Right edge of the disk } Tower.h #ifndef TOWER_H #define TOWER_H #include "Disk.h" #include <vector> #include <cstdlib> class Tower { public: /* Constructs a tower with no disks (diskless) */ Tower(); /* Constructs a tower with an initial number of disks.
{ "domain": "codereview.stackexchange", "id": 44421, "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 /* Constructs a tower with an initial number of disks. The disks will be stacked in increasing order from top to bottom. */ Tower(unsigned num_disks); /* Returns the number of disks on the tower */ unsigned num_disks() const; /* Returns the size of the topmost disk on the tower */ unsigned size_of_top() const; /* Returns the size of the largest disk on the tower */ unsigned size_of_largest_disk() const; /* Returns the size of a disk at a specific location on the tower. 0 is the bottom of the tower. */ unsigned size_of_disk_at(unsigned index) const; /* Returns true if the tower has no disks on it, returns false otherwise */ bool is_diskless() const; /* */ bool are_strictly_decreasing() const; /* Returns a reference to a specific disk on the tower */ const Disk& disk_at(unsigned index) const; /* Moves the topmost disk from this tower to another tower */ void top_to_top(Tower& dest_tower); /* */ bool compare(const Tower&) const; private: std::vector<Disk> disks_; }; /* Returns the number of disks on the tower with the most disks in the vector */ unsigned highestTower(const std::vector<Tower>& towers); #endif Tower.cpp #include "Tower.h" #include "Disk.h" #include <cassert> #include <climits> #include <iostream> Tower::Tower() { } Tower::Tower(unsigned num_disks) { while(num_disks > 0) { disks_.push_back(Disk(num_disks)); num_disks--; } } unsigned Tower::num_disks() const { // The cast is okay here since the number of disks on the tower is // guaranteed to be [0, UINT_MAX] return (unsigned)(disks_.size()); } unsigned Tower::size_of_top() const { assert(!is_diskless()); return disks_.back().size(); }
{ "domain": "codereview.stackexchange", "id": 44421, "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 unsigned Tower::size_of_top() const { assert(!is_diskless()); return disks_.back().size(); } unsigned Tower::size_of_largest_disk() const { assert(!is_diskless()); unsigned largest = size_of_disk_at(0); for(unsigned i = 0; i < num_disks(); i++) { if(size_of_disk_at(i) > largest) largest = size_of_disk_at(i); } return largest; } unsigned Tower::size_of_disk_at(unsigned index) const { assert(!is_diskless()); return disks_.at(index).size(); } bool Tower::is_diskless() const { return num_disks() == 0; } bool Tower::are_strictly_decreasing() const { assert(!is_diskless()); unsigned expected = size_of_disk_at(0); for(unsigned i = 0; i < num_disks(); i++) { if(size_of_disk_at(i) != expected) return false; expected--; } return true; } const Disk& Tower::disk_at(unsigned index) const { assert(!is_diskless()); return disks_.at(index); } void Tower::top_to_top(Tower& dest_tower) { assert(dest_tower.num_disks() < UINT_MAX); 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(unsigned i = 0; i < num_disks(); i++) { if(T.disk_at(i).size() != disk_at(i).size()) return false; } return true; } unsigned highestTower(const std::vector<Tower>& towers) { assert(!towers.empty()); unsigned 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 #ifndef TOWER_DRAWER #define TOWER_DRAWER #include <cstddef> #include <vector> class Tower;
{ "domain": "codereview.stackexchange", "id": 44421, "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 <cstddef> #include <vector> class Tower; class TowerDrawer { public: TowerDrawer(unsigned pole_height); unsigned pole_height() const; size_t draw(const Tower&) const; size_t draw(const std::vector<Tower>&) const; void set_pole_height(unsigned pole_height); private: void draw_spaces(unsigned num_spaces = 1) const; unsigned num_slashes(unsigned disk_size) const; unsigned num_chars(unsigned disk_size) const; unsigned center_of(unsigned disk_size) const; void draw_disk_row(unsigned disk_index, const Tower&) const; void draw_rod_row(const Tower&) const; void draw_rod_top(const Tower&) const; void draw_tower_row(unsigned row, const Tower&) const; unsigned pole_height_; }; #endif TowerDrawer.cpp #include "TowerDrawer.h" #include "Tower.h" #include <cassert> #include <iostream> #include <climits> TowerDrawer::TowerDrawer(unsigned pole_height): pole_height_(pole_height) {} unsigned 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(unsigned i = 0; i <= pole_height_; i++) { for(size_t t = 0; t < towers.size(); t++) { draw_tower_row(pole_height_ - i, towers.at(t)); draw_spaces(12); } std::cout << "\n"; } return towers.size(); } void TowerDrawer::set_pole_height(unsigned pole_height) { pole_height_ = pole_height; } void TowerDrawer::draw_spaces(unsigned n) const { for(; n > 0; n--) std::cout << " "; } unsigned TowerDrawer::num_slashes(const unsigned disk_size) const { return disk_size * 2 + 1; } unsigned TowerDrawer::num_chars(const unsigned disk_size) const { return 2 + num_slashes(disk_size); }
{ "domain": "codereview.stackexchange", "id": 44421, "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 unsigned TowerDrawer::center_of(const unsigned disk_size) const { return (num_chars(disk_size) - 1) / 2; } void TowerDrawer::draw_disk_row(const unsigned 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_solid_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(); std::cout << "|_|"; draw_spaces(); return; } draw_spaces(center_of(t.size_of_largest_disk()) - 1); std::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); std::cout << "_"; draw_spaces(2); return; } draw_spaces(center_of(t.size_of_largest_disk())); std::cout << "_"; draw_spaces(center_of(t.size_of_largest_disk())); } // todo: draws funnily when tower.num_disks() == tower.height() void TowerDrawer::draw_tower_row(unsigned 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: linux-debug win-64-debug linux-debug: towers-de towers-de: main.cpp game.cpp screen.cpp parse.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp game_parser.cpp g++ -std=c++17 -Wall -Wextra -Wpedantic -Wconversion -D PLATFORM_LINUX main.cpp game.cpp screen.cpp parse.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp game_parser.cpp -o towers-de -g win-64-debug: towers-de-win-x86-64.exe
{ "domain": "codereview.stackexchange", "id": 44421, "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 win-64-debug: towers-de-win-x86-64.exe towers-de-win-x86-64.exe: main.cpp game.cpp screen.cpp parse.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp game_parser.cpp x86_64-w64-mingw32-g++ -std=c++17 -Wall -Wextra -Wpedantic -Wconversion -D PLATFORM_WINDOWS main.cpp game.cpp screen.cpp parse.cpp help.cpp Disk.cpp Tower.cpp TowerDrawer.cpp game_parser.cpp -o towers-de-win-x86-64 -g clean: rm -f towers-de rm -f towers-de-win-x86-64.exe Answer: It's great to see all the improvements you've incorporated into your game! Clearing the screen As much as I would like to find a safe and portable alternative for system(), I have done some researching, and it seems there is no clean cut solution for this. … Until I find a better way to do this, the best I can do is passing system() the correct command for the appropriate operating system. You did at least address the issue that your previous solution did not work on Windows. But all the drawbacks of system() remain, in particular it is very inefficient and it might not actually do what you want if the user has a different shell environment where clear or cls do something unexpected. Also, even if there is no "clean cut solution", you can do better than this. Another issue you introduced is that you used a macro to define CLEAR_SCREEN_COMMAND, however apart from the include guards, you very rarely need to create macros in C++. You can instead define a regular constant: #ifdef PLATFORM_WINDOWS static const char CLEAR_SCREEN_COMMAND[] = "cls"; #else static const char CLEAR_SCREEN_COMMAND[] = "clear"; #endif Have a look at this StackOverflow question about clearing the screen in C++. There are various solutions prevented for both UNIX and Windows, many of them not needing system(). I would structure your code like so: void clearScreen() { #ifdef PLATFORM_WINDOWS // Windows-specific code that doesn't use system() here … #else std::cout << "\033[2J"; #endif } Use the Doxygen format to document your code
{ "domain": "codereview.stackexchange", "id": 44421, "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 Use the Doxygen format to document your code Improved documentation throughout.
{ "domain": "codereview.stackexchange", "id": 44421, "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 That's great, the documentation you wrote looks very good. Even better would be to make some small modifications so it conforms to the Doxygen format. This then allows the Doxygen tools to generate searchable HTML and PDF documents for your source code, among other things. It also can check that you documented all function. Doxygen also has standards for how to document function parameters and return values. Consider adding that as well. You can also document member variables. Avoid C functions if there are better C++ functions This is another issue you did not address since the previous version. Some of your code calls C functions when there are much better ways to do the same thing in C++. For example, parseLong() calls strtol() and deals with all the issues that that function has, but you could have used std::stol() instead, or possibly std::from_chars(). There are many ways to tokenize a string in C++ without having to resort to strtok(), and without needing any manual memory allocation. Return an enum from inputState() The function inputState() returns an integer, and you have to look up the documentation for the function to check what value means what. While it is great that there is documentation, it would be even better if you didn't have to check that. You are already using enums in many other places, including the return values for parseInput() and parseCommand(), you can do something similar here. Complexity @pacmaninbw mentioned complexity in the review of the previous version of your game. I think you already have done a good job keeping complexity down, at the point of even having very trivial functions like askQuestion(). However, there is still an area where complexity is higher than desired, and that is GameState. It has member variables dealing with the towers themselves, as well as variables dealing with the user interface. Just like you can split up functions, you can split up classes as well. Consider: struct TowerState { … };
{ "domain": "codereview.stackexchange", "id": 44421, "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 struct UIState { … }; struct GameState { TowerState towerState; UIState uiState; }; Functions that only need to access the state of the towers can be passed gameState.towerState, functions that need only to deal with the UI can be passed gameState.uiState, and only functions that need both can be given access to gameState as a whole. This simplifies the structs and makes it easier to keep things separate. Don't add empty destructors You don't have to write an empty destructor, C++ will generate a default destructor if you omit it. Consider using default member initialization Instead of explicitly initializing everything in the initializer list of the constructor, consider providing default values when declaring the member variables, for example: struct GameState { GameState(unsigned initialDisks); std::vector<std::string> tokens; bool requestQuit = false; bool gameOver = false; std::vector<Tower> towers; TowerDrawer towerDrawer; unsigned numDisks; unsigned moves = 0; std::string status; std::string question; }; GameState::GameState(unsigned initialDisks): towerDrawer(initialDisks + 3), numDisks(initialDisks) { } The advantage is that it's easier to add a new member variable and provide a default value right there, with less chance of forgetting to add an initializer to the constructor as well. And if you have multiple constructors, it can save a lot of code duplication.
{ "domain": "codereview.stackexchange", "id": 44421, "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++, reinventing-the-wheel, c++17, template-meta-programming Title: C++17 pointer_traits implementation Question: pointer_traits is a lightweight trait that provides a uniform interface to builtin pointers and user-defined fancy pointers. That said, things like element_type require template metaprogramming techniques to determine. This makes pointer_traits a good exercise. Here's my re-implementation under the name my_std::pointer_traits, put in a separate header pointer_traits.hpp because <memory> is way too comprehensive: // C++17 pointer_traits implementation #ifndef INC_POINTER_TRAITS_HPP_60HzB0lbek #define INC_POINTER_TRAITS_HPP_60HzB0lbek #include <cstddef> // for std::ptrdiff_t #include <memory> // for std::addressof #include <type_traits> // for std::add_lvalue_reference namespace my_std { template <class Ptr> struct pointer_traits; namespace pt_detail { template <class Tmpl> struct get_first_param { }; template <template <class, class...> class Tmpl, class T, class... Args> struct get_first_param<Tmpl<T, Args...>> { using type = T; }; template <class Tmpl> using get_first_param_t = typename get_first_param<Tmpl>::type; template <class Tmpl, class U> struct rebind_first_param { }; template <template <class, class...> class Tmpl, class T, class... Args, class U> struct rebind_first_param<Tmpl<T, Args...>, U> { using type = Tmpl<U, Args...>; }; template <class Tmpl, class U> using rebind_first_param_t = typename rebind_first_param<Tmpl, U>::type; template <class Ptr> auto element(int) -> typename Ptr::element_type; template <class Ptr> auto element(long) -> get_first_param_t<Ptr>; template <class Ptr> auto diff(int) -> typename Ptr::difference_type; template <class Ptr> auto diff(long) -> std::ptrdiff_t; template <class Ptr, class U> auto rebind(int) -> typename Ptr::template rebind<U>; template <class Ptr, class U> auto rebind(long) -> rebind_first_param_t<Ptr, U>; }
{ "domain": "codereview.stackexchange", "id": 44422, "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++, reinventing-the-wheel, c++17, template-meta-programming", "url": null }
c++, reinventing-the-wheel, c++17, template-meta-programming } template <class Ptr> struct pointer_traits { using pointer = Ptr; using element_type = decltype(pt_detail::element<Ptr>(0)); using difference_type = decltype(pt_detail::diff<Ptr>(0)); template <class U> using rebind = decltype(pt_detail::rebind<Ptr, U>(0)); static pointer pointer_to(std::add_lvalue_reference<element_type> r) { return Ptr::pointer_to(r); } }; template <class T> struct pointer_traits<T*> { using pointer = T*; using element_type = T; using difference_type = std::ptrdiff_t; template <class U> using rebind = U*; static pointer pointer_to(std::add_lvalue_reference<element_type> r) { return std::addressof(r); } }; } #endif I used N4659 as a reference. Answer: I tried a little bit your code and seems to work. If you want my opinion (review?) I find the techniques quite arcane. Perhaps it is my C++17 perspective, or maybe that the code you posted needs to be compatible with C++98 or 11 (?). I will base my review on the C++17 perspective since that is one of the labels of your post. First, I would factor out the manipulation of the first argument in a single class: template<class> struct first_param {}; template<template<class, class...> class Tmpl, class T, class... Args> struct first_param<Tmpl<T, Args...>> { using type = T; template<class U> using rebind = Tmpl<U, Args...>; }; Second, I would replace the trick of int, long, matching plus decltype with a modern tool designed to detect valid operations on types, which is std::experimental::detect_or_t. The class basically will tell if an operation is valid on a type and if not a fallback type is used. These are the operations that hypothetically need to be applied to the type, template<class T> using element_type_t = typename T::element_type; template<class T> using difference_type_t = typename T::difference_type;
{ "domain": "codereview.stackexchange", "id": 44422, "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++, reinventing-the-wheel, c++17, template-meta-programming", "url": null }
c++, reinventing-the-wheel, c++17, template-meta-programming The tricky one is the one that rebinds: template<class U> struct bind_second { template<class T> using rebind_t = typename T::rebind<U>; }; Note that at the end it is simply adding a level of indirection. As powerful as detect_or_t is, I profoundly dislike its syntax because it is impossible to figure out the meaning from reading: the first argument is the fallback, the second argument is the operator and the third argument is the target (probed) type. For this reason, I rearrange the dectect_or_t<fallback, operation, target> into a metafunction that is more readable valid_on<operation, target>::otherwise<fallback>: template<template<class...> class Op, class Target> struct valid_on { template<class Fallback> using otherwise = std::experimental::detected_or_t<Fallback, Op, Target>; }; This way each fallback case is read as in the documentation, that is in plain English: template <class Ptr> struct pointer_traits { using pointer = Ptr; using element_type = typename valid_on<element_type_t , pointer>::otherwise<typename first_param<Ptr>::type>; using difference_type = typename valid_on<difference_type_t, pointer>::otherwise<std::ptrdiff_t >; template<class U> using rebind = typename valid_on<bind_second<U>::template rebind_t, pointer>::otherwise<typename first_param<Ptr>::rebind<U>>; static constexpr pointer pointer_to(std::add_lvalue_reference<element_type> r) { return Ptr::pointer_to(r); } }; Finally, I encapsulate the needed functionality in a base class and add the T* specialization. The final full code looks like this: template<class> struct first_param {}; template<template<class, class...> class Tmpl, class T, class... Args> struct first_param<Tmpl<T, Args...>> { using type = T; template<class U> using rebind = Tmpl<U, Args...>; };
{ "domain": "codereview.stackexchange", "id": 44422, "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++, reinventing-the-wheel, c++17, template-meta-programming", "url": null }
c++, reinventing-the-wheel, c++17, template-meta-programming class pointer_trait_detail { protected: template<class T> using element_type_t = typename T::element_type; template<class T> using difference_type_t = typename T::difference_type; template<class U> struct bind_second { template<class T> using rebind_t = typename T::rebind<U>; }; template<template<class...> class Op, class Target> struct valid_on { template<class Fallback> using otherwise = std::experimental::detected_or_t<Fallback, Op, Target>; }; }; template <class Ptr> struct pointer_traits : private pointer_trait_detail { using pointer = Ptr; using element_type = typename valid_on<element_type_t , pointer>::otherwise<typename first_param<Ptr>::type>; using difference_type = typename valid_on<difference_type_t, pointer>::otherwise<std::ptrdiff_t >; template<class U> using rebind = typename valid_on<bind_second<U>::template rebind_t, pointer>::otherwise<typename first_param<Ptr>::rebind<U>>; static constexpr pointer pointer_to(std::add_lvalue_reference<element_type> r) { return Ptr::pointer_to(r); } }; template <class T> struct pointer_traits<T*> { using pointer = T*; using element_type = T; using difference_type = std::ptrdiff_t; template <class U> using rebind = U*; static pointer pointer_to(std::add_lvalue_reference<element_type> r) { return std::addressof(r); } }; Here is the full working code (in a namespace stx), alongside your code (in namespace my_std) and some test cases: https://godbolt.org/z/zGMhEssoc It works with GCC and clang (C++17 mode). Unfortunately clang requires inserting a few ::template keywords spinkled that make the code a bit less readable (as seen in the Godbolt link). If you find an error in my code I appreciate corrections.
{ "domain": "codereview.stackexchange", "id": 44422, "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++, reinventing-the-wheel, c++17, template-meta-programming", "url": null }
python, logging, meta-programming, color Title: Python colorized debug printer Question: In Python you can use print(locals()) to print a dictionary of all the local variables, but this has 3 shortcomings: Double underscore variables will be included that is not what we usually want. The output is in black and white, that can make it harder to read. Only the variable names and their values are printed, there is no way to automatically print the result of applying a function to each variable if possible and printing the result. It is possible to use a debugger, but sometimes having all the output in one place and being able to go back and forth can be more useful then stepping through a debugger. As such I have written the print_locals functions to solve these problems: def print_locals(locals_, funcs=[], label="", color=True): from collections import OrderedDict from pprint import pprint # https://stackoverflow.com/questions/60031216/how-to-change-the-key-color-when-printing-a-python-dictionary def dprint(d,key_format = "\033[1;32m",value_format = "\033[1;34m"): for key in d.keys() : print (f" {key_format}{key}: {value_format}{repr(d[key])[:500]}") locs = {key:value for key, value in locals_.items() if not key.startswith('__')} out = OrderedDict() def identity(x): return x for key, value in sorted(locs.items()): for func in [identity] + funcs: try: out[key+("_"+func.__name__ if func.__name__ != "identity" else "")] = func(value) except (TypeError, ValueError, AttributeError): pass print(("\n\033[1;33m" if color else "\n")+label) dprint(out, key_format = "\033[1;32m" if color else "", value_format = "\033[1;34m" if color else "") And here is an example usage: import numpy as np from scipy import stats
{ "domain": "codereview.stackexchange", "id": 44423, "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, logging, meta-programming, color", "url": null }
python, logging, meta-programming, color And here is an example usage: import numpy as np from scipy import stats def example(): def first_item(x): return x[0] def describe_flattened(x): return stats.describe(x.flatten()) x = [1,2,3,4,5] print_locals(locals(), [first_item, len, stats.describe, np.shape, int], "start") x += [7,9] name = "Caridorc" xs = np.array([[4,5,6], [7,8,18], [9,10,11], [12,13,14], [15,16,17]]) ys = np.mean(xs, axis=0) xs_squared = xs**2 big = np.random.rand(1000,1000) print_locals(locals(), [first_item, len, stats.describe, describe_flattened, np.shape, int], "end") if __name__ == "__main__": example() With output (in reality it is colorized but here color cannot be shown): start describe_flattened: <function example.<locals>.describe_flattened at 0x7f19cb8dd5e0> describe_flattened_shape: () first_item: <function example.<locals>.first_item at 0x7f19cb8dd550> first_item_shape: () x: [1, 2, 3, 4, 5] x_first_item: 1 x_len: 5 x_describe: DescribeResult(nobs=5, minmax=(1, 5), mean=3.0, variance=2.5, skewness=0.0, kurtosis=-1.3) x_shape: (5,)
{ "domain": "codereview.stackexchange", "id": 44423, "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, logging, meta-programming, color", "url": null }
python, logging, meta-programming, color end big: array([[0.98288814, 0.97630647, 0.26132766, ..., 0.58954191, 0.25681903, 0.33411866], [0.50299533, 0.65961947, 0.73978812, ..., 0.29573779, 0.23369551, 0.97092339], [0.90263252, 0.7760721 , 0.19466284, ..., 0.51350822, 0.52413125, 0.65852317], ..., [0.7144501 , 0.99647271, 0.82473009, ..., 0.31224817, 0.13596358, 0.47216351], [0.92383261, 0.42948829, 0.89493352, ..., 0.21755526, 0.18629585, 0.7345645 ], [0.09757243 big_first_item: array([9.82888140e-01, 9.76306470e-01, 2.61327662e-01, 8.91590583e-02, 9.55163546e-01, 9.08456958e-01, 7.53214382e-01, 6.82397143e-01, 4.95854979e-01, 2.87399085e-01, 6.63777609e-01, 4.19908536e-01, 4.11669375e-01, 9.92319543e-01, 2.26913289e-01, 6.02279465e-01, 4.05968774e-01, 7.71524127e-01, 2.14888903e-02, 1.83519681e-01, 4.59032104e-01, 6.65706325e-01, 3.71472360e-01, 1.23070128e-01, 5.79076106e-01, 1.52091773e-01, 6.34641048e-01, 1.34286564e-01, big_len: 1000 big_describe: DescribeResult(nobs=1000, minmax=(array([3.11409704e-04, 6.81647421e-04, 1.31582825e-04, 1.56104348e-03, 2.84670274e-03, 6.06042558e-04, 1.66119570e-03, 3.11966810e-04, 9.29703789e-04, 1.06716128e-03, 4.87965396e-04, 1.20570178e-03, 1.05329790e-03, 4.74552749e-04, 3.46799356e-04, 2.40614186e-04, 1.46001935e-03, 2.71866983e-04, 6.58164425e-04, 1.24498327e-03, 2.03076845e-04, 4.57861245e-03, 3.47527704e-03, 1.80359818e-04, 2.54012443e-03, 6.37231150e-04, 3 big_describe_flattened: DescribeResult(nobs=1000000, minmax=(4.2246054110517406e-07, 0.9999996319801028), mean=0.5001587336155897, variance=0.08331188852436676, skewness=0.0004189518459810173, kurtosis=-1.200281952258119) big_shape: (1000, 1000) describe_flattened: <function example.<locals>.describe_flattened at 0x7f19cb8dd5e0> describe_flattened_shape: () first_item: <function example.<locals>.first_item at 0x7f19cb8dd550>
{ "domain": "codereview.stackexchange", "id": 44423, "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, logging, meta-programming, color", "url": null }
python, logging, meta-programming, color describe_flattened_shape: () first_item: <function example.<locals>.first_item at 0x7f19cb8dd550> first_item_shape: () name: 'Caridorc' name_first_item: 'C' name_len: 8 name_shape: () x: [1, 2, 3, 4, 5, 7, 9] x_first_item: 1 x_len: 7 x_describe: DescribeResult(nobs=7, minmax=(1, 9), mean=4.428571428571429, variance=7.952380952380953, skewness=0.4423276254324468, kurtosis=-0.9777152282261832) x_shape: (7,) xs: array([[ 4, 5, 6], [ 7, 8, 18], [ 9, 10, 11], [12, 13, 14], [15, 16, 17]]) xs_first_item: array([4, 5, 6]) xs_len: 5 xs_describe: DescribeResult(nobs=5, minmax=(array([4, 5, 6]), array([15, 16, 18])), mean=array([ 9.4, 10.4, 13.2]), variance=array([18.3, 18.3, 23.7]), skewness=array([ 0.07797781, 0.07797781, -0.52792179]), kurtosis=array([-1.21521992, -1.21521992, -1.08024889])) xs_describe_flattened: DescribeResult(nobs=15, minmax=(4, 18), mean=11.0, variance=20.0, skewness=0.0, kurtosis=-1.210714285714286) xs_shape: (5, 3) xs_squared: array([[ 16, 25, 36], [ 49, 64, 324], [ 81, 100, 121], [144, 169, 196], [225, 256, 289]]) xs_squared_first_item: array([16, 25, 36]) xs_squared_len: 5 xs_squared_describe: DescribeResult(nobs=5, minmax=(array([16, 25, 36]), array([225, 256, 324])), mean=array([103. , 122.8, 193.2]), variance=array([ 6883.5, 8354.7, 14054.7]), skewness=array([ 0.51788093, 0.47995029, -0.19190912]), kurtosis=array([-1.08482927, -1.10598554, -1.39461119])) xs_squared_describe_flattened: DescribeResult(nobs=15, minmax=(16, 324), mean=139.66666666666666, variance=9974.666666666668, skewness=0.4476084348250222, kurtosis=-1.0493737094260638) xs_squared_shape: (5, 3) ys: array([ 9.4, 10.4, 13.2]) ys_first_item: 9.4 ys_len: 3 ys_describe: DescribeResult(nobs=3, minmax=(9.4, 13.2), mean=11.0, variance=3.8799999999999977, skewness=0.5076720034433699, kurtosis=-1.4999999999999998)
{ "domain": "codereview.stackexchange", "id": 44423, "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, logging, meta-programming, color", "url": null }