architecture – Repository Pattern with Services Layer – Good Practice?

This is my first time I am using repository pattern and applying a layered architecture in a project. I have followed the article found here. The complete code found on the article can also be found on the writer’s github.

I read the whole article beginning to end before getting my hands on the keyboard to start coding. It al made sense (still does).

I am not sure if I have to summarise the whole article here but in simple terms, he divided his solution into 4 projects. Core, Data, Services and WebApi. Repository Pattern and UnitOfWork is used to abstract data access.

After reading the article I decided to apply the very same logic to my project. After doing so, I realised it took me the whole day and I found myself writing a lot and a lot of code which seemed unnecessary and duplicated. For example, in this article he only have two entities. Hence it seemed like a very simple application. I currently have 28 and that’s only the beginning! This ment, apart from my actual model, I ended up having 28 separate repository interfaces, 28 separate service interfaces, 28 actual repositories, 28 actual service classes and similar number of DTOs (Resource classes) for mapping purposes.

So. I am happy to do the extra work if it will prove to be a solid foundation for my project and if it will contribute positively to my learning progress. However, something inside tells me I’ve done a lot of unnecessary work, which either could be simplified or probably have a better way of doing. Hence, I am here seeking advice if this article is guiding me in the right direction.

I am using the latest versions (including pre-release) of DotNet Core and Entity Framework Core.

microservices – Integration of socket service in reactor pattern: interfacing dispatcher with socket

I need an insight on how to better organize my project which implements a Reactor pattern, Flux specifically.

My struggle stands in accomodating a Socket Service Layer which is purely needed to interface Socket (Inbound Data) and Dispatcher (Outbound data, internal operations).

In particular, I would like to find a solution (or a pattern extension) on how to achieve a wiser organization (from a project structure POV) of socketHandlers and dispatcherHandlers (see last picture)

Pattern implementation
enter image description here

Self-explanatory code

class SocketService{
    constructor(){
        this._socketListeners = ();
        this._dispatcherListeners = ();   
    }
    init(io){ // Io is the server socket
        this._dispatcherListeners.map(func => {
            func(io);
        });
        io.on("connection",this.onConnectionReceived);
    }
    onConnectionReceived(socket){ // socket represents client connection
        this._socketListeners.map(func => {
            func(socket);
        });
    }
    registerDispatcherHandler(callable){
        this._dispatcherListeners.push(callable);
    }
    
    regiterSocketHandler(callable){
        this._socketListeners.push(callable)
    }
}


const exampleDispatcherListener = (io) => {
    dispatcher.addChangeListener(
        DispatcherEvents.USER_SAYS_HELLO,
        ({whoSays}) => {
            io.to(EVERYONE).emit(SocketEvents.SOMEONE_SAID_HELLO, whoSays)
        }
    )
}


const exampleSocketListener = (socket) => {
    socket.on(SocketEvents.SAY_HELLO, async ({whoSays}) => {
        dispatcher.dispatch({
            actionType: DispatcherEvents.USER_SAYS_HELLO,
            data: { whoSays }
        }); // This will trigger
    })
}

Project structure, folders of interest

actions
dbo
stores
socket.js // Binds socket to the server - initializes it.
services
  socket.js // Here's our SocketService, 
socket-dispatcher-handlers // Unsure if this is where socketHandlers should be
socket-handlers // Unsure if this is where socketHandlers should be

Is this a good pattern design for a Unity dispatcher for creating thread safe methods?

Well, my intention here is to allow users to execute Unity methods/properties in other threads by using this Dispatcher implementation:


using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Threading.Tasks;
using UnityEngine;

