<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: FaithInErrorsZORO</title>
    <description>The latest articles on DEV Community by FaithInErrorsZORO (@faith_in_errors_).</description>
    <link>https://dev.to/faith_in_errors_</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.us-east-2.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F3026937%2F68b81842-6f0b-4f35-8108-f6cedd686f25.jpg</url>
      <title>DEV Community: FaithInErrorsZORO</title>
      <link>https://dev.to/faith_in_errors_</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/faith_in_errors_"/>
    <language>en</language>
    <item>
      <title>Writing tests in python?</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:28:10 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/writing-tests-in-python-k3l</link>
      <guid>https://dev.to/faith_in_errors_/writing-tests-in-python-k3l</guid>
      <description>&lt;p&gt;from colorama import init, Fore&lt;br&gt;
from duration import *&lt;/p&gt;

&lt;p&gt;def print_pass(the_data, i):&lt;br&gt;
    print(f'{Fore.GREEN}Test {i} with {the_data} passed')&lt;/p&gt;

&lt;p&gt;def print_fail(the_data, i):&lt;br&gt;
    print(f'''{Fore.RED}*** Test {i} with {the_data} failed.''')&lt;/p&gt;

&lt;p&gt;def print_tests():&lt;br&gt;
    _test_default = Duration(60)&lt;br&gt;
    _test_minutes = Duration(10, "m")&lt;br&gt;
    _test_hours = Duration(2, "h")&lt;br&gt;
    _test_sec = Duration(120, "s")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print('''
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;Test #1 - simple declarations&lt;br&gt;
-----------------------------''')&lt;br&gt;
    test_objects = (&lt;br&gt;
        _test_default,&lt;br&gt;
        _test_minutes,&lt;br&gt;
        _test_hours,&lt;br&gt;
        _test_sec&lt;br&gt;
    )&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_print_out = (
    "60.00 s",
    "600.00 s",
    "7200.00 s",
    "120.00 s"
)

test_repr_out = (
    "Duration(60.00, 's')",
    "Duration(10.00, 'm')",
    "Duration(2.00, 'h')",
    "Duration(120.00, 's')"
)

for i, test_obj in enumerate(test_objects):
    try:
        assert str(test_obj) == test_print_out[i], f'Expected {test_print_out[i]} received {str(test_obj)}'
        print_pass(f'print of {test_obj}', i+1)
        assert repr(test_obj) == test_repr_out[i], f'Expected {test_repr_out[i]} received {repr(test_obj)}'
        print_pass(f'repr of {repr(test_obj)}', i+1)

    except AssertionError as test_data:
        print_fail(test_data, i+1)
        continue
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def add_tests():&lt;br&gt;
    print('''&lt;/p&gt;

&lt;p&gt;Test #2 - Addition&lt;br&gt;
------------------''')&lt;br&gt;
    _test_default = Duration(60)&lt;br&gt;
    _test_minutes = Duration(5, "m")&lt;br&gt;
    _test_hours = Duration(1, "h")&lt;br&gt;
    _test_list = [Duration(10), Duration(2, 'm'), Duration(1, 'h')]&lt;br&gt;
    _test_inc = Duration(60)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_objects = (
    _test_default + _test_minutes,
    _test_default + 30,
    sum(_test_list),
    15 + _test_minutes
)

test_add_out = (
    "Duration(360.00, 's')",
    "Duration(90.00, 's')",
    "Duration(3730.00, 's')",
    "Duration(5.25, 'm')"
)

for i, test_obj in enumerate(test_objects):
    try:
        assert repr(test_obj) == test_add_out[i], f'Expected {test_add_out[i]} received {repr(test_obj)}'
        print_pass(f'print of {repr(test_obj)}', i+1)

    except AssertionError as test_data:
        print_fail(test_data, i+1)
        continue

_test_inc += 30
try:
    assert repr(_test_inc) == "Duration(90.00, 's')", f'Expected Duration(90.00, s) received {repr(_test_inc)}'
    print_pass(f'Incremental test of {repr(_test_inc)}', 1)
