Improving F# conditional assignment with match expression In my code I declared a dictionary to store various counters

let counters = Dictionary<Type, int>()

Later, I need to generate several labels using these counters, like this:

First type a label is generated for a given type, it should consist of the type name itself:
"MyType"
Subsequent label should be the type name, appended with the number of times a label was previously generated for that type, in parentheses:
"MyType (2)"

Here's how I'm accomplishing this now:

let t : Type = ...

let label =
    if (counters.ContainsKey(t)) then
        counters.[t] <- counter.[t] + 1
        sprintf "%s (%i)" t.Name counters.[t]
    else
        counters.Add(t, 1)
        t.Name

This is exactly how I would write it if I had to use C# (with the exception of the in-line if / else), but after I wrote it F#, it seems clumsy and a little messy. I suspect there is a much more elegant, idiomatic way of writing this in F#. Perhaps using a match expression?

Thanks to the input provided in the other answers, here's what I've come up with:

let label =
    let (found, value) = this.counters.TryGetValue(t)
    this.counters.[t] <- value + 1
    if found
    then (sprintf "%s (%i)" t.Name (value + 1))
    else t.Name

Or using a match expression

let label =
    let (found, value) = this.counters.TryGetValue(t)
    this.counters.[t] <- value + 1
    match found with
    | true -> (sprintf "%s (%i)" t.Name (value + 1))
    | false -> t.Name

I've also refactored this into a separate function, so the actual assignment is just

let label = getNextLabel(t)

Both of these look better than my original code, though I'm not sure that the match has added any expressiveness to the code, so for now I'm keeping the plain old if / else statement. This is mostly just taking advantage of the built-in behavior of dictionaries in .NET (TryGetValue returns the default value if the key is not found, and the Item property's setter will perform an insert if necessary), but I'm still open to any suggestions on improving this more.


Python file with several function definitions I have a Python file with several function definitions in it. One of the functions, named 'main' will be called as soon as the Python file is run.

Example:

myFile.py
import sys
def main(arg1....):
  ---code---

--more functions--

main()

When a person wants to run my file they'll type:

python myFile.py arg1 arg2 ...

The main function is supposed to accept in x number of arguments, however, in case the user doesn't wish to pass in any arguments we're supposed to have default values.

My program looks something like this and I'm hoping there is actually a better way to do this than what I have:

myFile.py
import sys
#Even though my function has default values, if the user doesn't wish
#to input in any parameter values, they still must pass in the word False
#otherwise, pls pass in parameter value
def main(name = "Bill", age = 22, num_pets=5, hobby = "soccer"):
   if len(sys) > 1:
      i =0
      while i < len(sys):
         if i == 0:
            if sys.argv[i] == "False":
               i += 1
               continue
            else:
                name = sys.argv[i]
                i += 1
                continue
         elif i == 1:
            if sys.argv[i] == "False":
     --------etc. etc.-----------

In case the number of arguments is really long then you can use **kwargs to avoid cluttering up arguments in function definition block. I would also avoid naming the function as "main" and replace it with something like "execute".

def execute(**kwargs):
  name = kwargs.get('name', 'Bill')
  # get other values
  pass

if __name__ = "__main__":
  execute(*sys.argv[1:])


Getting the remaining days of the current week I'm trying to get the remaining days of the current week, excluding weekends and past days, and I'm lazily checking for possible continuity of the week in the next month. This is not the best solution that I can think of (and even so, perhaps there are flaws), is there a simpler and clean way to achieve what I want?

function getDaysInMonth(month, year, holidays) {
    var date = new Date(year, month, 1);
    var today = new Date();
    today.setHours(0, 0, 0, 0);
    var days = [];
    var firstDay = 0;
    var remaining = [];
    var isWeekend = (today.getDay() === 6) || (today.getDay() === 0);
    while (date.getMonth() === month) {
        if ((date >= today) && (date.getDay() != 0) && (date.getDay() != 6)) {
            days.push(new Date(date));
        }
        date.setDate(date.getDate() + 1);
    }
    month += 1;
    while (date.getMonth() === month) {
        if ((date.getDay() != 0) && (date.getDay() != 6)) {
            days.push(new Date(date));
        }
        date.setDate(date.getDate() + 1);
    }
    if (holidays) {
        for (var index = 0; index < holidays.length; index++) {
            var holiday = new Date(holidays[index]);
            for (var id = 0; id < days.length; id++) {
                if (holiday.getTime() === days[id].getTime()) {
                    days.splice(id, 1);
                    break;
                }
            }
        }
    }
    if (!isWeekend) firstDay = days[0].getDay();
    for (var index = 0; index < days.length; index++) {
        if (isWeekend) {
            remaining.push(new Date(days[index]));
            if (index === 4) break;
        } else {
            if (days[index].getDay() >= firstDay) {
                remaining.push(new Date(days[index]));
            } else {
                break;
            }
        }
    }
    return remaining;
}

Update: I've expanded the code to query for possible holidays, holidays an array of dates (mm/dd/YYY).

First of all, never calculate dates yourself. If possible, always defer to a library that's built by people who know more about dates, who keeps rules up to date, and has more eyes on it to spot bugs than you and your code. For that, I forward you to moment.js. With that, calculating the remaining week days would be as simple as finding today's day number with day and subtracting it from 6 (Saturday's number).

const daysUntilWeekend = 6 - moment().day()

For work days (week days sans holidays) you simply need at least 3 moment instances, the first representing the start of the week, the second representing the end of the week, and the third (or more) representing the holidays. Then you can use isBetween to check if any of your holiday dates fall between the first two, and subtract how many match from 6 accordingly.

// May fail when today's saturday or sunday. Adjust this code accordingly.
const start = moment().day(1).startOf('day')
const end = moment().day(6).startOf('day')
const holidayMoments = [moment(), moment()] // Holiday dates in moments
const holidays = holidayMoments.filter(h => h.isBetween(start, end)).length
const today = moment().day()
const remainingWorkDays = 6 - (today + holidays)


Factory pattern for image or shape marker I'm making a photo marker application and need to make a factory pattern for marker. I think it is not very flexible and overall not good.

Would you check my code and suggest what could be improved?

import Foundation

enum MarkerType: String {
    case Shape, Image
}

enum MarkerError: ErrorType {
    case ImageNoExist
    case ShapeNoExist
}

struct ImageMarker {
    static func make(type: String) -> UIImageView {
        var imageStr: String = ""
        switch type {
        case "X":
            imageStr = "close.png"
            break
        default: break
        }

        let image = UIImage(named: imageStr)
        let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)
        let imageView = UIImageView(image: tintedImage)
        imageView.tintColor = UIColor.redColor()
        return imageView
    }
}

struct ShapeMarker {
    static func make(type: String) -> UIView {
        var shape: UIView = UIView()
        switch type {
        case "CIRCLE":
            //shape = CircleView()
            break
        default: break
        }

        return shape
    }
}

typealias Factory = (String) -> AnyObject

class MarkerHelper {
    class func factoryFor(type: MarkerType) -> Factory {
        switch type {
        case .Shape:
            return ShapeMarker.make
        case .Image:
            return ImageMarker.make
        }
    }
}

In looking at your code, what I see are a series of effectively global functions that "make" things based on a string.

The object that calls factoryFor must know what the string is in order to know which type of maker to return (after all, if the string is going to be "X", then the object that calls factoryFor has to know not to pass Shape.) Also, the caller of the factory function must know what the factory is making in order to correctly cast the AnyObject that is returned.

This leads me to wonder what the MakerHelper.factoryFor function's responsibility is? I mean, it's job just seems to be to return the make global function that the caller already knows it wants, so why not just have the caller use the make function directly?

It seems to me that you could have written:

import UIKit

func tintedImageViewNamed(name: String) -> UIImageView {
    let image = UIImage(named: name)
    let tintedImage = image?.imageWithRenderingMode(.AlwaysTemplate)
    let imageView = UIImageView(image: tintedImage)
    imageView.tintColor = UIColor.redColor()
    return imageView
}

func make(type: String) -> UIView? /* thanks nhgrif */ {
    switch type {
    case "CIRCLE":
        //return CircleView()
        return UIView()
    case "X":
        return tintedImageViewNamed("close.png")
    default:
        return nil
    }
}

The above accomplishes the same thing your code does, is no less safe and no more testable than what you have and it's a lot less complex (which means less chance of bugs.)

I'd love to suggest a better solution, but to do that, I would have to better understand what problem you are trying to solve...


Increment up the build number in AssemblyInfo.cs on every build I just wrote this short little program to increment up the build number for my projects every time I build them.

After compiling this exe, I just call it in the pre-build command line.

I did take out the filename string because I used it thrice, and I figured I'd get some flack if I didn't.

static void Main()
{
    int num;
    string file = "AssemblyInfo.cs";
    if (File.Exists(file))
        File.WriteAllLines(file, File.ReadAllLines(file).Select(s => !s.Trim().StartsWith("[assembly: AssemblyFileVersion(") ? s : string.Join(".", s.Trim(']').Trim(')').Trim('"').Split('.').Select((n, i) => i != 3 ? n : !int.TryParse(n, out num) ? n : (num + 1).ToString())) + "\")]"));
}

I realize this is complex, and the average person wont be able to read it. I use magic numbers, and I do some things specifically to keep the glory on 1 line. Feel free to bask in the presence of psychedelic code (which just wants to be your friend).

Why not use Regex.Match instead of using those confusing joins/splits? Unless you are purposely trying to code golf this, doing it using regular expression is much easier to follow logically.

After taking into account delegates used with Regex.Replace (as explained in svick's comment), here is a functionally superior solution to the previous answer I posted. This eliminates much of the unnecessary lambda pieces. The original solution is arguably not a good use of LINQ because of the changes being made to the collection (ie. not a very strong use of queries, despite lambdas having that functionality).

static void Main()
{
    string file = "AssemblyInfo.cs";
    if (File.Exists(file))
        File.WriteAllText(file,
            Regex.Replace(
                File.ReadAllText(file),
                @"(?<=\[assembly: AssemblyFileVersion\(""[0-9]*.[0-9]*.)[0-9]*(?=.[0-9]*""\)\])",
                m => (Convert.ToInt16(m.Value) + 1).ToString()
            )
        );
    }
}

Still only one semi-colon, but at least it's possible to look at it and recognize each piece for what it does. Note I split the parentheses onto separate lines here for parameter readability, but some programmers disagree with this style of line-breaking.

It basically works similar to your original solution, but it basically finds and replaces the Regex.Match with an incremented value.


Generic pipe and filters I made a template pipe and filters to replace an old pipe and filters implementation that used inheritance and had a very heavy base class.

#include <iostream>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <list>

template <typename Data>
class pipeline {
    typedef boost::function<Data(Data)> filter_function;
    typedef std::list<filter_function> filter_list;
    filter_list m_list;

public:
    template<typename T>
    void add(T t) {
        m_list.push_back(boost::bind(&T::filter, t, _1));
    }

    Data run(Data data) {
        typedef typename filter_list::iterator iter;
        iter end = m_list.end();

        for(iter it = m_list.begin(); it != end; ++it) {
            data = (*it)(data);
        }

        return data;
    }
};

struct foo {
    int filter(int i) {
        return i + 1;
    }
};

int main(int argc, _TCHAR* argv[])
{
    pipeline<int> pipe;
    foo f;
    pipe.add(f);
    std::cout << pipe.run(0);
    char c;
    std::cin >> c;
}

Except the fact that add() is a template, are there any issues anyone sees with this approach?

As run() is several lines long, it should be defined outside the class.  Anything defined inside is automatically inlined.
Depending on the size of data when passing by value, it may be best to pass it to run() by const&, modify a local copy, and return that.  RVO should still kick in.
Is there a significance to the name foo here?  If not, it should be more accurate and start with a capital letter as it's a user-defined type.  The capitalization also applies to pipeline.
iter end = m_list.end(); seems pointless here.  You can just use m_list.end() inside the loop statement.

As m_list is not being modified inside the loop, you can instead use cbegin() and cend() for const-correctness.

If you have C++11, you can use auto to replace the defined iterator inside the loop statement.
Your "pause" is okay, but you can also use std::cin.get() to do the same thing.


Stack Implementation I would like comments on my implementation of a stack:

template <class T>
class Stack {
 public:
        void pop(T& element);
        void push(const T& element);
 Stack();

 private:
         int elementCount_;
         int stackTop_;
  static const int  MAX_ELEMS = 10;
  T elementArray_[MAX_ELEMS];
};

template <class T>
Stack<T>::Stack() :
elementCount_(0),stackTop_(-1)
{
}

template <class T>
void Stack<T>::push(const T& element)
{
 if (stackTop_ == MAX_ELEMS-1){
            std::cout << "Stack is full" << "\n" ;
            return;
 }
        elementArray_[++stackTop_] = element;
 elementCount_++;
}

template <class T>
void Stack<T>::pop(T& element)
{
    if (stackTop_ == -1){
     std::cout << "Stack is empty" << "\n";
     return;
    }
    elementCount_--;
    element =  elementArray_[stackTop_--];
}

Here are some things that may help you improve your code.

Throw errors rather than printing error messages

The user of your code may be creating a GUI with no command line available and will not appreciate having your code printing instead of indicating an error to the calling code.  The two ways that C++ programs generally signal an error are either by throwing an exception (if the circumstance really is exceptional) or by returning a value that indicates an error.

Use consistent formatting

The code as posted has inconsistent indentation which makes it hard to read and understand. Pick a style and apply it consistently.

Consider adding functionality

Since this is a fixed-size rather than a dynamically sized stack, it would make sense to either allow the user to specify that size (as perhaps with a default parameter for the constructor) and to query it.  Also, consider adding functions such as isFull() and isEmpty().


Recognizing elements and doing event handling for repeating templates This fiddle has an ADD button when you click it a Chat window is added.  When there are more than 1 windows the message from one window is reflected across all the windows.

Say you have templates (in above case "Chat Window") which will repeat in DOM (i.e. append and removal will happen dynamically):

var html="
Chat Window

<textarea rows='4' cols='50'>  </textarea>
<input type='button' value='send'>
";

The above template keeps repeating in the DOM i.e. when you click on the ADD button they are added inside:

I have an event handler which listens to the clicks in its innerHTML:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');
if(event.target.value=="send"){
    for(var i=0;i<chatWindows.length;++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";
    }
    event.target.previousElementSibling.value=null;
}
},false);