namespace DepotToolkit.Utils
{
    /// <summary>
    /// A thread-safe class which holds a queue with actions to execute on the next Update() method. It can be used to make calls to the main thread for
    /// things such as UI Manipulation in Unity. It was developed for use in combination with the Firebase Unity plugin, which uses separate threads for event handling
    /// </summary>
    public class UnityDispatcher : MonoBehaviour
    // : MonoSingleton<UnityDispatcher>
    {
        // TODO: Add timeout from https://gist.github.com/phizaz/f67f1ba7d25d30d8972c13b7b6a29319

        private static readonly ConcurrentQueue<Action> _executionQueue = new ConcurrentQueue<Action>();
        public static ObservableCollection<Exception> Exceptions { get; } = new ObservableCollection<Exception>();

        // TODO
        //private static readonly Queue<Action<object>> _executionQueue1 = new Queue<Action<object>>();
        //private static readonly Queue<Action<object, object>> _executionQueue2 = new Queue<Action<object, object>>();

        private void Exceptions_OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            foreach (var newItem in e.NewItems)
            {
                var item = newItem as Exception;
                Debug.LogError(item);
            }
        }

        public void Update()
        {
            while (_executionQueue.Count > 0)
            {
                if (_executionQueue.TryDequeue(out var act))
                    act.Invoke();
            }
        }

