object oriented – Which pattern from below options is more appropriate

Pattern 1 :

abstract class Account {
    int id;
    String password;
    void resetPassword() {}
}
        
abstract class Person extends Account {
    String name;            
}

Pattern 2 :

class Account {
    int id;
    String password;
    void resetPassword() {}
}
        
abstract class Person {
    String name;
    Account account;       
}

Out of the two patterns mentioned above, which pattern will help us in writing more modular clean code ?

8 – Pathauto pattern for a content type depending on a reference field?

This question is already asked here, but the answer selected does not work for Drupal8.

Description: There is a content-type, which has field, referencing taxonomy term. The term is in “Content class” dictionary. This term is used in views to filter the right content for the view. When a link in the view is clicked, it opens the node. This is OK.
So, it is needed pathauto to generate /Content class term/Content_title_name when this node is opened.

What did not work: (node:field_content_class:value)/(node:title). This is not accepted, produces error: Path pattern is using the following invalid tokens: (node:field_

The accepted (by Drupal) pattern: (node:field_content_class)/(node:title) generates alias, containing only the (node:title) part. The first component is empty.

This is made to not create separate content-types for nodes with the same fields.

hardware – Graphics glitch – checkered pattern in Chrome

I’ve had this MacBook Pro (16-inch, 2019) for a while now, but today it glitched out with huge green fields in all apps.

After a reboot I see this checkered black/green glitch pattern in Google Chrome on some sites, in some “sizes”. Basically if I resize the browser window the glitch goes away, but if I resize it too much it comes back.

Happens both on the internal and on external display.

I am hoping this is a software glitch, but I am afraid it’s my graphics card. Would be very grateful if someone knows the answer.

Here’s the stackoverflow logo with the glitch:

StackOverflow logo glitched

c# – Asp.Net overall design pattern integrating REST, dependency injection, and Hosted Services (See full project at Github)

I’m new to C#, and want to conform as much as possible to good design patterns. This code is the beginning of a Microservice, running as Asp.Net. It is based on a Microsoft tutorial doing similar work.

It has three functional components currently:

  1. Converts a CSV file to JSON, for return via REST
  2. A REST controller to test the conversion of the CSV to JSON return
  3. A background service which monitors a directory looking for changed files. The file attributes (Path, Date, Checksum) are stored in a MongoDB database via a Repository.

Opinions/Recommendations regarding the design patterns welcomed.

The full code can be found at: https://github.com/BioComSoftware/unite-radimaging-source-n2m2.git

BONUS: Notice in FileSearchHostedService.cs, I instantiate the Repository objects explicitly. I think it would be more appropriate to have them as Dependency Injection – but I couldn’t get it to work. Notice the commented-out lines that would have done this. My understanding is; I would need to do this with IScopedProcessingService – but I have no idea how to do this with this specific code.

Structure

(Startup.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Repositories;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
//using Microsoft.OpenApi.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2 {
    public class Startup {
        public Startup(IConfiguration configuration) {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime.
        // Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services) {

            services.AddControllers();

            services.AddScoped<IFoundFileContext, FoundFileContext>();
            services.AddScoped<IFoundFileRepository, FoundFileRepository>();
        }

        // This method gets called by the runtime.
        // Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            app.UseExceptionHandler("/error");
            app.UseRouting();
            app.UseAuthorization();
            app.UseEndpoints(endpoints => { 
                endpoints.MapControllers(); 
            });
        }
    }
}

(FoundFileRepository.cs)

