#StackBounty: #c# #design-patterns Anemic class that binds functionality

Bounty: 100

I have cleanly separated functionality of a message bus – namely the diagnostics (optional), sending, decoding and the bus driver, I need to now bind this together and have done so with a MessageBus class.

It feels anemic though, with a lot of pass through methods.

On the flip side it is necessary for coordinating StartAsync() which links dependencies on the driver and receiver (binding them so they can call back) – I saw no other way of achieving this if I registered all individual interfaces via an inversion of control container as it would get out of sync (how to bind the driver to the decoder for instance).

If this is the wrong place for comments on code please let me know and I will remove straight away. Any pointers much appreciated.

public class MessageBus : IDisposable
{
    private readonly MessageBusReceiver receiver;
    private readonly MessageBusPublisher publisher;
    private readonly IMessageBusDriver driver;
    private int isRunning;
    private readonly MessageBusDiagnostics diagnostics = null;

    public MessageBus(IMessageBusDriver driver, SerializerRegistry serializerRegistry, ITypeIdentifier typeIdentifier, ILoggerFactory loggerFactory, bool isDebug = false)
    {
        this.driver = driver;
        this.publisher = new MessageBusPublisher(serializerRegistry, driver, typeIdentifier);
        this.receiver = new MessageBusReceiver(serializerRegistry, typeIdentifier, loggerFactory.CreateLogger<MessageBusReceiver>());
        if (isDebug)
            diagnostics = new MessageBusDiagnostics(driver, loggerFactory.CreateLogger<MessageBusDiagnostics>());
    }

    void AssertIsRunning()
    {
        if (this.isRunning == 0)
            throw new InvalidOperationException($"{nameof(StartAsync)} must be called before calling other methods.");
    }

    public async Task SubscribeAsync(string topic, QualityOfService qos, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.driver.SubscribeAsync(topic, qos, null, null, null, cancellationToken);
    }

    public async Task UnsubscribeAsync(string topic, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.driver.UnsubscribeAsync(topic, cancellationToken);
    }

    public async Task StartAsync(Func<object, Task> receiveApplicationMessage)
    {
        if (Interlocked.CompareExchange(ref this.isRunning, 1, 0) == 1)
            throw new InvalidOperationException("Already running.");

        this.receiver.OnMessageDecoded = receiveApplicationMessage;
        await this.driver.StartAsync(this.receiver.ReceiveMessageFromMessageBusDriver);
    }

    public async Task StopAsync()
    {
        if (Interlocked.CompareExchange(ref this.isRunning, 0, 1) == 0)
            throw new InvalidOperationException("Not running.");

        await this.driver.StopAsync();
    }

    public async Task PublishAsync(object notification, string busPath, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.publisher.PublishAsync(notification, busPath, qos, cancellationToken);
    }

    public async Task PublishAsync(object notification, Dictionary<string, string[]> pathTokens = null, QualityOfService qos = QualityOfService.AtMostOnce, CancellationToken cancellationToken = default)
    {
        AssertIsRunning();
        await this.publisher.PublishAsync(notification, pathTokens, qos, cancellationToken);
    }

    public void Dispose()
    {
        this.driver.Dispose();
        this.diagnostics?.Dispose();
    }
}


Get this bounty!!!

#StackBounty: #python #object-oriented #design-patterns #flask Python: separation of concern User Model and User DB

Bounty: 150