        /// <summary>
        /// Locks the queue and adds the IEnumerator to the queue
        /// </summary>
        /// <param name="action">IEnumerator function that will be executed from the main thread.</param>
        public void Enqueue(Action action)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(ActionWrapper(action));
            });
        }

        public void Enqueue(EnumeratorJobWrapper job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        public void Enqueue(JobWrapper job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        public void Enqueue(JobWrapper<object> job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        public void Enqueue<T>(JobWrapper<T> job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        public void Enqueue<T1, TTResult>(JobWrapper<T1, TTResult> job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        public void Enqueue<T>(JobEnumeratorWrapper<T> job)
        {
            _executionQueue.Enqueue(() =>
            {
                StartCoroutine(JobWrapper(job));
            });
        }

        /// <summary>
        /// Locks the queue and adds the Action to the queue
        /// </summary>
        /// <param name="action">function that will be executed from the main thread.</param>
        public void Invoke(Action action)
        {
            Enqueue(action);
        }

        // Alias for Enqueue
        public void Invoke(EnumeratorJobWrapper job)
        {
            Enqueue(job);
        }

        public void Invoke(JobWrapper job)
        {
            Enqueue(job);
        }

        public void Invoke(JobWrapper<object> job)
        {
            Enqueue(job);
        }

        public void Invoke<T>(JobWrapper<T> job)
        {
            Enqueue(job);
        }

        public void Invoke<T1, TResult>(JobWrapper<T1, TResult> job)
        {
            Enqueue(job);
        }

        /// <summary>
        /// Locks the queue and adds the Action to the queue, returning a Task which is completed when the action completes
        /// </summary>
        /// <param name="action">function that will be executed from the main thread.</param>
        /// <returns>A Task that can be awaited until the action completes</returns>
        public Task EnqueueAsync(Action action)
        {
            var tcs = new TaskCompletionSource<bool>();

            void WrappedAction()
            {
                try
                {
                    action();
                    tcs.TrySetResult(true);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            }

            Enqueue(WrappedAction);
            return tcs.Task;
        }

        private IEnumerator ActionWrapper(Action a)
        {
            a();
            yield return null;
        }

        private IEnumerator JobWrapper(EnumeratorJobWrapper wrap)
        {
            var enumerator = wrap.Callback;
            while (enumerator.MoveNext())
            {
                object obj = null;
                bool isException = false;
                try
                {
                    obj = enumerator.Current;
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                    isException = true;
                }

                if (!isException)
                    yield return obj;
                else
                    yield break;
            }

            wrap.Finished.Set();
        }

        private IEnumerator JobWrapper(JobWrapper wrap)
        {
            try
            {
                wrap.Callback();
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                //Exceptions.Add(ex);
            }

            yield return null;
            wrap.Finished.Set();
        }

        private IEnumerator JobWrapper(JobWrapper<object> wrap)
        {
            object result = null;
            try
            {
                wrap.Job.Invoke(out result);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                //Exceptions.Add(ex);
            }

            wrap.Result = result;
            yield return null;
            wrap.Finished.Set();
        }

        private IEnumerator JobWrapper<T>(JobWrapper<T> wrap)
        {
            T result = default;
            try
            {
                wrap.Job.Invoke(out result);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                //Exceptions.Add(ex);
            }

            wrap.Result = result;
            yield return null;
            wrap.Finished.Set();
        }

        private IEnumerator JobWrapper<T1, TResult>(JobWrapper<T1, TResult> wrap)
        {
            TResult result = default;
            try
            {
                wrap.Job.Invoke(wrap.Value, out result);
            }
            catch (Exception ex)
            {
                Debug.LogException(ex);
                //Exceptions.Add(ex);
            }

            wrap.Result = result;
            yield return null;
            wrap.Finished.Set();
        }

        private IEnumerator JobWrapper<T>(JobEnumeratorWrapper<T> wrap)
        {
            var enumerator = wrap.Job.Invoke(out var result);
            while (enumerator.MoveNext()) yield return null;
            wrap.Result = result;
            wrap.Finished.Set();
        }

        private static UnityDispatcher _instance;

        public static UnityDispatcher Instance
        {
            get
            {
                if (_instance == null)
                {
                    try
                    {
                        // Search for existing instance.
                        _instance = (UnityDispatcher)FindObjectOfType(typeof(UnityDispatcher));

                        // Create new instance if one doesn't already exist.
                        if (_instance == null)
                        {
                            // Need to create a new GameObject to attach the singleton to.
                            var singletonObject = new GameObject();
                            _instance = singletonObject.AddComponent<UnityDispatcher>();
                            singletonObject.name = $"{nameof(UnityDispatcher)} (Singleton)";

                            //((MonoSingleton<T>)_instance).IsStarted = false;

                            // Make instance persistent.

                            if (Application.isPlaying) DontDestroyOnLoad(singletonObject);
                        }
                    }
                    catch
                    {
                        // This is not thread safe
                        throw new Exception(
                            "UnityMainThreadDispatcher could not find the UnityMainThreadDispatcher object. Please ensure you have added the MainThreadExecutor Prefab to your scene.");
                    }
                }

                return _instance;
            }
        }

        private void Awake()
        {
            Exceptions.CollectionChanged += Exceptions_OnCollectionChanged;

            if (_instance == null)
            {
                _instance = this;
                DontDestroyOnLoad(this.gameObject);
            }
        }

        private void OnDestroy()
        {
            _instance = null;
        }
    }
}

Where the JobWrapper class is this:

using System;
using System.Collections;
using System.Threading;

namespace DepotToolkit.Utils
{
    public class EnumeratorJobWrapper
    {
        public IEnumerator Callback { get; }
        public ManualResetEvent Finished { get; }

        private EnumeratorJobWrapper()
        {
        }

        public EnumeratorJobWrapper(IEnumerator callback, ManualResetEvent finished)
        {
            Callback = callback;
            Finished = finished;
        }
    }

    public class JobWrapper
    {
        public Action Callback { get; }
        public ManualResetEvent Finished { get; }

        private JobWrapper()
        {
        }

        public JobWrapper(Action callback, ManualResetEvent finished)
        {
            Callback = callback;
            Finished = finished;
        }
    }

    public class JobWrapper<T>
    {
        public delegate void DelegateJob(out T result);

        public DelegateJob Job { get; }
        public ManualResetEvent Finished { get; }
        public T Result { get; set; }

        private JobWrapper()
        {
        }

        public JobWrapper(DelegateJob job, ManualResetEvent finished)
        {
            Job = job;
            Finished = finished;
        }
    }

    public class JobWrapper<T1, TResult>
    {
        public delegate void DelegateJob(T1 t1, out TResult result);

        public DelegateJob Job { get; }
        public ManualResetEvent Finished { get; }
        public T1 Value { get; }
        public TResult Result { get; set; }

        private JobWrapper()
        {
        }

        public JobWrapper(T1 value, DelegateJob job, ManualResetEvent finished)
        {
            Value = value;
            Job = job;
            Finished = finished;
        }
    }
}

An example of what I’m doing:

using System;
using System.Threading;
using DepotToolkit.Utils;
using UnityEngine;
using UnityEngine.Core;
using Object = UnityEngine.Object;

namespace DepotToolkit.CommonCode
{
    public static class ThreadSafeUtils
    {
        internal class ThreadChecker : MonoSingleton<ThreadChecker>
        {
            public Thread UnityThread { get; private set; }

            private void Awake()
            {
                UnityThread = Thread.CurrentThread;
            }
        }

        public static bool IsMainThread => Thread.CurrentThread.Equals(ThreadChecker.Instance.UnityThread);

        public static T() ThreadSafe_GetComponentsInChildren<T>(this GameObject obj)
        {
            if (IsMainThread)
                return obj.GetComponentsInChildren<T>();

            var mre = new ManualResetEvent(false);
            var job = new JobWrapper<GameObject, T()>(obj, Impl_GetComponentsInChildren, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
        }

        private static void Impl_GetComponentsInChildren<T>(GameObject obj, out T() result)
        {
            result = obj.GetComponentsInChildren<T>();
        }

        // Object.Instantiate

        public static GameObject Instantiate(GameObject obj)
        {
            if (IsMainThread)
                return Object.Instantiate(obj);

            var mre = new ManualResetEvent(false);
            var job = new JobWrapper<GameObject, GameObject>(obj, Impl_Instantiate, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
        }

        private static void Impl_Instantiate(GameObject obj, out GameObject result)
        {
            result = Object.Instantiate(obj);
        }
    }
}

As you can see I’m checking If I’m in the current thread by creating a MonoSingleton instance of a MonoBehaviour:

using System;
using System.Threading;
using DepotToolkit.Utils;
using uzLib.Lite.ExternalCode.Extensions;
using uzSourceToolkit.ThirdParty.uSrcTools.Extensions;

namespace UnityEngine.Core
{
#if UNITY_2020 || UNITY_2019 || UNITY_2018 || UNITY_2017 || UNITY_5

    /// <summary>
    ///     Inherit from this base class to create a singleton.
    ///     e.g. public class MyClassName : Singleton<MyClassName> {}
    /// </summary>
    public class MonoSingleton<T> : MonoBehaviour // , IStarted
        where T : MonoBehaviour
    {
        // Check to see if we're about to be destroyed.
        private static bool m_ShuttingDown;

        private static readonly object m_Lock = new object();
        protected static T m_Instance;

        /// <summary>
        ///     Access singleton instance through this propriety.
        /// </summary>
        public static T Instance
        {
            get
            {
                if (m_ShuttingDown)
                {
                    // FIX: Shutting down takes affect after playing a scene, this makes (ie) SteamWorkshopWrapper unavailable on Editor
                    // (check for ExecuteInEditrMode attribute, if available, shutthing down shuld not be performed)
                    // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                    //                    if (MonoSingletonSettings.ShowWarning)
                    //#pragma warning disable 162
                    //                        // ReSharper disable once HeuristicUnreachableCode
                    //                        Debug.LogWarning("(Singleton) Instance '" + typeof(T) +
                    //                                     "' already destroyed. Returning null.");
                    //#pragma warning restore 162
                    return null;
                }

                lock (m_Lock)
                {
                    if (m_Instance == null)
                    {
                        // Search for existing instance.
                        try
                        {
                            m_Instance = (T)FindObjectOfType(typeof(T));
                        }
                        catch (UnityException)
                        {
                            // Call with the Dispatcher...

                            var mre = new ManualResetEvent(false);
                            var job = new JobWrapper<T>(Impl_GetInstance, mre);
                            UnityDispatcher.Instance.Invoke(job);
                            mre.WaitOne();
                            m_Instance = job.Result;
                        }

                        // Create new instance if one doesn't already exist.
                        if (m_Instance == null)
                        {
                            // Need to create a new GameObject to attach the singleton to.
                            try
                            {
                                var singletonObject = new GameObject();
                                m_Instance = singletonObject.AddComponent<T>();
                                singletonObject.name = typeof(T).Name + " (Singleton)";

                                //((MonoSingleton<T>)m_Instance).IsStarted = false;

                                // Make instance persistent.
                                if (IsPlaying()) DoAction(() => DontDestroyOnLoad(singletonObject)); // TODO
                            }
                            catch (UnityException)
                            {
                                var singletonObject = CreateGameObject();
                                m_Instance = AddComponent<T>(singletonObject);
                                DoAction(() => singletonObject.name = typeof(T).Name + " (Singleton)");
                            }
                        }
                    }

                    return m_Instance;
                }
            }
            protected set => m_Instance = value;
        }

        private static void Impl_GetInstance(out T result)
        {
            result = (T)FindObjectOfType(typeof(T));
        }

        private static void Impl_CreateInstance(out GameObject obj)
        {
            obj = new GameObject();
        }

        private static void Impl_IsPlaying(out bool result)
        {
            result = Application.isPlaying;
        }

        private static void Impl_AddComponent<TMethod>(GameObject obj, out TMethod result)
            where TMethod : Component
        {
            result = obj.AddComponent<TMethod>();
        }

        private static GameObject CreateGameObject()
        {
            var mre = new ManualResetEvent(false);
            var job = new JobWrapper<GameObject>(Impl_CreateInstance, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
        }

        private static TMethod AddComponent<TMethod>(GameObject gameObject)
            where TMethod : Component
        {
            var mre = new ManualResetEvent(false);
            var job = new JobWrapper<GameObject, TMethod>(gameObject, Impl_AddComponent, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
        }

        private static void DoAction(Action action)
        {
            var mre = new ManualResetEvent(false);
            var job = new JobWrapper(action, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
        }

        private static bool IsPlaying()
        {
            var mre = new ManualResetEvent(false);
            var job = new JobWrapper<bool>(Impl_IsPlaying, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
        }

        public bool ExecuteInEditMode => GetType().IsExecutingInEditMode();

        public bool IsStarted { get; set; }

        public static T Create()
        {
            var go = new GameObject(typeof(T).Name);
            return go.GetOrAddComponent<T>();
        }

        private void OnApplicationQuit()
        {
            if (!ExecuteInEditMode) m_ShuttingDown = true;
        }

        private void OnDestroy()
        {
            if (!ExecuteInEditMode) m_ShuttingDown = true;
        }
    }

#endif
}

As you can see, the MonoSingleton class is already protected from external thread calls by using try/catch blocks with UnityExceptions.

My main three concerns about my implementation are the following:

  • I’m not able to figure out how to make easier the implementation of the JobWrapper, as you can see every time I need to create a thread-safe method I use the following four lines that are repeated lots and lots of times:
var mre = new ManualResetEvent(false);
            var job = new JobWrapper<GameObject, T()>(obj, Impl_GetComponentsInChildren, mre);
            UnityDispatcher.Instance.Invoke(job);
            mre.WaitOne();
            return job.Result;
  • On the attached code from above you can see Impl_GetComponentsInChildren which is the alias for doing this simple thing (THAT IS EXECUTED ON THE UNITY THREAD):
private static void Impl_GetComponentsInChildren<T>(GameObject obj, out T() result)
        {
            result = obj.GetComponentsInChildren<T>();
        }

My question here is there a nicer way to do this?

  • Has my Unity Dispatcher a good design on the memory / CPU usage part? I mean, this will be called lots and lots of times and I didn’t benchmark this yet. So, can you suggest to me something lighter or a tip to keep in mind on this topic?

notepad++ – Is there a way to break lines that match a string pattern, but only if that pattern falls between matching strings?

I’m using the code below to break lines that match a pattern:

Find what: ((0-9)) ((A-Z))
Replace with: 1n2

so that …

Super Bowl 3,1:56.2 Armbro Goal 3,1:54.3

… becomes

Super Bowl 3,1:56.2 
Armbro Goal 3,1:54.3

But I have to do it manually because I have tens of thousands of lines and if I use Replace All it will break lines in areas I do not want broken.

Specifically, I want to break lines that match the pattern in areas that lie between “zyxl” and “1st Dam”, but not break any lines with matching patterns between “1st Dam” and “zyxl”

The following code will find the areas where I want lines broken:
(?s)^tzyxl(.|rn)?1st Dam

And this code will find areas where I don’t want code broken:
(?s)^t1st Dam (.|rn)?zyxl

Is there a way, either by combining these methods, or otherwise, to rearrange the text so that …

zyxl
QUEENB BLUE CHIP  
Super Bowl 3,1:56.2 Armbro Goal 3,1:54.3 Grassbed 2,1:59.1  
1st Dam 
RICHESSE OBLIGE Varenne. 13 wins, 2 thru 5. This is her first foal. 
zyxl

VENERATE 
Super Bowl 3,1:56.2 Armbro Goal 3,1:54.3 Grassbed 2,1:59.1  
1st Dam RICHESSE OBLIGE 13 wins, 2 thru 5. This is her first foal. 
Zyxl

… becomes

zyxl
QUEENB BLUE CHIP  
Super Bowl 3,1:56.2
Armbro Goal 3,1:54.3
Grassbed 2,1:59.1  
1st Dam 
RICHESSE OBLIGE Varenne. 13 wins, 2 thru 5. This is her first foal. 
zyxl

VENERATE 
Super Bowl 3,1:56.2
Armbro Goal 3,1:54.3
Grassbed 2,1:59.1  
1st Dam RICHESSE OBLIGE 13 wins, 2 thru 5. This is her first foal. 
zyxl

And yes, “1st Dam” sometimes begins a long line, and sometimes it is the only text on a line, but it always precedes the area that I need untouched by line breaks (followed by “zyxl”).

Thank you in advance for your time and assistance.

20.04 – Kubuntu 20.08 randomly lock screen without specific pattern

The problem I’m facing is that my Kubuntu 20.04 does randomly lock screen. At this moment I could found any pattern to explain the random lock screen. This has been happening in my computer for 2 months when I had Kubuntu 18.04 and it’s still happening despite I’ve upgraded to 20.04 (thought that upgrading the dist could solve it).
Lock, Log out and Switch User works perfectly, meaninig that after a randomly lock I can log in again without problem and all the programs still open.
I’ve dual boot Kubuntu and Window 10 and I can confirm that this does not happen in Windows, so I discard a hardware problem. ¿Any command to know which process are interfering wiht my lock screen?

KR,

Maxi

forms – UX pattern for implementing calendars

In my recent development I am required to implement a calendar view which is having month view for each month for given date range. See below.

enter image description here

I have already done the programming part. It is required allows users to select all Sundays, all Mondays, all Tues days etc.. The existing swing UI like this. (Hope this will help to get an idea) see below.

enter image description here

As you can see both Sundays and Tues check boxes are selected and marked in calendar as well. Calendar days are are not clickable and only the check boxes can be selected.

Pure idea is to allow users to selected week/end days and see them on calendar view. Calendar days are not clickable. First thought came to mind is implementing the same behavior as given above for web UI as well.

Hope you all thoughts on this.

Thanks
Nuwan

proof writing – Is pattern matching an appropriate way to show that two infinite series are equal?

I want to show that

$$e^{a}e^{b} = e^{(a+b)}$$ using their infinite series representation ${displaystyle exp x:=sum _{k=0}^{infty }{frac {x^{k}}{k!}}=1+x+{frac {x^{2}}{2}}+{frac {x^{3}}{6}}+{frac {x^{4}}{24}}+cdots }$

“Proof”:

LHS $= (1+ a + a^2/2! + ldots) (1+b + b^2/2! + ldots) = (1 + a + b + a^2/2! + b^2/2! + ab + ldots) $

RHS $= (1 + a+b + (a+b)^2/2! + ldots ) = (1+ a + b + a^2/2! + b^2/2! + ab + ldots)$

These terms seem to match up, so that LHS = RHS.

Can anyone offer a critique to the above method?

python – Reverse for ‘user_edit’ not found. ‘user_edit’ is not a valid view function or pattern name

I’ve been stuck on this for a while, can’t seem to fix the error. I’ve checked the code a hundred times but obviously there is something I’m missing. I have installed my app also.

I created CRUD operations for User with 3 buttons: Details, Edit and Delete. The second 2 works exactly how it should be, but the first one ‘Details’ gives me this error: NoReverseMatch at /users/details/1
Reverse for ‘user_edit’ not found. ‘user_edit’ is not a valid view function or pattern name.
I’m trying to render user_details function, and I can’t find why gives me user_edit error message.

Can anybody see what I’m missing?

views.py

def user_details(request, id=None):
    context = {}
    context('user') = get_object_or_404(User, id=id)
    return render(request, 'userdetails.html', context)

def user_add(request):
    context = {}
    if request.method == 'POST':
        u = user_form = UserForm(request.POST)
        context('user_form') = user_form
        if user_form.is_valid():
            user_form.save()
            return HttpResponseRedirect(reverse('feedback:users'))
        else:
            return render(request, 'useradd.html', context)
    else:
        user_form = UserForm()
        context('user_form') = user_form
        return render(request, 'useradd.html', context)

def user_edit(request, id=None):
    context = {}
    user = get_object_or_404(User, id=id)
    if request.method == 'POST':
        user_form = UserForm(request.POST, instance=user)
        context('user_form') = user_form
        if user_form.is_valid():
            user_form.save()
            return HttpResponseRedirect(reverse('feedback:users'))
        else:
            return render(request, 'useredit.html', context)
    else:
        user_form = UserForm(instance=user)
        context('user_form') = user_form
        return render(request, 'useredit.html', context)

def user_delete(request, id=None):
    context = {}
    return render(request, 'userdelete.html', context)

urls.py

path('users/', views.users, name="users"),
path('users/add', views.user_add, name="useradd"),
path('users/details/<int:id>', views.user_details, name="userdetails"),
path('users/edit/<int:id>', views.user_edit, name="useredit"),
path('users/delete/<int:id>', views.user_delete, name="userdelete"),

users.html (basicaly my index page for the CRUD navigation)

{% extends 'main.html' %}

{% block content%}

    <h1>Users</h1>
    <a href="http://stackoverflow.com/users/add">Add user</a>
    <h2>List of {{title}} </h2>
    {% if users %}
        <ul>
            {% for user in users %}
                <li>
                    {{user.first_name}} &nbsp; {{user.last_name}}
                    <td class="text-center">
                        <a class="btn btn-primary float-center" href="{% url 'feedback:userdetails' user.id %}">Details</a>
                        <a class="btn btn-warning float-center" href="{% url 'feedback:useredit' user.id %}">Edit</a>
                        <a class="btn btn-danger float-center" href="{% url 'feedback:userdelete' user.id %}">Delete</a>
                    </td>
                </li>
            {% endfor %}
        </ul>
        {% else %}
            <p>There is no users available</p>
        {% endif %}
{% endblock content %}

php – Learning factory design pattern

I’m making the very common example of Factory design pattern which creates a factory of cars and return an instance of a car. I found a example here https://refactoring.guru/design-patterns/factory-method/php/example and decided to make my own factory. My question is why do I need a Creator for each car?

<?php


interface Car
{
    public function drive();
} 
<?php
require_once('Car.php');

class Audi implements Car
{
    public function drive()
    {
        return "driving an Audi";
    }
}
<?php
require_once('Car.php');

class Mercedes implements Car
{

    public function drive()
    {
       return "driving an Mercedes";
    }
}
<?php


abstract class CarFactory
{
    abstract public function factoryMethod(): Car;

    public function someOperation(): string
    {
        // Call the factory method to create a Product object.
        $product = $this->factoryMethod();
        // Now, use the product.
        $result = "I want to drive something..... " .
            $product->drive();

        return $result;
    }
}
<?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Audi.php');

class AudiCreator extends CarFactory
{

    public function factoryMethod(): Car
    {
        return new Audi();
    }
}
<?php
require_once('CarFactory.php');
require_once('Car.php');
require_once('Mercedes.php');

class MercedesCreator extends CarFactory
{

    public function factoryMethod(): Car
    {
       return new Mercedes();
    }
}
<?php

require_once('car/AudiCreator.php');
require_once('car/MercedesCreator.php');

function clientCode(CarFactory $carFactory)
{
    // ...
    echo "Client: "
        . $carFactory->someOperation();
    // ...
}

echo "The client . <br>";
clientCode(new AudiCreator());
echo "rn";
echo  "<br>";
echo  "<br>";

clientCode(new MercedesCreator());

react.js – React state management design pattern new approach thoughts

Hey people on the internet!

I do not know where to share my new npm package so I am asking you do you know of a good place to share my package?

Also I would really appreciate if you take a look on it and give me your honest opinion on it react-spear

In short the goal of this package is to make state management more appealing then redux/MobX.
It uses an object of store that contains Subjects that can subscribe to global value change and synchronize with local state.

I have made an effort to contribute to the developers community with this package and I hope it is a good one.

Please share with me your thoughts

If you have a counter like this:

src/Counter.(jsx/tsx)

import React from 'react';
import { Down } from './Down';
import { Up } from './Up';
import { Display } from './Display';

export const Counter = () => {
  return (
    <div>
      <Up />
      <Down />
      <Display />
    </div>
  );
};

That takes an Up and Down buttons compnent that needs to share their state.
You will have a store like this:

src/store.(js/ts)

import { Subject } from 'react-spear';

export const Store = {
  counter: new Subject(0),
  // You can add Some other values here to the store,
  // and even an entire Store object to be nested here, whatever you want.
};

The Down and Up components should look like this:

src/Up.(jsx/tsx)

import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';

export const Up = () => {
  const count = useSensable(Store.counter);
  return <button onClick={() => Store.counter.broadcast(count + 1)}>Up {count}</button>;
};

src/Down.(jsx/tsx)

import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';

export const Down = () => {
  const count = useSensable(Store.counter);
  return <button onClick={() => Store.counter.broadcast(count - 1)}>Down {count}</button>;
};

And the Display component will look loke this:

src/Display.(jsx/tsx)

import React from 'react';
import { useSensable } from 'react-spear';
import { Store } from './store';

export const Display = () => {
  const count = useSensable(Store.counter);
  return (
    <div>
      <div>Count is {count}</div>
    </div>
  );
};

Explanation

  • When creating the store you are creating a subscribable object that can listen to changes.

  • When using the broadcast method(you can help me think other names if you don’t like this one),
    you emit the next value of the state, actualy like setState but globally.

  • Then with the useSensable hook you are sensing the changes from the store(listening to broadcast event of that specific subject).
    Inside it uses useState to manage the update of the incoming new value,
    and useEffect to manage subscription to that value.

  • So everytime you broadcast a new value every component that consume that value via useSensable
    are getting rerendered with the new value.

Hope it make sense because it does to me.