Implementing growth in Snake?

I’m new at this, so I thought I’d start simple. Snake. I started with pygame, just looking some things up, and I’ve now got movement, random fruit generation, and a score counter.

pygame.init()

size = width, height = (800, 440)
screen = pygame.display.set_mode(size)
pygame.display.set_caption('snake from scratch')

clock = pygame.time.Clock()

notBlack = (40,50,50)
white = (255,255,255)
red = (255,0,0)
blue = (0,0,255)
green = (0,255,0)

w = 20, 760

x1 = 400
y1 = 220
x1Velocity = 0
y1Velocity = 0
x2 = 0
y2 = 0

player = pygame.Rect(x1, y1, 20, 20)
fruit = pygame.Rect(x2, y2, 20, 20)
fruitOnScreen = False
score = 0

def roundTo(x, base):
    return base * round(x/base) #rounds to whatever you put as base

def offScreen(x, y):
    while x >= 760 or y >= 400:
        if x > 760:
            x -= 5
        if y > 400:
            y -= 5
        if x < 770 and y < 405:
            break
    return x, y #forces x and y pos back on screen

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_ESCAPE:
                running = False
            if event.key == pygame.K_LEFT:
                x1Velocity = -20
                y1Velocity = 0
            if event.key == pygame.K_RIGHT:
                x1Velocity = 20
                y1Velocity = 0
            if event.key == pygame.K_UP:
                x1Velocity = 0
                y1Velocity = -20
            if event.key == pygame.K_DOWN:
                x1Velocity = 0
                y1Velocity = 20

    x1 += x1Velocity
    y1 += y1Velocity
    
    player = pygame.Rect(x1, y1, 20, 20)
    fruit = pygame.Rect(x2, y2, 20, 20)
    collide = player.colliderect(fruit)

    if not fruitOnScreen:
        x2 = random.randrange(20, 760)
        y2 = random.randrange(20, 400)
        x2 = roundTo(x2, 20)
        y2 = roundTo(y2, 20)
        x2, y2 = offScreen(x2, y2)
        fruitOnScreen = True #Generates random coords for fruit
    elif collide:
        score += 1
        fruitOnScreen = False
        print(score)

    screen.fill(white)
    
    pygame.draw.rect(screen, red, (x2, y2, 20, 20))
    pygame.draw.rect(screen, blue, (x1, y1, 20, 20))
    pygame.draw.rect(screen, notBlack, (0, 0, 800, 440), 40) #Draws a 20pixel thick border
    pygame.display.update()
    clock.tick(8)

pygame.quit()
quit()

I think this is pretty good for not having much of any experience, but now I’m stuck. I want to have the body get longer, but I don’t know where to even start. Just looking at it, is it even possible to implement it using what I’ve already got?

seo – Are there pitfalls to implementing a hybrid site with both responsive layouts and dynamic serving layouts?

I have a 20 year old site that I want to upgrade to a responsive layout. Originally it was a desktop-only layout but when a significant portion of my user base went mobile I implemented dynamic serving layouts where I sniff the user agent and serve different HTML based on whether the user agent is for a mobile device or not.

I started to implement the responsive layouts, but I found that about 5% of my user base is on older browsers that don’t have all the CSS and JavaScript I would like to use. For example, only 95.42% of users fully support CSS grid layouts: https://caniuse.com/css-grid
While I wouldn’t want to take the time to develop a site just 5% of my users, I already have a site that works for those users and I don’t want to lose that much of my traffic when I move to responsive.

My current plan is to still do server side tests based on the user agent like this pseudo code:

use responsive-layout if (bot) 
use desktop-layout if (msie or firefox < 54 or chrome < 58  or edge < 16)
use mobile-layout if (opera-mini or android-browser or samsung-internet < 5 or safari-mobile < 10.3)
use responsive-layout otherwise

Most of my users and search engine crawlers would get the responsive layout. Only specific non-capable and older browsers would get my existing static layouts.

I know that Google supports either responsive layouts or dynamic serving layouts but I haven’t been able to find any information about a hybrid approach like this. Are there any pitfalls (especially with regards to SEO) of mostly using responsive but falling back to dynamic serving for some browsers?

