samedi 16 juillet 2022

What data model to use for tables in Blazor

I am building a .Net 6 Blazor web app. I needs to display lots of html tables with data. For example I need tables that look like this:

       |Jul 17 | Jul 16  | Jul 15
--------------------------------- . . .
Hour 1 | 11.213 | 123.23 | 123.54
Hour 2 | 12.234 | 234.45 | 54.34
.
.
.

Code:

I want to display a lot of tabular data and I would like to be able to compute new tabular data based on the ones I already have, like calculating averages of an existing "table" models rows.

I considered having a data structure like this:

public class DataTable
{
    public DataTable(Dictionary<string, Dictionary<string, decimal?>>? values)
    {
        Values = values ?? new Dictionary<string, Dictionary<string, decimal?>>();
    }

    public Dictionary<string, Dictionary<string, decimal?>>? Values { get; set; }
}

Questions:

  • Is this a good approach?
  • How can I store optional row and column headers?
  • What if I want to create a table with strings? I can't restrict extension methods for a generic class to "number" types, so it seems to no be good design.

PEP8, blank line convention and reduced readability in dense code

Most of the time, PEP8 does not allow more than 1 blank line inside function or more than 2 blank lines between functions. When code is dense, even 2 blank lines can reduce readability.

Is there any guidance how to overcome this? Use some visual elements composed of ASCII characters?

def fun1():
    """
    This does x
    """

    ## Problem 1

    # Subproblem 1.1    
    ...

    # Subproblem 1.2
    ...

    ## -------------------
    ## Problem 2
    ...

# ------------------------
def fun2():
    """
    This does y
    """
    pass   

vendredi 15 juillet 2022

Circular design pattern?

I have a class A and class B. Class A has a parameter which is a list of objects of class B. Class B has a parameter which is an object of instance A.

Would inheritance help me somehow here?

What would be the best design pattern to solve this problem?

constructing completely private and anonymous static singleton

I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this:

namespace {

class curl_guard {
public:
    curl_guard()
    {
        puts("curl_guard constructor");
        // TODO: curl_global_init
    }
    ~curl_guard()
    {
        puts("curl_guard destructor");
        // TODO: curl_global_cleanup
    }
};

curl_guard curl{}; // nothing is ever printed to terminal

}

But when I link this into an executable and run it, there's no output, because it is optimized out (verified with objdump), even in debug build. As I understand, this is intended, because this type is never accessed in any way. Is there any way to mark it so that it is not excluded? Preferably without making it accessible to the user of the library. I'd prefer a general solution, but GCC-only also works for my purposes.

I am aware of typical singleton patterns, but I think this is a special case where none of them apply, because I never want to access this even from internals, just simply have a class tucked away which has one simple job of initializing and deinitializing a C library which is caused by the library being linked in and not something arbitrary like "just don't forget to construct this in main" which is as useful as going back to writing C code.

jeudi 14 juillet 2022

How to determine design pattern from time complexity

I've encountered this question on an informal test.

T(n) is a reccurance relation

If the time complexity of an algorithm with input size of n is defined as:

T(1)=A

T(n)=T(n-1)+B when n>1

Where A and B are positive constant values.

Then the algorithm design pattern is best described as:


A. Decrease and Conquer - Correct answer

B. Divide and Conquer

C. Quadratic

D. Generate and Test

T(n) converges down to T(n) = nB + A -> O(n)

  1. What's the difference between answer A and B?

  2. Why is the answer Decrease and Conquer?

Chain of transformations based on generic types

I'm thinking about a chain, that will allow me to perform a set of transformations with data type changing from transformation to transformation. So far I've got something like this:

public abstract class TransformationStep<T, TY>
{
    public abstract TY Execute(T input);
}

public class Times2<TY> : TransformationStep<int, TY>
{
    public Times2(TransformationStep<int, TY> next)
    {
        Next = next;
    }

    public TransformationStep<int, TY> Next { get; set; }

    public override TY Execute(int input)
    {
        var res = input * 2;
        return Next.Execute(res);
    }
}

public class ToString<TY> : TransformationStep<int, TY>
{
    public ToString(TransformationStep<string, TY> next)
    {
        Next = next;
    }

    public TransformationStep<string, TY> Next { get; }

    public override TY Execute(int input)
    {
        var res = input + "!!!";
        return Next.Execute(res);
    }
}

The only problem I see is the end chain type, where I can't convert T to TY.

public class End<T, TY> : TransformationStep<T, TY>
{
    public override TY Execute(T input)
    {
        return input;
    }
}

Do you have any solution? Also what do you think about this design and do you know any good materials on stuff like that?

Should I improve something in this Node.js code? Iam newbie please help me I can't sign up my webapp that Iam creating (error 404 server) [closed]

I just want to make sure that this is the right code for using node.js ? or am i missing something ? Iam not tough backend guy please suggest me

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');

mongoose.connect(
  process.env.MONGO_DB_URI,
  { useNewUrlParser: true, useUnifiedTopology: true },
);


const usersRouter = require('./routes/users');
const listRouter = require('./routes/list'); 
const databaseRouter = require('./routes/database');

const publicPath = path.join(__dirname, 'build');

const app = express();
app.use(cors());


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// I just import my logic 
app.use('/users', usersRouter);
app.use('/database', databaseRouter);
app.use('/list', listRouter); 

app.get('*', (req, res) => {
  res.send(path.join(publicPath, 'index.html'));
});


app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res) => {
 
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and file that I want to execute (have shabang -> #!/usr/bin/env node )

const app = require('../app');
const debug = require('debug')('backend:server');
const http = require('http');
 


 
//Create HTTP server
const server = http.createServer(app);
 
 
  //Get port from environment and store in Express
const port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
 //Normalize a port into a number, string, or false
function normalizePort(val) {
   const port = parseInt(val, 10);
 
   if (isNaN(port)) {
     // named pipe
     return val;
   }
 
   if (port >= 0) {
     // port number
     return port;
   }
 
   return false;
 }
 
  //Listen on provided port, on all network interfaces
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


//This function will check which type of error occurred,
// log something different, and exit gracefully from our nodejs server.
function onError(error) {
   if (error.syscall !== 'listen') {
     throw error;
   }
 
   const bind = typeof port === 'string'
     ? `Pipe ${port}`
     : `Port ${port}`;
 
  
   switch (error.code) {
     case 'EACCES':
       console.error(`${bind} requires elevated privileges`);
       process.exit(1);
       break;
     case 'EADDRINUSE':
       console.error(`${bind} is already in use`);
       process.exit(1);
       break;
     default:
       throw error;
   }
 }
 
//Event listener for HTTP server "listening" event
 
function onListening() {
   const addr = server.address();
   const bind = typeof addr === 'string'
     ? `pipe ${addr}`
     : `port ${addr.port}`;
   debug(`Listening on ${bind}`);
}

Any mistake that I made please correct me or want some information that need to show please tell me. Thankyou