using unite.radimaging.source.n2m2.Data;
using unite.radimaging.source.n2m2.Entities;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace unite.radimaging.source.n2m2.Repositories {
   public class FoundFileRepository : IFoundFileRepository {
       private readonly IFoundFileContext _context;
       public FoundFileRepository(IFoundFileContext context) {
           _context = context ?? throw new ArgumentNullException(nameof(context));
       }

       public async Task<IEnumerable<FoundFile>> GetFiles() {
       return await _context
           .FoundFiles
           .Find(p => true)
           .ToListAsync();
       }

       public async Task<FoundFile> GetFile(string id) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Id == id)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByPath(string path) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Path == path)
                          .FirstOrDefaultAsync();
       }

       public async Task<FoundFile> GetFileByChecksum(string checksum) {
           return await _context
                          .FoundFiles
                          .Find(p => p.Checksum == checksum)
                          .FirstOrDefaultAsync();
       }

       //public async Task<IEnumerable<FoundFile>> GetFileByMtime(string mtime) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<DateTime>(p => p.Mtime, mtime);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       //public async Task<IEnumerable<FoundFile>> GetFileBySize(long size) {
       //    FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.ElemMatch<long>(p => p.Size, size);

       //    return await _context
       //                    .FoundFiles
       //                    .Find(filter)
       //                    .ToListAsync();
       //}

       public async Task CreateFile(FoundFile foundFile) {
           await _context.FoundFiles.InsertOneAsync(foundFile);
       }

       public async Task<bool> UpdateFile(FoundFile foundFile) {
           var updateResult = await _context.FoundFiles.ReplaceOneAsync(
               filter: g => g.Path == foundFile.Path, replacement: foundFile);
           return updateResult.IsAcknowledged && updateResult.ModifiedCount > 0;
       }

       public async Task<bool> DeleteFile(string path) {
           FilterDefinition<FoundFile> filter = Builders<FoundFile>.Filter.Eq(p => p.Path, path);

           DeleteResult deleteResult = await _context
                                               .FoundFiles
                                               .DeleteOneAsync(filter);

           return deleteResult.IsAcknowledged
               && deleteResult.DeletedCount > 0;
       }
   }
}

(FileSearchHostedService.cs)

using unite.radimaging.source.n2m2.Repositories;
using unite.radimaging.source.n2m2.Entities;
using unite.radimaging.source.n2m2.Data;
using Serilog;
using Microsoft.Extensions.Configuration;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace unite.radimaging.source.n2m2.HostedServices {
    public class FileSearchHostedService : BackgroundService {
        private readonly IConfiguration _configuration;
        //private IFoundFileRepository _repository;

        public FileSearchHostedService(
            //IFoundFileRepository repository,
            IConfiguration configuration
            ) {
            //_repository = repository ?? throw new ArgumentNullException(nameof(repository));
            _configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));
        }

        protected override async Task ExecuteAsync(CancellationToken cancellationToken) {
            Log.Information("FileSearchHostedService: File searching started.");

            cancellationToken.Register(() => Log.Information("Processing service stopped"));

            //string checksum;
            string _current_path;
            FileInfo _current_file;
            FoundFile _foundFile;
            FoundFile _existingFile;
            FoundFile _addFoundFile;
            FoundFileContext FoundfileContext = new FoundFileContext(_configuration); // Normal instantiation, in leiu of injection
            FoundFileRepository _repository = new FoundFileRepository(FoundfileContext);  // Normal instantiation, in leiu of injection

            while (!cancellationToken.IsCancellationRequested) {
                Log.Information("Searching files...");
                string dir = _configuration.GetValue<string>("FileSearchSettings:SearchDir");
                string() files = Directory.GetFiles(dir);
                foreach (string filename in files) {
                    Log.Debug($"Parsing '{filename}'");

                    _current_file     = new FileInfo(filename);
                    _current_path = Path.GetFullPath(Path.Combine(_current_file.Directory.ToString(), _current_file.Name));

                    _foundFile = new FoundFile() {
                        Path = _current_path,
                        Size = _current_file.Length,
                        Mtime = _current_file.LastWriteTime,
                        Checksum = FileChecksum.getChecksum(filename)
                    };
                    Console.WriteLine("==========================");
                    _existingFile = await _repository.GetFileByPath (_current_path);
                    Console.WriteLine("past _repository.GetFileByPath");

                    try {
                        Console.WriteLine($"{_existingFile.Path} exists!!!");
                        Console.WriteLine($"     _existingFile.Checksum: {_existingFile.Checksum}");
                        Console.WriteLine($"     _existingFile.Length = {_existingFile.Size}");
                        Console.WriteLine($"     _existingFile.LastWriteTime = ({_existingFile.Mtime}");
                    }
                    catch {
                        Console.WriteLine($"Creating MongoDB for file {_foundFile.Path} ");
                        _addFoundFile = new FoundFile() {
                            Path = _foundFile.Path,
                            Size = _foundFile.Size,
                            Mtime = _foundFile.Mtime,
                            Checksum = _foundFile.Checksum
                        };
                        await _repository.CreateFile(_addFoundFile);
                    }
                }

                await Task.Delay(
                    _configuration.GetValue<int>("FileSearchSettings:Delay"),
                    cancellationToken
                    );
            }
        }
    }
}

path aliases – [D8/Drupal8]: Pathauto pattern for a content type depending on a reference field?