reinventing the wheel – Implementing conditinional execution in Python

I found abandoned project on GitHub and curious is it possible to implement part of it on just Python?

Goal:

  • Call functions only under some condition.
  • Track if ANY of inner function were triggered.
  • Reuse variables from the same scope to be more flexible with inner functions calls.

I have PoC working, but I wonder is any better algorithmic approach to do the same in Python? Most obvious way to do something similar to bellow. But is there more elegant way to get rid of repeating if ...: processed = True pattern?

def boo(a, c):
  # do something
  return True

def foo(a, b, c):
  # do something more
  return True

def setup(a, b, c):
   processed = False

   if ((a == "boo") & (c == 1)):
      if boo(a, c):
         processed = True

   if ((a == "boo") & ((c == 2) | (b == 3))):
      if foo(a, b, c):
         processed = True
   ...
   return processed

c# – Verify implementing Microsoft Graph 4.0.0 for SSO in Azure is implemented correctly

I originally posted this on SO, and I know cross-linking is generally frowned upon. But, I am not sure if this falls under question or code review because the code works where I do not know if it is implemented correctly. Anyways, here it is:

https://stackoverflow.com/questions/68868685/need-help-demystifying-the-new-feature-introduced-on-microsoft-graph-4-0-0

Question:

Do we need to acquire the access token from Microsoft.Graph using either silent or interactive modes? From what I can tell the answer is, No. (see Context below)

The new implementation seems to be drastically scaled down with the whole idea of silent and interactive token retrieval being removed. Is this correct?

using Azure.Identity;
using Microsoft.Graph;
using System;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string() args)
        {
            var scopes = new() { "User.Read" };

            // Multi-tenant apps can use "common",
            // single-tenant apps must use the tenant ID from the Azure portal
            var tenantId = "SomeGuid";

            // Value from app registration
            var clientId = "SomeGuid";

            var options = new InteractiveBrowserCredentialOptions
            {
                TenantId = tenantId,
                ClientId = clientId,
                AuthorityHost = AzureAuthorityHosts.AzurePublicCloud,
                // MUST be http://localhost or http://localhost:PORT
                // See https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/wiki/System-Browser-on-.Net-Core
                RedirectUri = new Uri("http://localhost:1234"),
            };

            // https://docs.microsoft.com/dotnet/api/azure.identity.interactivebrowsercredential
            var interactiveCredential = new InteractiveBrowserCredential(options);

            var graphClient = new GraphServiceClient(interactiveCredential, scopes);
            
            // Interactive browser login occurs here.
            var me = graphClient.Me.Request().GetAsync().Result;

            // Printing the results
            Console.WriteLine("-------- Data from call to MS Graph --------");
            Console.Write(Environment.NewLine);
            Console.WriteLine($"Id: {me.Id}");
            Console.WriteLine($"Display Name: {me.DisplayName}");
            Console.WriteLine($"Email: {me.Mail}");
            //Console.ReadLine();
        }
    }
}

Context:

As part of our routine maintenance, I was tasked with upgrading our NuGet packages on a Winforms desktop application that is running in Azure and whose users are in Azure Active Directory Services (AADS). One of the packages, Microsoft.Graph, had a major version change. https://www.nuget.org/packages/Microsoft.Graph/4.0.0

The documentation on it indicated a new feature for handling the TokenCredentialClass. https://github.com/microsoftgraph/msgraph-sdk-dotnet/blob/4.0.0/docs/upgrade-to-v4.md#new-capabilities

From what I can tell, there is a separate and distinct break on how the token is retrieved. Previously, we followed the method provided here: https://docs.microsoft.com/en-us/azure/active-directory/develop/tutorial-v2-windows-desktop#add-the-code-to-initialize-msal

Old way:

using Microsoft.Graph;
using Microsoft.Graph.Auth;
using Microsoft.Identity.Client;
using System;
using System.Linq;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string() args)
        {
            _PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
                    .WithRedirectUri("http://localhost:1234")
                    .WithAuthority(AzureCloudInstance.AzurePublic, TenantId)
                    .Build();

            // We sign the user in here
            bolIsAutorizeSSO = CallMicrosoftSSO().GetAwaiter().GetResult();
            InteractiveAuthenticationProvider = new InteractiveAuthenticationProvider(PublicClientApp, Scopes);
            GraphServiceClient = new Microsoft.Graph.GraphServiceClient(InteractiveAuthenticationProvider);

            if (bolIsAutorizeSSO)
            {
                // We also signt the user in here.
                var User = GraphServiceClient.Me.Request().GetAsync().Result;

                // Printing the results
                Console.WriteLine("-------- Data from call to MS Graph --------");
                Console.Write(Environment.NewLine);
                Console.WriteLine($"Id: {User.Id}");
                Console.WriteLine($"Display Name: {User.DisplayName}");
                Console.WriteLine($"Email: {User.Mail}");
            }
            else
            {
                // signout
                Console.ReadLine();
            }
        }

        public static async Task<bool> CallMicrosoftSSO()
        {
            AuthenticationResult authResult = null;
            var app = PublicClientApp;
            var accounts = await app.GetAccountsAsync();

            try
            {
                authResult = await app.AcquireTokenInteractive(Scopes)
                    .WithAccount(accounts.FirstOrDefault())
                    .WithPrompt(Microsoft.Identity.Client.Prompt.ForceLogin)
                    .ExecuteAsync();
            }
            catch (MsalUiRequiredException _Exception)
            {
                // A MsalUiRequiredException happened on AcquireTokenSilent. 
                // This indicates you need to call AcquireTokenInteractive to acquire a token.
                
                Console.WriteLine(_Exception.Message);
            }
            catch (MsalException msalex)
            {
                if (msalex.ErrorCode != "authentication_canceled")
                {
                    Console.WriteLine(msalex.Message);
                }
            }
            catch (Exception _Exception)
            {
                Console.WriteLine(_Exception.Message);
            }

            if (authResult != null)
            {
                return true;
            }
            return false;
        }

        private static string ClientId = "SomeGuid";
        private static string TenantId = "SomeGuid";
        private static string() Scopes = new string() { "User.Read" };
        private static Microsoft.Graph.GraphServiceClient GraphServiceClient;
        private static bool bolIsAutorizeSSO = false;
        private static InteractiveAuthenticationProvider InteractiveAuthenticationProvider;

        private static IPublicClientApplication _PublicClientApp;
        public static IPublicClientApplication PublicClientApp { get { return _PublicClientApp; } }
    }
}

I am struggling to make sense of it. Partly because the feature is brand new and there are very few code samples up on the internet that say do it this way. What I have found seems to point me back to what we already are using (more on that in a bit). So, the examples may not yet be fully updated.

Implementing Dynamic Partitions instead AB systems

Is there an easy way to implement dynamic partitions for the oneplus 7 or any other phone built in with AB partitions system
I want to support super.img to be able to test CGI images without the need for full wipe

django – Failed lookup for key – implementing pagination with elided_page

I am attempting to implement pagination with elided_page based on this blog post. My goal is to have pagination with only a few pages being showed and increase as a new page is viewed as I will eventually have over a hundred pages.

view

def home(request):

page = request.GET.get('page', 1)
paginator = Paginator(Post.objects.all(), 2)
page_range = paginator.get_elided_page_range(number=page)

context = { 'page_range':page_range, 'page':page, 'paginator':paginator}

return render(request, 'blog/home.html', context)

template

<ul class="pagination justify-content-center flex-wrap mt-2 mb-4">
{% if page_obj.has_previous %}
    <li class="page-item"><a class="page-link" href="?page={{ page_obj.previous_page_number }}">&laquo;</a></li>
{% else %}
    <li class="disabled page-item"><span class="page-link">&laquo;</span></li>
{% endif %}
{% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %}
    {% if page_obj.number == i %}
        <li class="active page-item"><span class="page-link">{{ i }} <span class="sr-only">(current)</span></span>
        </li>
    {% else %}
        {% if i == page_obj.paginator.ELLIPSIS %}
            <li class="page-item"><span class="page-link">{{ i }}</span></li>
        {% else %}
            <li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
        {% endif %}
    {% endif %}
{% endfor %}
{% if page_obj.has_next %}
    <li class="page-item"><a class="page-link" href="?page={{ page_obj.next_page_number }}">&raquo;</a></li>
{% else %}
    <li class="disabled page-item"><span class="page-link">&raquo;</span></li>
{% endif %}