I have a couple of questions regarding it:

Say each of the template has an event with it and a respective handler so say I add this template 10 times in DOM (i.e. click add button in the fiddle 10 times) then I want to do event handling for each of them, possible ways:

I append event handler to each of this template by giving the elements ID so I will have 10 event handlers which I feel is inefficient.
I have one event handler on the parent of these chat windows and then use event.target to extract the particular values (like I have done in fiddle as shown above). But its side effect is that it also listens to click events other then on the SEND button.

Which strategy to use from above?

I want to know that SEND button of which chat window was pressed i.e. chat window of what index but Ii don't want to give ID to my templates then how do I do it?
this will help me to display that message is coming from which chat window:

  Chat window {index} says: " check the above fiddle

You want to recognize individual/particular group of elements in JavaScript DOM the known ways are:

Provide ids to the elements dynamically before appending in DOM
Provide class names
Provide name attribute or any of your own attributes with some values

Among above which is most recommended?  Or if there is any other way too, then please specify.

In the Fiddle provided above, when you add more than one Chat window and then you type a msg and press SEND, I select all elements with P tag and replace their innerHTML to show message across all windows. As shown above in the handler and Fiddle.

But I know it is unsafe as, if there are other P tags in the page then they too will be screwed.  Can you suggest the best strategy for this?  How can I make sure that only P tags meant to display the chat message have their content changed?

Formatting Improvements

I don't have time for a full review, but I will help with some of these formatting issues.

Quoted sources: Douglas Crockford

1... You've got some invalid code in there. "Quotes" in JavaScript can't span multiple lines.

Invalid:

var html="
Chat Window

<textarea rows='4' cols='50'>  </textarea>
<input type='button' value='send'>
";

Valid:

var html = "
Chat Window

" +
        "<textarea rows='4' cols='50'>  </textarea>" +
        "<input type='button' value='send'>
";

2... Assignment operators, =, should be padded by a space.

Messy:

html="

Neat:

html = "

3... Variable names should be human readable.

Messy:

var e = document.getElementById('chatApp');

Neat:

var chatAppElem = document.getElementById('chatApp');

4... The parentheses of anonymous function literals should have one space of padding on either side.

Messy:

e.addEventListener("click", function(event){

Neat:

e.addEventListener("click", function (event) {

  If a function literal is anonymous, there should be one space between
  the word function and the ( (left parenthesis). If the space is
  omited, then it can appear that the function's name is function, which
  is an incorrect reading. -DC

5... Spaces should only be made in intervals of 4.

Messy:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');

Neat:

var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
    var chatWindows=document.getElementsByTagName('p');

  The unit of indentation is four spaces. Use of tabs should be avoided
  because (as of this writing in the 21st Century) there still is not a
  standard for the placement of tabstops. The use of spaces can produce
  a larger filesize, but the size is not significant over local
  networks, and the difference is eliminated by minification. -DC

6... Lines should be no longer than 80 characters.

Messy:

chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";

Neat:

chatWindows[i].innerHTML+= "Chat window {index} says: " +
    event.target.previousElementSibling.value+"
";

  Avoid lines longer than 80 characters. When a statement will not fit
  on a single line, it may be necessary to break it. Place the break
  after an operator, ideally after a comma. A break after an operator
  decreases the likelihood that a copy-paste error will be masked by
  semicolon insertion. The next line should be indented 8 spaces. -DC

7... Comments should be used generously. And remember: "Why" not "How".

Bad Practice:

  var e = document.getElementById('chatApp');
e.addEventListener("click", function(event){
 var chatWindows=document.getElementsByTagName('p');
if(event.target.value=="send"){
    for(var i=0;i<chatWindows.length;++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: "+ event.target.previousElementSibling.value+"
";
    }
    event.target.previousElementSibling.value=null;
}
},false);

Good Practice:

// Trigger a chat window when button is clicked.

var chatAppElem = document.getElementById('chatApp');      // Info about the purpose
chatAppElem.addEventListener("click", function (event) {   // of significant lines
var chatWindows = document.getElementsByTagName('p');      // will be a plus later on.
if(event.target.value == "send"){
    for(var i = 0; i < chatWindows.length; ++i){
        chatWindows[i].innerHTML+= "Chat window {index} says: " +
            event.target.previousElementSibling.value + "
";
    }
    event.target.previousElementSibling.value = null;
}
},false);

  Be generous with comments. It is useful to leave information that will
  be read at a later time by people (possibly yourself) who will need to
  understand what you have done. The comments should be well-written and
  clear, just like the code they are annotating. An occasional nugget of
  humor might be appreciated. Frustrations and resentments will not.

  It is important that comments be kept up-to-date. Erroneous comments
  can make programs even harder to read and understand.

  Make comments meaningful. Focus on what is not immediately visible.
  Don't waste the reader's time with stuff like

  i = 0; // Set i to zero.

  Generally use line comments. Save block comments for formal documentation -DC


Finding the longest overlapping period I have a list of records containing Id, DateFrom, DateTo. For the sake of this question we can use this one:

List<(int, DateTime, DateTime)> data = new List<(int, DateTime, DateTime)>
        {
            (1, new DateTime(2012, 5, 16), new DateTime(2018, 1, 25)),
            (2, new DateTime(2009, 1, 1), new DateTime(2011, 4, 27)),
            (3, new DateTime(2014, 1, 1), new DateTime(2016, 4, 27)),
            (4, new DateTime(2015, 1, 1), new DateTime(2015, 1, 3)),
        };

In my real case the List could be a lot bigger, for now I assume that there is only one entry for a certain Id.

The task is to find the two records that has the longest time overlap and to return the ids and the number of days overlapped.

Which in this sample case means that these should be records 1 and 3, because 2 is not overlapping with anyone, and 4 overlaps for shorter time.

My implementation of this is the following:

    public (int, int, int) GetLongestElapsedPeriod(List<(int, DateTime, DateTime)> periods)
    {
        int firstId = -1;
        int secondId = -1;
        int periodInDays = 0;

        foreach (var period in periods)
        {
            var Id = period.Item1;
            var dateFrom = period.Item2;
            var dateTo = period.Item3;

            for (int i = 0; i < periods.Count; i++)
            {
                if (Id != periods[i].Item1)
                {
                    var tempId = periods[i].Item1;
                    var tempDateFrom = periods[i].Item2;
                    var tempDateTo = periods[i].Item3;

                    if (tempDateFrom < dateTo && tempDateTo > dateFrom)
                    {
                        DateTime commonStartingDate = tempDateFrom > dateFrom ? tempDateFrom : dateFrom;
                        DateTime commonEndDate = tempDateTo > dateTo ? dateTo : tempDateTo;

                        var elapsedPeriod = commonEndDate - commonStartingDate;

                        if ((int)elapsedPeriod.TotalDays > periodInDays)
                        {
                            periodInDays = (int)elapsedPeriod.TotalDays;
                            firstId = Id;
                            secondId = tempId;
                        }
                    }
                }
            }
        }
        return (firstId, secondId, periodInDays);
    }

But I think this way is not very efficient and I'm looking for ideas to optimize this logic. Also, I suspect that this is variation of some more general algorithmic problem.

I am not a c# programmer.

Firstly, you use a for each and a nested for loop, but both of these are iterating through the same List. For consistency (and for the next comment to make sense), I suggest that you use for loops.

for (int i = 0; i < periods.Count; i++)

You could start i not from 0. but from your current location + 1 in the outer loop. The logic behind this is that you have already compared the pairs of periods previous to this - no need to double handle. Hence why using similar for loops will make this easier - you will be counting where you are in the List in the outer loop.

Making this small change means that if (Id != periods[i].Item1 is no longer needed - reducing one nesting level in the code.

As a 'meaningful name thing', I would call commonStartingDate and commonEndDate overlapStart and overlapEnd respectively - this is more descriptive of what you mean.
overlapStart = max(period1.Start, period2.Start)
overlapEnd = min(period1.End,period2.End)

Error checking: check that Item2 is always less than Item3 (and fix if not), otherwise your logic will be broken.

You could simplify var elapsedPeriod = commonEndDate - commonStartingDate and the following code by using:

int elapsedPeriod = (int)(commonEndDate - commonStartingDate).TotalDays

May not look simpler above, but in the next block:

                if (elapsedPeriod > periodInDays)
                {
                    periodInDays = elapsedPeriod;
                    firstId = Id;
                    secondId = tempId;

You don't use elapsedPeriod for anything else.

The main logic is good - I remember having to solve this problem 25 years ago when developing an accommodation booking database.


How to properly add some new arguments in a subclass? I am trying to subclass list in order to implement a callback function that would be called whenever a list item is being set.

I have this:

class CustomList(list):
    def __init__(self, *args, **kwargs):
        self.setitem_callback = kwargs['setitem_callback']
        del kwargs['setitem_callback']
        super().__init__(*args, **kwargs)

    def __setitem__(self, *args, **kwargs):
        super().__setitem__(*args, **kwargs)
        self.setitem_callback()

def callback():
    print('callback')

 l = ['a', 'b', 'c']
 custom_list = CustomList(l, setitem_callback=callback)
 custom_list[1] = 'd' # prints 'callback'

It works as expected, but I am concerned about having to do del kwargs['setitem_callback'] in order for the superclass' __init__ to work. Is it a bad practice? Are there any other ways to achieve the same?

As @Peilonrayz said in the comments: You can just write

class CustomList(list):
    def __init__(self, *args, setitem_callback, **kwargs):
        self.setitem_callback = setitem_callback
        super().__init__(*args, **kwargs)

    def __setitem__(self, *args, **kwargs):
        super().__setitem__(*args, **kwargs)
        self.setitem_callback()

def callback():
    print('callback')

l = ['a', 'b', 'c']
custom_list = CustomList(l, setitem_callback=callback)
custom_list[1] = 'd' # prints 'callback'

as long as you're okay with slightly different behavior when the caller forgets to pass setitem_callback= at all. With your original code, you get a KeyError:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    custom_list = CustomList(l)
  File "test.py", line 3, in __init__
    self.setitem_callback = kwargs['setitem_callback']
KeyError: 'setitem_callback'

With a proper keyword argument, you get a TypeError with a more tailored message:

Traceback (most recent call last):
  File "test.py", line 16, in <module>
    custom_list = CustomList(l)
TypeError: __init__() missing 1 required keyword-only argument: 'setitem_callback'


Recursive Fibonacci generator I decided to write a function that would generate an index of the Fibonacci sequence making use of Python's mutable default parameter. It's inspired by a question I answered on Stack Overflow where someone was converting a script with this idea from JavaScript to Python and I wanted to expand on it to see how I could handle it.

I wanted to basically try calling an index of the list and if it doesn't exist, try generating it from the previous two indices. However if they don't exist, then keep going back until two existing cached results are found and work off of those. I wanted to guard against errors from exceeding the recursion depth without necessarily rejecting a number. For instance, calling fib(1800) immediately exceeds (my) recursion depth, but my while loop will allow you to get the result.

For values that prove too high, I reject them with a ValueError. Though this does print every line of the recursive call's error. I'd like to know how I can handle this raise better to avoid that.

I'd also like to know if I could actually increase the viable number, if there's a good way to calculate what is a reasonable number better. I currently halve the recursion limit value mostly for safety but I'm sure that's not the best way. I'm also interested to know about any potential dangers of the cache getting too large and how those should be dealt with.

from sys import getrecursionlimit

rec = getrecursionlimit() * 0.9

def fib(n, rec=rec, memo=[0,1]):
    """Return the sum of the fibonacci sequence up until n

    rec is the recursion limit, and should be left as default.
    memo is the cached list of fibonacci values.
    raises a ValueError if your value is too high.
    If that happens, call lower values to build up the cache first."""

    while (n - len(memo)) >= rec:
        rec /= 2
        try:
            fib(int(len(memo) + rec), rec)
        except RuntimeError:
            raise ValueError("Input is too high to calculate.")

    try:
        return memo[n]
    except IndexError:
        # Calculate the answer since it's not stored
        memo.append(fib(n - 1) + fib(n - 2))
        return memo[n]

As pointed out, top-down recursive approaches are almost never a good idea when it comes to Fibonacci numbers. Consider the alternative iterative approach:

def fib(n):
    while n <= len(fib.cache):
        fib.cache.append(fib.cache[-1] + fib.cache[-2])
    return fib.cache[n]
fib.cache = [0, 1]

Notice how the memoization cache is stored as an attribute of the function, which is the closest thing in Python to having a static variable inside a function.


Entity Framework Code First Softball Stats Database Schema I am creating a website for my buddies and I to track all of our offensive softball stats. I am getting tired of maintaining a huge excel spreadsheet and emailing it out every week, so a website is the way to go.

I've created the DB a few times but I want to make sure I am making this thing right without duplicating data. Here is what I have for models:

public class Person
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string NickName { get; set; }
}

public class Player : Person
{
    public int Id { get; set; }

    public virtual ICollection<Team> Teams { get; set; }
}

public class Manager : Person
{
    public int ID { get; set; }

    public ICollection<Team> Teams { get; set; }
}

public class Game
{

    public int ID { get; set; }
    public int TeamID { get; set; }
    public String Opponent { get; set }
    public DateTime? GameDate { get; set; }
    public string Score { get; set; }
    public Results Result { get; set; }

    public virtual Team Team { get; set; }
    public virtual ICollection<Stat> Stats { get; set; }
}

public class League
{
    public int ID { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Team> Teams { get; set; }
}

public enum Results
{
    W, L
}

public class Stat
{
    public int ID { get; set; }
    public int PlayerID { get; set; }
    public int GameID { get; set; }

    public virtual Player Player { get; set; }
    public virtual Game Game { get; set; }

    public int? BattingOrder { get; set; }
    public int? PA { get; set; }
    public int? Single { get; set; }
    public int? Double { get; set; }
    public int? Triple { get; set; }
    public int? HR { get; set; }
    public int? RBI { get; set; }
    public int? BB { get; set; }
    public int? SAC { get; set; }
    public int? RBoE { get; set; }
    public int? R { get; set; }

    public int? H { get { return Single + Double + Triple + HR; } }
    public int? AB { get { return PA - (BB + SAC + RBoE); } }
    public double? BA { get { return Math.Round(((double)H / (double)AB), 3); } }
    public int? TB { get { return Single + 2 * Double + 3 * Triple + 4 * HR; } }
    public double? SLG { get { return Math.Round(((double)TB / (double)AB), 3); } }
    public double? OBP { get { return Math.Round(((double)(H + BB) / (double)(AB + BB + SAC)), 3); } }
    public double? TBP { get { return Math.Round(((double)(H + BB) / (double)(AB + BB)), 3); } }
    public double? RC { get { return Math.Round(((double)OBP * (double)TB), 3); } }
}

public class Team
{
    public int ID { get; set; }
    public string Name { get; set; }
    public WeekNights WeekNight { get; set; }
    public int? Year { get; set; }

    public int ManagerID { get; set; }
    public virtual Manager Manager { get; set; }
    public virtual League League { get; set; }
    public virtual ICollection<Game> Games { get; set; }
}

public enum WeekNights
{
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday
}

The 1-1 relationships aren't an issue, it's relating players to a team and a game and linking the stats that's hanging me up. If anyone has any advice or better, a schema drawing, that would be awesome.

Also, is it better to have Angular calculate the 'calculated' stats on the front end instead of trying to save them in the database? I didn't know how much that would slow down the sight calculating the stats every time you click a new player or game.

It depends on how you are planning on aggregating the stats.

Right now you have fields in your stat table that appear to really only apply when they are associated with a specific entity (player or team). For example, what does RBI on a stats record associated with a team mean?

I would avoid a design where a field like RBI means different things depending on what it's associated with. I'd personally prefer something like RBI to be only associated with a player.

In the case you do want to generate stats like "give me all RBI for the game" too and store it in the same field, you can use table per hierarchy and make entities TeamStats and PlayerStats based on a discriminator, and have RBI on the base class. I will caution that this approach is more difficult to set up and can lead to difficulty when maintaining it.

Another option is to track stats by player and compute team stats/game stats on demand (maybe via a stored proc, etc). The drawback there is that if doing so becomes computationally expensive then you have to worry about staging the data and dealing with possibly out-of-date data.

I would recommend setting up the following relationship structures:

Players belong to Teams
Games have their own Id and 2 Team FKs (so two teams can play multiple times)
A Stat is the stats for a player for 1 game, that has a composite PK consisting of Player Id and Game Id (I think this is no longer a hassle with EF).

The stats-per-player-per-game approach will allow you the most flexibility but also potentially the most on-demand computational overhead, but I'd start there until you start experiencing bottlenecks.

Since you're going to be doing decimal computations I'd avoid float and go with decimal to avoid potential loss of precision.

As for how to present the computed stats, I'd use stored procedures/functions whose results get mapped to web API models so the data is immutable as soon as you get it from the database. If that becomes annoying or too complex, you can also go the route of querying and aggregating/computing the stats in a middle application layer. I would avoid doing any computations on the front end.


How to set multiple variables at once in JavaScript? I have been setting multiple variables like this

function doSomething() {

    var FirstName = $FirstName.data("ov");
    var LastName = $LastName.data("ov");
    var Company = $Company.data("ov");
    var Website = $Website.data("ov");

}

I just read some reviewed code and both reviewers advised setting the variables in a single statement, like this:

function doSomething() {

    var FirstName = $FirstName.data("ov"),
        LastName = $LastName.data("ov"),
        Company = $Company.data("ov"),
        Website = $Website.data("ov");

}

What would be the advantage of doing it the second way? Is there a performance benefit? Is it that there is less code?

From a very good book called JavaScript Patterns:

  Using a single var statement at the top of your functions is a useful pattern to adopt.  It has the following benefits:

  Provides a single place to look for all the local variables needed by the function
  Prevents logical errors when a variable is used before it's defined
  Helps you remember to declare variables and therefore minimize globals
  Is less code (to type and to transfer over the wire)

The author also recommends initializing the variables when you declare them when possible.


A PHP function to check for cookies I've written a php function and some helper functions that checks for cookies when somebody lands on a page but it's not so fast. I want to know is there any way to make it faster or improve it i know it's possible to check for cookies client side using javascript but what if it is disabled also so i need a pure server side solution.

<?php

function check_cookie(){
    if(is_cookie_disabled()){
        header("location:cookie_is_disabled.php");
        exit;
    }
}

function is_cookie_disabled(){
    $curr_url = $_SERVER['PHP_SELF'];
    if(isset($_COOKIE['testCookie']) && !(isset($_COOKIE['cookie']))){
        $original_url = original_url ($curr_url);
        header("location: ".$original_url);
        setcookie("cookie", 'enabled');
        exit;
    } elseif(!(isset($_COOKIE['testCookie']))) {
        if(isset($_GET['temp'])){
            return true;
        } else{
            if(if_parameters_exist_in_url($curr_url)){
                $url = $curr_url."&temp=temp";
            } else {
                $url = $curr_url."?temp=temp";
            }
            header("location: ".$url);
            setcookie("testCookie", 'test');
            exit;
        }
    }
    return false;
}

function original_url ($curr_url){
    if (!empty($_GET)){
        if (isset($_GET['temp'])) {
            if(count($_GET)>0){
                return removeqsvar($curr_url, 'temp');
            } else {
                return removeallvars($curr_url);
            }
        }
    }
    return $curr_url;
}

function removeqsvar($url, $varname) {
    return preg_replace('/([?&])'.$varname.'=[^&]+(&|$)/','$1',$url);
}

function removeallvars($url){
    return $url = strtok($url, '?');
}

function if_parameters_exist_in_url($url){
    if (strpos($url, '=')) {
        return true;
    } else {
        return false;
    }
}

//at the top of your pages
check_cookie();

?>

It could be slow from all of the location redirects. But I've never done anything like that so I can't be sure.

Is it possible to lazily set the cookies. For instance, set a session and cookie on the first page load. And then, on the second page load check if the cookie is present.

This is how you could check if the page has loaded.

session_start();
$_SESSION['first_load'] = isset($_SESSION['first_load']) ? false : true;

if( !$_SESSION['first_load'] && isset($_COOKIE['testCookie']) )
  echo 'cookies enabled!'
else
  echo 'no cookies for you!'


Remove the first N elements from an array while reducing the N variable I'm trying to remove the first $offset elements from an array and reduce the offset for future adds to the array. The loop must also end if I reach the end of the array.

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

I'm trying to find a better way to do it. At least a way to use the values of $offset and count($elements) (which are changing) without having to create aux variables.

Code style

Variable names

Make sure that your variable names are descriptive of what they contain. In particular $max1 and $max2 use a poor naming style as it is unclear what you expect them to contain.

Whitespace

Make sure to keep whitespace around your operators, even in a for-loop. This increases readability, and thus decreases the chance for bugs.

Unneeded bookkeeping

You currently use $offset--; but do not use the result. Remove code you do not use.

Bugs

Your current code only works once, because you keep the keys. Considering the following code:

$offset = 3;
$elements = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

$max1 = $offset;
$max2 = count($elements);
for ($i=0; ($i<$max1 && $i<$max2); $i++) {
    unset($elements[$i]);
    $offset--;
}

var_dump($elements);

// Result: array(11) { [3]=> int(3) [4]=> int(4) [5]=> int(5) [6]=> int(6) [7]=> int(7) [8]=> int(8) [9]=> int(9) [10]=> int(10) [11]=> int(11) [12]=> int(12) [13]=> int(13) }

You would expect it to remove the first 3 elements twice, but because the keys are not reset, the second iteration of your code will try to remove key 0, 1 and 2, while the first key is 3.

Algorithm

Your current code modifies an array in-place while keeping the keys. Modifying arrays while looping over them is aweful in any language, as you need to be mindful that conditions in loops may be pre-calculated, and element pointers may skip elements.

Since you use a for-loop, I can assume you use an array with numeric keys, which makes it odd that you would want to keep the current keys.

Alternative creating a new array

In php you can use array_slice to obtain a new array with only a slice of the original array. This will reset the keys of the array.

$elements = array_slice($elements, $offset);

No loop required.

Alternative deleting elements

You can use array_splice to modify an array in-place by deleting a consecutive chunk of array elements. It returns the deleted elements and the original array has a few less elements. This will also reset the keys.

array_splice($elements, 0, $offset);

Again, no loop required.

Alternative with a loop

You can also use a loop and use array_shift to remove the first element of the array repeatedly. For numeric keys the keys are reset, while literal keys are left untouched.

for ($i = 0; $i < $offset; $i++) {
  $result = array_shift($elements);
  if (is_null($result)) {
    // The array is empty, so safe us some time
    break;
  }
}

Filter to keep keys

If we want to keep keys, we can use array_filter. The following code works exactly like your own code, as in: It works the first time you invoke it, and then it breaks.

$elements = array_filter(
  $elements,
  function ($item, $index) use ($offset) {
    return $index >= $offset;
  },
  ARRAY_FILTER_USE_BOTH
);

You can improve that code by using and checking against $offset + $first_key.

reset($elements);
$first_key = key($array);


Converting from decimals to roman numerals I've submitted the following code for a job interview, and I wanna know if there is anything I can improve on it, or better ways to do the same thing.

const algarismsMap = {
    1 : {
        1 : 'I',
        4 : 'IV',
        5 : 'V',
        9 : 'IX'
    },
    1e1 : {
        1 : 'X',
        4 : 'XL',
        5 : 'L',
        9 : 'XC'
    },
    1e2 : {
        1 : 'C',
        4 : 'CD',
        5 : 'D',
        9 : 'CM'
    },
    1e3: {
        1 : "I\u0305",
        4 : 'I\u0305V\u0305',
        5 : 'V\u0305',
        9 : 'I\u0305X\u0305'
    },
    1e4: {
        1 : "X\u0305",
        4 : 'X\u0305L\u0305',
        5 : 'L\u0305',
        9 : 'X\u0305C\u0305'
    },
    1e5 : {
        1 : "C\u0305",
        4 : 'C\u0305D\u0305',
        5 : 'D\u0305',
        9 : 'C\u0305M\u0305'
    }
}

const divisors = Object.keys( algarismsMap ).reverse()

const romanizeNumber = module.exports = function( n ) {

    // not throwing an error because this can happen while recursing
    if ( n <= 0 ) {
        return ''
    }

    // welp, for numbers greater than 3999999 we break roman rules of not repeating the same algarism more than 3 times,
    //   or we need to add more dashes, which is not really documented, at least I could not find some reliable source about it.
    if ( n >= 4e6 ) {
        throw new Error( 'The max supported number to be converted is 3999999' )
    }

    let romanizedNumber = ''

    // Some special cases for the M algarism.
    if ( n >= 1e3 && n <= 3999 ||  n >= 1e6 && n <= 3999999 ) {

        romanizedNumber += ( n >= 1e6 ? 'M\u0305' : 'M' ).repeat( n / (n >= 1e6 ? 1e6 : 1e3 ) )
        romanizedNumber += romanizeNumber( n % (n >= 1e6 ? 1e6 : 1e3 ) )

    } else {

        for ( let i = 0; i < divisors.length; i++ ) {

            const currDivisor = divisors[i]|0
            const currDivisorInfo = algarismsMap[currDivisor]

            const internalDivisors = Object.keys( currDivisorInfo ).reverse()

            // The number is not divisible by this one, keep going (we could just check if n < currDivisor duh)
            if ( n % currDivisor === n ) {
                continue
            }

            for ( let k = 0; k < internalDivisors.length; k++ ) {

                const currInternalDivisor = internalDivisors[k]|0
                const currInternalDivisorAlgarism = currDivisorInfo[currInternalDivisor]

                if ( n >= currInternalDivisor * currDivisor ) {

                    // the 1 check here is basically for the same motive than the 'M' check above.
                    romanizedNumber += currInternalDivisor === 1 ? currInternalDivisorAlgarism.repeat( n / currDivisor ) : currInternalDivisorAlgarism

                    romanizedNumber += romanizeNumber( n % (currInternalDivisor * currDivisor) )

                    return romanizedNumber
                }
            }
        }

    }

    return romanizedNumber
}

The \u0305 is the unicode for the combining overline character: https://en.wikipedia.org/wiki/Overline

I would define a constant overline="\u0305" and then use interpolation further down: 4 : `C${overline}D#{overline}`,, it might even make sense to define overlineD and overlineC constants. An alternative might be to create an overline method and write something like 4: overline('CD') or even a tagged template literal (4: overline`CD`) if you want to impress.
Object.keys( algarismsMap ).reverse(): The order of keys in a hash is not guaranteed, it can vary depending on the implementation and if keys have been deleted, etc. If you need order you should use an array. Also rather than reversing just define it backwards.
Rather than if {...} else [lots of code] I find it better to use an early return if {...; return; } [lots of code]
One of the biggest thing to me is the lack of tests.  I would expect to see something in an interview assignment, it doesn't have to use a framework, I would be fine with something like:

function test(number, roman) {
  if (romanizeNumber(number) !== roman)
    console.error(`Failed! ${number} should be ${roman} but was ${romanizeNumber(number)}`);
}
test(10, 'X');
test(11, 'XI');
...


Generate String Combinations I have created an algorithm that can generate all possible combinations of a string given its length, and character set (it uses a custom numeral system to do this). How could I improve its performance and readability?

using System;
using System.Text;

public class Program
{
    public static void Main(string[] args)
    {
        Bruteforce brute = new Bruteforce(9, new Range(0, Helpers.Chars.Length - 1));
        brute.PrintResults();

        Console.ReadKey(true);
    }
}

public class Bruteforce
{
    private int _Length;
    private Range _Range;

    public int Length
    {
        get
        {
            return _Length;
        }
    }

    public Range Range
    {
        get
        {
            return _Range;
        }
    }

    public Bruteforce(int length, Range range)
    {
        _Length = length;
        _Range = range;
    }

    public Bruteforce(int length, int min, int max)
    {
        _Length = length;
        _Range = new Range(min, max);
    }

    public void PrintResults()
    {
        int num = this.Range.Max;
        int[] arr = new int[this.Length];
        for (int c = 0; c < arr.Length; c++) arr[c] = this.Range.Min;
        while (true)
        {
            arr[0]++;
            if (arr[0] > this.Range.Max)
            {
                for (int i = 1; i < arr.Length; i++)
                {
                    if (arr[i - 1] > this.Range.Max)
                    {
                        arr[i - 1] = this.Range.Min;
                        arr[i]++;
                    }
                }
            }

            int num2 = arr[0];
            for (int i = 1; i < arr.Length; i++) num2 += arr[i];

            Console.WriteLine(Helpers.ArrayToString(arr));

            if (num2 == this.Range.Max * arr.Length) break;
        }
    }

    private void PrintArray(int[] arr)
    {
        for (int i = 0; i < arr.Length; i++)
        {
            if (i == arr.Length - 1)
            {
                Console.WriteLine(arr[i]);
            }
            else
            {
                Console.Write(arr[i] + ", ");
            }
        }
    }
}

public class Helpers
{
    public static char[] Chars = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' };
    public static string ArrayToString(int[] arr)
    {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < arr.Length; i++)
        {
            if (arr[i] >= 0)
            {
                builder.Append(Helpers.Chars[arr[i]]);
            }
            else
            {
                throw new Exception();
            }
        }
        return builder.ToString();
    }
}

public class Range
{
    private int _Max, _Min;

    public int Max
    {
        get
        {
            return _Max;
        }
    }

    public int Min
    {
        get
        {
            return _Min;
        }
    }

    public Range(int min, int max)
    {
        _Max = max;
        _Min = min;
    }
}

string.Join(string, IEnumerable<T>)

Your method ArrayToString can be replaced with a single line :

public static string ArrayToString(int[] arr)
{
    return string.Join("", arr.Select(x => Chars[x]));
}

Your method PrintArray is never used but I assume it's just there for testing purpose.

Code style

Auto properties

You can use auto-properties to avoid explicitly creating a backing field for your variables :

private int _Length;

public int Length
{
    get
    {
        return _Length;
    }
}

Can be simplified to a single property :

public int Length { get; }

You can do the same for all of your properties.

Redundant this qualifier

You don't have to write this. everywhere e.g this.Range.Max as there are no variables with the same names there, the compiler will guess that you are referring to the container class.


Merge sort Java implementation for an interview I just learned Merge sort, and I really like this Merge sort implementation since it is very logical and very easy to follow. If I was asked in an interview to implement merge sort, will this implementation suffice?

I know creating those new arrays every time the mergeSort() method is called is bad practice. I fully understand merge sort, I can explain it in very good detail as I implement it, but will this implementation lose me some "points" because of the the way I am creating all these new arrays?

Are there any other things that may lose me some points?

public static void mergeSort(int[] a) {
    if(a.length < 2) return;

    int mid = a.length / 2;

    int[] left = new int[mid];
    int[] right = new int[a.length - mid];

    //Filling left and right arrays.
    for(int i = 0; i < left.length; i++)
        left[i] = a[i];
    for(int i = 0; i < right.length; i++)
        right[i] = a[i + mid];

    mergeSort(left);
    mergeSort(right);
    merge(left, right, a);
}

public static void merge(int[] left, int[] right, int[] a) {
    int i = 0; //For left array
    int j = 0; //For right array
    int k = 0; //For a array

    while(i < left.length && j < right.length) {
        if(left[i] <= right[j])
            a[k++] = left[i++];
        else
            a[k++] = right[j++];
    }

    //Filling remaining integers, for the array that has left over numbers.
    while(i < left.length)
        a[k++] = left[i++];
    while(j < right.length)
        a[k++] = right[j++];

}

This is tested and working.

Here are some thoughts on things you might improve:

Always use curly braces, even when they're optional. This is a common source of errors when existing code is modified.

int i == 0; //For left array should be int leftArrayIndex = 0. Don’t use a comment to label a variable .. use the variable’s name to do that. Same thing for j and k.

mid should be midpoint, perhaps? originalArray instead of a? Variable names should be clear and descriptive. Avoid abbreviations where possible.

Almost all Java style guides put a space between if, for, or while and their opening paren. This easily differentiates them from method calls.

Variables that don’t change should be declared final.

Learn and use the libraries. In particular, System.arraycopy() is preferable to looping to manually copy array entries.

merge should be private, not public.


how can I optimize this code for a powerline? I made this code for a past test, I only got 30/100 points obtainable, because it went out of time,how can I make it more efficient?
#include <iostream>
#include <fstream>
bool check(int s[], int n)
{
    for (int i = 0; i < n; i++)
    {
        if (s[i] < s[i + 1] && i != n - 1)
        {
            return false;
        }
    }
    return true;
}
int main()
{
    std::ifstream in("input.txt");
    std::ofstream out("output.txt");
    int n;
    int s[1000000];
    bool legge = false;
    int c = 0;
    in >> n;
    for (int i = 0; i < n; i++)
    {
        in >> s[i];
    }
    legge = check(s,n);
    while (!legge)
    {
        for (int i = 0; i < n; i++)
        {
            int m = i+1;
            if (s[i] < s[m] && i != n-1)
            {
                s[i] = s[m];
            }
        }
        legge = check(s,n);
        c ++;
    }
    out << c;
}

Text:
In order to increase their efficiency, a new law mandates that every tower in a power line must be at least
as high as the following one. Luca needs to change the height of some towers, in order to meet the new
requirements. Every day, starting from the first tower, Luca will increase the height of every tower to
the same height of the next one. Of course, if one tower is already taller than the following one it will
not be modified. How many days does Luca need to finish the job?

There are several reasons why your solution is slow. However, the main reason is because you are actually performing all the steps that Luca would do, but the goal is just to determine the number of days Luca would need. So try to think of a way to determine that number by just looking at the all the tower heights once.
It helps to look at a few special cases first. Consider the towers having stricly descending heights:
5, 4, 3, 2, 1

It is clear that nothing has to be done, so this would take 0 days. Now look at the towers having strictly ascending heights:
1, 2, 3, 4, 5

It should be fairly obvious that it will take Luca 4 days to fix this, as the result of every day's worth is that it basically shifts the heights to the left, like so:
day 1: 2, 3, 4, 5, 5
day 2: 3, 4, 5, 5, 5
day 3: 4, 5, 5, 5, 5
day 4: 5, 5, 5, 5, 5

So now let's look at a more complex case:
4, 5, 1, 2, 3

The key insight is that there are two distinct regions of increasing heights:
4, 5 and 1, 2, 3

The first region takes one day to fix, the second two days. But this happens in parallel of course, so it's just a matter of finding the largest region of increasing heights, and subtract one from its length to get the number of days Luca needs. There's just one complication, let's look at this example:
2, 3, 1, 4, 5

Again there are two regions of strictly increasing heights, but it should be clear that since the second region's maximum height is larger than the first region's, it will actually take 4 days to finish the job. So what you should do is divide it in regions that each end at the maximum possible height. For example, take this example:
1, 3, 5, 7, 9, 2, 8, 4, 6
            ^     ^     ^
            |     |     |

I marked the positions of the end of each region. The first region's length is 5, the second and third have length 2. So the number of days necessary is 4. But how to find these maxima efficiently? If you scan forward you wouldn't know where the maximum of the first region is until you've seen all numbers. You then need to repeat this for all the points after the maximum. However, if you work backwards you only need to go through the heights once: you keep track of the maximum so far, and how many points you have visited. As soon as you see a height larger than the maximum you have so far, you store the length so far if that is the largest length you've seen so far, and then replace the current maximum with the new maximum you just found:
int maximum = -1; // assuming no tower has negative height
int length = 0;
int longest = 0;

for (int i = n - 1; i >= 0; i--)
{
    if (s[i] > maximum) {
        if (length > longest)
            longest = length;
        maximum = s[i];
        length = 0;
    } else {
        length++;
    }
}

if (length > longest)
    longest = length;

out << longest << "\n";


Implementation of mergesort in C I have implemented mergesort in C. Any advice on making it more compact? My merge function seems less than fully optimal.

//mergeSort in C

#include <stdio.h>
#include <stdlib.h>

void merge(int [], int[], int[], int, int);
void mergesort(int[], int);

int main()
{
    int unsorted[] = {4, 1, 3, 0, 10, 2, 5, 5};
    int size = sizeof(unsorted)/sizeof(int);
    mergesort(unsorted, size);
    printf("The sorted array is: ");
    for(int i = 0; i < size; i++)
    {
        printf("%d, ", *(unsorted+i));
    }

    return 0;
}

void merge(int *original, int* first, int* second, int len1, int len2)
{
    int i = 0;
    int firPtr = 0;
    int secPtr = 0;

    while(i < (len1+len2))
    {
        if(firPtr == len1)
        {
            original[i] = second[secPtr++];
        }

        else if(secPtr == len2)
        {
            original[i] = first[firPtr++];
        }

        else if(first[firPtr] < second[secPtr])
        {
            original[i] = first[firPtr++];
        }

        else
        {
            original[i] = second[secPtr++];
        }
        i++;
    }
}
void mergesort(int unsorted[], int size)
{
    if(size <= 1 || unsorted == NULL)
    {
        return;
    }

    int *first = (int *)malloc((size/2)*sizeof(int));
    int *second = (int *)malloc((size - size/2)*sizeof(int));;

    int mid = size/2;

    for(int i = 0; i < mid; i++)
    {
        *(first+i) = *(unsorted+i);
    }

    //Common Error/Note to self: Make sure when initializing j to
    //not 0, the code block truly requires that.
    for(int j = (mid); j <  size; j++)
    {
        *(second+(j-mid)) = *(unsorted+j);
    }

    mergesort(first, mid);
    mergesort(second, size - mid);
    merge(unsorted, first, second, mid, size - mid);
    free(first);
    free(second);
}

Taking memory into consideration:

That code uses \$(n*log(n))\$`sizeof(int)` bytes of heap memory for array elements storage.

This code makes it n `sizeof(int)`. By creating temporary memory only once and passing it to other functions, it saves significant memory in case of large arrays.

/* sorts given input array in ascending order */

void merge_sort (int * arr,int size)
{
    int *temp;
    if((temp = (int*)malloc(sizeof(int)*size))!=NULL)
      msort(arr,temp,0,size-1) ;
}

void msort(int * arr,int * temp,int first,int last)
{
    if (first>= last) return ;

    int split = (first+last) / 2 ;

    msort(arr,temp,first,split) ;
    msort(arr,temp,split+1,last) ;
    merge(arr,temp,first,split,last) ;
}

void merge (int * arr,int *temp,int f_start,int f_end,int s_end)
{
                                /*    s_start == f_end+1      */
    int i = f_start ;
    int j = f_end+1 ;
    int k = f_start ;

    while (i<=f_end && j<=s_end)
    {
        if (arr[i]<arr[j])
            temp[k++] = arr[i++] ;
        else
            temp[k++] = arr[j++] ;
    }

    while (i<=f_end)
            temp[k++] = arr[i++] ;

    while (j<=s_end)
            temp[k++] = arr[j++] ;

    for (i=f_start ; i<=s_end ; i++)
    {
        arr[i] = temp[i] ;
    }
}


Using deftype to create a wrapper class for byte arrays I want to create a wrapper class for byte arrays so that I can use them as keys in fastutil's Object2LongAVLTreeMap. I have created a wrapper like this:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [this other]
    (let [m (alength ^bytes (.ba this))
          n (alength ^bytes (.ba other))
          l (min m n)]
      (loop [i 0]
        (if (< i l)
          (let [a (aget ^bytes (.ba ^Bytes this) i)
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))

The wrapper needs to implement Comparable for the insertions in the AVL Tree.

I am looking for feedback regarding my overall approach and my implementation of compareTo. I will be inserting lots of entries into the tree so I don't want to be creating unnecessary objects, etc. during the comparison.

EDIT: I believe the code above has a bug. See my comment below.

First, your calls to .ba aren't being resolved for other, so that's forcing use of reflection. If you run lein check, you'll see:

Reflection warning, thread_test.clj:22:22 - reference to field ba on java.lang.Object can't be resolved.

This has the potential to slow the method down, although it only happens once per call, so the effect wouldn't be huge.

Use explicit type hints to ensure it knows what types you're working with, just like you did below that:

(let [m (alength ^bytes (.ba ^Bytes this))
      n (alength ^bytes (.ba ^Bytes other))

I tried type hinting the parameters instead, and got an error I've never gotten before. I think it was looking for a compareTo with Object parameters, so saying the parameters were Bytes was throwing it.

Other than that, I don't see anything performance related. I'll just point out, in case you don't know, this' ba is actually in scope. You can use it directly which gets rid of some bulk, although makes some of the code less symmetrical:

(deftype Bytes [^bytes ba]
  Comparable
  (compareTo
    [_ other]
    (let [m (alength ba) ; Here
          n (alength ^bytes (.ba ^Bytes other))
          l (min m n)]
      (loop [i 0]
        (if (< i l)
          (let [a (aget ba i) ; And here
                b (aget ^bytes (.ba ^Bytes other) i)
                d (compare a b)]
            (if (zero? d)
              (recur (inc i))
              d))
          (compare m n))))))


Improvements to data access layer public class EmployeeDBHandler
    {
        public List<Employee> GetEmployees()
        {
            List<Employee> empList = new List<Employee>();
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("GetAllEmployee", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlConn.Open();
            using (SqlDataReader reader = sqlCmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var emp = new Employee()
                    {
                        EId = (int)(reader["EmpID"]),
                        FirstName = Convert.ToString(reader["FirstName"]),
                        LastName = Convert.ToString(reader["LastName"])
                    };
                    empList.Add(emp);
                }
            }
            return empList;
        }
        public List<Employee> FetchEmployee(int empid)
        {
            List<Employee> empList = new List<Employee>();
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_FetchEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID", empid);
            sqlConn.Open();
            using (SqlDataReader reader = sqlCmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    var emp = new Employee()
                    {
                        EId = (int)(reader["EmpID"]),
                        FirstName = (reader["FirstName"].ToString()),
                        LastName = (reader["LastName"].ToString())
                    };
                    empList.Add(emp);
                }
            }
            return empList;
        }
        public void AddEmployeeInfo(string firstname, string lastname)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("AddEmployee", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
            sqlCmd.Parameters.AddWithValue("@LastName", lastname);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }
        public void UpdateEmployee(int empid,string firstname, string lastname)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_UpdateEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID", empid);
            sqlCmd.Parameters.AddWithValue("@FirstName", firstname);
            sqlCmd.Parameters.AddWithValue("@LastName", lastname);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }
        public void DeleteEmployee(int empid)
        {
            string sqlConnstr = Utils.GetDBConnection();
            SqlConnection sqlConn = new SqlConnection(sqlConnstr);
            SqlCommand sqlCmd = new SqlCommand("usp_DeleteEmployeeDetails", sqlConn);
            sqlCmd.CommandType = CommandType.StoredProcedure;
            sqlCmd.Parameters.AddWithValue("@EmpID",empid);
            sqlConn.Open();
            sqlCmd.ExecuteNonQuery();
            sqlConn.Close();
        }

    }

I'm try to build a 3-tier arch. but I feel these code can be improvised so please review my above Data Access Layer code and give suggestions and corrections, if any, to improvise my code.

something along these lines

public static class DTExtensions
{
    public static List<T> ToList<T>(this System.Data.DataTable dt) where T : new()
    {
        var obj = dt.Rows.OfType<System.Data.DataRow>().Select(dr => dr.ToObject<T>()).ToList();
        return obj;
    }
    public static T ToObject<T>(this System.Data.DataRow dataRow) where T : new()
    {
        T item = new T();
        var itemType = item.GetType();
        foreach (System.Data.DataColumn column in dataRow.Table.Columns)
        {
            System.Reflection.PropertyInfo property = itemType.GetProperty(column.ColumnName);

            if (property != null && dataRow[column] != DBNull.Value)
            {
                var result = Convert.ChangeType(dataRow[column], property.PropertyType);
                property.SetValue(item, result, null);
            }
        }

        return item;
    }
}

public class DataHandler
{
    private readonly string _ConnectionInfo = String.Empty;
    public DataHandler(string connectioninfo)
    {
        _ConnectionInfo = connectioninfo;
    }

    public async Task<System.Data.DataTable> DataAsync( string commandSQL, IEnumerable<System.Data.SqlClient.SqlParameter> listParameter=null)
    {
        System.Data.DataTable dt = new System.Data.DataTable("data");

        using (System.Data.SqlClient.SqlConnection connection = new System.Data.SqlClient.SqlConnection(_ConnectionInfo))
        {
            try
            {
                await connection.OpenAsync().ConfigureAwait(false);
            }
            catch (InvalidOperationException ex)
            {
                return null;
            }
            catch (System.Data.SqlClient.SqlException ex)
            {
                return null;
            }
            using (System.Data.SqlClient.SqlCommand command = new System.Data.SqlClient.SqlCommand(commandSQL, connection))
            {
                command.CommandType = System.Data.CommandType.StoredProcedure;
                if (listParameter != null && listParameter.Any())
                {
                    command.Parameters.AddRange(listParameter.Where(p => p != null).ToArray());
                }
                using (var r = await command.ExecuteReaderAsync(System.Data.CommandBehavior.SequentialAccess).ConfigureAwait(false))
                {
                    dt.Load(r);
                }
                command.Parameters.Clear();
            }
            connection.Close();
        }

        return dt;
    }
}

public sealed class Employee
{
    public string EmpID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class EmployeeDBHandler
{
    private readonly DataHandler _DataHandler;
    public EmployeeDBHandler(DataHandler datahandler)
    {
        _DataHandler = datahandler ?? throw new System.ArgumentNullException("datahandler");
    }

    public async Task<List<Employee>> GetEmployees()
    {
        System.Data.DataTable dt = await _DataHandler.DataAsync("GetAllEmployee").ConfigureAwait(false);
        if (dt != null)
        {
            //OR look into using yeild
            //yield return employee
            //OR
            var list = dt.ToList<Employee>();
            return list;
        }
        return null;
    }

    public async Task<List<Employee>> FetchEmployee(int empid)
    {
        List<Employee> empList = new List<Employee>();
        var parameters = new List<System.Data.SqlClient.SqlParameter> { new SqlParameter("@EmpID", empid) };
        System.Data.DataTable dt = await _DataHandler.DataAsync("usp_FetchEmployeeDetails", parameters).ConfigureAwait(false);
        if (dt != null && dt.Rows.Count>0)
        {
            var list = dt.ToList<Employee>();
            return list;
        }
        return null;
    }
}

//  main program:
public class MainProgram
{
    public void DoSomeWork()
    {
        string sqlConnstr = @"Data Source=<...>; Initial Catalog=<...>; User ID=username; Password=password"; //Utils.GetDBConnection();
        var dbHandler = new DataHandler(sqlConnstr);
        var employeeHandler = new EmployeeDBHandler(dbHandler);

        var employees = employeeHandler.GetEmployees();
        if (employees != null)
        {
            //.....
        }
    }
}


jQuery cookie scroll position I'm using jquery and cookie.jquery to remember the scroll position. Is there anything I can do to improve my code? Thanks!

$(document).ready(function() {

    // convert cokkie variable for easy access
    var prev_scroll_position = $.cookie('prev_scroll_position');

    // scroll to position
    $(window).scrollTop(prev_scroll_position);

    // update cookie when user scrolls
    $(window).scroll(function (event) {
        var scroll_positon = $(window).scrollTop();
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    });

});

@EthanBierlein Made a really good point, but he forgot something important.
It's always a good idea to wrap your code on an anonymous function:
(function ($) {
    $(document).ready(function () {
        [code]
    });
})(window.jQuery);

This prevents problems in case you run jQuery.noConflict() before, but you forget it.

You have the following code block:
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();
    $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
});

Instead of this, consider wrapping the $.cookie call in a setTimeout:
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();
    setTimeout(function () {
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    }, 10);
});

This won't block the scroll event, which may improve UI responsiveness.
Why is that? The scroll event may be triggered multiple times a second, and that setTimeout schedules the cookie writting to a time that the browser is free.
Or that has some time for writing the cookie.
You should experiment with it.

Update!
As @Pevara pointed out in the comment section, this is not 100% a good idea.
He suggests to use a clearTimeout. From there, I could infer what he was trying to say.
Still follow the advice to use a setTimeout, but with a bigger delay (as he suggested: 250ms).
But now, the twist:
var timeout;
$(window).scroll(function (event) {
    var scroll_positon = $(window).scrollTop();

    clearTimeout(timeout); //clear it to avoid crazy writing

    //and create a new interval to write it later
    timeout = setTimeout(function () {
        $.cookie('prev_scroll_position', scroll_positon, { expires: 7, path: '/' });
    }, 250);
});

This will eliminate all the craziness of writing cookies like mad! And will write it only once, saving the browser from re-re-re-re-writing it.


Defining a class that behaves exactly like an `int` This is an exercise to create a class that behaves exactly like an int.

Questions

Am I missing anything?
Or did I going about this about this the wrong way?
Is there anything I could improve on?
Are there any tricks that I could learn from this?
How about style; does the style look OK?

#include <iostream> // std::cout
#include <utility>  // std::move

class jd_int {
public:
    jd_int() = default;

    jd_int(int i)             : _i{i}                   { }
    jd_int(const jd_int& jdi) : _i{jdi._i}              { }
    jd_int(jd_int&& jdi)      : _i{std::move(jdi._i)}   { }

    jd_int operator= (int i)             { _i = i; return *this;                 }
    jd_int operator= (double d)          { _i = d; return *this;                 }
    jd_int operator= (const jd_int& jdi) { _i = jdi._i; return *this;            }
    jd_int operator= (jd_int&& jdi)      { _i = std::move(jdi._i); return *this; }

    ~jd_int() = default;

    operator bool()   { return !!_i;                    }
    operator int()    { return static_cast<int>(_i);    }
    operator double() { return static_cast<double>(_i); }

    jd_int operator+=(jd_int jdi) { return _i += jdi._i; }
    jd_int operator+ (jd_int jdi) { return _i +  jdi._i; }

    jd_int operator-=(jd_int jdi) { return _i -= jdi._i; }
    jd_int operator- (jd_int jdi) { return _i -  jdi._i; }

    jd_int operator*=(jd_int jdi) { return _i *= jdi._i; }
    jd_int operator* (jd_int jdi) { return _i *  jdi._i; }

    jd_int operator/=(jd_int jdi) { return _i /= jdi._i; }
    jd_int operator/ (jd_int jdi) { return _i /  jdi._i; }

    jd_int operator%=(jd_int jdi) { return _i %= jdi._i; }
    jd_int operator% (jd_int jdi) { return _i %  jdi._i; }

    jd_int operator++()    { return ++_i;                          }
    jd_int operator++(int) { jd_int tmp = *this; ++_i; return tmp; }

    jd_int operator--()    { return --_i;                          }
    jd_int operator--(int) { jd_int tmp = *this; --_i; return tmp; }

    friend bool operator< (jd_int lhs, jd_int rhs);
    friend bool operator> (jd_int lhs, jd_int rhs);
    friend bool operator<=(jd_int lhs, jd_int rhs);
    friend bool operator>=(jd_int lhs, jd_int rhs);
    friend bool operator==(jd_int lhs, jd_int rhs);
    friend bool operator!=(jd_int lhs, jd_int rhs);

private:
    int _i;

    friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
    friend std::istream& operator>>(std::istream& is, jd_int jdi);
};

bool operator< (jd_int lhs, jd_int rhs) { return (lhs._i <  rhs._i); }
bool operator> (jd_int lhs, jd_int rhs) { return (lhs._i >  rhs._i); }
bool operator<=(jd_int lhs, jd_int rhs) { return (lhs._i <= rhs._i); }
bool operator>=(jd_int lhs, jd_int rhs) { return (lhs._i >= rhs._i); }
bool operator==(jd_int lhs, jd_int rhs) { return (lhs._i == rhs._i); }
bool operator!=(jd_int lhs, jd_int rhs) { return (lhs._i != rhs._i); }

std::ostream& operator<<(std::ostream& os, const jd_int jdi) {
    os << jdi._i;
    return os;
}

std::istream& operator>>(std::istream& is, jd_int jdi) {
    is >> jdi._i;
    return is;
}
```

I would make the bool operator explicit (and const)

The explicit will prevent the object being auto converted to bool in situations where you don't want it too. This may break with int type but is usually a better work match.

explicit operator bool() const  { return !!_i;                    }

I know how the !! works but it is obscure and a lot of people will raise an eyebrow. At least write a comment about it.

These methods should be const

operator int()    const { return static_cast<int>(_i);    }
operator double() const { return static_cast<double>(_i); }
//                ^^^^^

They do not change the state of the class.

All the assignment operator methods are defined wrong.

jd_int operator+=(jd_int jdi) { return _i += jdi._i; }

// Should be:

jd_int& operator+=(jd_int const& jdi) { _i += jdi._i; return *this; }

The op= is modifying the current object. Thus you should return a reference (not an object). Consequentially the return should return *this. There is no need to pass the input parameter by value (this could cause an unrequited copy). Rather pass the parameter by const reference to avoid this.

All the simple operator could be done better

jd_int operator+ (jd_int jdi) { return _i +  jdi._i; }

// Should be:

jd_int operator+ (jd_int const& jdi) { return jd_int(*this) += idi; }

Pass the parameter by const reference. Then use the op-assignment to do the work.

You define all the operators as members of the class. Personally I would also do this. But there is an argument for making the free standing functions.

id_int + int  => works.             (int will be converted to id_int then addition done)
int + id_int  => fails to compile.

If you convert the above members into free standing functions then you will get either side to auto convert.

The freestanding friend functions.

friend bool operator< (jd_int lhs, jd_int rhs);
...
friend std::ostream& operator<<(std::ostream& os, const jd_int jdi);
friend std::istream& operator>>(std::istream& is, jd_int jdi);

You declare them in the function and then define them later. Why? These are trivial functions define them inside the class. Splitting the declaration and definition does not provide any benefit.

Also pass the parameters by const reference when you can.

friend bool operator< (jd_int const& lhs, jd_int const& rhs)         {return (lhs._i <  rhs._i); }
...
friend std::ostream& operator<<(std::ostream& os, jd_int const& jdi) {return os << idi._i;}
friend std::istream& operator>>(std::istream& is, jd_int& jdi)       {return is >> idi._i;}

I think you are missing a couple of operations (binary and and binary or sprint to mind).

I hate it when people use underscore as the first character of an identifier.

int _i;

There are some complex rules around its usage. Not everybody knows these rules exactly so something best avoided. Also why i why not value at least that is a bit more meaningful.


Submit random choices on Google form I've written a Python script that randomly selects radio buttons for each question, and submits the google form. My main questions for improvement are:

Algorithm: I collect all the buttons into a 2D array, then use random.choice to select the radio buttons based on each nested array. I'm sure there's a better way to do this, since my algorithm is basically hard coded.
Performance: I know random.choice takes a lot more time than other methods, but it's the only way I know enough to write with it.
Wait Time: Right now, I wait .75 seconds before entering in another form. I'm wondering if there's a way to wait for the page to load completely, rather than wait and hope that it loads fast enough to not generate a page not found error.

script.py

#run with python3
from selenium import webdriver
import random
import time

#Setup paths and open chrome browser
chrome_path = "desktop/code/python/driver/chrome/chromedriver"
website_path = "https://docs.google.com/forms/d/e/1FAIpQLSdcWrIYQlNbywuLg276z0CbBw-GyQOj_s2ncR9qVA7F7FPARQ/viewform"
driver = webdriver.Chrome(chrome_path)
driver.get(website_path)

#Define options based on each section

#EXCEPT: 9 18 25 28 31 (for text areas)
options = [
    [0, 1, 2, 3],
    [4, 5, 6],
    [7, 8],
    [10, 11],
    [12, 13, 14, 15],
    [16, 17],
    [19, 20, 21],
    [22, 23, 24],
    [26, 27],
    [29, 30],
    [32, 33]
]

#Main loop
def main(counter):
    count = counter + 1

    #Collect all buttons on page and submit button
    buttons = driver.find_elements_by_xpath("//*[@class='freebirdFormviewerViewItemsRadioOptionContainer']")
    submit = driver.find_element_by_xpath("//*[@class='quantumWizButtonPaperbuttonLabel exportLabel']")

    """
    Randomly chooses an option from the 2D array based on what i is, and that
    number is the index of `buttons`, which the button in that index will be clicked
    """
    for i in range(len(options)):
        buttons[random.choice(options[i])].click()

    #Submit form
    submit.click()

    #Go to previous page, which will be the form
    driver.execute_script("window.history.go(-1)")

    #Output how many forms have been submitted thus far
    print(f"Form #{count} has been submitted!")

    #Wait for page to load again, then call main to run again
    time.sleep(.75)
    main(count)

if __name__ == '__main__':
    main(0)

I don't think there's much to review here! Since your options are hard coded, there's not a lot of wiggle room. There are a couple things you can add if you're feeling up to it.

Docstrings: These allow documentation to see what your code is doing, marked with """

Constants: Variables that are constants should be uppercase LIKE_THIS


Truncating Incomplete UTF-8 character I created a function that truncates an incomplete UTF-8 character at the end of std::string in C++.

C++'s Standard Library does not yet support character based substr on UTF-8 characters and does substr by number of bytes only.

Because of that, in the example below, substr causes a weird broken character to appear in the end.

std::string utfstr = "옷三옷白옷옷-어<어<어<어<-";
std::cout << utfstr.substr(0, 5) << std::endl;

It seems like my function is working, but, I would like to get some feedback on possible problems and improvements.

#include <string>
#include <iostream>
using namespace std;

ssize_t TrimEndUTF8(std::string& str) {
  // Scans backward from the end of string.
  const char* cptr = &str.back();
  int num = 1;
  int numBytesToTruncate = 0;

  for (int i = 0; 6 > i; ++i) {
    numBytesToTruncate += 1;
    if ((*cptr & 0x80) == 0x80) { // If char bit starts with 1xxxxxxx
      // It's a part of unicode character!
      // Find the first byte in the unicode character!

      //if ((*cptr & 0xFC) == 0xFC) { if (num == 6) { return 0; } break; }
      //if ((*cptr & 0xF8) == 0xF8) { if (num == 5) { return 0; } break; }

      // If char binary is 11110000, it means it's a 4 bytes long unicode.
      if ((*cptr & 0xF0) == 0xF0) { if (num == 4) { return 0; } break; }
      // If char binary is 11100000, it means it's a 3 bytes long unicode.
      if ((*cptr & 0xE0) == 0xE0) { if (num == 3) { return 0; } break; }
      if ((*cptr & 0xC0) == 0xC0) { if (num == 2) { return 0; } break; }

      num += 1;
    } else {
      // If char bit does not start with 1, nothing to truncate!
      return 0;
    }

    cptr -= 1;
  }
  str.resize(str.length() - numBytesToTruncate);
  return numBytesToTruncate;
}

int main() {
  for (int i = 1; 30 > i; ++i) {
    std::string utfStr = "안-녕<하>세d요e만f나g서반갑습니다";
    std::string substred = utfStr.substr(0, i);
    size_t trimmed = TrimEndUTF8(substred);
    cout << "Trimmed " << trimmed << " bytes" << endl;
    cout << substred << endl;
  }

  for (int i = 1; 30 > i; ++i) {
    std::string utfStr = "_____------";
    std::string substred = utfStr.substr(0, i);
    size_t trimmed = TrimEndUTF8(substred);
    cout << "Trimmed " << trimmed << " bytes" << endl;
    cout << substred << endl;
  }

  return 0;
}

There is currently no error checking to validate that this is valid UTF-8. If this is deliberate it should be documented.

You are testing the 1's at the top of a UTF-8 encoded string. But not correctly validating the trailing 0.

  if ((*cptr & 0xC0) == 0x80) { ...
  if ((*cptr & 0xF8) == 0xF0) { ...
  if ((*cptr & 0xF0) == 0xE0) { ...
  if ((*cptr & 0xE0) == 0xC0) { ...
         ///   ^^^^  You should extend the mask one more bit
         ///         So that your test validates that the next
         ///         bit is zero.

The way your function is written it will mutate the string if it finds a partial. This may not always be necessary I would break this into two functions. One that finds the amount of mutation needed and another that does the mutation. That way another user can potentially use only the non mutating part and get better performance (say if they were passing it to a function using iterators).

 std::size_t trimEndUTF8(std::string& str) {
     std::size_t trim = findEndUTF8Trim(str);
     str.resize(str.size() - trim);
     return trim;
 }

If you implement the above function split. You now make it easy for your self to implement a slight return optimization.

 if ((*cptr & 0xF8) == 0xF0) {
     if (num == 4) {
         return 0;
     }

     // break;
     // Change your break into a return.
     //
     // Because we are not mutating we don't need to worry about
     // changing the input in thus function and can just return the
     // size of the trim. Since this is the head character of a UTF-8
     // sequence the next character must be end of a UTF-8 character.
     //
     return num; // or is it num + 1 you should check.
 }

Prefer not to use yoda conditionals.

 for (int i = 0; 6 > i; ++i)
                 ^^^^^  Yoda conditional

They are a cognitive drain and less intuitive to read (unless you are yoda). Prefer the more traditional style as it makes it easy to read fof developers.

 for (int i = 0; i < 6; ++i)

Note you are assuming there are at least 6 characters in the string. I would not do that (especially since people are likely to throw all kinds of crap at it). A badly formed UTF-8 string is going to cause undefined behavior.

Standard warning about:

using namespace std;

Read any other C++ review on this site. We say don't use this. Read another review and you will find why.

Naming conventions. It is more traditional to use an initial lowercase letter for objects(this includes functions/methods).

ssize_t findEndUTF8Trim(std::string const& str) {

    // If the last character is a single character return
    // Don't need to do any further checking or trimming.
    if ((str.back() & 0x80) == 0x00)
        return 0;
    }

    // Check that we have a valid UTF-8 sequence.
    char const* cptr = &str.back();
    int const   end  = std::min(6, str.size()); // Max theoritical len == 6
    for (int num = 1; num <= end; ++num, --cptr) {
        if ((*cptr & 0xF8) == 0xF0) { return (num == 4) ? 0 : num; }
        if ((*cptr & 0xF0) == 0xE0) { return (num == 3) ? 0 : num; }
        if ((*cptr & 0xE0) == 0xC0) { return (num == 2) ? 0 : num; }
    }
    // If reach here then there is a malformed UTF-8 character sequence.
    throw std::runtime_error("Unexpected UTF-8 string");
}