This question is already asked here, but the answer selected does not work for Drupal8.

Description: There is a content-type, which has field, referencing taxonomy term. The term is in “Content class” dictionary. This term is used in views to filter the right content for the view. When a link in the view is clicked, it opens the node. This is OK.
So, it is needed pathauto to generate /Content class term/Content_title_name when this node is opened.

What is tried: (node:field_content_class:value)/(node:title). This is not accepted, produces error: Path pattern is using the following invalid tokens: (node:field_

The accepted (by Drupal) pattern: (node:field_content_class)/(node:title) generates alias, containing only the (node:title) part. The first component is empty.

This is made to not create separate content-types for nodes with the same fields.

How to create Webform Pattern regular expression for restrict email domain

I want to create a Pattern regular expression in a webform email element to reject form submission if user input in email element/field @gmail.com or @yahoo.com or @hotmail.com etc

Pattern like here

^(?=.*?b@gmail.comb).*$

rest – Which message pattern should I use for synchronous communincation in Nodejs Microservices?

My Nodejs microservices currently running on Kubernetes are communicating over REST. Does the request-reply model of NATS, which replier needs to return (large data ~ 500kb currently single endpoint response), cause performance increase? Some benchmarks say it’s 10 times faster (1), but I got a bad result on a little test I did at my local (but the conditions weren’t equal, I’ll repeat the test on more equal terms). On the other hand, I have read that RabbitMQ does not have a good performance on request-reply. I want to discuss here, how can I decide which communication model is advantageous / performance in situations that require synchronous communication?

In addition, when REST is used, resources can be documented with Swagger. What needs to be done when using NATS?

  1. https://www.youtube.com/watch?v=JNQM_aq9pd4&ab_channel=VinothSelvaraj
  2. https://www.vinsguru.com/nats-performance-comparison-with-rest/

logic – Complexity of pattern matching for modus ponens logical conclusions

Is a Turing machine with added the following contant-time operation equivalent (in the sense that polynomial time remains polynomial time and exponential time remains exponential time) to a (usual) Turing machine:

By predicates I will mean predicates in first-order predicate calculus. (Note that predicates may have free variables.)

  • constant-time modus-ponens resolution (yes or no) and then adding $y$ to the end of this array if yes, for given predicates $x$ and $y$ and an array (or a linked list) of predicates. By definition of modus ponens, it’s yes, if and only if some element of the arrays is $XRightarrow y$ where $X$ is a pattern matching $x$.

Remark: The above operation is a part of the standard procedure of proof-checking is first-order predicate logic.

If the above hypothesis is false, then what is the running time upped bounds of the above operation in different kinds of Turning machine equivalents (such as Turing machine, Markov algorithms, von Neumann architecture with infinitely many infinitely big words of memory, etc.)?

BTW, is von Neumann architecture with infinitely many infinitely big words of memory a Turning machine equivalent? (I think yes, but not 100% sure.)

API-based Architecture Pattern – Software Engineering Stack Exchange

After studying some basics about n-layer architecture, I face to a new proyect where my database is an ERP and the way to connect with it is via API calls. I can perform queries to obtain data but the only way to insert and update is using the API.

I have to write two applications, a website and a web service. Obviously I cannot just public my ERP API as webservice because a I need to make some restrictions. I’d like to share most of the code, so I have thought writting two presentation layers, using MVC pattern with their own model each one. Functionality might be different, but having shared procedures.

Since bussines logic is mainly done at ERP level, but I still need to implement very simple restrictions, and that persistance layer is based on an API and not directly to a database, what kind of architecture should I use?

Having a domain layer with that very simple business logic seems to overkill for me, and I dont know how if we should implement a data access layer since I don’t really have a typical database. All my thoughts are about creating just one layer for this business and data access, but I’d like to know if this is a common pattern I could read or study about.

P.S: I work in a very little team. I still want to separate concepts and make a clean use of layers, but I don’t want too much extra work for such a little team. We all will probably work at every layer.

unit testing – Testable pattern for bytecode interpreter

I am developing virtual machine for prototype-oriented language. And i found one problem.

I dont know how to write interpreter that can be tested using unit tests – naive implementation of interpret needs whole environment to do anything and making unit testing impossible.

Only idea i have is too split bytecode executor(executing bytecodes) and environment holder (holding frames etc.)
But i think this is not enough.
Is there any document about developing testable interpreters?