However when i run this i get the error

Failed lookup for key (page_obj) in ({'True': True, 'False': False, 'None': None}, {}, {}, {'page_range': <generator object Paginator.get_elided_page_range at 0x000001FB70D20E40>, 'page': '3', 'paginator': <django.core.paginator.Paginator object at 0x000001FB70D7A490>})

on this line

{% for i in page_range|default_if_none:page_obj.paginator.get_elided_page_range %}

if I edit that line and just have it as {% for i in page_range %} it sort of works but displays every page leading me to believe the error is with this part of the statement |default_if_none:page_obj.paginator.get_elided_page_range

enter image description here

I am not that great with the templates but in my research I came across this stack post. Where a user was experiencing a similar issue and say that this is just a bug in django that wont be fixed. Is this true? If not how would I remedy this issue or am I just going about this the wrong way.

What are the best practices when implementing C++ error handling?

FYI: I was asked to post this on softwareengineering – this question was originally posted on stack overflow, but they are a bit funny about broad questions over there, hence I was told to post here instead…

I have searched stackoverflow for relevant questions and was surprised to find that I couldn’t find any questions tagged with C++ with in depth discussions of best practices for error handling in C++.

I found this suprising for a number of reasons:

  • There are other questions which are quite famous within the community on similar subject areas. Notable examples include the in-depth discussions of how to implement the many different operators in user-defined C++ classes. (Including mathematical operators such as operator+ as well as io operators such as operator<<… I’m sure many of those reading will recall which question and answer I refer to here.)

  • There appear to be lots of possible choices to make when writing error handling code, just as there is when writing operator implementations. However, just as with operators, there is probably only one “sensible” implementation. For example, one could implement a matrix multiply using the operator<<, but this would not be the expected behaviour for this function and so it makes little logical sense to make such a decision. Similarly with errors, one can “throw” just about anything, including just std::string objects implicitly constructed from const char*‘s.

Intro: C style errors, reasons not to use them in C++

I know roughly how I can implement errors and error handling code in C++, but I am not confident that I know how to do this in a way which is approved of by industry. I would like to correct my ways by asking this question.

The C style of error handling is simple: One writes functions which return int and then one defines error codes which can be returned.

There are several problems with this:

  • Error codes have to be global variables, and are probably defined in some obscure file hidden in the source code folders somewhere.
  • Error codes have to be (should be) unique. It is difficult to maintain a list of unique codes unless they are all in the same file. If one is writing an application with several independent components, it makes little to no sense to define all the error codes for two seperate components in the same file.
  • If one splits the error codes into two or more files there may be conflicts and clashes causing nonsensical code to compile ok.

Here is an example, consider a math module and a network module.

const int ERROR_CODE_MATH_DOMAIN_ERROR = 100;
const int ERROR_CODE_NETWORK_IP_UNREACHABLE = 100;

int math_function(argument)
{
    return ERROR_CODE_MATH_DOMAIN_ERROR;
}

int main()
{
    if(math_function(arguments) == ERROR_CODE_NETWORK_IP_UNREACHABLE)
    // works, and compiles, and detects the right kind of error
    // but makes literally zero sense to the reader
}

The other advantage of C++ errors using try-catch is that error flow is seperated from normal no-error program flow.

Given the above, it would be better to use try-catch symantics to handle errors.

Often when programming I am quite lazy at dealing with errors, so I often find myself defaulting to the C-style-return-an-error-code paradigm.


I am aware that one can do this:

 void error_throwing_function()
 {
     if(true)
     {
         throw "an error has certainly occured";
     }
 }

However, some questions arrise:

  • Is this good code?
  • What kind of error does this throw? A std::string object?
  • How do I catch this kind of error without catching all errors?
  • Is this considered bad practice?

To explain the 3rd bullet in more detail, to catch this error one may do something like this:

try
{
    error_throwing_function()
}
catch (... what goes here? ...)
// catch(std::string) // does this work? does it make sense?
{
    // only option is to catch "all possible errors" - maybe?
}