I am working on a small side-project since a couple of weeks, I am using Flask but trying to use as few libraries as possible and no ORMs (for learning purposes.

I am currently working on the User service on my application and currently stuck in the registration email confirmation part regarding my design.

Since I am not using any ORM, I wrote those classes:

  • UserRepository: interact with the user table in the database (add, get, delete user and save)
  • UserService: actions on a User (registration, deactivate user, update stats)
  • User: representation of a User entity, no methods, methods are in the UserService (most of them take a User as a parameter expect the one to create a new User)

Current issue:

When a new user register, I send a registration email with a URL link to activate the account. I am using URLSafeTimedSerializer to do that and dump the user.email to generate the account confirmation URL.
The email is sent and when the user click on the link, I am able to decrypt the user.email using URLSafeTimedSerializer.loads(). But with my current design, I am not quite confident how I am going to retrieve the user.email. Maybe the UserService class should take the UserRepository as an argument?

user/views.py

user = Blueprint('user', __name__, template_folder='templates')

# ----------
# STUCK HERE 
# ----------
@user.route('/activate/<activation_token>', methods=["GET"])
def activate(activation_token):
    private_key = current_app.config['SECRET_KEY']
    s = URLSafeTimedSerializer(private_key)
    user_email = s.loads(activation_token)
    # now I need to check if that user is already confirmed, if not I have to change current User confirmed value from from False to True
    # I should probably create a new UserService instance and create a method get_user_by_email(email) ?

   def generate_registration_token(email):
    private_key = current_app.config['SECRET_KEY']
    s = URLSafeTimedSerializer(private_key)
    u = s.dumps(email)
    return u

def send_registration_email(email):
    from prepsmarter.blueprints.user.tasks import deliver_contact_email
    token = generate_registration_token(email)
    host = current_app.config['HOST']
    activation_url = f"{host}/activate/{token}"
    try:
        deliver_contact_email(email, activation_url)
        return "ok"
    except Exception as e:
        return str(e)
    
@user.route('/register')
def login():
    return render_template('register.html')

@user.route('/new-user',methods = ['POST'])
def register_user():
    form_email = request.form.get('email')
    form_password = request.form.get('psw')
    form_password_repeat = request.form.get('psw-repeat')
    registration_form = RegistrationForm(form_email, form_password, form_password_repeat).validate_registration()
    if registration_form:
        new_user = UserService().register_user(form_email, form_password)
        user_repository = UserRepository(conn, 'users')
        user_repository.add_user(new_user)
        user_repository.save()
        send_registration_email(new_user.email)
        return "new user created" #will probably change return statements later on
    return "new uer not created" #will probably change return statements later on

user/models.py (User class)

class User():
    def __init__(self, email, password, registration_date, active, sign_in_count, current_sign_in_on, last_sign_in_on):
        self.email = email
        self.password = password
        self.registration_date = registration_date
        self.active = active
        self.confirmed = False

user/services.py (UserRepository)

class UserRepository():
    def __init__(self, conn, table):
        self.conn = conn
        self.table = table  
    
    #select exists(select 1 from users where email='pamousset75@gmail.com')
    def add_user(self, user):
        sql = "INSERT INTO users (email, password, is_active, sign_in_count, current_sign_in_on, last_sign_in_on) VALUES (%s, %s, %s, %s, %s, %s)"
        cursor = self.conn.cursor()
        # the is_active column in the DB is a tinyint(1). True = 1 and False = 0
        if user.active == True:
            is_active = 1
        is_active = 0
        cursor.execute(sql, ( user.email, user.password, is_active, user.sign_in_count, user.current_sign_in_on, user.last_sign_in_on))
        resp = cursor.fetchall()
        return resp
    
    def delete_user(self):
        return ""
    
    def get_user(self):
        return ""
    
    def save(self):
        self.conn.commit()
    

user/services.py (UserService)

class UserService():

def register_user(self,
                  email,
                  password):
    sign_in_count = 1
    today_date = datetime.today().strftime('%Y-%m-%d')
    active = True
    new_user = User(email, password, today_date, active,
                    sign_in_count, today_date, today_date)
    return new_user        

def desactivate_user(self, User):
    if User.active == False:
        print(f"User {User.email} is already inactive")
    User.active = False

def reactive_user(self, User):
    if User.active == True:
        print(f"User {User.email} is already active")
    User.active = True

def is_active(self, User):
    return User.is_active


Get this bounty!!!

#StackBounty: #php #design-patterns Return payload in service layer

Bounty: 50

In my project I am using the ADR architecture, a branch of MVC.

In my actions (Controllers) I handle only data that comes from the request.

When there is a business rule that defines which status code I return, I do this treatment in my service.

Imagine this scenario:

When editing a user, I check if the user’s email already exists, if it exists, I return an error informed to your message. This treatment is done in the service, and in these cases I get the error in it.

I would like to hear from you about my approach to, in some cases, the service layer returning the payload.

Action:

class CreateUserAction extends Action
{
    private $userService;


    /**
     * @param UserService $userService
     */
    public function __construct(UserService $userService)
    {
        $this->userService = $userService;
    }

    public function handle(Request $request) : JsonResponse
    {
        $data = $request->getData();

        $payload = $this->userService->create($data, $user);

        return response()->json($payload->body, $payload->statusCode);
    }
}

Service:

class UserService extends BaseService
{
    private $userRepository;

    public function __construct(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function create(array $data) : object
    {
        if ($this->userRepository->findByEmail($data['email'])) {
            $this->setPayloadError(
                __('messages.user.contributor_email_already_exists'),
                Response::HTTP_BAD_REQUEST
            );
            return $this->getPayload();
        }
        
        $userCreated = $this->userRepository->create($data);

        $this->setPayload($userCreated, Response::HTTP_CREATED);
        return $this->getPayload();

    }
}
```


Get this bounty!!!

#StackBounty: #c++ #object-oriented #c++11 #design-patterns #sfml Resource management classes in C++ game

Bounty: 50

This is a part of simple sfml C++ game, but I think neither the library nor the language is that much crucial here. I am mainly worried about the design.

I have a class template ResourceHolder<Key, Resource> to hold one type of Resource such as texture or sound, inside a map. A key is usually an enum but can be anything.

I also have a class ResourceManager that keeps all available ResourceHolders in one place.

A simplified class diagram:

enter image description here

I am providing the full code for those classes:

ResourceHolder.h:

template <typename Key, typename Resource>
class ResourceHolder {
public:
    explicit ResourceHolder(std::string resourcesDir = "../resources/")
            : resourcesDir{std::move(resourcesDir)}
    {}

    template <typename... Args>
    void insert(const Key& key, Args&&... args) {
        auto resPtr = std::make_unique<Resource>();
        if (!resPtr->loadFromFile(resourcesDir + std::forward<Args>(args)...)) {
            msgErrorLoading(std::forward<Args>(args)...);
            ///* todo: should I e.g. "throw ErrorLoadingResource" here? */
        }
        resources.emplace(key, std::move(resPtr));
    }

    Resource& get(const Key& key) const {
        if (auto resource = resources.find(key); resource != std::end(resources)) {
            return *(resource->second);
        } throw std::invalid_argument{"No such resource id."};
    }

    void erase(const Key& key) noexcept {
        if (auto found = resources.find(key); found != std::end(resources)) {
            resources.erase(key);
        }
    }

    void eraseAll() {
        resources.clear();
    }

private:
    std::string resourcesDir;
    std::unordered_map<Key, std::unique_ptr<Resource>> resources;

public:
    template <typename... Args>
    ResourceHolder& operator+=(const ResourceInserter<Key, Args...>& inserter) {
        insert(std::move(inserter.key), std::move(std::get<Args>(inserter.args)...));
        return *this;
    }

    inline const Resource& operator[](const Key& key) const {
        return get(std::move(key));
    }

    inline Resource& operator[](const Key& key) {
        return get(std::move(key));
    }

    auto& getResources() const {
        return resources;
    }

    auto& getResourcesDir() const {
        return resourcesDir;
    }

    void setResourcesDir(std::string newPath) {
        resourcesDir = std::move(newPath);
    }

private:
    template <typename... Args>
    void msgErrorLoading(const Args... args) {
         std::cerr << "Failed loading resource: { Type: "" << typeid(Resource).name()<< "", File name: "";
        (std::cerr << ... << args) << "" }" << std::endl;
    }
};

ResourceManager.h:

class ResourceManager {
public:
    ResourceManager();

private:
    ResourceHolder<res::Texture, sf::Texture> textures;
    ResourceHolder<res::Sound, sf::SoundBuffer> sounds{"../resources/sound/"};

    void loadTextures();
    void loadSounds();

public:
    auto& getTextures() {
        return textures;
    }

    auto& getSounds() {
        return sounds;
    }
};

ResourceManager.cpp:

ResourceManager::ResourceManager() {
    loadTextures();
    loadSounds();
}

void ResourceManager::loadTextures() {
    textures.insert(res::Texture::Wizard, "wizard.png");
    textures.insert(res::Texture::Gray,   "gray.png");
    textures.insert(res::Texture::Orange, "orange.png");
}

void ResourceManager::loadSounds() {
    sounds += ResourceInserter(res::Sound::Bullet, "boing.wav");
    sounds += ResourceInserter(res::Sound::Bing,   "boing_long.wav");
    sounds += ResourceInserter(res::Sound::Poof,   "poof.wav");
}

ResourceInserter.h:

/** Operator += must take one argument
 *  This is a proxy class for operator+=
 *  You can use operator+= instead of insert() as an alternative insertion method
 */

template <typename Key, typename... Args>
class ResourceInserter {
public:
    explicit ResourceInserter(Key&& key, Args&&... args)
            : key{std::forward<Key>(key)}
            , args{std::forward<Args>(args)...}
    {}

    Key key;
    std::tuple<Args...> args;
};

template <typename T, typename... Args>
ResourceInserter(T&&, Args&&... args) -> ResourceInserter<T, Args...>;

Resources.h

namespace res {
    enum class Texture {
        Gray,
        Orange,
        Wizard
    };

    enum class Sound {
        Bullet,
        Poof,
        Bing
    };
}

Some basic usage (inside parent/caller/owner class):

auto wizardTexture = textures.get(res::Texture::Wizard);
auto bulletSound   = sounds[res::Sound::Bullet];

I am not asking for a deep-throughout review as I imagine it’d take too much off of your time.


I have few questions, answering any of them would be absolutely helpful.

  1. Whatever you think of that looks smelly or problematic, please do let me know.
  2. What’s wrong with my design from OOP/design patterns point of view? (I am especially worried about the part where I am inserting all the resources inside ResourceManager.cpp)
  3. What’s wrong with my code from C++ point of view? (I am especially interested in parts where I attempted using move semantics/perfect forwarding e.g. insert method or operator+=)
  4. Is there something confusing related to naming identifiers?

The reason why I am using enums as keys is that it works as a sort of connection interface for both insertion and then retrieval of the resource. If I insert a resource of key Enum_Type::Enum_Item, then I can also retrieve it using the same key.

I’d rather not hardcode the insertion process inside ResourceManager.cpp, and preferably keep it in a separate file, but the fact that I am using Enum as a key is kind of an obstacle here for me. Not sure how to fix it.


Thanks a lot!


Get this bounty!!!

#StackBounty: #object-oriented #design-patterns #swift #macos Trying (and failing) to implement the best conventions on OOP Swift

Bounty: 100

I’m making a MacOS app that will do some analysis on the user’s calendar data. For now it only supports Apple’s native calendar (EventKit), but I will later add support to Google, outlook, etc.

Models/Events/Base.swift:

import Foundation

struct EventData {
    var title: String;
    var startDate: Date;
    var endDate: Date;
    var organizerName: String;
    var notes: String;
    var location: String;        
}

struct CalendarData {
    var title: String;
    var isSubscribed: Bool;
}

class Events {
    init() {
        checkForAuthorization();
    }

    func checkForAuthorization() {}
    func requestAccess() {}
    func getCalendars() -> [CalendarData] {
        return [];
    }
    func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
        return [];
    }
}

Models/Events/iCal.swift:

import Foundation
import EventKit

class iCal: Events {

    let eventStore = EKEventStore();
    var calendars: [EKCalendar]?;

    override func checkForAuthorization() {
        let status = EKEventStore.authorizationStatus(for: EKEntityType.event);

        switch (status) {
            case EKAuthorizationStatus.notDetermined:
                self.requestAccess();
                break;
            case EKAuthorizationStatus.authorized:
                break;
            case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
                break;
         }
    }

    override func requestAccess() {
        eventStore.requestAccess(to: EKEntityType.event, completion:{ (accessGranted: Bool, error: Error?) in
            if accessGranted == true {
                print("Granted")
            } else {
                print("Denied")
            }
        });
    }

    override func getCalendars() -> [CalendarData] {
        let _cals = self.eventStore.calendars(for: .event);
        var cals: [CalendarData] = [];

        for cal: EKCalendar in _cals {
            cals.append(CalendarData(title: cal.title, isSubscribed: cal.isSubscribed));
        }
        return cals;
    }
    override func getEvents(calendarName: String, from: Date, to: Date) -> [EventData] {
        let cals = self.eventStore.calendars(for: .event);
        var events: [EventData] = [];

        if let calIndex: Int = cals.firstIndex(where: { $0.title == calendarName }) {
            let selectedCalendar: EKCalendar = cals[calIndex];

            let predicate = eventStore.predicateForEvents(withStart: from, end: to, calendars: [selectedCalendar])
            let _events = eventStore.events(matching: predicate) as [EKEvent];

            for ev: EKEvent in _events {
                events.append(
                    EventData(
                        title: ev.title,
                        startDate: ev.startDate,
                        endDate: ev.endDate,
                        organizerName: ev.organizer?.name ?? "",
                        notes: ev.notes ?? "",
                        location: ev.location ?? ""
                    )
                );
            }

        }

        return events;
    }
}

And I use this class like this:

let calendar = iCal();
for cal in calendar.getCalendars() {
   print("****** (cal.title) *******n");
   print(calendar.getEvents(calendarName: cal.title, from: Calendar.current.date(byAdding: .day, value: -2, to: Date())!, to: Calendar.current.date(byAdding: .day, value: 1, to: Date())!))
}

This works, but it feels very wrong…
I know the semi-colons are not needed, but I always used it in other languages and the linting will delete them anyway after.

Questions:

  1. How can I improve this?
  2. Would it be better to instantiate the class
    Events, by passing the calendar type as an argument (eg. iCal,
    outlook, etc)
  3. Are those structs ok? As in should they go in another
    file?

Thank you


Get this bounty!!!

#StackBounty: #android #design-patterns #android-recyclerview #android-jetpack apply Clean Architecture principles to recycler view pag…

Bounty: 50

I want to build an app following clean architecture principles. There is a recycler view with pagination which asks data in the domain layer and domain gets from the Data layer
as
List<ToiletPaper>. I want to use Pagging lib from Jetpack, but it returns

PagedList<ToiletPaper>

Since Data and Domain layers should not be bound to any platform or frameworks I don’t want to include them in these layers. How to add Jetpack Paging Library with Adapter Design Pattern without changing the Domain layer?

my source code


Get this bounty!!!

#StackBounty: #python #python-3.x #object-oriented #design-patterns Utility for Python date ranges

Bounty: 100

I’m trying to write something that can take a description and a date range and return all the dates that satisfy that description.

Descriptions can be anything from the following…

parsed_tests_dict = [
    {"Saturday": [5]},
    {"Sunday": [6]},
    {"Weekend": [5, 6]},
    {"Weekday": [0, 1, 2, 3, 4]},
    {"Monday-Saturday": [0, 1, 2, 3, 4, 5]},
    {"Jan": "", "Feb": "", "Mar": "", "Nov": "", "Dec": ""},
    {"Jan-Feb": "", "Jan-Mar": "", "Jan-Apr":"", "Mar-Oct": "Apr-Oct", "May-Oct": "",
     "Jul-Nov": "", "Nov-Feb": "", "Nov-Mar": "", "Nov-Dec": "", "Dec-Jun": ""}

So we could have a situation whereby Monday-Saturday appears, so the utility would bucket all the dates within the date range that fall between Monday-Saturday and then another bucket for all the dates that are Sunday.

Now there can also be a situation whereby, we need to bucket Jan-Mar, Apr-Oct, Nov-Dec AND Weekends – in this scenario, we would go through say 1-year date range, bucket every weekday that is between Jan-Mar, Apr-Oct and Nov-Dec and finally, all the Weekends in between would be bucketed under Weekends

I want to try to be as efficient and fast as possible and have been trying a method of this structure:

STR2WKDAY = {
        'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6,
        'wkd': [0, 1, 2, 3, 4], 'wke': [5, 6], 'all': [0, 1, 2, 3, 4, 5, 6],
}
STR2MON = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
}

This is what I have so far, but I would be interested to see other solutions to this problem as mine feels a bit ‘wrong’ –

class DateRange(Database):

    parsed_dates = []

    def __init__(self, days, weekdays, months):
        super().__init__()
        self.days = str(days)
        self.weekdays = frozenset(DateRange.flatn(weekdays))  # flat set of ints
        self.months = frozenset(DateRange.flatn(months))  # flat set of ints

    def __repr__(self):
        return self.days

    def accepts(self, dt):
        return any([
            dt.weekday() in self.weekdays,
            dt.month in self.months,
        ])

    @staticmethod
    def get_days(description):
        for days in description:
            wkdays = list()
            months = list()
            for item in days:
                item = item.strip().lower().replace('ee', '', 1)  # weekend,weekday => wke,wkd
                if '-' not in item:
                    if item[:3] in Constants.STR2WKDAY:
                        wkdays.append(Constants.STR2WKDAY[item[:3]])
                    elif item[:3] in Constants.STR2MON:
                        months.append(Constants.STR2MON[item[:3]])
                else:
                    f, t = item.split('-', 2)
                    f = f.strip()
                    t = t.strip()
                    if f[:3] in Constants.STR2WKDAY:
                        f = Constants.STR2WKDAY[f[:3]]
                        t = Constants.STR2WKDAY[t[:3]]
                        if f > t:
                            wkdays.append([i for i in range(t + 1)])
                            wkdays.append([i for i in range(f, 7)])
                        else:
                            wkdays.append([i for i in range(f, t + 1)])
                    elif f[:3] in Constants.STR2MON and t[:3] in Constants.STR2MON:
                        f = Constants.STR2MON[f[:3]]
                        t = Constants.STR2MON[t[:3]]
                        if f > t:
                            months.append([i for i in range(t + 1)])
                            months.append([i for i in range(f, 13)])
                        else:
                            months.append([i for i in range(f, t + 1)])

            DateRange.parsed_dates.append(DateRange(days[0], wkdays, months))

    @staticmethod
    def flatn(array):
        if isinstance(array, list):
            for element in array:
                yield from DateRange.flatn(element)
        else:
            yield (array)

    @staticmethod
    def date_range(from_date, to_date):
        for n in range((to_date - from_date).days + 1):
            yield from_date + timedelta(n)

Then calling this I just pass a Numpy array of descriptions atm to get_days() – I.E:

[['Saturdays'], ['Sundays'], ['Weekdays']]

This will then bucket every date that falls into each description. – This is long, so thanks to anyone who has a go and I appreciate any advice as I’m fairly new to programming.

Example usage

from datetime import timedelta, datetime
from collections import defaultdict


class Constants:
    STR2WKDAY = {
        'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6,
        'wkd': [0, 1, 2, 3, 4], 'wke': [5, 6], 'all': [0, 1, 2, 3, 4, 5, 6],
    }
    STR2MON = {
        'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6,
        'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12,
    }


def usage(start_date, end_date, description):
    active_dates_dict = defaultdict(list)
    # populate the list in DateRange with dates that match the description for given date range
    DateRange.active_days(description)
    for date in DateRange.parsed_dates:
        # iterate over the dates and organise them into buckets that match the description
        for dt in [dt for dt in DateRange.date_range(datetime.strptime(start_date, '%Y-%m-%d').date(),
                                                     datetime.strptime(end_date, '%Y-%m-%d').date())
                   if date.accepts(dt)]:
            # add the datetime objects to a list of values with the description as the key
            active_dates_dict[str(date)].append(str(dt.isoformat()))

    return active_dates_dict


if __name__ == '__main__':
    a = usage(start_date="2020-01-01", end_date="2020-01-04", description=[['Monday-Saturday']])
    print(a)

    '''

    Possible descriptions - it's worth noting that you can have more than one of these descriptions at the same time 

    i.e     we could have Nov-Dec AND Weekend so we would need to bucket all dates that are from Nov-Dec that are also no weekends 
            and then the remaining dates would do in the Weekend bucket 

      Saturday
      Sunday
      Weekend
      Weekday
      Monday-Saturday
      Jan  
      Feb
      Mar
      Nov
      Dec
      Jan-Feb 
      Jan-Mar
      Jan-Apr
      Mar-Oct 
      Apr-Oct
      May-Oct
      Jul-Nov
      Nov-Feb
      Nov-Mar
      Nov-Dec
      Dec-Jun

      Not supported yet (Not sure how) - nice to have but not a Must have 

      3rd Nov - Dec
      9th Mar - 2nd Nov
      Jan-8th Mar
      3rd Nov-8th Mar
    '''

Any improvements are appreciated


Get this bounty!!!

#StackBounty: #ruby #oop #design-patterns #sinatra Split routes in Sinatra with private methods?

Bounty: 50

I want to do these:

  1. Use rails-like user_params to specify allowed keys to be updated.
  2. Split routes like http://sinatrarb.com/extensions.html.

The code below works, but leaks user_params to other files. How can I keep user_params private?

# app/routes/reset_passwords.rb
 module MyApp
   module Routes 
     module ResetPasswords 
       class << self 
         def registered(app) 
           app.patch '/reset_passwords' do

            # ...

            if @user.update(Routes::ResetPasswords.user_params(params))
              status 204
            end
          end

        def user_params(params)
          params.fetch('user', {}).slice('password')
        end
# app.rb
module MyApp
  class App < Sinatra::Base
    register Routes::ResetPasswords
  end
end


Get this bounty!!!

#StackBounty: #object-oriented #design-patterns #swift Implement The Singleton Pattern for Persistency managers Swift

Bounty: 50

I am creating an iOS app and I want to implement Singleton Pattern.
I have created “Singleton” LibraryAPI to act as an entry point UserManager object to get data from web API. after that I used a facade Pattern “method” to call UserManager implementation.

final class LibraryAPI {

    static let shared  =  LibraryAPI()
    private let userManager  =  UsersManager()
    private let isOnline  =  false 

    private init(){

    }

    func getUsers() -> [User] {
        return userManager.getUsers()
    }
}

my questions:

  1. if I have another Manager Class like “album” class should I use the same LibraryAPI and it will become a monolithic class and how to avoid that?
  2. should I create a “Singleton” LibraryAPI class for each manager object like UserLibraryAPI and albumLibraryAPI?

Note: any references or articles are welcome 🙂


Get this bounty!!!

#StackBounty: #generics #design-patterns #data-structures #types #dart How to store a collection path for a model?

Bounty: 50

I’m building models for my app in Dart/Flutter. Here’s how a model looks like:

abstract class Model {
  /// A unique identifier of the model.
  /// Gets generated by Firestore.
  final String id;

  Model(this.id);
}

class MyModel extends Model {
  final String name;
  final String description;
  final int order;

  MyModel(String id, this.name, this.items, this.order) : super(id);
}

Those models would be stored in Google Firestore in mymodels collection:

mymodels/abc
mymodels/def
...

To fetch a list of these models from Firestore I need to store the collection path (mymodels) for MyModel type somewhere. So I could use it later when fetching models:

Future<List<T>> fetchList() {
  // How to know `path` by knowing T?
  _firestore.collection('path').getDocuments()
}

Where to store that collection path? I was thinking to declare a static property in Model interface, but Dart doesn’t seem to allow override static properties.

Would Dart annotations be a good fit for that?


Get this bounty!!!