except AssertionError as test_data:
    print_fail(test_data, 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def sub_tests():&lt;br&gt;
    print('''&lt;/p&gt;

&lt;p&gt;Test #3 - Test all subtraction cases&lt;br&gt;
------------------------------------''')&lt;br&gt;
    _test_default = Duration(120)&lt;br&gt;
    _test_minutes = Duration(1, "m")&lt;br&gt;
    _test_dec = Duration(100)&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;test_objects = (
    _test_default - _test_minutes,
    _test_default - 30
)

test_sub_out = (
    "Duration(60.00, 's')",
    "Duration(90.00, 's')"
)

try:
    reverse_sub = 200 - Duration(60, "s")
    assert repr(reverse_sub) == "Duration(140.00, 's')", \
        f"Expected Duration(140.00, 's') received {repr(reverse_sub)}"
    print_pass(f'reverse subtraction: {repr(reverse_sub)}', 6)
except AssertionError as test_data:
    print_fail(test_data, 6)

for i, test_obj in enumerate(test_objects):
    try:
        assert repr(test_obj) == test_sub_out[i], f'Expected {test_sub_out[i]} received {repr(test_obj)}'
        print_pass(f'print of {repr(test_obj)}', i+1)

    except AssertionError as test_data:
        print_fail(test_data, i+1)
        continue

_test_dec -= 40
try:
    assert repr(_test_dec) == "Duration(60.00, 's')", f'Expected Duration(60.00, s) received {repr(_test_dec)}'
    print_pass(f'Decremental test of {repr(_test_dec)}', 1)
except AssertionError as test_data:
    print_fail(test_data, 1)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def comp_tests():&lt;br&gt;
    print('''&lt;/p&gt;

&lt;p&gt;Test #4 - Test comparisons between Duration objects&lt;br&gt;
--------------------------''')&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;_test_comp1 = Duration(60)
_test_comp2 = Duration(1, "m")
_test_comp7 = Duration(100)
_test_comp8 = Duration(101)

count = 1
try:
    assert _test_comp1 == _test_comp2, f'Equality tested failed for {repr(_test_comp1)} and {repr(_test_comp2)}'
    print_pass(f'comparison: {repr(_test_comp1)} = {repr(_test_comp2)} ', count)
except AssertionError as test_data:
    print_fail(test_data, count)

count += 1
try:
    assert not (_test_comp7 &amp;gt; _test_comp8), f'Greater than test failed for {repr(_test_comp7)} and {repr(_test_comp8)}'
    print_pass(f'comparison: {repr(_test_comp7)} not &amp;gt; {repr(_test_comp8)} ', count)
    assert _test_comp7 &amp;lt; _test_comp8, f'Less than test failed for {repr(_test_comp7)} and {repr(_test_comp8)}'
    print_pass(f'comparison: {repr(_test_comp7)} &amp;lt; {repr(_test_comp8)} ', count)
except AssertionError as test_data:
    print_fail(test_data, count)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;def exception_tests():&lt;br&gt;
    print('''&lt;/p&gt;

&lt;p&gt;Test #5 - Test Exceptions&lt;br&gt;
-------------------------''')&lt;br&gt;
    count = 1&lt;br&gt;
    try:&lt;br&gt;
        Duration("abc")&lt;br&gt;
        print_fail(f'Value error not thrown when value is string', count)&lt;br&gt;
    except ValueError as msg:&lt;br&gt;
        try:&lt;br&gt;
            assert str(msg) == "Value must be a number", f'Value error does not have correct message. Received {msg}'&lt;br&gt;
            print_pass(f'Value error thrown with message: {msg} as expected', count)&lt;br&gt;
        except AssertionError as test_data:&lt;br&gt;
            print_fail(test_data, count)&lt;br&gt;
    count += 1&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    Duration(-10)
    print_fail(f'Less than zero exception not thrown when value is negative', count)
except DurationLessThanZeroException as msg:
    try:
        assert str(msg) == "Duration cannot be negative", f'Exception does not have correct message. Received {msg}'
        print_pass(f'Negative-value error thrown with message: {msg} as expected', count)
    except AssertionError as test_data:
        print_fail(test_data, count)

count += 1
try:
    Duration(10, "abc")
    print_fail(f'Incorrect unit exception not thrown', count)
except TimeUnitNotDefinedException as msg:
    try:
        assert str(msg) == "Unit cannot be used", f'Exception does not have correct message. Received {msg}'
        print_pass(f'Unit error thrown with message: {msg} as expected', count)
    except AssertionError as test_data:
        print_fail(test_data, count)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    init(autoreset=True)&lt;br&gt;
    print_tests()&lt;br&gt;
    add_tests()&lt;br&gt;
    sub_tests()&lt;br&gt;
    comp_tests()&lt;br&gt;
    exception_tests()&lt;/p&gt;

</description>
      <category>coding</category>
      <category>python</category>
      <category>testing</category>
    </item>
    <item>
      <title>Dice comprehension list in python</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:26:49 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/dice-comprehension-list-in-python-4mhi</link>
      <guid>https://dev.to/faith_in_errors_/dice-comprehension-list-in-python-4mhi</guid>
      <description>&lt;p&gt;import random&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    # Two Dice&lt;br&gt;
    dice_combos = [(d1, d2) for d1 in range(1, 7) for d2 in range(1, 7)]&lt;br&gt;
    dice_rolled = [random.choice(dice_combos) for _ in range(100)]&lt;br&gt;
    sum_of_rolls = {i: 0 for i in range(2, 13)}&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;for roll in dice_rolled:
    sum_of_rolls[sum(roll)] += 1
print("2 Dice Rolled:", dice_rolled[:5], "...") # Preview
print("2 Dice Sums:", sum_of_rolls)

# Three Dice
dice_combos_3 = [(d1, d2, d3) for d1 in range(1, 7) for d2 in range(1, 7) for d3 in range(1, 7)]
dice_rolled_3 = [random.choice(dice_combos_3) for _ in range(100)]
sum_of_rolls_3 = {i: 0 for i in range(3, 19)}

for roll in dice_rolled_3:
    sum_of_rolls_3[sum(roll)] += 1
print("3 Dice Sums:", sum_of_rolls_3)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;/p&gt;

</description>
      <category>code</category>
      <category>programming</category>
      <category>python</category>
    </item>
    <item>
      <title>Hello world app with dictionaries and comprehension lists in python.</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:26:16 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/hello-world-app-with-dictionaries-and-comprehension-lists-in-python-1m0k</link>
      <guid>https://dev.to/faith_in_errors_/hello-world-app-with-dictionaries-and-comprehension-lists-in-python-1m0k</guid>
      <description>&lt;p&gt;def add_entry(phone_book):&lt;br&gt;
    name = input("Enter name: ").title()&lt;br&gt;
    if name in phone_book:&lt;br&gt;
        print("There is already an entry for a student by that name, try another name")&lt;br&gt;
    else:&lt;br&gt;
        phone = input("Enter phone number: ")&lt;br&gt;
        phone_book[name] = phone&lt;/p&gt;

&lt;p&gt;def search_entry(phone_book):&lt;br&gt;
    name = input("Enter name: ").title()&lt;br&gt;
    if name in phone_book:&lt;br&gt;
        print(f"{name}: {phone_book[name]}")&lt;br&gt;
    else:&lt;br&gt;
        print("There is no entry for a student by that name.")&lt;/p&gt;

&lt;p&gt;def search_prefix(phone_book):&lt;br&gt;
    prefix = input("Enter starting letters: ").title()&lt;br&gt;
    matches = {k: v for k, v in phone_book.items() if k.startswith(prefix)}&lt;br&gt;
    if not matches:&lt;br&gt;
        print("No matches found.")&lt;br&gt;
    else:&lt;br&gt;
        for k in sorted(matches.keys()):&lt;br&gt;
            print(f"{k}: {matches[k]}")&lt;/p&gt;

&lt;p&gt;def print_book(phone_book):&lt;br&gt;
    for key in sorted(phone_book.keys()):&lt;br&gt;
        print(f"{key}: {phone_book[key]}")&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    phone_book = {}&lt;br&gt;
    while True:&lt;br&gt;
        choice = input("\n1-Add, 2-Search, 3-Search Prefix, 4-Print All, 5-Exit: ")&lt;br&gt;
        if choice == '1': add_entry(phone_book)&lt;br&gt;
        elif choice == '2': search_entry(phone_book)&lt;br&gt;
        elif choice == '3': search_prefix(phone_book)&lt;br&gt;
        elif choice == '4': print_book(phone_book)&lt;br&gt;
        elif choice == '5': break&lt;br&gt;
        else: print("Error: Invalid choice.")&lt;/p&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>coding</category>
      <category>python</category>
      <category>tutorial</category>
    </item>
    <item>
      <title>Reading and writing with files in python?</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:25:09 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/reading-and-writing-with-files-in-python-a9g</link>
      <guid>https://dev.to/faith_in_errors_/reading-and-writing-with-files-in-python-a9g</guid>
      <description>&lt;p&gt;def sum_column(filename):&lt;br&gt;
    total, error_count = 0, 0&lt;br&gt;
    with open(filename, 'r') as file:&lt;br&gt;
        for line in file:&lt;br&gt;
            try:&lt;br&gt;
                total += int(line.strip())&lt;br&gt;
            except ValueError:&lt;br&gt;
                error_count += 1&lt;br&gt;
    return total, error_count&lt;/p&gt;

&lt;p&gt;def sum_all(filename):&lt;br&gt;
    total, error_count = 0, 0&lt;br&gt;
    with open(filename, 'r') as file:&lt;br&gt;
        for line in file:&lt;br&gt;
            for num in line.split():&lt;br&gt;
                try:&lt;br&gt;
                    total += int(num)&lt;br&gt;
                except ValueError:&lt;br&gt;
                    error_count += 1&lt;br&gt;
    return total, error_count&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    filename = input("Enter a file name: ")&lt;br&gt;
    operation = input("Enter operation (sum_column or sum_all): ")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;try:
    if operation == "sum_column":
        result, errors = sum_column(filename)
        print(f"Sum: {result}, Errors: {errors}")
    elif operation == "sum_all":
        result, errors = sum_all(filename)
        print(f"Sum: {result}, Errors: {errors}")
    else:
        print("Invalid operation entered.")
except FileNotFoundError:
    print(f"User-friendly message: The file '{filename}' does not exist.")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;/p&gt;

</description>
      <category>beginners</category>
      <category>code</category>
      <category>programming</category>
      <category>python</category>
    </item>
    <item>
      <title>Python classes ? being pythonic</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:24:37 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/python-classes-being-pythonic-epe</link>
      <guid>https://dev.to/faith_in_errors_/python-classes-being-pythonic-epe</guid>
      <description>&lt;p&gt;class MassLessThanZeroException(Exception):&lt;br&gt;
    pass&lt;/p&gt;

&lt;p&gt;class UnitNotDefinedException(Exception):&lt;br&gt;
    pass&lt;/p&gt;

&lt;p&gt;class Mass:&lt;br&gt;
    _conversion = {&lt;br&gt;
        'mg': 0.000001,&lt;br&gt;
        'g': 0.001,&lt;br&gt;
        'kg': 1,&lt;br&gt;
        'lb': 0.453592,&lt;br&gt;
        'oz': 0.02835,&lt;br&gt;
        'stone': 6.35029&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;def __init__(self, value, unit='kg'):
    if not isinstance(value, (int, float)) or isinstance(value, bool):
        raise ValueError("Value must be a number")
    if value &amp;lt; 0:
        raise MassLessThanZeroException("Value cannot be negative")
    if unit not in self._conversion:
        raise UnitNotDefinedException("Unit cannot be used")

    self.value = value
    self.unit = unit

def convert_to_kg(self):
    return self.value * Mass._conversion[self.unit]

def __str__(self):
    return f"{self.convert_to_kg():.2f} kg"

def __repr__(self):
    return f"Mass({self.value:.2f}, '{self.unit}')"

def __add__(self, other):
    if isinstance(other, (int, float)):
        total = self.convert_to_kg() + other
    else:
        total = self.convert_to_kg() + other.convert_to_kg()
    return Mass(total / Mass._conversion[self.unit], self.unit)

def __iadd__(self, other):
    return self + other

def __radd__(self, other):
    return self + other

def __sub__(self, other):
    if isinstance(other, (int, float)):
        total = self.convert_to_kg() - other
    else:
        total = self.convert_to_kg() - other.convert_to_kg()
    return Mass(max(0, total) / Mass._conversion[self.unit], self.unit)

def __isub__(self, other):
    return self - other

def __rsub__(self, other):
    if isinstance(other, (int, float)):
        total = other - self.convert_to_kg()
    else:
        total = other.convert_to_kg() - self.convert_to_kg()
    return Mass(max(0, total) / Mass._conversion[self.unit], self.unit)

def __lt__(self, other):
    return self.convert_to_kg() &amp;lt; other.convert_to_kg()

def __gt__(self, other):
    return self.convert_to_kg() &amp;gt; other.convert_to_kg()

def __eq__(self, other):
    return abs(self.convert_to_kg() - other.convert_to_kg()) &amp;lt; 0.01
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>code</category>
      <category>coding</category>
      <category>programming</category>
      <category>python</category>
    </item>
    <item>
      <title>getting into python functional programming any thoughts ?</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 14 Oct 2026 02:19:00 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/getting-into-python-functional-programming-any-thoughts--3el0</link>
      <guid>https://dev.to/faith_in_errors_/getting-into-python-functional-programming-any-thoughts--3el0</guid>
      <description>&lt;p&gt;from functools import reduce&lt;/p&gt;

&lt;h1&gt;
  
  
  1. CUSTOM DISCOUNT CALCULATOR (Scenario: Retail Discounts)
&lt;/h1&gt;

&lt;p&gt;def make_discount_calculator(discount_rate):&lt;br&gt;
    def calculate_discount(price):&lt;br&gt;
        return price * discount_rate&lt;br&gt;
    return calculate_discount&lt;/p&gt;

&lt;h1&gt;
  
  
  2. CONVERT TO A PURE FUNCTION (Scenario: Applying Wholesale Markup)
&lt;/h1&gt;

&lt;p&gt;def apply_markup(costs):&lt;br&gt;
    if not costs:&lt;br&gt;
        return []&lt;br&gt;
    return [costs[0] * 1.25] + apply_markup(costs[1:])&lt;/p&gt;

&lt;h1&gt;
  
  
  3. ID NUMBER GENERATOR (Scenario: Database ID Assignment)
&lt;/h1&gt;

&lt;p&gt;def make_id_tracker(current_id):&lt;br&gt;
    def get_next_id():&lt;br&gt;
        return current_id, make_id_tracker(current_id + 1)&lt;br&gt;
    return get_next_id&lt;/p&gt;

&lt;h1&gt;
  
  
  4. REWRITE WITH YIELD (Scenario: Database ID Assignment Generator)
&lt;/h1&gt;

&lt;p&gt;def make_id_tracker_2(current_id):&lt;br&gt;
    while True:&lt;br&gt;
        yield current_id&lt;br&gt;
        current_id += 1&lt;/p&gt;

&lt;h1&gt;
  
  
  5. GAME SCORES REPORT (Scenario: Multiplayer Match Results)
&lt;/h1&gt;

&lt;p&gt;def process_scores(scores):&lt;br&gt;
    qualifying_scores = filter(lambda x: x &amp;gt;= 50, scores)&lt;br&gt;
    buffed_scores = map(lambda x: x + 10, qualifying_scores)&lt;br&gt;
    total_team_score = reduce(lambda x, y: x + y, buffed_scores, 0)&lt;br&gt;
    return total_team_score&lt;/p&gt;

&lt;h1&gt;
  
  
  6. INVENTORY TRACKER SIMULATION (Scenario: Warehouse Stock)
&lt;/h1&gt;

&lt;p&gt;def make_inventory(stock_level):&lt;br&gt;
    def inventory(action, quantity):&lt;br&gt;
        if action == "restock":&lt;br&gt;
            return make_inventory(stock_level + quantity)&lt;br&gt;
        elif action == "sell":&lt;br&gt;
            return make_inventory(stock_level - quantity)&lt;br&gt;
        elif action == "audit":&lt;br&gt;
            return stock_level, make_inventory(stock_level)&lt;br&gt;
        else:&lt;br&gt;
            raise ValueError("Unknown action")&lt;br&gt;
    return inventory&lt;/p&gt;

&lt;h1&gt;
  
  
  7. EVENT PROCESSING WITHOUT LOOPS (Scenario: Applying Buffs to Player Stats)
&lt;/h1&gt;

&lt;p&gt;def map_recursively(operation, elements):&lt;br&gt;
    if not elements:&lt;br&gt;
        return []&lt;br&gt;
    return [operation(elements[0])] + map_recursively(operation, elements[1:])&lt;/p&gt;

&lt;h1&gt;
  
  
  8. IMAGE PROCESSING PIPELINE (Scenario: Batch Image Resizing)
&lt;/h1&gt;

&lt;p&gt;def compose_funcs(f, g):&lt;br&gt;
    return lambda x: f(g(x))&lt;/p&gt;

&lt;p&gt;def make_image_processor():&lt;br&gt;
    downscale = lambda pixels: pixels * 0.5&lt;br&gt;
    apply_brightness = lambda pixels: pixels + 15&lt;br&gt;
    compress = lambda pixels: round(pixels, 0)&lt;br&gt;
    return compose_funcs(compress, compose_funcs(apply_brightness, downscale))&lt;/p&gt;

&lt;h1&gt;
  
  
  9. TEXT FORMATTING PIPELINE (Scenario: Chat Filter)
&lt;/h1&gt;

&lt;p&gt;def strip_vowels(word):&lt;br&gt;
    if not word:&lt;br&gt;
        return ""&lt;br&gt;
    char = word[0]&lt;br&gt;
    rest = strip_vowels(word[1:])&lt;br&gt;
    if char.lower() in "aeiou":&lt;br&gt;
        return rest&lt;br&gt;
    return char + rest&lt;/p&gt;

&lt;p&gt;def chain_processors(routines):&lt;br&gt;
    return lambda data: reduce(lambda current_val, routine: routine(current_val), routines, data)&lt;/p&gt;

&lt;h1&gt;
  
  
  10. FLATTENING DEPARTMENT DATA (Scenario: Corporate Org Chart)
&lt;/h1&gt;

&lt;p&gt;def unnest_structure(hierarchy):&lt;br&gt;
    if not hierarchy:&lt;br&gt;
        return []&lt;br&gt;
    if isinstance(hierarchy[0], list):&lt;br&gt;
        return unnest_structure(hierarchy[0]) + unnest_structure(hierarchy[1:])&lt;br&gt;
    return [hierarchy[0]] + unnest_structure(hierarchy[1:])&lt;/p&gt;

&lt;p&gt;def main():&lt;br&gt;
    print("--- 1. CUSTOM DISCOUNT CALCULATOR ---")&lt;br&gt;
    student_discount = make_discount_calculator(0.20)&lt;br&gt;
    print(f"20% discount on $200: ${student_discount(200)}")&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;print("\n--- 2. CONVERT TO A PURE FUNCTION ---")
costs = [100, 200, 50]
print(f"Original costs: {costs}")
print(f"With markup: {apply_markup(costs)}")

print("\n--- 3. ID NUMBER GENERATOR ---")
tracker = make_id_tracker(1000)
id1, tracker = tracker()
id2, tracker = tracker()
print(f"Generated IDs: {id1}, {id2}")

print("\n--- 4. REWRITE WITH YIELD ---")
tracker_gen = make_id_tracker_2(1000)
print(f"Generated IDs (yield): {next(tracker_gen)}, {next(tracker_gen)}")

print("\n--- 5. GAME SCORES REPORT ---")
scores = [40, 80, 55, 30, 90]
print(f"Processed Total Score: {process_scores(scores)}")

print("\n--- 6. INVENTORY TRACKER SIMULATION ---")
inv = make_inventory(500)
inv = inv("restock", 200)
inv = inv("sell", 50)
current_stock, inv = inv("audit", 0)
print(f"Current Inventory Stock: {current_stock}")

print("\n--- 7. EVENT PROCESSING WITHOUT LOOPS ---")
double_buff = lambda x: x * 2
stats = [10, 20, 30]
print(f"Buffed Stats: {map_recursively(double_buff, stats)}")

print("\n--- 8. IMAGE PROCESSING PIPELINE ---")
pipeline = make_image_processor()
print(f"Processed Pixel Value (from 100): {pipeline(100)}")

print("\n--- 9. TEXT FORMATTING PIPELINE ---")
strip_whitespace = lambda s: s.strip()
lowercase = lambda s: s.lower()
text_pipeline = chain_processors([strip_whitespace, lowercase, strip_vowels])
print(f"Processed Text: {text_pipeline('  HELLO World  ')}")

print("\n--- 10. FLATTENING DEPARTMENT DATA ---")
org_chart = ["Executive", ["Engineering", ["Frontend", "Backend"]], "HR"]
print(f"Flattened Org Chart: {unnest_structure(org_chart)}")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;if &lt;strong&gt;name&lt;/strong&gt; == "&lt;strong&gt;main&lt;/strong&gt;":&lt;br&gt;
    main()&lt;/p&gt;

</description>
      <category>functional</category>
      <category>programming</category>
      <category>python</category>
    </item>
    <item>
      <title>Some asp.net fizz buzz testing</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 30 Sep 2026 02:28:17 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/some-aspnet-fizz-buzz-testing-1h1c</link>
      <guid>https://dev.to/faith_in_errors_/some-aspnet-fizz-buzz-testing-1h1c</guid>
      <description>&lt;p&gt;using System;&lt;br&gt;
using System.Collections.Generic;&lt;br&gt;
using PartA.Models; &lt;br&gt;
using Xunit;&lt;/p&gt;

&lt;p&gt;namespace PartA.Tests&lt;br&gt;
{&lt;br&gt;
    public class FizzBuzzTests&lt;br&gt;
    {&lt;br&gt;
        private readonly FizzBuzz _fizzBuzz;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public FizzBuzzTests()
    {
        _fizzBuzz = new FizzBuzz();
    }

    // 1st test - Returns list 1 to 100[cite: 3]
    [Fact]
    public void GetList_ReturnsList1To100_WhenNoParametersPassed()
    {
        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList();

        // ASSERT
        Assert.Equal(100, result.Count);
        Assert.Equal("1", result[0]);
        Assert.Equal("Buzz", result[99]); // Number 100
    }

    // 2nd test - Fizz for 3 multiples[cite: 3]
    [Fact]
    public void GetList_ReturnsFizz_ForMultiplesOfThree()
    {
        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList();

        // ASSERT
        Assert.Equal("Fizz", result[2]); // Index 2 represents number 3
        Assert.Equal("Fizz", result[8]); // Index 8 represents number 9
    }

    // 3rd test - Buzz for 5 multiples[cite: 3]
    [Fact]
    public void GetList_ReturnsBuzz_ForMultiplesOfFive()
    {
        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList();

        // ASSERT
        Assert.Equal("Buzz", result[4]); // Index 4 represents number 5
        Assert.Equal("Buzz", result[9]); // Index 9 represents number 10
    }

    // 4th test - FizzBuzz for 3&amp;amp;5[cite: 3]
    [Fact]
    public void GetList_ReturnsFizzBuzz_ForMultiplesOfThreeAndFive()
    {
        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList();

        // ASSERT
        Assert.Equal("FizzBuzz", result[14]); // Index 14 represents number 15
        Assert.Equal("FizzBuzz", result[29]); // Index 29 represents number 30
    }

    // 5th test - Upper limit with default[cite: 3]
    [Fact]
    public void GetList_RespectsUpperLimit_WhenPassed()
    {
        // ARRANGE
        int bramUpperLimit = 10;

        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList(bramUpperLimit);

        // ASSERT
        Assert.Equal(10, result.Count);
        Assert.Equal("Buzz", result[9]); // Number 10
    }

    // 6th test - Lower limit with default[cite: 3]
    [Fact]
    public void GetList_RespectsLowerLimit_WhenPassed()
    {
        // ARRANGE
        int bramUpperLimit = 20;
        int bramLowerLimit = 15;

        // ACT
        List&amp;lt;string&amp;gt; result = _fizzBuzz.getList(bramUpperLimit, bramLowerLimit);

        // ASSERT
        Assert.Equal(6, result.Count); // 15, 16, 17, 18, 19, 20
        Assert.Equal("FizzBuzz", result[0]); // Number 15
    }

    // 7th test - Argument out of Range exception[cite: 3]
    [Fact]
    public void GetList_ThrowsArgumentOutOfRangeException_WhenLowerGreaterThanUpper()
    {
        // ARRANGE
        int bramUpperLimit = 10;
        int bramLowerLimit = 20;

        // ACT &amp;amp; ASSERT
        Assert.Throws&amp;lt;ArgumentOutOfRangeException&amp;gt;(() =&amp;gt; _fizzBuzz.getList(bramUpperLimit, bramLowerLimit));
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>softwaredevelopment</category>
      <category>testing</category>
    </item>
    <item>
      <title>Getting into C# testing</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 30 Sep 2026 02:18:23 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/getting-into-c-testing-3kho</link>
      <guid>https://dev.to/faith_in_errors_/getting-into-c-testing-3kho</guid>
      <description>&lt;p&gt;Here are the tests I am running for a school registration system : using System.Collections.Generic;&lt;br&gt;
using System.ComponentModel.DataAnnotations;&lt;br&gt;
using SportsWeb.Models;&lt;br&gt;
using Xunit;&lt;/p&gt;

&lt;p&gt;namespace SportsWeb.Tests.Models&lt;br&gt;
{&lt;br&gt;
    public class RegistrationViewModelValidationTests&lt;br&gt;
    {&lt;br&gt;
        private static IList Validate(object model)&lt;br&gt;
        {&lt;br&gt;
            var ctx = new ValidationContext(model, serviceProvider: null, items: null);&lt;br&gt;
            var results = new List();&lt;br&gt;
            Validator.TryValidateObject(model, ctx, results, validateAllProperties: true);&lt;br&gt;
            return results;&lt;br&gt;
        }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    [Fact]
    public void Missing_Season_IsInvalid()
    {
        // ARRANGE: Simulating a missing drop-down selection
        var vm = new RegistrationViewModel
        {
            AthleteName = "Bram",
            Season = null, 
            Sport = "Basketball"
        };

        // ACT
        var results = Validate(vm);

        // ASSERT
        Assert.Contains(results, r =&amp;gt; r.MemberNames.Contains(nameof(RegistrationViewModel.Season)));
    }

    [Fact]
    public void Missing_Sport_IsInvalid()
    {
        // ARRANGE: Simulating no radio button being selected
        var vm = new RegistrationViewModel
        {
            AthleteName = "Bram",
            Season = "Fall",
            Sport = null 
        };

        var results = Validate(vm);

        Assert.Contains(results, r =&amp;gt; r.MemberNames.Contains(nameof(RegistrationViewModel.Sport)));
    }

    [Fact]
    public void Valid_RegistrationModel_Passes()
    {
        // ARRANGE
        var vm = new RegistrationViewModel
        {
            AthleteName = "Bram",
            Season = "Winter",
            Sport = "Basketball"
        };

        // ACT
        var results = Validate(vm);

        // ASSERT
        Assert.Empty(results);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;using System;&lt;br&gt;
using SportsWeb.Models;&lt;br&gt;
using SportsWeb.Services;&lt;br&gt;
using Xunit;&lt;/p&gt;

&lt;p&gt;namespace SportsWeb.Tests.Services&lt;br&gt;
{&lt;br&gt;
    public class RegistrationServiceTests&lt;br&gt;
    {&lt;br&gt;
        private readonly IRegistrationService _service;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RegistrationServiceTests()
    {
        // Testing the concrete service implementation
        _service = new RegistrationService(); 
    }

    [Fact]
    public void CalculateFee_ReturnsStandardRate_ForWinterBasketball()
    {
        // Arrange
        var vm = new RegistrationViewModel { Season = "Winter", Sport = "Basketball" };

        // Act
        decimal fee = _service.CalculateFee(vm);

        // Assert
        Assert.Equal(150m, fee);
    }

    [Theory]
    [InlineData("Summer", "Soccer", 100)]
    [InlineData("Spring", "Tennis", 120)]
    public void CalculateFee_ReturnsCorrectRates_ForAllSeasons(string season, string sport, decimal expectedFee)
    {
        // Arrange
        var vm = new RegistrationViewModel { Season = season, Sport = sport };

        // Act
        decimal fee = _service.CalculateFee(vm);

        // Assert
        Assert.Equal(expectedFee, fee);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;here are the controller tests : using Microsoft.AspNetCore.Mvc;&lt;br&gt;
using Moq;&lt;br&gt;
using SportsWeb.Controllers;&lt;br&gt;
using SportsWeb.Models;&lt;br&gt;
using SportsWeb.Services;&lt;br&gt;
using Xunit;&lt;/p&gt;

&lt;p&gt;namespace SportsWeb.Tests.Controllers&lt;br&gt;
{&lt;br&gt;
    public class RegistrationControllerTests&lt;br&gt;
    {&lt;br&gt;
        private readonly Mock _mockService;&lt;br&gt;
        private readonly RegistrationController _controller;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public RegistrationControllerTests()
    {
        _mockService = new Mock&amp;lt;IRegistrationService&amp;gt;();
        _controller = new RegistrationController(_mockService.Object);
    }

    [Fact]
    public void CreatePost_InvalidModel_ReturnsSameView()
    {
        // ARRANGE
        // Simulate ASP.NET Core catching a missing radio button selection
        _controller.ModelState.AddModelError("Sport", "Please select a sport.");

        var vm = new RegistrationViewModel { AthleteName = "Bram", Season = "Fall", Sport = null };

        // ACT
        var result = _controller.Create(vm) as ViewResult;

        // ASSERT
        Assert.NotNull(result);
        Assert.False(_controller.ModelState.IsValid);
        Assert.Same(vm, result.Model); // Ensure the form is sent back to the user with their inputs intact

        // Verify the database/service was NOT called since the model was invalid
        _mockService.VerifyNoOtherCalls(); 
    }

    [Fact]
    public void CreatePost_ValidModel_CallsServiceAndRedirects()
    {
        // ARRANGE
        var vm = new RegistrationViewModel { AthleteName = "Bram", Season = "Winter", Sport = "Basketball" };

        // Set up the mock to return true when saving
        _mockService.Setup(s =&amp;gt; s.ProcessRegistration(vm)).Returns(true);

        // ACT
        var result = _controller.Create(vm) as RedirectToActionResult;

        // ASSERT
        Assert.NotNull(result);
        Assert.Equal("Success", result.ActionName); // Ensure it redirects to the Success page

        // Verify the service was called exactly once with the provided model
        _mockService.Verify(s =&amp;gt; s.ProcessRegistration(vm), Times.Once);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>csharp</category>
      <category>dotnet</category>
      <category>programming</category>
      <category>testing</category>
    </item>
    <item>
      <title>Getting started with C# SOLID Principles</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 30 Sep 2026 02:00:55 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/getting-started-with-c-solid-principles-2h44</link>
      <guid>https://dev.to/faith_in_errors_/getting-started-with-c-solid-principles-2h44</guid>
      <description>&lt;p&gt;In my repo I've got this `using MusicLab.Projects.Models;&lt;br&gt;
using System.Collections.Generic;&lt;br&gt;
using System.Linq;&lt;/p&gt;

&lt;p&gt;namespace MusicLab.Projects.Data&lt;br&gt;
{&lt;br&gt;
public class InstrumentRepository : IInstrumentRepository&lt;br&gt;
{&lt;br&gt;
private readonly MusicDbContext _context;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public InstrumentRepository(MusicDbContext context)
{
    _context = context;
}

public List&amp;lt;Instrument&amp;gt; GetInstruments()
{
    return _context.GetInstruments();
}

public List&amp;lt;Instrument&amp;gt; GetInstrumentsByCategory(string category)
{
    return _context.GetInstruments().Where(i =&amp;gt; i.Category == category).ToList();
}

public Instrument FindById(int id)
{
    return _context.FindById(id);
}

public void Add(Instrument i)
{
    _context.Add(i);
}

public void Update(Instrument i)
{
    _context.Update(i);
}

public void Remove(int id)
{
    _context.Remove(id);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
}`&lt;/p&gt;

&lt;p&gt;and then in my interface :&lt;/p&gt;

&lt;p&gt;C#&lt;br&gt;
using MusicLab.Projects.Models;&lt;/p&gt;

&lt;p&gt;namespace MusicLab.Projects.Utils&lt;br&gt;
{&lt;br&gt;
    public interface ITaxCalculator&lt;br&gt;
    {&lt;br&gt;
        decimal CalculateTax(Instrument instrument);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class DefaultTaxCalculator : ITaxCalculator
{
    public decimal CalculateTax(Instrument instrument)
    {
        // Standard tax calculation replacing the static method
        return instrument.Price * 0.15m; 
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
and then my csv exporter :&lt;/p&gt;

&lt;p&gt;C#&lt;br&gt;
using MusicLab.Projects.Models;&lt;br&gt;
using System.Collections.Generic;&lt;br&gt;
using System.Text;&lt;/p&gt;

&lt;p&gt;namespace MusicLab.Projects.Utils&lt;br&gt;
{&lt;br&gt;
    public interface ICsvExporter&lt;br&gt;
    {&lt;br&gt;
        string ExportInstrumentsCsv(List instruments);&lt;br&gt;
    }&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public class CsvExporter : ICsvExporter
{
    public string ExportInstrumentsCsv(List&amp;lt;Instrument&amp;gt; instruments)
    {
        var sb = new StringBuilder();
        sb.AppendLine("Id,Name,Price,Category");
        foreach (var i in instruments)
        {
            sb.AppendLine($"{i.Id},{i.Name},{i.Price},{i.Category}");
        }
        return sb.ToString();
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
and then the controller :&lt;/p&gt;

&lt;p&gt;C#&lt;br&gt;
using Microsoft.AspNetCore.Mvc;&lt;br&gt;
using MusicLab.Projects.Data;&lt;br&gt;
using MusicLab.Projects.Models;&lt;br&gt;
using MusicLab.Projects.Utils;&lt;br&gt;
using System.Collections.Generic;&lt;br&gt;
using System.Text;&lt;/p&gt;

&lt;p&gt;namespace MusicLab.Projects.Controllers&lt;br&gt;
{&lt;br&gt;
    public class InstrumentsController : Controller&lt;br&gt;
    {&lt;br&gt;
        private readonly IInstrumentRepository _repository;&lt;br&gt;
        private readonly ICsvExporter _exporter;&lt;br&gt;
        private readonly ITaxCalculator _taxCalculator;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    public InstrumentsController(IInstrumentRepository repository, ICsvExporter exporter, ITaxCalculator taxCalculator)
    {
        _repository = repository;
        _exporter = exporter;
        _taxCalculator = taxCalculator;
    }

    public IActionResult Index(string category)
    {
        List&amp;lt;Instrument&amp;gt; instruments;

        if (!string.IsNullOrWhiteSpace(category))
        {
            instruments = _repository.GetInstrumentsByCategory(category);
        }
        else
        {
            instruments = _repository.GetInstruments();
        }

        return View(instruments);
    }

    public IActionResult Details(int id)
    {
        Instrument instrument = _repository.FindById(id);
        if (instrument == null) return NotFound();

        ViewData["Tax"] = _taxCalculator.CalculateTax(instrument);
        return View(instrument);
    }

    [HttpPost]
    public IActionResult Create(Instrument model)
    {
        if (model == null) return BadRequest("No data");

        // Replaced manual model.IsValid() with built-in ModelState validation
        if (!ModelState.IsValid) return BadRequest("Invalid instrument"); 

        _repository.Add(model);
        return Redirect("/Instruments/Index");
    }

    public IActionResult Export()
    {
        List&amp;lt;Instrument&amp;gt; instruments = _repository.GetInstruments();
        string csv = _exporter.ExportInstrumentsCsv(instruments);
        byte[] bytes = Encoding.UTF8.GetBytes(csv);
        return File(bytes, "text/csv", "instruments.csv");
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;br&gt;
and then program.cs :&lt;/p&gt;

&lt;p&gt;C#&lt;br&gt;
using Microsoft.AspNetCore.Builder;&lt;br&gt;
using Microsoft.Extensions.DependencyInjection;&lt;br&gt;
using MusicLab.Projects.Data;&lt;br&gt;
using MusicLab.Projects.Utils;&lt;/p&gt;

&lt;p&gt;var builder = WebApplication.CreateBuilder(args);&lt;/p&gt;

&lt;p&gt;builder.Services.AddControllersWithViews();&lt;/p&gt;

&lt;p&gt;// Register the mock DbContext as a Singleton so the list persists in memory&lt;br&gt;
builder.Services.AddSingleton(); &lt;/p&gt;

&lt;p&gt;// Register dependencies for Dependency Injection&lt;br&gt;
builder.Services.AddScoped();&lt;br&gt;
builder.Services.AddScoped();&lt;br&gt;
builder.Services.AddScoped();&lt;/p&gt;

&lt;p&gt;var app = builder.Build();&lt;/p&gt;

&lt;p&gt;app.UseRouting();&lt;br&gt;
app.MapControllerRoute(&lt;br&gt;
    name: "default",&lt;br&gt;
    pattern: "{controller=Instruments}/{action=Index}/{id?}");&lt;/p&gt;

&lt;p&gt;app.Run();&lt;/p&gt;

</description>
      <category>architecture</category>
      <category>backend</category>
      <category>csharp</category>
      <category>dotnet</category>
    </item>
    <item>
      <title>Using sessions in asp.net anyone have any insight?</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Fri, 17 Apr 2026 03:39:10 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/using-sessions-in-aspnet-anyone-have-any-insight-3pnn</link>
      <guid>https://dev.to/faith_in_errors_/using-sessions-in-aspnet-anyone-have-any-insight-3pnn</guid>
      <description>&lt;p&gt;here is how i set it up in program.cs : &lt;/p&gt;

&lt;p&gt;builder.Services.AddDistributedMemoryCache();&lt;br&gt;
builder.Services.AddSession(options =&amp;gt;&lt;br&gt;
{&lt;br&gt;
    options.IdleTimeout = TimeSpan.FromMinutes(10); // [cite: 16]&lt;br&gt;
    options.Cookie.HttpOnly = true;&lt;br&gt;
    options.Cookie.IsEssential = true;&lt;br&gt;
});&lt;/p&gt;

&lt;p&gt;var app = builder.Build();&lt;/p&gt;

&lt;p&gt;[cite_start]// 2. Add Session Middleware (between Routing and Endpoints) [cite: 17]&lt;br&gt;
app.UseRouting();&lt;br&gt;
app.UseSession(); &lt;br&gt;
app.UseAuthorization();&lt;/p&gt;

&lt;p&gt;here is how i reference the session&lt;/p&gt;

&lt;p&gt;[[HttpPost]&lt;br&gt;
public IActionResult Index(string lastName)&lt;br&gt;
{&lt;br&gt;
    var player = _context.Players.FirstOrDefault(p =&amp;gt; p.LastName == lastName);&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;if (player == null)
{
    ViewBag.Message = "No player found with that last name.";
    return View();
}

// Store IDs in Session for later use
HttpContext.Session.SetString("playerId", player.PlayerId.ToString());
HttpContext.Session.SetInt32("coachId", player.CoachId ?? 0);
HttpContext.Session.SetInt32("teamId", player.TeamId ?? 0);

return View("Display", player);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;action to show the stats:&lt;/p&gt;

&lt;p&gt;public IActionResult ShowStats()&lt;br&gt;
{&lt;br&gt;
    var pId = HttpContext.Session.GetString("playerId");&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var playerWithStats = _context.Players
    .Include(p =&amp;gt; p.GameRecords)
        .ThenInclude(gr =&amp;gt; gr.StatCategory)
    .FirstOrDefault(p =&amp;gt; p.PlayerId.ToString() == pId);

return View(playerWithStats);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

&lt;p&gt;dif types : &lt;/p&gt;

&lt;p&gt;public IActionResult ShowCoach()&lt;br&gt;
{&lt;br&gt;
    var pId = HttpContext.Session.GetString("playerId");&lt;br&gt;
    var cId = HttpContext.Session.GetInt32("coachId");&lt;br&gt;
    var tId = HttpContext.Session.GetInt32("teamId");&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;var player = _context.Players.Find(int.Parse(pId));
var coach = _context.Coaches.Find(cId);
var team = _context.Teams.Find(tId);

// Join class/ViewModel to pass all three objects to the view
var viewModel = new PlayerCoachTeamViewModel { 
    Player = player, 
    Coach = coach, 
    Team = team 
};

return View(viewModel);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;}&lt;/p&gt;

</description>
      <category>backend</category>
      <category>csharp</category>
      <category>dotnet</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Making good/ proper line queries in c#?</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Wed, 01 Apr 2026 15:49:20 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/making-good-proper-line-queries-in-c-133p</link>
      <guid>https://dev.to/faith_in_errors_/making-good-proper-line-queries-in-c-133p</guid>
      <description>&lt;p&gt;Query ?:var customerOrdersQuery = (from c in db.Customers&lt;br&gt;
                           join o in db.Orders on c.CustomerId equals o.CustomerId&lt;br&gt;
                           select new &lt;br&gt;
                           { &lt;br&gt;
                               CustomerName = c.Name, &lt;br&gt;
                               OrderDate = o.OrderDate &lt;br&gt;
                           }).ToList();&lt;/p&gt;

&lt;p&gt;Method:var customerOrdersMethod = db.Customers&lt;br&gt;
    .Join(&lt;br&gt;
        db.Orders,                             // 1. Table to join&lt;br&gt;
        c =&amp;gt; c.CustomerId,                     // 2. Key from the first table (Customers)&lt;br&gt;
        o =&amp;gt; o.CustomerId,                     // 3. Key from the second table (Orders)&lt;br&gt;
        (c, o) =&amp;gt; new                          // 4. The data you want to select&lt;br&gt;
        { &lt;br&gt;
            CustomerName = c.Name, &lt;br&gt;
            OrderDate = o.OrderDate &lt;br&gt;
        }&lt;br&gt;
    ).ToList();&lt;/p&gt;

&lt;p&gt;And then to display : @model IEnumerable&lt;/p&gt;

&lt;p&gt;@{&lt;br&gt;
    ViewData["Title"] = "Full Order Report";&lt;br&gt;
}&lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;h2&amp;gt;Customer Order Report&amp;lt;/h2&amp;gt;

&amp;lt;table&amp;gt;
    &amp;lt;thead&amp;gt;
        &amp;lt;tr&amp;gt;
            &amp;lt;th&amp;gt;Customer Name&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Product Purchased&amp;lt;/th&amp;gt;
            &amp;lt;th&amp;gt;Date of Order&amp;lt;/th&amp;gt;
        &amp;lt;/tr&amp;gt;
    &amp;lt;/thead&amp;gt;
    &amp;lt;tbody&amp;gt;
        @* Loop through the joined data stored in the ViewModels *@
        @foreach (var item in Model)
        {
            &amp;lt;tr&amp;gt;
                &amp;lt;td&amp;gt;@item.CustomerName&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;@item.ProductName&amp;lt;/td&amp;gt;
                &amp;lt;td&amp;gt;@Html.DisplayFor(modelItem =&amp;amp;gt; item.OrderDate)&amp;lt;/td&amp;gt;
            &amp;lt;/tr&amp;gt;
        }
    &amp;lt;/tbody&amp;gt;
&amp;lt;/table&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

</description>
      <category>csharp</category>
      <category>database</category>
      <category>dotnet</category>
      <category>programming</category>
    </item>
    <item>
      <title>SQL triggers for blocking</title>
      <dc:creator>FaithInErrorsZORO</dc:creator>
      <pubDate>Fri, 20 Mar 2026 12:58:26 +0000</pubDate>
      <link>https://dev.to/faith_in_errors_/sql-triggers-for-blocking-2llo</link>
      <guid>https://dev.to/faith_in_errors_/sql-triggers-for-blocking-2llo</guid>
      <description>&lt;p&gt;AFTER INSERT, UPDATE&lt;br&gt;
AS&lt;br&gt;
BEGIN&lt;br&gt;
    SET NOCOUNT ON;&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;-- Look for the modified InvoiceId in the list of invoices exceeding the limit
IF (SELECT TOP 1 InvoiceId FROM Inserted) IN (
    SELECT InvoiceId
    FROM (
        SELECT IL.InvoiceId, COUNT(*) AS count
        FROM InvoiceLine IL
        JOIN Track T ON IL.TrackId = T.TrackId
        WHERE T.GenreId = 32 --  Genre
        GROUP BY IL.InvoiceId
    ) AS Summary
    WHERE count &amp;gt; 3
)
BEGIN
    RAISERROR ('Market Overload! Max 3 Anime items per invoice.', 16, 1);
    ROLLBACK TRANSACTION;
END
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;END;&lt;/p&gt;

</description>
      <category>backend</category>
      <category>database</category>
      <category>programming</category>
      <category>sql</category>
    </item>
  </channel>
</rss>