Is it best practice to implement my own classes for types of error which may occur in my library? (Using inheritance.)

The C++ standard library defines a number of default errors. These can be found here.

All possible C++ error inherit from std::exception… This raises a new question linked to the previous section:

  • What happens if one throws an instance of a const char*, suc as:

    throw “a lazy error throw”;

Further, the STL defines a set of default errors which are used in STL. Notable examples include the std::out_of_range error type which is thrown by the STL containers when something like at() is called and the argument references a section of memory which is out of bounds. Link

  • When implementing a new library, should one make used of the STL errors? Is it good olr bad practice to do so? Why?

  • Or should one define new classes inheriting from std::exception to implement new types of error which related to a new libary implementation?

  • Should these error types always inherit from the base class std::exception or should they sometimes inherit from another (derived) STL error type such as std::out_of_range?

Always good to be aware of as much information as possible so is there anything I have missed so far?

This question doesn’t particularly relate to any version of C++, but since most of us are writing C++11 or later code, those standards are likely of particular interest.

template meta programming – Implementing apply_each for tuple c++

I’m implementing apply_each for tuple-like object as a general function which may be a combined version of for_each and tuple_transform in some implementations for tuple iteration.

As the name suggests, the first argument which is invocable will apply each element of the tuple.


Function Prototype of apply_each:

template <typename F, typename... Tuples>
constexpr decltype(auto) apply_each(F&& f, Tuples&&... ts);

As usual, you can iterate over the tuple

std::tuple tup_1 {1, 2.5, "three", 'F'};
gold::apply_each(()(const auto& elem) {
  std::cout << elem << ' ';
}, tup_1);

Output:

1 2.5 three F

Tuple-like object can also be used

gold::apply_each(()(const auto& elem) {
  std::cout << elem << ' ';
}, std::array{1, 2, 3, 4});

Output:

1 2 3 4

How about two or more tuples? Sure! No problem

The function apply_each takes the first parameter that is callable and the arity should match with the number of elements from the tuple. There is internally a zipper function that zips the function so that the tuples that are zipped can be traversed together.

You don’t need to worry about the length of every tuple because it automatically selects the minimum size of the tuples and truncates it.

std::tuple tup_1 {1, 2, 3, 4};
std::tuple tup_2 {1, 2, 3, 4, 5};
std::tuple tup_3 {1, 2, 3};

gold::apply_each((i = 1)(const auto&... args) mutable {
  if (i == 1) std::cout << "Taking the sum of each element..." << 'n';
  std::cout << "Iteration " << i++ << ": " << (args + ...) << 'n';
}, tup_1, tup_2, tup_3);

Output:

Taking the sum of each element...
Iteration 1: 3
Iteration 2: 6
Iteration 3: 9

Well you can still use the parameter list: const auto& arg1, const auto& arg2, const auto& arg3.


What about the return type? Sure!

std::tuple tup_1 {1, 2, 3, 4};
std::tuple tup_2 {1, 2, 3, 4, 5};
std::tuple tup_3 {1, 2, 3};

auto sum_tuple = gold::apply_each(()(const auto&... args) mutable {
  return (args + ...);
}, tup_1, tup_2, tup_3);

static_assert(std::is_same_v<std::tuple<int, int, int>, decltype(sum_tuple)>); // passed!

gold::apply_each((i = 1)(const auto& elem) mutable {
  std::cout << "Sum " << i++ << ": " << elem << 'n';
}, sum_tuple);

Output:

Sum 1: 3
Sum 2: 6
Sum 3: 9

What about mutating them? Hmmm…

Well…

std::tuple<int, double> tup_1;

gold::apply_each(()(auto& elem){
  if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
    elem = 3;
  } else {
    elem = 3.14159; 
  }
}, tup_1);

gold::apply_each(()(const auto& elem){
  std::cout << elem << ' ';
}, tup_1);

It seems to be compiled, but! The tuple doesn’t change…

0 0

Why? Well, it’s difficult for me to make communicate with references when that invocable object is passed, and I can’t figure out easily the argument type of the function because it may be a template or not. So… I used a reference_wrapper!, because that’s the only one who saved me.

