7 votes

What programming/technical projects have you been working on?

This is a recurring post to discuss programming or other technical projects that we've been working on. Tell us about one of your recent projects, either at work or personal projects. What's interesting about it? Are you having trouble with anything?

12 comments

  1. foxaru
    Link
    I've been working my way through AoC'22 to help me learn Rust (as well as reading the book and doing rustlings), currently on Day 11: Monkey Keep Away! Part 1. So far, I've built the Monkey struct...

    I've been working my way through AoC'22 to help me learn Rust (as well as reading the book and doing rustlings), currently on Day 11: Monkey Keep Away! Part 1.

    So far, I've built the Monkey struct to hold all the values and I've written parsing functions that transform the input into blocks of 7 lines that are then transformed into a Monkey.

    The problem I envision running into next is how to iterate through a collection of mutable Monkeys with references to each other, such that they can pass items between one another. I'm thinking of building a struct MBox that holds a Vec of Monkeys, but we'll see!

    6 votes
  2. [2]
    scrambo
    Link
    I was gonna make a distinct topic about this, but figured that it might do better here first. I'm working on a Fishing Tournament program for a tourney that my uncle hosts every year. I'm...

    I was gonna make a distinct topic about this, but figured that it might do better here first.

    I'm working on a Fishing Tournament program for a tourney that my uncle hosts every year. I'm currently in the process of laying out the database structure, and I'm having an issue visualizing how to apply scoring rules to what I have so far. Any suggestions or even links to existing systems would be super helpful.

    Basic Schema (without anything for Rule or RuleGroup).
    It's very anemic right now, but I'd like to start small and add sugar to it later once I have a better idea of where to go.

    Tournament
    | List<Participants>: participants
    | List<Rule>: rules
    
    Participant
    | String: name
    | List<Catch>: haul
    | int: score
    
    Catch
    | Fish: fish
    | Boolean: lure
    
    Fish
    | string: species
    | float: length
    

    First idea was to have some sort of Rule object defined in a table, but the more I think of that, the less I like that idea. Maybe something like a Calculator(Fish, Rule) that takes a fish, and a "Rule" and spits a score out. That makes it stateless and only dependent on input. That still leaves me pretty lost on how to define Rule(s) in the context of the application.

    So for an example to work through.
    There are tiers of fish, and each tier is worth different amounts of points per inch.

    • T1: 10 points / inch (Black Drum)
    • T2: 5 points / inch (Puffer)
    • Trash Fish: 2 points / inch (Shark or Skate)

    IF a fish is caught with a lure, that's an extra 100 points per inch.

    There's also bonus points if fish are over a certain size:

    • If T1: 10 ppi then 5 more ppi over 10 inches

    Meaning an 11 inch Tier 1 fish, no lure, would be worth 115 points

    So on so forth for T2 and Trash fish.


    Going through this, maybe I have the score defined as the return value from a Rule, when it's given a fish? Multiple pre-defined rules, have a haul filtered and each Catch sent to the appropriate Rule to calculate it's score? But that still seems a little... brittle?

    4 votes
    1. whispersilk
      (edited )
      Link Parent
      Would it be possible to define score as the return value from a Rule, like you said, but instead of filtering just apply every rule to every fish (or, rather, every catch)? That way you could...

      Would it be possible to define score as the return value from a Rule, like you said, but instead of filtering just apply every rule to every fish (or, rather, every catch)? That way you could stick all the rules in a list and just iterate over them, adding together the scores each one generates for a given fish. Something like (in Java, assuming some surrounding support code):

      public static final List<Function<Fish, int>> RULES = List.of(
          tierRule,
          lureRule,
          bonusRule
      );
      
      public static int tierRule(Catch catch) {
          Fish fish = catch.getFish();
          return match (speciesToTier(fish.getSpecies())) {
              case "T1" -> 10 * fish.getLength();
              case "T2" -> 5 * fish.getLength();
              case "Trash" -> 2 * fish.getLength();
          }
      }
      
      public static int lureRule(Catch catch) {
          return (catch.getLure() ? 100 * catch.getFish().getLength() : 0);
      }
      
      public static int bonusRule(Catch catch) {
          Fish fish = catch.getFish();
          if (speciesToTier(fish.getSpecies()).equals("T1")) {
              return Math.max(5 * (fish.getLength() - 10), 0);
          }
      }
      
      // Apply all rules to a fish, adding the points from each one.
      public static int scoreCatch(Catch catch) {
          RULES.stream().reduce(0, (acc, rule) -> acc + rule(catch)); 
      }
      

      So for your example catch of

      {
          "fish": {
              "species": "T1",
              "length": 11.0,
          },
          "lure": false
      }
      

      you would effectively have tierRule(catch) + lureRule(catch) + bonusRule(catch) = 100 + 0 + 5.

      5 votes
  3. [8]
    moocow1452
    Link
    My brother is going to college for Astrophysics and I'm helping in with a data entry project. I'm using Matplotlib and Jupiter through python, and the end goal is that he can take a list of x...

    My brother is going to college for Astrophysics and I'm helping in with a data entry project. I'm using Matplotlib and Jupiter through python, and the end goal is that he can take a list of x variables, run it through a polynomial function and plot out a graph with it. When I try to feed the list of variables into the function, it chokes on the exponents and says that lists are not a valid input, so how can I get this to work?

    2 votes
    1. [7]
      gpl
      Link Parent
      Can you give a bit more detail? What does the list of x variables look like, and what is the polynomial function? If you have a code snippet that could be great.

      Can you give a bit more detail? What does the list of x variables look like, and what is the polynomial function? If you have a code snippet that could be great.

      2 votes
      1. [6]
        moocow1452
        Link Parent
        from matplotlib import pyplot as plt import numpy as np # X-axis values [0, 1, -1, np.pi, 3*1e8, np.e, -3/2] # Function of X def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4 # Function to plot...
        from matplotlib import pyplot as plt
        import numpy as np
        
        # X-axis values
        [0, 1, -1, np.pi, 3*1e8, np.e, -3/2]
        
        # Function of X
        def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
        
        # Function to plot
        plt.plot(x, f(x))
        
        # function to show the plot
        plt.show()
        

        It gives me this text,

        TypeError                                 Traceback (most recent call last)
        Cell In[82], line 8
              5 def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
              7 # Function to plot
        ----> 8 plt.plot(x, f(x))
             10 # function to show the plot
             11 plt.show()
        
        Cell In[82], line 5, in f(x)
        ----> 5 def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
        
        TypeError: unsupported operand type(s) for ** or pow(): 'list' and 'int'
        

        I'm using Jupyter for this work, and this isn't hard data so much as it is a proof of concept. Ideally it would graph the function and make a table, but baby steps.

        1 vote
        1. gpl
          Link Parent
          You should make the list a numpy array instead of a python list so that you can operate on it with **. For example, I think: from matplotlib import pyplot as plt import numpy as np # X-axis values...

          You should make the list a numpy array instead of a python list so that you can operate on it with **. For example, I think:

          from matplotlib import pyplot as plt
          import numpy as np
          
          # X-axis values
          x = np.array([0, 1, -1, np.pi, 3*1e8, np.e, -3/2])
          
          # Function of X
          def f(x): return pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
          
          # Function to plot
          plt.plot(x, f(x))
          
          # function to show the plot
          plt.show()
          

          Should work.

          3 votes
        2. [4]
          PetitPrince
          Link Parent
          Several things: One: def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4 This function doesn't return anything. It computes a value, but doesn't make it available outside of the scope of the function. Try...

          Several things:
          One:

          def f(x): pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
          

          This function doesn't return anything. It computes a value, but doesn't make it available outside of the scope of the function.

          Try instead

          def f(x): 
            return pow(x,3)*5 - pow(x, 2)*6 + x*2 +4
          

          Two:

          plt.plot(x, f(x))
          

          Assuming x was defined as x=[0, 1, -1, np.pi, 3*1e8, np.e, -3/2]

          What you actually gave to the f function is a list of integers, and not an individual integer. So Python try to exponent [0, 1, -1, π, ...] but doesn't know what to do with it.

          What you probably meant to do is to apply the function on every individual element of the list, and make another list out of those. The usual way to do it is with a list comprehension.

          So try this instead:

          x=[0, 1, -1, np.pi, 3*1e8, np.e, -3/2]
          y=[f(el) for el in x]
          plt.plot(x,y)
          plt.show()
          
          2 votes
          1. [3]
            moocow1452
            Link Parent
            Thanks for your help. Regarding the second point, I'm a little confused on what you're referencing with el.

            Thanks for your help. Regarding the second point, I'm a little confused on what you're referencing with el.

            1 vote
            1. whispersilk
              Link Parent
              el isn’t referencing anything, it’s binding. y=[f(el) for el in x] is saying “create an array called y by iterating over each element in x, which we will call el, and calling f(el) on it.” So y...

              el isn’t referencing anything, it’s binding. y=[f(el) for el in x] is saying “create an array called y by iterating over each element in x, which we will call el, and calling f(el) on it.”

              So y will be equal to [f(x[0]), f(x[1]), …].

              3 votes
            2. PetitPrince
              (edited )
              Link Parent
              What /u/uwhispersilk said. A list comprehension is like a tiny for loop that create a list out of another list, and I had to name the temporary variable somehow. I've chosen el, short for...

              What /u/uwhispersilk said. A list comprehension is like a tiny for loop that create a list out of another list, and I had to name the temporary variable somehow. I've chosen el, short for "element" but I could have chosen i or foo or heyEEAAOwonSeveralOscarsAintThatNice instead. It's as if I wrote:

              y = []
              for el in x:
                y.append(f(el))
              

              But with a one liner instead.


              Also look at /u/gpl answer. It's important to know what your function inputs and outputs. Generally Python's standard library assumes doing operation on a single number, but lot's of time in the numeric computation / scientific fields what you want is to work on vectors (for ease of use/readability, but also for performance reasons).

              So you'll likely use numpy, and this library includes both an optimized container to hold a collection of number (the numpy array), and the usual math function that works with those container. For instance you have math.sin in the standard library, and it has its counterpart in numpy: numpy.sin. As per the example, it works on both individual number but also numpy arrays:

              import matplotlib.pylab as plt
              x = np.linspace(-np.pi, np.pi, 201)
              plt.plot(x, np.sin(x))
              plt.xlabel('Angle [rad]')
              plt.ylabel('sin(x)')
              plt.axis('tight')
              plt.show()
              

              (linspace(a,b,n) create a numpy array of n evenly spaced numbers between a and b)

              There's also a numpy version of power that works similarly:

              >>> x1 = np.arange(6)
              >>> x1
              [0, 1, 2, 3, 4, 5]
              >>> np.power(x1, 3)
              array([  0,   1,   8,  27,  64, 125])
              
              1 vote
  4. akkartik
    Link
    I built a little flash card program over an evening to help our kids practice their spelling. But now we might end up just using physical note cards. Anyways, here it is:...

    I built a little flash card program over an evening to help our kids practice their spelling. But now we might end up just using physical note cards. Anyways, here it is:

    https://git.sr.ht/~akkartik/spell-cards.love

    Happy to help if someone wants to try using it.

    2 votes