Let’s see…

gold::apply_each(()(auto& elem){
  if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
    elem = 3;
  } else {
    elem = 3.14159;
  }
}, std::ref(tup_1));

Oops!! It seems the compiler is very angry. Well, the elem is still actually a reference_wrapper so the error is about operator= mismatch, and is not converted into primitive reference because it is a generic lambda.

So, I find another solution and overload is the key!

gold::apply_each(gold::overload(
  ()(int& elem){ elem = 3; },
  ()(double& elem) { elem = 3.14159; }
), std::ref(tup_1));

The compiler seems very happy now :)

A reference wrapper is implicitly converted into reference type because the argument type is known which is int& and double&

What is the other way for passing a generic lambda? So I created a struct overload_unref!

gold::apply_each(gold::overload_unref(
  ()(auto& elem) {
    if constexpr (std::is_integral_v<std::decay_t<decltype(elem)>>) {
      elem = 3;
    } else {
      elem = 3.14159;
    }
  }
), std::ref(tup_1));

The mechanics of overload_unref is that it will unwrap the argument if the type is reference_wrapper.

Here is the full implementation of apply_each together with the helper tuple_zip function:

namespace gold {

  namespace detail {
    template <typename>
    struct is_ref_wrapper_ : std::false_type {};

    template <typename T>
    struct is_ref_wrapper_<std::reference_wrapper<T>> : std::true_type {};

    template <typename T>
    inline constexpr bool is_ref_wrapper_v_ = is_ref_wrapper_<T>::value;

    template <typename T>
    struct maybe_unwrap_ref_wrapper_ {
      using type = std::conditional_t<is_ref_wrapper_v_<T>, std::unwrap_reference_t<T>, T>;
    };

    template <typename T>
    using maybe_unwrap_ref_wrapper_t_ = typename maybe_unwrap_ref_wrapper_<T>::type;

    template <typename T>
    using get_ref_wrap_type_t_ = typename T::type;

    template <std::size_t I, typename... Tuple>
    using zip_tuple_at_index_t_ = std::tuple<
      std::conditional_t<
        is_ref_wrapper_v_<std::decay_t<Tuple>>,
          std::reference_wrapper<
            std::conditional_t<
              std::is_const_v<std::experimental::detected_or_t<Tuple, get_ref_wrap_type_t_, Tuple>>,
              const std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>,
              std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>
            >
          >,
        std::tuple_element_t<I, std::decay_t<maybe_unwrap_ref_wrapper_t_<Tuple>>>
      >...
    >;

    template <std::size_t I, typename... Tuple>
    constexpr zip_tuple_at_index_t_<I, Tuple...> zip_tuple_at_index_(Tuple&&... ts) {

      return { ()<typename T>(T&& t) {
        if constexpr (is_ref_wrapper_v_<std::remove_cvref_t<T>>) {
          using type_ = std::remove_reference_t<typename T::type>; // reference_wrapper<T>::type
          if constexpr (std::is_const_v<type_>)
            return std::cref(std::get<I>(std::forward<T>(t).get()));
          else
            return std::ref(std::get<I>(std::forward<T>(t).get()));
        } else
           return std::get<I>(std::forward<T>(t));
      }(std::forward<Tuple>(ts)) ... };

    }

    template <typename... Tuple, std::size_t... Is>
    constexpr std::tuple<zip_tuple_at_index_t_<Is, Tuple...>...>
    tuple_zip_impl_(std::index_sequence<Is...>, Tuple&&... ts) {
        return { zip_tuple_at_index_<Is>(std::forward<Tuple>(ts)...)... };
    }
  
  } // namespace detail

  // tuple_zip
  template <typename... Tuple> requires (sizeof...(Tuple) > 0)
  constexpr decltype(auto) tuple_zip(Tuple&&... ts) {
    constexpr auto min_size_ = std::ranges::min({
      std::tuple_size_v<std::decay_t<detail::maybe_unwrap_ref_wrapper_t_<Tuple>>>...
    });
    return detail::tuple_zip_impl_(
      std::make_index_sequence<min_size_>{},
      std::forward<Tuple>(ts)...
    );
  }

  namespace detail {
    
    template <typename F, typename... Tuple, std::size_t... Is> requires (sizeof...(Tuple) > 0)
    constexpr decltype(auto) apply_each_impl_(std::index_sequence<Is...>, F&& f, Tuple&&... ts) {
      decltype(auto) zipped_ = tuple_zip(std::forward<Tuple>(ts)...);
      using result_t_ = decltype((&){
        return (std::apply(std::forward<F>(f), std::get<Is>(zipped_)), ...);
      }());

      if constexpr (std::is_void_v<result_t_>) {
        return (
          std::apply(std::forward<F>(f), std::get<Is>(zipped_)), ...
        );
      } else {
        return std::make_tuple(
          std::apply(
            std::forward<F>(f), std::get<Is>(zipped_)
          )...
        );
      }
    }

  } // namespace detail

  // apply_each
  template <typename F, typename... Tuple>
  constexpr decltype(auto) apply_each(F&& f, Tuple&&... ts) {
    using indices_ = std::make_index_sequence<std::ranges::min({
      std::tuple_size_v<std::decay_t<detail::maybe_unwrap_ref_wrapper_t_<Tuple>>>...
    })>;
    return detail::apply_each_impl_(indices_{}, std::forward<F>(f), std::forward<Tuple>(ts)...);
  }

  // unref
  template <typename T>
  constexpr T&& unref(T&& t) {
    return std::forward<T>(t);
  }

  template <typename T>
  constexpr T& unref(std::reference_wrapper<T> t) {
    return t.get();
  }

  // overload
  template <typename... Fs>
  struct overload : Fs... {
    using Fs::operator()...;
  };

  // I have to provide this, otherwise, I would get a compilation error that I can't explain further...
  template <typename... Fs>
  overload(Fs...) -> overload<Fs...>;

  namespace requirements {
    template <typename... Ts>
    concept has_at_least_ref_wrapper_ = (detail::is_ref_wrapper_v_<std::remove_cvref_t<Ts>> || ...);
  } // namespace requirements

  // overload_unref
  template <typename... Fs>
  struct overload_unref : overload<Fs...> {

    overload_unref(Fs&&... fs)
    : overload<Fs...>{ std::forward<Fs>(fs) ... } {}

    using overload<Fs...>::operator();

    template <typename... Ts>
      requires requirements::has_at_least_ref_wrapper_<Ts...>
    constexpr auto operator()(Ts&&... args) {
       return (*this)(unref(std::forward<Ts>(args))...);
    }

  };
 
} // namespace gold

Current problems:

  • The definition of alias zip_tuple_at_index_t_ is over complicated even though I’m the one who wrote this but I can’t further simplify this one.
  • Same to zip_tuple_at_index_.
  • I don’t know if it’s safe to use std::experimental::detected_or_t even if it’s experimental.
  • I’m writing decltype(auto) for no reason but I don’t know if that affects the value category of the type.

web development – Which is a better way in implementing the QR code in this system?

1st choice:
User1 registers on the website. Upon registration, the system will generate a QR code for the user. The user then goes to be vaccinated, and upon vaccination, someone will be able to scan his/ her QR code and the status of the user will be updated as vaccinated with the 1st dose of the vaccine. Additional information will also include, the date for the 2nd dose of vaccination, the doctor who was responsible for the vaccination, date and time of the vaccination. The user can also give his feedback for the side effects per dosage.

2nd Choice:
In the admin dashboard, adding a vaccine will generate a QR code per dosage. Let’s say it was printed out to be posted. The user1 will then scan the qr code of the dosage of the vaccine they’ve taken. Upon scanning, the user1’s vaccination status will be updated with the same information mentioned above.

php – implementing SOLID principles and oop

im reading clean code, and practicing SOLID principles, can someone help me to improve this code, suggestions are welcome:

<?php 

require_once ('database.class.php');

class EncryptPassword{
    
    public function encrypt(string $password){
        $encrypted_password = sha1($password);
        return $encrypted_password;
    }

}

class insertUser extends EncryptPassword{

    private $id_user_type;
    private $name;
    private $lastname;
    private $email;
    private $password;
    

    public function __construct(int $id_user_type, string $name, string $lastname, string $email, string $password){

        $this->id_user_type = $id_user_type;
        $this->name = $name;
        $this->lastname = $lastname;
        $this->email = $email;
        $this->password = $password;
        
    }

    public function insert(){

        try {

            $db = database::getInstance();

            $password = parent::encrypt($this->password);

            $sql = $db->prepare("INSERT INTO users (id_user_type, name, lastname, email, password) VALUES (?, ?, ?, ?, ?)");

            $sql->bindParam(1, $this->id_user_type);
            $sql->bindParam(2, $this->name);
            $sql->bindParam(3, $this->lastname);
            $sql->bindParam(4, $this->email);
            $sql->bindParam(5, $password);

            $result = $sql->execute();

            if($result==true){
                return "inserted";
            } else {
                return "not inserted";
            }

        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class updateUser extends EncryptPassword{

    private $id_user;
    private $id_user_type;
    private $name;
    private $lastname;
    private $email;
    private $password;
    

    public function __construct(int $id_user, int $id_user_type, string $name, string $lastname, string $email, string $password=''){

        $this->id_user = $id_user;
        $this->id_user_type = $id_user_type;
        $this->name = $name;
        $this->lastname = $lastname;
        $this->email = $email;
        $this->password = $password;
        
    }

    public function update(){

        try {

            $db = database::getInstance();
            $password = parent::encrypt($this->password);

            if(!empty($password)){

                $sql = "UPDATE users SET id_user_type=?, name=?, lastname=?, email=?, password=? WHERE id=?";
                $stmt= $db->prepare($sql);
                $result = $stmt->execute(($this->id_user_type, $this->name, $this->lastname, $this->email, $password, $this->id_user));
                
            } else {

                $sql = "UPDATE users SET id_user_type=?, name=?, lastname=?, email=? WHERE id=?";
                $stmt= $db->prepare($sql);
                $result = $stmt->execute(($this->id_user_type, $this->name, $this->lastname, $this->email, $this->id_user));
                
            }

            if($result==true){
                return "updated";
            } else {
                return "not updated";
            }

        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}


class getUsers{

    public function getAllUsers(){

        try {

            $db = database::getInstance();

            $sql = 'SELECT id, name, lastname, email, active, date FROM users';
            $stm = $db->prepare($sql);
            $stm->execute();
            $result = $stm->fetchAll(PDO::FETCH_ASSOC);

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class getUserInfo{

    public function __construct(int $id_user){
        $this->id_user = $id_user;
    }

    public function getUser(){

        try {

            $db = database::getInstance();

            $sql = "SELECT id, name, lastname, email, active, date FROM users where id=:id";
            $stm = $db->prepare($sql);
            $stm->bindParam(':id', $this->id_user, PDO::PARAM_INT);
            $stm->execute();
            $result = $stm->fetch();

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

class OnOff{

    public function __construct(int $id_user, int $actdeact){
        $this->id_user = $id_user;
        $this->actdeact = $actdeact;
    }

    public function statusUser(){

        try {

            $db = database::getInstance();

            $sql = "UPDATE users SET active=? WHERE id=?";
            $stmt= $db->prepare($sql);
            $result = $stmt->execute(($this->actdeact, $this->id_user));

            return $result;
        
        } catch (Exception $e) {
            print $e->getMessage();        
        }

    }

}

The database class:

<?php

class database {

    protected static $instance;

    protected function __construct() {}

    public static function getInstance() {

        if(empty(self::$instance)) {

            $db_info = array(
                "db_host" => "localhost",
                "db_port" => "3306",
                "db_user" => "localhost",
                "db_pass" => "xxxxxxxxxx",
                "db_name" => "xxxxxxxxxx",
                "db_charset" => "UTF-8");

            try {

                self::$instance = new PDO("mysql:host=".$db_info('db_host').';port='.$db_info('db_port').';dbname='.$db_info('db_name'), $db_info('db_user'), $db_info('db_pass'));
                self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);  
                self::$instance->query('SET NAMES utf8');
                self::$instance->query('SET CHARACTER SET utf8');

            } catch(PDOException $error) {
                echo $error->getMessage();
            }

        }
        return self::$instance;
    }
}

?>