Retrieving ListBox.column values and store into objects I know there must be a better way to perform the above sub than using multiple If statements. I was thinking of storing the obj.PropertName into a collection and run it through a for loop.

'Create instance
Dim wellObj As CWell
Set wellObj = New CWell

.
.
.

Private Sub Well_List_Click()

    'Must check if null..
    If Not (Well_List.Column(1, row) = "") Then
        wellObj.wellName = Well_List.Column(1, row)
    End If

    If Not (Well_List.Column(2, row) = "") Then
         wellObj.wellActive = Well_List.Column(2, row)
    End If

    If Not (Well_List.Column(3, row) = "") Then
         wellObj.wellDiameter = Well_List.Column(3, row)
    End If

    If Not (Well_List.Column(4, row) = "") Then
         wellObj.wellCasing = Well_List.Column(4, row)
    End If

    If Not (Well_List.Column(5, row) = "") Then
         wellObj.screenedInterval = Well_List.Column(5, row)
    End If

    If Not (Well_List.Column(6, row) = "") Then
         wellObj.wellSock = Well_List.Column(6, row)
    End If

    If Not (Well_List.Column(7, row) = "") Then
        wellObj.wellDepth = Well_List.Column(7, row)
    End If

End Sub

Refactored:

NB: wellObj has all properties type String

Private Sub Well_List_Click()

    Dim properties(1 To 7) As String
    Dim value As String
    Dim row As Integer

    'Skip header
    row = Well_List.ListIndex + 1

    'Must check if null..
    properties(1) = "WellName"
    properties(2) = "WellActive"
    properties(3) = "WellDiameter"
    properties(4) = "wellCasing"
    properties(5) = "ScreenedInternal"
    properties(6) = "WellSock"
    properties(7) = "WellDepth"

    For i = 1 To 7
        value = Well_List.Column(i, row)
        If value <> vbNullString Then
            CallByName wellObj, properties(i), VbLet, value
        End If
    Next

End Sub

Start with proper indentation. There shouldn't be anything (other than subroutine/line labels) at the same level of indentation as a Private Sub statement, other than the End Sub.

Code blocks are more readable and code as a whole is easier to follow when code blocks are indented. General rule of thumb, if there's an End X for a statement, you're in a code block. Give that Tab key some lovin'!

Private Sub DoSomething()
|...If Not FooBar Then
|...|...DoSomethingElse
|...End If
End Sub DoSomething

Using a For..Next loop here is tricky, because you're accessing a different property every time. You're going to need to access the properties by name, and to do that you need them in an indexed structure, like an array:

Dim properties(1 To 7) As String
properties(1) = "wellName"
properties(2) = "wellActive"
properties(3) = "wellDiameter"
properties(4) = "wellCasing"
properties(5) = "screenedInternal"
properties(6) = "wellSock"
properties(7) = "wellDepth"

Now you can go from 1 to 7 and, assuming CWell is a class module (I'm not all that familiar with Access, I hope my assumption is correct)...

For i = 1 To 7
    value = Well_List.Column(i, row)
    If value <> vbNullString Then SetPropertyValue wellObj, properties(i), value
Next

Notice I'm using vbNullString instead of an empty string literal "". vbNullString is a null string pointer, which isn't allocated a memory address. "" has its own memory spot. No biggie, but not needed either.

So, how would that SetPropertyValue method be implemented? The VBA standard library has this little wonder in its VBA.Interaction module, called CallByName:

Private Sub SetPropertyValue(ByRef instance, ByVal member, ByVal value)
    CallByName instance, member, vbLet, value
End Sub

This is assuming CWell exposes a Property Let accessor/mutator. If wellName and friends are public fields, you need to properly encapsulate them and expose them via properties.

That said, public members should be PascalCase, so "wellName" would be "WellName".

Now, I really introduced that SetPropertyValue method just to make an abstraction level for the sake of this answer. The one-liner could just as well be inlined:

Dim properties(1 To 7) As String
properties(1) = "wellName"
properties(2) = "wellActive"
properties(3) = "wellDiameter"
properties(4) = "wellCasing"
properties(5) = "screenedInternal"
properties(6) = "wellSock"
properties(7) = "wellDepth"

For i = 1 To 7
    value = Well_List.Column(i, row)
    If value <> vbNullString Then
        CallByName wellObj, properties(i), vbLet, value
    End If
Next


EventList a generic list implementation that raises events when items are added and removed I created this class for a project when I wanted to have List<T> properties on a class and also listen for items being added and removed.

I looked at using BindingList<T> or ObservableCollection<T> but I felt that their collection changed events are too complicated. I simply wanted to know when items are added and removed.

public class EventList<T> : IList<T>
{
    private readonly List<T> _list;

    public EventList()
    {
        _list = new List<T>();
    }

    public EventList(IEnumerable<T> collection)
    {
        _list = new List<T>(collection);
    }

    public EventList(int capacity)
    {
        _list = new List<T>(capacity);
    }

    public event EventHandler<EventListArgs<T>> ItemAdded;
    public event EventHandler<EventListArgs<T>> ItemRemoved;

    private void RaiseEvent(EventHandler<EventListArgs<T>> eventHandler, T item, int index)
    {
        var eh = eventHandler;
        eh?.Invoke(this, new EventListArgs<T>(item, index));
    }

    public IEnumerator<T> GetEnumerator()
    {
        return _list.GetEnumerator();
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }

    public void Add(T item)
    {
        var index = _list.Count;
        _list.Add(item);
        RaiseEvent(ItemAdded, item, index);
    }

    public void Clear()
    {
        for (var index = 0; index < _list.Count; index++)
        {
            var item = _list[index];
            RaiseEvent(ItemRemoved, item, index);
        }

        _list.Clear();
    }

    public bool Contains(T item)
    {
        return _list.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        _list.CopyTo(array, arrayIndex);
    }

    public bool Remove(T item)
    {
        var index = _list.IndexOf(item);

        if (_list.Remove(item))
        {
            RaiseEvent(ItemRemoved, item, index);
            return true;
        }

        return false;
    }

    public int Count => _list.Count;
    public bool IsReadOnly => false;

    public int IndexOf(T item)
    {
        return _list.IndexOf(item);
    }

    public void Insert(int index, T item)
    {
        _list.Insert(index, item);
        RaiseEvent(ItemRemoved, item, index);
    }

    public void RemoveAt(int index)
    {
        var item = _list[index];
        _list.RemoveAt(index);
        RaiseEvent(ItemRemoved, item, index);
    }

    public T this[int index]
    {
        get { return _list[index]; }
        set { _list[index] = value; }
    }
}

public class EventListArgs<T> : EventArgs
{
    public EventListArgs(T item, int index)
    {
        Item = item;
        Index = index;
    }

    public T Item { get; }
    public int Index { get; }
}

The typical use case would be something like this:

public class MyClass
{
    public MyClass()
    {
        MyItems = new EventList<string>();

        MyItems.ItemAdded += (sender, args) =>
        {
            // do something when items are added
        };

        MyItems.ItemRemoved += (sender, args) =>
        {
            // do something when items are removed
        };
    }

    public EventList<string> MyItems { get; }
}

I'm posting this here for code review for general feedback, but also to ask if I've missed something obvious, like an alternative class in the .NET framework or a 3rd party library that might do the same sort of thing?

Bug

public void Insert(int index, T item)
{
    _list.Insert(index, item);
    RaiseEvent(ItemRemoved, item, index);
}

I don't think that you want to raise an ItemRemoved event in the case of inserting an item.

In general I like your implementation. It is leightweight and is doing exactly what it should.

But for sure I have something to critizise:

The name EventList<T> which reads like a list of events instead of a list with events. Because there is already a ObservableCollection<T> maybe an ObservableList<T> would be a better name.
You implement IList<T> but have the underlaying list as a List<T> instead of an IList<T> like private readonly IList<T> _list;.
The RemoveAt() could be simplified by calling the Remove() method like so

public void RemoveAt(int index)
{
    Remove(_list[index]);
}

 See @RomanReiner's answer here
IMO the raising of multiple ItemRemoved events inside the Clear() method isn't that good because you are raising the event before the item is removed. You should either have an additional event ItemsCleared or you should raise the ItemRemoved events after the clearing of that list.


My first Meteor autocomplete I am trying to learn Meteor, so I tried to write a basic location autocomplete.

Currently, given a string, it will request suggestions from https://photon.komoot.de/ (amazing free location autocomplete btw) and display them in an ul-li. What is not done yet is keyboard navigation.

autocomplete.html

<template name="autocomplete">
    <input id="{{name}}" class="autocomplete-input {{className}}"
        placeholder="{{placeholder}}" autocomplete="off"/>

</template>

autocomplete.js

(function() {
    var inputEl, suggestionsEl, timeout, displayedSuggestions, selectedSuggestion;
    var search = function(inputString) {
        if (timeout) {
            clearTimeout(timeout);
        }
        timeout = setTimeout(function() {
            HTTP.get("https://photon.komoot.de/api/?q=" + inputString + "&lang=" + globalConfig.language, {},
                function(error, response) {
                    if (error) {

                    } else {
                        displayedSuggestions = response.data.features;
                        display(displayedSuggestions);
                    }
                });
        }, 300);
    };

    var suggestionString = function (suggestion) {
        return suggestion.properties.name + ' (' + suggestion.properties.country + ')';
    };

    var selectSuggestion = function(elt) {
        inputEl.value = elt.innerHTML;
        selectedSuggestion = displayedSuggestions[elt['data-index']];
        suggestionsEl.style.display = 'none';
    };

    var display = function(data) {
        suggestionsEl.innerHTML = '';
        suggestionsEl.style.display = 'block';
        for (var i = 0; i < data.length; i++) {
            var suggestion = data[i];
            var li = document.createElement('li');
            li.className = "suggestion";
            li.onclick = function() {selectSuggestion(this);};
            li['data-index'] = i;
            li.innerHTML = suggestionString(suggestion);
            suggestionsEl.appendChild(li);
        }

    };

    Template.autocomplete.onRendered( function(){
        inputEl = this.find('.autocomplete-input');
        suggestionsEl = this.find('.suggestions');
    });

    Template.autocomplete.events({
        "keyup .autocomplete-input": function (event) {
            search(event.target.value);
        }
    });
})();

Two things does not seem very "meteor"-like. First, I have a lot of local functions, and local variables. Are they supposed to be put somewhere else?

Also, I am worried about performance. The keyup event is based on the class of the input. If it is looking through the DOM at each keystroke, it might get slow. I tried using inputEl instead, but this does not seem possible (or is it?).

The first thing I look for in an autocomplete widget is how the list is implemented. First, you are using inline styles to display/hide the list. You can simply use CSS :empty to hide the list container when nothing is listed. That way, you don't have to deal with toggling the visibility in JS. All you need to worry is if the list should be empty or not.

.suggestions:empty{
  display: none;
}

My Meteor is rusty, but I remember it had some form of reactive programming by way of session (correct me if I'm wrong) variables and templates. When these variables change, any UI bound to it changes. Suggesting you create an array and bind it to the UI. That way, all you have to care about is populating/unpopulating that array, and not mess around with innerHTML.

function(error, response) {
  if (error) {

  } else {
    displayedSuggestions = response.data.features;
    display(displayedSuggestions);
  }
}

// to

function(error, response){
  if(error) return; // throw new Error('nothing') or console.warn('')
  displayedSuggestions = response.data.features;
  display(displayedSuggestions);
}

So essentially, you're swallowing the error. That's fine, however you can simplify the code by returning early. On the other hand, a few debugging hints won't hurt. Suggesting you throw an error, or log it as a warning.

I see a timer, but it looks weird coupled with the nearby AJAX call. Then I found out it was a form of debouncing. Suggesting you move that function out into a more verbose form to avoid mistaking the timer as a form of asynchronous utility function and making the AJAX look like some synchronous operation. Something like:

function debounce(fn, delay){
  var timer = null;
  return function(){
    if(timer) clearTimeout(timer);
    setTimeout(fn, delay || 300);
  }
}

var search = debounce(function(){
  // Your AJAX code
});

In the above, search (or any function for that matter) will have automatic debounce capabilities once "wrapped" by debounce without the clutter that came with it.


Numerical precision of implementation for convex quadrilateral area I have implemented a method to compute a convex quadrilateral area in R3. The method works fine, but I am having numerical precision problems in the 8th decimal place. Take a look on the method:

internal static double GetTriangleArea(double ax, double ay, double az,
            double bx, double by, double bz,
            double cx, double cy, double cz
            )
        {
            /**
             * AB = B-A = (ux, uy, uz)
             * AC = C-A = (wx, wy, wz)
             *
             * S = 0.5*sqrt{(uy*wz - uz*wy)² + (uz*wx - ux*wz)² + (ux*wy - uy*wx)²}
             * */

            var ux = bx - ax;
            var uy = by - ay;
            var uz = bz - az;

            var wx = cx - ax;
            var wy = cy - ay;
            var wz = cz - az;

            var t1 = uy*wz - uz*wy;
            var t2 = uz*wx - ux*wz;
            var t3 = ux*wy - uy*wx;
            var s = 0.5*Math.Sqrt(t1*t1 + t2*t2 + t3*t3);

            return s;
        }

        internal static double GetConvexQuadrilateralArea(double ax, double ay, double az,
            double bx, double by, double bz,
            double cx, double cy, double cz,
            double dx, double dy, double dz)
        {
            var triangle1 = GetTriangleArea(ax, ay, az, bx, by, bz, cx, cy, cz);
            var triangle2 = GetTriangleArea(ax, ay, az, cx, cy, cz, dx,dy,dz);

            return triangle1 + triangle2;
        }

And this is the test:

[TestMethod]
        public void ParallelogramOfBaseBAndHeightHMustHaveAreaEqualToBTimesH()
        {
            var random = new Random(1);
            const double scale = 10000;
            for (var counter = 0; counter < 1000; counter++)
            {
                double baseLength = random.NextDouble() * scale;
                double height = random.NextDouble() * scale;

                double dx = random.NextDouble()*scale;

                var a = new[] { 0, 0, 0 };
                var b = new[] { baseLength, 0, 0 };
                var c = new[] { baseLength+dx, height, 0 };
                var d = new[] { 0F+dx, height, 0 };

                double expected = baseLength * height;

                var result = MathUtils.GetConvexQuadrilateralArea(a[0], a[1], a[2], b[0], b[1], b[2], c[0], c[1], c[2],
                    d[0], d[1], d[2]);

                Assert.AreEqual(expected, result, Epsilon*scale,
                    string.Format("sideA: {0}, height: {1}, dx: {2}", baseLength, height, dx));
            }
        }

This test fails with the following message: Expected a difference no greater than <1E-09> between expected value 74813926.2967871 and actual value 74813926.2967871. sideA: 8552.44307245707, height: 8747.66726454146, dx: 4721.64729829954.

My question is: is there a way to increase the numerical precision of my implementation while still using double precision numbers?

Debugging floating-point precision issues is, as @Bobby mentioned, off-topic for this site, so this is going to be just a code review :)

The first thing that strikes me, is the cryptic two-letter identifiers.

Let's start with the signature for GetTriangleArea. You're taking 9 parameters, this is bad. In reality you really need 3 groups of 3 numbers. Your code has failed to make this abstraction, and this is why you end up with a1-a2-a3 -style identifiers.

What if GetTriangleArea had a signature like this?

internal static double GetTriangleArea(Point3D pointA, Point3D pointB, Point3D pointC)

Given a Point3D struct with members X, Y and Z, the rest of the code would be much less cryptic.

The same applies to GetConvexQuadrilateralArea, which could look much less crowded like this:

internal static double GetConvexQuadrilateralArea(Point3D pointA, Point3D pointB, Point3D pointC, Point3D pointD)

Lastly, I'm not sure, but I think GetConvexQuadrilateralArea is lying - the method isn't actively verifying the convex-ness of the points it's given, which may or may not be problematic.


What is the 10001st prime number? Project Euler problem 7 says:

  By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.  What is the 10001st prime number?

I believe that my code is working, but very very slowly. I guess the increment divisor can be changed, but I'm not sure how.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace p7
{
    //    By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.
    //    What is the 10001st prime number?

    class Program
    {
        //          - SET 'divisor' TO 13
        //          - WHILE( divisor <= ceil[ sqrt(number) ] )
        //          - IF number%divisor == 0 && number != divisor THEN
        //          - Not prime / divisible by 'divisor'
        //          - ELSE IF ceil[ sqrt(number) ] == divisor THEN
        //          - PRIME!!!
        //          - ELSE increment divisor by 2
        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            int count = 6; // we already know 6 primes: 2,3,5,7,11,13
            long x = 14; // so can look for a prime after number 13

            while (count < 10001)
            {
                if (IsPrime(x, 13))
                {
                    count++;
                    x++;
                }
            }
            Console.WriteLine(x);
            Console.WriteLine("Time used (float): {0} ms", sw.Elapsed.TotalMilliseconds);
            Console.WriteLine("Time used (rounded): {0} ms", sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
        static bool IsPrime(Int64 p, Int64 divisor)
        {
            Int64 sqrt = (Int64)Math.Ceiling(Math.Sqrt(p));
            while (divisor <= sqrt)
           {
                if (p % divisor == 0)
                    return false;
                else if (sqrt == divisor)
                    return true;
                divisor += 2;
            }
            return true;
        }
    }
}

Your prime testing code is wrong. For example, it would consider 14 to be a prime! You cannot take a shortcut by only testing divisors > 13. Instead:

static bool IsPrime(Int64 p)
{
    if (p % 2 == 0) return false;
    Int64 max = (Int64) Math.Ceiling(Math.Sqrt(p));
    for (Int64 divisor = 3; divisor < max; divisor += 2)
    {
        if (p % divisor == 0) return false;
    }
    return true;
}

Points to note:

I use a for loop instead of while, as this better expresses what I'm doing.
I only go up to divisor < ceiling(sqrt(p)), which saves one iteration. Not significant, but it's less redundant this way.
While I do test for p % 2 == 0, this branch will never be taken because we will later modify our prime number search loop to only search odd numbers. I leave that test here for correctness.
Note also that smaller numbers are more likely to be divisors than larger numbers. It's therefore advantageous to test them early.

Your prime search loop looks at each number in from 13 onward. However with the exception of 2, only odd numbers can be primes. We can therefore halve the search time by incrementing in steps of two.

int count = 6;
int targetCount = 10001;
long x;
for (x = 13 + 2; count < targetCount; x += 2)
{
    if (IsPrime(x)) count++;
}

But wait! If we are finding all prime numbers from 13 onward we can use those to speed up our prime test by only testing appropriate prime factors! We can do this by creating a table of primes:

long[] primes = new long[targetCount];
primes[0] =  2;
primes[1] =  3;
primes[2] =  5;
primes[3] =  7;
primes[4] = 11;
primes[5] = 13;

int counter = 6;
for (long x = primes[counter - 1] + 2; counter < targetCount; x += 2)
{
    if (IsPrime(x, primes)) primes[counter++] = x;
}
// the result is in primes[targetCount - 1]

where IsPrime has been changed to

static bool IsPrime(Int64 p, long[] primes)
{
    Int64 max = (Int64) Math.Ceiling(Math.Sqrt(p));
    foreach (long divisor in primes)
    {
        if (divisor > max) break;
        if (p % divisor == 0) return false;
    }
    return true;
}

And hey presto, is this fast! I get 104743 as an answer in a matter of milliseconds.

How did I make this code so fast?

Write correct code without taking bad shortcuts.
Think about what I need and what I have anyway.
Then, figure out an elegant way to connect those two states. Here, my experience with dynamic programming reminded me to build a table of primes.


Fibonacci calculator in Haskell I'm just starting to look into Haskell. I've written a naive Fibonacci implementation, and I've also written a more advanced one that uses tail-call recursion for efficiency.

module Fibonacci where

import System.Environment

fibonacci :: Integer -> Integer
fibonacci 0 = 0
fibonacci 1 = 1
fibonacci n
    | n < 0 = error "Cannot find a negative fibonacci number"
    | otherwise = fibonacci (n - 1) + fibonacci (n - 2)

fibonacci' :: Integer -> Integer
fibonacci' n
    | n < 0 = error "Cannot find a negative fibonacci number"
    | otherwise = fibHelper n 0 1
    where
        fibHelper :: Integer -> Integer -> Integer -> Integer
        fibHelper n a b
            | n == 0 = a
            | otherwise = fibHelper (n - 1) b (a + b)

firstNumberFrom :: [String] -> Integer
firstNumberFrom [] = 10
firstNumberFrom args = read $ args !! 0

main = do
    args <- getArgs
    let num = firstNumberFrom args in
        putStrLn $ show (fibonacci' num)

I'd appreciate any reviews on correctness and idiomatic usage.

The many approaches in main and firstNumberFrom can be unified:

main = print . fibonacci' . maybe 10 read . listToMaybe =<< getArgs

The explicit recursion in fibbonacci' is captured by iterate:

fibbonacci' n = fst $ iterate (\(a,b) -> (b, a+b)) (0,1) !! n


Return list of tuples of date ranges I have a start and end date. I would like to return a list of tuples, which have the start and end dates of each month.
Input
start_date = '2020-10-14'
end_date = '2021-03-26'

Output
[('2020-10-14', '2020-10-31'),
 ('2020-11-01', '2020-11-30'),
 ('2020-12-01', '2020-12-31'),
 ('2021-01-01', '2021-01-31'),
 ('2021-02-01', '2021-02-28'),
 ('2021-03-01', '2021-03-26')]

My code
from datetime import datetime, timedelta, date
import calendar

def get_first_day(year, month):
    return f'{year}-{str(month).zfill(2)}-01'

def get_last_day(year, month):
    # https://stackoverflow.com/a/23447523/5675288
    dt = datetime.strptime(f'{year}-{month}', '%Y-%m')
    dt = (dt.replace(day=1) + timedelta(days=32)).replace(day=1) - timedelta(days=1)
    return dt.strftime('%Y-%m-%d')

def diff_month(d1, d2):
    # https://stackoverflow.com/a/4040338/5675288
    return abs((d1.year - d2.year) * 12 + d1.month - d2.month)

def add_months(sourcedate, months):
    # https://stackoverflow.com/a/4131114/5675288
    month = sourcedate.month - 1 + months
    year = sourcedate.year + month // 12
    month = month % 12 + 1
    day = min(sourcedate.day, calendar.monthrange(year,month)[1])
    return date(year, month, day)

def get_dates(start_date, end_date):
    """get list of tuples of dates
    [
        (start_date, end-of-month),
        (start-of-next-month, end-of-next-month),
        (start-of-next-next-month, end-of-next-next-month),
        ...
        (start-of-last-month, end_date)
    ]
    """
    sd = datetime.strptime(f'{start_date}', '%Y-%m-%d')
    ed = datetime.strptime(f'{end_date}', '%Y-%m-%d')

    diff_months = diff_month(sd, ed)

    first_days = []
    last_days = []

    for month in range(diff_months+1):
        d = add_months(sd, month)
        first_days.append(get_first_day(d.year, d.month))
        last_days.append(get_last_day(d.year, d.month))

    first_days = [start_date] + first_days[1:]
    last_days = last_days[:-1] + [end_date]

    return list(zip(first_days, last_days))

start_date = '2020-10-14'
end_date = '2021-03-26'

print(get_dates(start_date, end_date))

Is there a cleaner / better approach for this?

None of this code should deal in strings, except maybe the final output stage. It can all be thrown away in favour of a single generator function that uses the highly-useful dateutil library. Also type hints will help:
from datetime import date
from typing import Iterable, Tuple
from dateutil.relativedelta import relativedelta

def get_dates(start: date, end: date) -> Iterable[Tuple[date, date]]:

    while True:
        next_start = start + relativedelta(months=1, day=1)
        this_end = next_start - relativedelta(days=1)

        if end <= this_end:
            yield start, end
            break

        yield start, this_end
        start = next_start

def main() -> None:
    start = date.fromisoformat(input('Enter start date: '))
    end = date.fromisoformat(input('Enter end date: '))
    for range_start, range_end in get_dates(start, end):
        print(f'{range_start.isoformat()} - {range_end.isoformat()}')

if __name__ == '__main__':
    main()

Output:
Enter start date: 2020-10-14
Enter end date: 2021-03-26
2020-10-14 - 2020-10-31
2020-11-01 - 2020-11-30
2020-12-01 - 2020-12-31
2021-01-01 - 2021-01-31
2021-02-01 - 2021-02-28
2021-03-01 - 2021-03-26


Gravity problem solver in Factor After answering a question about Factor, I decided that it looked interesting. To get the hang of the syntax and such, I decided to write some basic physics code to "solve" the three-body problem. Then, I realized that math is harder than I thought it would be, so instead I just made a vocabulary to solve some basic problems about classical gravitational attraction.

I'm looking for advice on:

Idiomatic-ness: The functions feel pretty long for Factor, but they seem about as short as they'll get.
Naming: Some of my function names are subpar, but I can't find better names for them.
Separation: I feel like the vector arithmetic should be in its own vocabulary, but I'm not sure. Also, I have no idea how to do that.
Removing rounding errors: The program is fairly accurate, but some rounding error leads to ever-so-slightly wrong numbers (i.e. \$49.99999999999999\$ instead of \$50\$)

USING: locals math.functions math.vectors math.trig math.constants ;
IN: q.physics.gravitational-attraction

TUPLE: body
  { mass     initial: 0       }
  { position initial: { 0 0 } }
  { velocity initial: { 0 0 } }
;
:: array>body ( array -- obj )
  body new
    array first         >>mass
    array second 2 head >>position
    array third 2 head  >>velocity
;
: >body ( mass position velocity -- obj )
  3array array>body
;

! Constants
SYMBOLS: G ;
! Throws an error if it's 6.674e−11 so let's use 1
1 G set

:: vector-between ( from to -- v )
  to first from first -
  to second from second -
  2array
;

:: dot ( u v -- rad )
  u first v first * u second v second * +
  u first sq u second sq + sqrt v first sq v second sq + sqrt *
  /
;
: angle-between ( u v -- rad ) dot ;

:: v+ ( u v -- sum )
  u first v first +
  u second v second +
  2array
;

:: s*v ( k v -- scaled )
  v first k *
  v second k *
  2array
;

:: -1*v ( v -- neg )
  v first -1 *
  v second -1 *
  2array
;

:: magnitude ( v -- num )
  v first sq v second sq + sqrt
;

:: unit ( v -- unit )
  v magnitude :> len
  v first len /
  v second len /
  2array
;

:: force-on ( obj from -- force )
  obj position>> from position>> vector-between :> vec
  G get obj mass>> * from mass>> *
  vec magnitude
  /
  vec unit s*v
;

:: forces ( bodies -- forces )
  bodies [
    :> body
    body bodies remove [
      body swap force-on
    ] map
  ] map
;

I don't know the math well enough to test the edge cases, but I did check with this code:

SYMBOLS: b1 b2 b3 ;
10 { 0 0 } { 0 0 } >body b1 set
10 { 1 0 } { 0 0 } >body b2 set
10 { 0 1 } { 0 0 } >body b3 set
b1 get b2 get b3 get 3array forces [| f | f first f second v+ ] map .

which gave me the result:

{
    { 100.0 100.0 }
    { -150.0 49.99999999999999 }
    { 49.99999999999999 -150.0 }
}

And according to my math, that's correct. Note that the results are in terms of \$G\$, not multiplying by it, since it gives me an error when I try to put in 6.674e−11.

I'm not quite skilled enough at Factor yet to review your code in full, but I would just like to note as a response to

  I don't know the math well enough to test the edge cases, but I did check with this code

Factor has really slick builtin unit-testing. Here are the docs; I'll pull an example from my factor/work directory:

USING: tools.test mk-initialism ;
IN: mk-initialism.tests

{ "LASER" } [ "Light Ablah by S of Ed Radiof" >initialism ] unit-test
{ "USA"   } [ "United S OF Americaof" >initialism ]         unit-test
{ "USA"   } [ "united states and america" >initialism ]     unit-test
{ "JTW"   } [ "Jordan Of the World" >initialism ]           unit-test

To create the test file, open the listener and do:

USE: tools.scaffold
"q.physics.gravitational-attraction" scaffold-tests

To run the tests, just run "q.physics.gravitational-attraction" test.


Is it possible to make a generic method out of this, or at least separate them? I'm using ImageProcessor in C# and I can't come up with a way to make a generic method out of its methods as to avoid writing the same code more than once.

Say, I have two methods, crop and resize.

 public Image Resize(Image image, int width, int height)
{
    // Create a Image to be returned after being scaled, call it resizedImage:
    Image resizedImage;
    // Create a Size for the image to be scaled to, call it size:
    var size = new Size(width, height);
    // Create an ImageFactory to process the image, call it imageFactory:
    using (var imageFactory = new ImageFactory(preserveExifData: true))
    {
        // Create a MemoryStream to temporarily store the processed image, call it imageStream:
        using (var imageStream = new MemoryStream())
        {
            // Scale the image using the ImageProcessor library
            // Load the image to be resized, resize it and save it to the MemoryStream:
            imageFactory.Load(image)
                        .Resize(size)
                        .Save(imageStream);
            // Assign the processed image to the previously declared resizedImage:
            resizedImage = Image.FromStream(imageStream);
        }
    }

    // Return the resized image:
    return resizedImage;
}
public Image Crop(Image image, float left, float top, float right, float bottom, bool isModePercentage = true)
{
    // Create a Image to be returned after being cropped, call it croppedImage:
    Image croppedImage;
    // Create a CropMode to specify what cropping method to use (Percentage or Pixels), call it cropMode
    // If isModePercentage = true we use CropMode.Percentage, otherwise use CropMode.Pixels:
    var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;
    // Create a CropLayer to specify how and how much the image should be cropped, call it cropLayer:
    var cropLayer = new CropLayer(left, top, right, bottom, cropMode);
    // Create an ImageFactory to process the image, call it imageFactory:
    using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
    {
        // Create a MemoryStream to temporarily store the processed image, call it imageStream:
        using (MemoryStream imageStream = new MemoryStream())
        {
            // Crop the image using the ImageProcessor library
            // Load the image to be cropped, crop it and save it to the MemoryStream:
            imageFactory.Load(image)
                        .Crop(cropLayer)
                        .Save(imageStream);
            // Assign the processed image to the previously declared croppedImage:
            croppedImage = Image.FromStream(imageStream);
        }
    }
    // Return the cropped image:
    return croppedImage;
}

How can I avoid having to instantiate imagefactory and memory stream multiple times, reducing the size of my methods and avoid to write the same code twice?

Well, it works well, but as you said, it can be optimized

Review:

You are commenting each line which is not good, only comment meaningful code sections. Commonly the names of the functions and variables you are calling is intuitive enough to know how the code is working. When it is insufficient then it is the moment to comment.

Refactoring:

You may create two class fields (ImageFactory,MemoryStream) and work with these.

private ImageFactory imageFactory;
private MemoryStream imageStream;

public [ClassName]() //the constructor if doubts
{
    imageFactory = ImageFactory(preserveExifData: true);
    imageStream = MemoryStream();
}

public Image Resize(Image image, int width, int height)
{
    imageFactory.Load(image).Resize(new Size(width, height)).Save(imageStream);
    return Image.FromStream(imageStream);
}

public Image Crop(Image image, float left, float top, float right, float bottom,
    bool isModePercentage = true)
{
    var cropMode = isModePercentage ? CropMode.Percentage : CropMode.Pixels;
    var cropLayer = new CropLayer(left, top, right, bottom, cropMode);

    imageFactory.Load(image).Crop(cropLayer).Save(imageStream);

    return Image.FromStream(imageStream);
}

Hope it has been helpful.


Alert dialog manger class I want to make a general alert dialog to use across the whole app. I created a class called AlertDialogManager and just one method to show AlertDialog.

Is there a way to refine my code or this code?

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;

public class AlertDialogManager {
    /**
     * Function to display simple Alert Dialog
     * @param context - application context
     * @param title - alert dialog title
     * @param message - alert message
     * @param status - success/failure (used to set icon)
     *               - pass null if you don't want icon
     * */
    public void showAlertDialog(Context context, String title, String message,
            Boolean status) {
        AlertDialog alertDialog = new AlertDialog.Builder(context).create();

        // Setting Dialog Title
        alertDialog.setTitle(title);

        // Setting Dialog Message
        alertDialog.setMessage(message);

        if(status != null)
            // Setting alert dialog icon
            alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);

        // Setting OK Button
        alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });

        // Showing Alert Message
        alertDialog.show();
    }
}

The use of Boolean for status as a kind of 'ternary type' (true, false, null) feels a little misleading, even if it's documented in the Javadoc.

I would replace it with either three static final int constants or an enum.


Showing the domain of a URL I have such a method which takes a URL, such as http://twitter.com/ttt or twitter.com/dasd, and should show its domain with http: http://twitter.com and name twitter

def show_domain(url):
    sites = {
        'twitter': ['http://www.twitter.com/', 'twitter'],
        'facebook': ['http://www.facebook.com/', 'facebook'],
        'pininterest': ['http://www.pininterest.com/', 'pininterest']
    }

    if sites['twitter'][0] in url:
        link = sites['twitter'][0]
        brand = sites['twitter'][1]
    elif sites['facebook'][0] in url:
        link = sites['facebook'][0]
        brand = sites['facebook'][1]

    else:
        link = sites['pininterest'][0]
        brand = sites['pininterest'][1]
    return link, brand

Is there way to optimise this code?

You can use tuple unpacking/list unpacking to write :

if sites['twitter'][0] in url:
    link, brand = sites['twitter']
elif sites['facebook'][0] in url:
    link, brand = sites['facebook']
else:
    link, brand = sites['pininterest']
return link, brand

Now, the data structure you are using is a bit akward because you don't use the key at all. Instead of mapping string to list of strings, you could have a list of list of strings. Even better, you could use list of tuple of strings :

sites = [
    ('http://www.twitter.com/', 'twitter'),
    ('http://www.facebook.com/', 'facebook'),
    ('http://www.pininterest.com/', 'pininterest')
]

if sites[0][0] in url:
    link, brand = sites[0]
elif sites[1][0] in url:
    link, brand = sites[1]
else:
    link, brand = sites[2]
return link, brand

Now, this seems to be begging to be written with a loop

for (link, brand) in sites:
    if link in url:
        return link, brand
return None # or anything you like


Returning total number of rows in query Oftentimes I find myself wanting the total number of rows returned by a query even though I only may display 50 or so per page. Instead of doing this in multiple queries like so:

SELECT first_name,
       last_name,
       (SELECT count(1) FROM  sandbox.PEOPLE WHERE trunc(birthday) = trunc(sysdate) ) as totalRows
FROM  sandbox.PEOPLE
WHERE trunc(birthday) = trunc(sysdate);

It has been recommended to me to do this:

SELECT first_name,
            last_name,
            count(*) over () totalRows
FROM  sandbox.PEOPLE
WHERE trunc(birthday) = trunc(sysdate);

I am just looking for what is better as far as performance and if performance is a wash. Does this really improve readability of SQL? It is certainly cleaner/easier to write.

The latter query will be much more efficient-- it only requires hitting the table once.  You can do a quick test yourself to confirm this.

I'll create a simple two-column table with 1 million rows where the second column is one of 10 distinct values

SQL> create table t (
  2    col1 number,
  3    col2 number
  4  );

Table created.

SQL> insert into t
  2    select level, mod(level,10)
  3      from dual
  4   connect by level <= 1000000;

1000000 rows created.

Now, I'll run two different queries that retrieve 10% of the data.  I've set SQL*Plus to not bother displaying the data but to display the query plan and the basic execution statistics.  With the first query, note that the query plan shows that Oracle has to access the table twice and then do a sort and aggregate.  The query does ~10,000 consistent gets which is a measure of the amount of logical I/O being done (note that this is independent of whether data is cached so it is a much more stable measure-- if you run the same query many times, the consistent gets figure will fluctuate very little)

SQL> set autotrace traceonly;
SQL> select col1
  2        ,(select count(*) from t where col2=3)
  3    from t
  4   where col2 = 3;

100000 rows selected.

Execution Plan
----------------------------------------------------------
Plan hash value: 3335345748

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|   1 |  SORT AGGREGATE    |      |     1 |    13 |            |          |
|*  2 |   TABLE ACCESS FULL| T    | 85706 |  1088K|   525   (3)| 00:00:07 |
|*  3 |  TABLE ACCESS FULL | T    | 85706 |  2176K|   525   (3)| 00:00:07 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("COL2"=3)
   3 - filter("COL2"=3)

Note
-----
   - dynamic sampling used for this statement (level=2)

Statistics
----------------------------------------------------------
         32  recursive calls
          1  db block gets
      10465  consistent gets
          0  physical reads
        176  redo size
    2219528  bytes sent via SQL*Net to client
      73850  bytes received via SQL*Net from client
       6668  SQL*Net roundtrips to/from client
          0  sorts (memory)
          0  sorts (disk)
     100000  rows processed

On the other hand, with the analytic function approach, the query plan shows that we only have to hit the table once.  And we only have to do ~1,900 consistent gets-- less than 20% of the logical I/O that the first query had to do.

SQL> select col1,
  2         count(*) over ()
  3    from t
  4   where col2 = 3;

100000 rows selected.

Execution Plan
----------------------------------------------------------
Plan hash value: 2291049666

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|   1 |  WINDOW BUFFER     |      | 85706 |  2176K|   525   (3)| 00:00:07 |
|*  2 |   TABLE ACCESS FULL| T    | 85706 |  2176K|   525   (3)| 00:00:07 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - filter("COL2"=3)

Note
-----
   - dynamic sampling used for this statement (level=2)

Statistics
----------------------------------------------------------
          4  recursive calls
          0  db block gets
       1892  consistent gets
          0  physical reads
          0  redo size
    2219510  bytes sent via SQL*Net to client
      73850  bytes received via SQL*Net from client
       6668  SQL*Net roundtrips to/from client
          1  sorts (memory)
          0  sorts (disk)
     100000  rows processed

Now, to be fair, you probably won't cut out 80% of your consistent gets moving to the analytic function approach using this particular query because it is likely that far fewer than 10% of the rows in your PEOPLE table have a birth date of today.  The fewer rows you return, the less the performance difference will be.

Since this is Code Review, the analytic function approach is much easier to maintain over time because you don't violate the DRY principle and you have to remember to make all the same changes to your inline query that you make in the main query.


Check if JavaScript input is empty Having a general utility function to see if the input is empty makes sense to me. Empty means different things depends on the type. I just spent ~5 minutes writing this one up, so I'm sure it's missing edge cases, and maybe I'm approaching the whole problem incorrectly.

Function

function isEmpty(input: any) {
    switch (typeof input) {
        case 'string':
            return input.length === 0;
        case 'object':
            return (input instanceof Array)? input.length === 0: Object.getOwnPropertyNames(input).length === 0;
        case 'number':
        default:
            return input === undefined;
    }
}

Basic [SONA!] testing

let s = '';
let o = {};
let n: number;
let a = [];

console.log('isEmpty(s): ' + isEmpty(s));
console.log('isEmpty(o): ' + isEmpty(o));
console.log('isEmpty(n): ' + isEmpty(n));
console.log('isEmpty(a): ' + isEmpty(a));

I'm tempted to modify the object line to check if the length property is defined, rather than restricting to Arrays, but that's all I can think of offhand. Any other ideas on making this more general?

One edge case you're missing is how to handle null. isEmpty(null) will  fail because Object.getOwnPropertyNames(null) will throw TypeError: can't convert null to object.

Also be aware that isEmpty(NaN) will return false, which may or may not be what you want.


Possible letter combinations of a dial pad in linear time using a recursive approach Time complexity: I walk the initial unzipped array of keys representing the number O(N) backwards. I then do an inner walk of the proceeding array of letters *O(L^2), mapping it to every value in the target O(T)). finally, I  flattening the values and repeat to get O(N^3)

I know this can not be solved in linear time, but can the runtime be improved (maybe recursively) and is my time analysis correct?

let letters_keys = {
  2: ['a', 'b', 'c'],
  3: ['d', 'e', 'f'],
  4: ['g', 'h', 'i'],
  5: ['j', 'k', 'l'],
  6: ['m', 'n', 'o'],
  7: ['p', 'q', 'r', 's'],
  8: ['t', 'u', 'v'],
  9: ['w', 'x', 'y', 'z']
}

function all_possable(num) {
  return num.toString().split('').map(x => new Set(letters_keys[x]))
}

function remp(possable) {
  possable = all_possable(possable)
  possable = possable.map(x => [...x])

  let v = possable.reduceRight((x, a) => {

    if (x.length === 0) {
      x = a
    } else {

     let k = x.map(c => a.map(b => b + c))
      x = k.reduce((acc, a) => acc.concat(a), [])
    }
    return x
  }, [])
  return v.sort()

}

console.log(remp(5678).sort())

What is your purpose in writing this code?

If the entire task is enumerate the combinations, it's not possible to do less work than going through all combinations. An \$ n \$ digit number will have between \$ 3^n \$ and \$ 4^n \$ possible combinations, depending on how many of those digits are 7s and 9s.

On the other hand, additional knowledge about the purpose of the function could guide the search for something more useful. For example, I imagine this function might then be the input to a filter which narrows them down it to dictionary words. In that case, you could preemptively stop searching if there are no words in the dictionary that start with a given prefix. (The trie data structure is a classic option for keeping track of this sort of thing.)

Assorted other comments on the code

Because what you are passing is fundamentally a sequence of keypresses rather than a number per se, consider having remp take a string instead of a number.
Set is probably unnecessary expense and complexity if all you want is to enumerate a few characters. Whatever data type you use, consider sharing an object for all usages of a given digit's letters.
all_possable isn't a particularly descriptive name for that function. I also have no idea what remp means.
Although it doesn't affect the code, the correct spelling is possible.


LeetCode Rotate Array I have started learning Java and was trying to solve some easy problems from different websites like HackerRank and leetcode.I am relatively new to programming so please don't mind if this is too naive. I found a problem in LeetCode to rotate array.The problem can be found here

I have implemented the solution using two different methods:

The first method(my initial solution) rotateArray1 is very straightforward where we divide the array into two parts and then copy the elements back into the main array.

I found the logic for the second method in programcreek which says :

  1. Divide the array two parts: 1,2,3,4 and 5, 6
  2. Reverse first part: 4,3,2,1,5,6
  3. Reverse second part: 4,3,2,1,6,5
  4. Reverse the whole array: 5,6,1,2,3,4

This is my solution where I implemented both the methods.I am trying to get better at writing good code for my solutions. Please give me your suggestions and also can anyone please tell me which one of these two methods is more efficiant in terms of time complexity.

 import java.util.Scanner;

/*Problem: Rotate an array of n elements to the right by k steps.
 For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7]
 is rotated to [5,6,7,1,2,3,4]. */

public class RoatateArray {
    public static Scanner Keyboard = new Scanner(System.in);

    public static void main(String[] args) {

        int size = Keyboard.nextInt();
        int[] array = new int[size];
        fillArray(array);
        System.out.println("Array before rotation is :");
        printArray(array);
        System.out
                .println("\nEnter the number of steps the array needs to be rotated");
        int order = Keyboard.nextInt();
        if (order == array.length) {
            System.out
                    .println("The order of the array will be same after rotation of "
                            + order + "steps");

        } else {
            System.out
                    .println("enter choice 1 : arrayRotate1  or choice 2 for : arrayrotate2");
            int choice = Keyboard.nextInt();
            switch (choice) {
            case 1:
                arrayRotate1(array, order);

                break;
            case 2:
                arrayRotate2(array, order);
                break;
            default:
                break;
            }

        }

    }

    private static void arrayRotate1(int[] array, int order) {
        if (order > array.length) {
            order = order % array.length;
        }
        int[] arr1 = new int[order];
        int[] arr2 = new int[array.length - order];
        System.arraycopy(array, array.length - order, arr1, 0, arr1.length);
        System.arraycopy(array, 0, arr2, 0, arr2.length);
        // copy arr1 and arr2 into original array
        System.arraycopy(arr1, 0, array, 0, arr1.length);
        System.arraycopy(arr2, 0, array, arr1.length, array.length - order);
        printArray(array);

    }

    private static void printArray(int[] array) {
        for (int i = 0; i < array.length; i++) {
            System.out.print(array[i] + " ");
        }

    }

    private static int[] fillArray(int[] array) {

        for (int i = 0; i < array.length; i++) {
            array[i] = Keyboard.nextInt();
        }

        return array;
    }

    private static void arrayRotate2(int[] array, int order) {

        if (order > array.length) {
            order = order % array.length;
        }

        // get the length of the first part

        int a = array.length - order;

        reverse(array, 0, a - 1);
        reverse(array, a, array.length - 1);
        reverse(array, 0, array.length - 1);
        printArray(array);

    }

    private static void reverse(int[] array, int left, int right) {
        while (left < right) {
            int temp = array[left];
            array[left] = array[right];
            array[right] = temp;
            left++;
            right--;
        }

    }

}

If you use ArrayList instead of int[] you can write rotate2 like this (it's less efficient):

  public static List<Integer> rotate2(List<Integer> numsList, int k) {
    k = k % numsList.size();
    List<Integer> firstPart = numsList.subList(0, numsList.size() - k);
    List<Integer> secondPart = numsList.subList(numsList.size() - k, numsList.size());
    Collections.reverse(firstPart);
    Collections.reverse(secondPart);

    ArrayList<Integer> rotated = new ArrayList<>();
    rotated.addAll(firstPart);
    rotated.addAll(secondPart);

    return rotated;
  }

The arrayRotate1 can also be written this way, I don't know whether it's more readable or not but it's definitely less efficient:

  public static void rotate(int[] nums, int k) {
    k = k % nums.length;
    Queue<Integer> queue = new ArrayDeque<>(k);
    for (int i = 0; i < Math.min(k, nums.length); i++) queue.add(nums[i]);
    for (int i = 0; i < nums.length; i++) {
      int index = (i + k) % nums.length;
      queue.add(nums[index]);
      nums[index] = queue.remove();
    }
  }


Query the github api and filter the last 1000 commits which include and exclude certain words from the top 3 repositories in a given organization This code should query the github api and filter, out of the last 1000 commits, which ones include and exclude certain words from the top 3 repositories in a given organization.
For example, I could query the endpoint /search with parameters such as org:facebook and include:fixed exclude:try. This should then return, out of the 3 most popular facebook repositories, and out of the 1000 most recent commits, the commit messages which include and exclude fixed and try, respectively.
from flask import Flask, request
import requests
import json

app = Flask(__name__)

NUM_REPOS = 3
MAX_PER_PAGE = 100
NUM_PAGES = 10
HEADERS = {"Accept": "application/vnd.github.cloak-preview"}

def get_matches():
    if request.method == 'POST':
        try:
            org = request.get_json()["org"]
            include = request.get_json()["include"]
            word_to_ignore = request.get_json()["ignore"]

        except:
            return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}

        repo_data = requests.get( f"https://api.github.com/search/repositories?q=org:{org}&sort=stars&order=desc&per_page={NUM_REPOS}").content
        repo_data_dict = json.loads(repo_data.decode('utf-8'))

        if not "items" in repo_data_dict:
            if "errors" in repo_data_dict:
                return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}
            else:
                return {"reached_api_limit": True}
        else:
            repo_list = repo_data_dict["items"]

        matches = []

        for repo in repo_list:
            repo_info = {}
            repo_name = repo["name"]

            repo_info["repo"] = repo_name

            page = 1
            items_exist = True
            total_count = 0

            while (items_exist and page <= NUM_PAGES):
                commits = requests.get( f"https://api.github.com/search/commits?q={include} repo:{org}/{repo_name}&per_page={MAX_PER_PAGE}&page={page}", headers=HEADERS).content
                commits = json.loads(commits.decode('utf-8'))

                if "message" in commits:
                    matches.append({"reached_api_limit": True})
                    return {"matches": matches}

                if "items" in commits and len(commits["items"]) > 0 and (page == 1 or commits["total_count"] > page-1 * MAX_PER_PAGE):

                    for commit in commits["items"]:

                        if word_to_ignore in commit["commit"]["message"]:
                            continue

                        repo_info["message"] = commit["commit"]["message"]

                        matches.append(repo_info)

                        if commits["total_count"] < MAX_PER_PAGE:
                            items_exist = False

                else:
                    items_exist = False

                page += 1

        return {"matches": matches}

@ app.route('/search', methods=['POST'])
def example():
    return get_matches()

if __name__ == '__main__':
    app.run()

if request.method == 'POST': is redundant; delete it.
Your

your request is missing the 'org', 'include' or 'ignore' parameters

is less than helpful. Why not tell the user exactly what they're missing?
This except block:
    try:
        org = request.get_json()["org"]
        include = request.get_json()["include"]
        word_to_ignore = request.get_json()["ignore"]

    except:
        return {"error": "your request is missing the 'org', 'include' or 'ignore' parameters"}

will tell the user that their request is missing a parameter even if the server runs out of memory, or the entire payload is the string banana instead of a well-formed JSON body; or someone attaches the server process to a console and presses Ctrl+C to break it. Are you sure that all three of these exceptions constitute the user having submitted a well-formed JSON payload missing one or more keys? Never bare except:.
Move your query string parameters into a params dictionary sent to requests.
This:
    if not "items" in repo_data_dict:
        if "errors" in repo_data_dict:
            return {"invalid_organization": f"{org} does not exist or doesn't have any repositories"}
        else:
            return {"reached_api_limit": True}

is a wild and crazy guess. What if 'errors' told you that the server is down for maintenance, or you submitted a malformed payload, or the endpoint is deprecated? You need to pay attention to the contents of the error message given to you.
Don't json.loads here. Just call .json() on the response.
Be sure to check for HTTP error conditions via response.raise_for_status().
You need to break up get_matches into multiple methods.
You need to improve separation of concerns - get_matches returns dictionaries intended for consumption by the REST API, but that shouldn't be done in that function - payload dictionary formation should be done above, in the Flask handler function. To indicate errors, you can throw your own exceptions, catch them in the method above and add that to the response dictionary. To indicate whether you hit the API limit, you can add a boolean to your return tuple.
total_count is unused; delete it.
Your response format is flat, and this can be inconvenient and inefficient to consume on the client side. Instead consider a dictionary of repositories, each value being a list of messages, rather than adding the repo name to every response element.
This check:
                    if commits["total_count"] < MAX_PER_PAGE:
                        items_exist = False

seems to exist at the wrong level of indentation, since it applies to commits in general and not the current iterated commit.
This:
commits["total_count"] > page-1 * MAX_PER_PAGE

almost certainly does not do what you want, since it's doing
page - (1*MAX_PER_PAGE)

and not
(page - 1)*MAX_PER_PAGE

so add parens as appropriate.
Some of the above suggestions baked into an example:
from pprint import pprint
from typing import List, Tuple

import requests

NUM_REPOS = 3
MAX_PER_PAGE = 100
NUM_PAGES = 10
HEADERS = {"Accept": "application/vnd.github.cloak-preview"}

class InvalidOrganizationError(Exception):
    pass

class APILimitError(Exception):
    pass

# @app.route('/search', methods=('POST',))
def handle_search() -> dict:
    payload = request.get_json()

    try:
        org = payload['org']
    except KeyError:
        return {'error': 'Missing the "org" parameter'}

    try:
        include = payload['include']
    except KeyError:
        return {'error': 'Missing the "include" parameter'}

    try:
        word_to_ignore = payload['word_to_ignore']
    except KeyError:
        return {'error': 'Missing the "word_to_ignore" parameter'}

    matches, api_limited = get_matches(org, include, word_to_ignore)
    return {'matches': matches, 'reached_api_limit': api_limited}

def get_repo(org: str) -> dict:
    with requests.get(
        'https://api.github.com/search/repositories',
        params={
            'q': f'org:{org}',
            'sort': 'stars',
            'order': 'desc',
            'per_page': NUM_REPOS,
        },
        headers=HEADERS,
    ) as resp:
        resp.raise_for_status()
        repo_data_dict = resp.json()

    repo_list = repo_data_dict.get('items')
    if repo_list is not None:
        return repo_list

    if 'errors' in repo_data_dict:
        raise InvalidOrganizationError(
            f'{org} does not exist or does not have any repositories'
        )
    raise APILimitError()

def get_commits(org: str, include: str, repo_name: str, page: int) -> dict:
    with requests.get(
        'https://api.github.com/search/commits',
        params={
            'q': f'{include} repo:{org}/{repo_name}',
            'per_page': MAX_PER_PAGE,
            'page': page,
        },
        headers=HEADERS,
    ) as resp:
        resp.raise_for_status()
        return resp.json()

def get_matches(
    org: str, include: str, word_to_ignore: str,
) -> Tuple[
    List[object],  # All matches
    bool,          # Did we hit the API limit?
]:
    repo_list = get_repo(org)

    matches = []

    for repo in repo_list:
        messages = []
        repo_info = {'repo': repo['name'], 'messages': messages}
        matches.append(repo_info)

        page = 1
        items_exist = True

        while items_exist and page <= NUM_PAGES:
            commits = get_commits(org, include, repo['name'], page)

            if "message" in commits:
                return matches, True

            if "items" in commits and (
                page == 1 or commits["total_count"] > (page-1) * MAX_PER_PAGE
            ):
                for commit in commits["items"]:
                    message = commit["commit"]["message"]

                    if word_to_ignore in message:
                        continue

                    messages.append(message)

            else:
                break

            if commits["total_count"] < MAX_PER_PAGE:
                items_exist = False

            page += 1

    return matches, False

def test():
    matches, api_limited = get_matches('microsoft', 'repo', 'fetch')
    pprint(matches)

if __name__ == '__main__':
    test()


Create new DataFrame containing mean information I have a dataframe with the columns "Action", "Filt" and "Val" which measure the resulting error of filtering an action. I want to calculate the mean of the error for each "Action" and "Filt". Currently, I do this by iterating through each combination of "Action" and "Filt". However, I'm afraid the slicing is taking up more time than I would like.

import pandas as pd

in_dat = [
    ("run", "raw", 1),
    ("run", "deep", 1),
    ("jump", "raw", 2),
    ("jump", "deep", 2),
    ("run", "raw", 2),
    ("run", "deep", 2),
    ("jump", "raw", 3),
    ("jump", "deep", 3)

]

all_err = pd.DataFrame(in_dat, columns=("action", "filt", "val"))

mean_vals = []

for act in tuple(all_err.action.unique()):
    for filt in tuple(all_err.filt.unique()):
        mean_val = all_err[(all_err.action == act) & (all_err.filt == filt)].val.mean()
        mean_vals.append((act, filt, mean_val))

mean_err = pd.DataFrame(mean_vals, columns=("Action", "Filt", "Error"))

This gives the result of mean_err being:

  Action  Filt  Error
0    run   raw    1.5
1    run  deep    1.5
2   jump   raw    2.5
3   jump  deep    2.5

What's a faster way to do this with Pandas and getting a similar result?

pandas is deep

The pandas toolkit is very deep and can take a while to grok some of the basics.  In the case of your code, you are replicating the functionality in pandas.DataFrame.groupby().  groupby gathers all of the elements together with matching values in the fields indicated and then allows those elements to be worked on as a group.  In the case of:

for act in tuple(all_err.action.unique()):
    for filt in tuple(all_err.filt.unique()):

This code is referencing all values of the action and filt columns into two variables.  Then:

mean_val = all_err[(all_err.action == act) & (all_err.filt == filt)].val.mean()
mean_vals.append((act, filt, mean_val))

These lines perform a mean on the val column for each row that matches in the two grouped columns, and stores those results into a list.  Pandas has a shortcut for these sorts of operations called groupby.  The above four lines, plus the list initialization, can be equivalently written as:

all_err.groupby(['action', 'filt']).val.mean()

How?

Starting with:

all_err.groupby(['action', 'filt'])

produces a pandas.core.groupby.DataFrameGroupBy.  This object instance understands how to iterate over the dataframe a group at a time, allowing access to these groups in various ways.  So then,

all_err.groupby(['action', 'filt']).val

selects the val column to work against, and finally,

all_err.groupby(['action', 'filt']).val.mean()

asks for the mean value of that column.

Results:

mean_err = all_err.groupby(['action', 'filt']).val.mean()
print(mean_err)

  Action  Filt  Error
0    run   raw    1.5
1    run  deep    1.5
2   jump   raw    2.5
3   jump  deep    2.5


Text-wrapping function in JavaScript I have the following code on my server that takes a string and inserts newlines in such a way that the string is separated into lines, all of which are shorter than maxLineLength in characters. This ensures that the text, when printed, will fit within a certain width.

const formatTextWrap = (text, maxLineLength) => {
  var words = text.replace(/[\r\n]+/g, ' ').split(' ')
  var lineLength = 0
  var output = ''
  for (var word of words) {
    if (lineLength + word.length >= maxLineLength) {
      output += `\n${word} `
      lineLength = word.length + 1
    } else {
      output += `${word} `
      lineLength += word.length + 1
    }
  }
  return output
}

What optimizations could I make? This code works, but are there any pitfalls to using this?

I would modify a bit logic regarding spacing between words in lines. With your solution you might end up with unnecessary spaces on line ends.

Additionally using Array.reduce instead of for loop is more JS-way to join array.

const formatTextWrap = (text, maxLineLength) => {
  const words = text.replace(/[\r\n]+/g, ' ').split(' ');
  let lineLength = 0;

  // use functional reduce, instead of for loop
  return words.reduce((result, word) => {
    if (lineLength + word.length >= maxLineLength) {
      lineLength = word.length;
      return result + `\n${word}`; // don't add spaces upfront
    } else {
      lineLength += word.length + (result ? 1 : 0);
      return result ? result + ` ${word}` : `${word}`; // add space only when needed
    }
  }, '');
}

let testingText = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam blandit mauris id venenatis tincidunt. Vestibulum at gravida sapien. Mauris tellus augue, aliquet sed laoreet blandit, pulvinar sed felis. Phasellus nec est vitae enim blandit facilisis.
Vestibulum fermentum ligula sit amet volutpat fermentum. Sed in faucibus orci. Pellentesque a dui ex. Curabitur sollicitudin, nulla id dignissim lacinia, odio mauris blandit nisi, eget auctor arcu odio nec est.`;
console.log(formatTextWrap(testingText, 20));


Assigning value to cells with Excel VBA I have an Excel Worksheet consisting of two columns, one of which is filled with strings and the other of which is empty.  I would like to use VBA to assign the value of the cells in the empty column based on the value of the adjacent string in the other column.

Dim regexAdmin As Object
Set regexAdmin = CreateObject("VBScript.RegExp")
regexAdmin.IgnoreCase = True
regexAdmin.Pattern = "Admin"

Dim i As Integer
For i = 1 To 10 'let's say there is 10 rows
    Dim j As Integer
    For j = 1 To 2
        If regexAdmin.test(Cells(i, j).Value) Then
            Cells(i, j + 1).Value = "Exploitation"
        End If
    Next j
Next i

The problem is that when using this loop for a big amount of data, it takes way too long to work and, most of the time, it simply crashes Excel.

Does anyone know a better way of doing this?

The short answer is:

Don't use vba, use a formula. In particular, a combination of IF and SEARCH.

=IF(SEARCH($A1,"Admin")>0,"Exploitation","")

But this is code review, so let's do that anyway.

Regex is slow. It seems that you're only using it for it's case insensitivity. Given that, you can directly compare cell values by using StrComp with the vbTextCompare option. (useful article on StrComp)
i and j are typically used for loop counters, but row and col make more sense in this case.

Here is what this could could look like:

Dim row As Integer
For row = 1 To 10 'let's say there is 10 rows
    Dim col As Integer
    For col = 1 To 2
        If StrComp("Admin",Cells(row, col).Value,vbTextCompare) Then
            Cells(row, col + 1).Value = "Exploitation"
        End If
    Next col
Next row


Merging two arrays of objects with different keys/properties I have two different arrays:

var array1 = [
    {id: "foo", name: "Foo Smith"},
    {id: "caa", name: "CAA"},
    {id: "bar", name: "Bar Jones"},
    {id: "baz", name: "Baz Apple"},
    {id: "boo", name: "Boo Ghost"},
    {id: "dah", name: "DAH-123"}
];

var array2 = [
    {name: "bar", key1: false, key2: false, key3: "abcdef", id: "abc123"},
    {name: "foo", key1: true, key2: false, key3: "abcdef", id: "def456"},
    {name: "dah", key1: false, key2: true, key3: "abcdef", id: "jkl012"},
    {name: "doo", key1: false, key2: false, key3: "ghijkl", id: "mno345"},
    {name: "laa", key1: false, key2: true, key3: "ghijkl", id: "pqr678"},
    {name: "boo", key1: true, key2: true, key3: "ghijkl", id: "ghi789"},
    {name: "fib", key1: true, key2: false, key3: "abcdef", id: "stu901"}
];

And the following requirements:

Requirements:

Get the intersection of array1 and array2 based off of matching
array1['id'] to array2['name']
Output needs to look like array1 with the following requirements:

key1, key2 and key3 need to be merged into array1 for intersecting objects
id of array2 needs to be mapped to new_id in array1

If no intersecting object, then defaultOptions need to be applied to array1

So that the output should look like:

$scope.outputArray = [
    {id: "foo", name: "Foo Smith", key1: true, key2: false, key3: "abcdef", new_id: "def456"},
    {id: "caa", name: "CAA", key1: false, key2: false, key3: null},
    {id: "bar", name: "Bar Jones", key1: false, key2: false, key3: "abcdef", new_id: "abc123"},
    {id: "baz", name: "Baz Apple", key1: false, key2: false, key3: null},
    {id: "boo", name: "Boo Ghost", key1: true, key2: true, key3: "ghijkl", new_id: "ghi789"},
    {id: "dah", name: "DAH-123", key1: false, key2: true, key3: "abcdef", new_id: "jkl012"}
];

What works:

var defaultOptions = {
    key1: false,
    key2: false,
    key3: null
};

var intersection = _.intersection(_.pluck(array1, 'id'), _.pluck(array2, 'name'));
var intersectionArr1 = _.sortBy(_.filter(array1, function(person) {
    return intersection.indexOf(person.id) >= 0;
}), 'id');
var intersectionArr2 = _.sortBy(_.filter(array2, function(person) {
    return intersection.indexOf(person.name) >= 0;
}), 'name');

_.each(intersectionArr1, function(person, idx) {
    _.assign(person, _.pick(intersectionArr2[idx], ['key1', 'key2', 'key3']));
    _.defaults(person, { new_id: intersectionArr2[idx].id });
});

var diff = _.difference(_.pluck(array1, 'id'), _.pluck(array2, 'name'));
var leftoverArr1 = _.filter(array1, function(person) {
    return diff.indexOf(person.id) >=0;
});

_.each(leftoverArr1, function(person) {
    _.defaults(person, defaultOptions);
});

$scope.newOutputArray = array1;

and here is the CodePen.

While this works, I'm looking for speed improvements.  Both array will eventually be very large 50-100K.

Any help would be greatly appreciated.

When you merge two arrays, where the one array contains a key value, you can save a lot of time by indexing the keys. Consider an index on the array2 name column.

It is really easy to index the data using an Object with named properties:

var indexed = {};

_.each(array2, function(data) {
  indexed[data["name"]] = data;
});

Now, we have a fast way to find any data record in array2 for a given name.

Using that structure becomes easy again, by looping for each of the array1 values, and updating them based on the value that was indexed, if any. Loop for each record, search in the index, use the default if the index value was not found.

To make the code a bit more flexible, and because the "column" names change from id to new_id, it helps to have a structure containing this column mapping:

var mapCols = {
  key1: "key1",
  key2: "key2",
  key3: "key3",
  id: "new_id"
}

The mapCol indicates that key1 should become key1, and so on, but id should become new_id.

This allows us to then make the "simple" nested loops:

_.each(array1, function(person){
  var use = indexed[person["id"]] || defaultOptions;
  _.each(mapCols, function(key) {
    person[mapCols[key]] = use[key];
  });
});

You can see this running here in your forked code.

In theory, this will turn your code from an \$O(n \times m)\$ operation to become an \$O(n + m)\$ one, where \$n\$ and \$m\$ are the sizes of the two arrays.


Binary Tree Longest Consecutive Sequence I written code to solve this problem which I found on leetcode. My solution worked for the vast majority of the test cases run against it but failed on 2 for some reason. The first test case it failed on had a extremely large input size for the tree so it's really hard to determine what is actually wrong with the algorithm I wrote:

class TreeNode(object):
    def __init__(self, x):
        self.val = x
        self.left = None
        self.right = None

def lcs(root):
    if root is None:
        return 0
    left_lcs = lcs(root.left)
    right_lcs = lcs(root.right)
    add_to_left = 0
    add_to_right = 0
    if root.left is not None:
        if root.left.val - root.val == 1:
            add_to_left = 1
    if root.right is not None:
        if root.right.val - root.val  ==1:
            add_to_right =1
    if root.right is None and root.left is None:
        return 1
    return max(add_to_left + left_lcs, add_to_right + right_lcs)

Are there any glaring issues with the code that I'm just missing?

Recursion is probably your main problem, as Graipher mentioned in the comments.

You could refactor it to be iterative:

def lcs(root):
    if root is None:
        return 0
    longest_sequence = 0
    nodes = dict()
    nodes[root] = 1
    while True:
        new_nodes = dict()
        for node, length in nodes.items():
            for subnode in (node.left, node.right):
                if subnode:
                    if subnode.val - node.val == 1:
                        new_nodes[subnode] = length + 1
                    else:
                        new_nodes[subnode] = 1
            longest_sequence = max(longest_sequence, length)
        nodes = new_nodes
        if not nodes:
            break
    return longest_sequence


Infinite Continued Fraction - iterative and recursive Given the following exercise:

  Exercise 1.37.  a. An infinite
  continued fraction is an expression of
  the form

  As an example, one can show that the
  infinite continued fraction expansion
  with the Ni and the Di all equal to 1
  produces 1/, where is the golden ratio
  (described in section 1.2.2). One way
  to approximate an infinite continued
  fraction is to truncate the expansion
  after a given number of terms. Such a
  truncation -- a so-called k-term
  finite continued fraction -- has the
  form

  Suppose that n and d are procedures of
  one argument (the term index i) that
  return the Ni and Di of the terms of
  the continued fraction. Define a
  procedure cont-frac such that
  evaluating (cont-frac n d k) computes
  the value of the k-term finite
  continued fraction. Check your
  procedure by approximating 1/ using

(cont-frac (lambda (i) 1.0)
           (lambda (i) 1.0)
           k)

  for successive values of k. How large
  must you make k in order to get an
  approximation that is accurate to 4
  decimal places?

  b. If your cont-frac procedure
  generates a recursive process, write
  one that generates an iterative
  process. If it generates an iterative
  process, write one that generates a
  recursive process.

I wrote the following two functions:

Recursive:

(define (cont-frac n_i d_i k)
  (define (recurse n)
    (define (next n) (+ n 1))
    (if (= n k) (/ (n_i k) (d_i k))
        (/ (n_i n) (+ (d_i n) (recurse (next n))))))
  (recurse 1))

Iterative:

(define (i-cont-frac n_i d_i k)
  (define (iterate result n)
    (define (next n) (- n 1))
    (if (= n 1) (/ (n_i n) result)
        (iterate (+ (d_i (next n))
                    (/ (n_i n) result)) (next n))))
  (iterate (d_i k) k))

What do you think of my solution?

Your solutions look good.

I don't see any significantly different way to do the recursive solution.  My preferences for whitespace (mostly concerning the if) are a little different.  Also, I wouldn't define a function for next in this situation.  If for some reason you don't want to simply put (+ n 1) as an argument a let expression would be more applicable.

(define (cont-frac n_i d_i k)
   (define (recurse n)
     (if (= n k)
         (/ (n_i k) (d_i k))
         (/ (n_i n) (+ (d_i n) (recurse (+ n 1)))) ))
   (recurse 1))

OR

(define (cont-frac n_i d_i k)
   (define (recurse n)
     (if (= n k)
         (/ (n_i k) (d_i k))
         (let ((next_n (+ n 1)))
           (/ (n_i n) (+ (d_i n) (recurse next_n)))) ))
   (recurse 1))

PS - write a function for the nth_odd_square and try this

(/ 4.0 (+ 1 (i-cont-frac nth_odd_square (lambda (i) 2.0) 500000)))


Popular questions by view count I made this query to create a graph of a user's popular questions and the view count on that question. It allows for a minimum of 500 views, and a score of 3.

DECLARE @allowed_min_views INT = 500;
DECLARE @allowed_min_score INT = 3;

DECLARE @user_id INT = ##UserId:int?-1##;
DECLARE @min_views INT = ##MinimumViews:int?500##;
DECLARE @min_score INT = ##MinimumScore:int?3##;
DECLARE @question INT = 1;

IF (@min_views < @allowed_min_views)
BEGIN
  PRINT '@MinimumViews must be larger than 499.'
END

IF (@min_score < @allowed_min_score)
BEGIN
  PRINT '@MinimumScore must be larger than 2.'
END

IF (@min_views >= @allowed_min_views AND @min_score >= @allowed_min_score)
BEGIN
  SELECT
      ViewCount
    , Score
    FROM Posts WHERE
      PostTypeId = @question
      AND OwnerUserId = @user_id
      AND ViewCount >= @min_views
      AND Score >= @min_score
    ORDER BY ViewCount ASC;
END

Finally, here's some sample input (I'm using @Mat'sMug's user ID):

@user_id:   23788
@min_views: 500
@min_score: 7

Good things
You use good local variables, and you are consistent with your naming. The typical naming for T-SQL is using PascalCase, however there are no standards and snake_case or camelCase work just as good, as long as you are consistent (which you are).
You validate your values, although I am not quite sure why you chose 500 and 3 as arbitrary minimums (might be worth documenting).

Results are not very useful...
As written, your query returns this:
ViewCount Score
--------- -----
571       10
629       5
685       6
721       10
728       11
761       12
840       25
849       7
870       17
888       9
1065      10
...
Which is all well and good, except, it doesn't give much information. Let's say we rewrite it a bit like this:
IF (@min_views >= @allowed_min_views AND @min_score >= @allowed_min_score)
BEGIN
  SELECT
      ViewCount
    , Score
    , [User Link] = @user_id
    , [Post Link] = Id
    , CreationDate
    , [Tags] = Tags
    FROM Posts
    WHERE
      PostTypeId = @question
      AND OwnerUserId = @user_id
      AND ViewCount >= @min_views
      AND Score >= @min_score
    ORDER BY ViewCount DESC;
END

Notice I changed ORDER BY to DESC, I think it makes more sense to show highest first.
Then we get a more sensible result set, e.g.:


Read coordinates from many files and calculate polygon areas My goal with this snippet is to create an array of coordinates which in turn is a tuple of 68 elements, area and modified area array for all 10k elements and assign it to the df column.

Running the complete code results in 5.3, 4.8, 4.6, 4.5 seconds.

#%%

arrayc = [] #array for array of coordinates
areaAr = [] #area type 1
modifiedarea = [] #area type 2
ts = time.time()

for i in range(10708): #number of files
        f = open(df["filepath"][i], "r") #df has column of filepaths
        x,y = [], []
        for l in f:
            row = l.split()
            x.append(int(float(row[0]))) #68 pairs are of kind 3.82382323e+02 4.563524234e+02.
            y.append(int(float(row[1]))) #I am taking int rounded off to three digits.
        arrayc.append((x,y))
        f.close()
        #x= arrayc[i][0]
        #y = arrayc[i][1]
        areaAr.append(PolyArea(x[36:41],y[36:41]))
        distance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45]))
        modifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance)

te = time.time()
print(-ts+te)
def PolyArea(x,y):
        return 0.5*np.abs(np.dot(x,np.roll(y,1))-np.dot(y,np.roll(x,1)))

How can I minimise the execution time ?

Updates:

File generator code:

import numpy as np
filepath = []
root = '~/Desktop/test/'
for i in range(10):
    for j in range(68):
        numx = ( np.random.randint(100,200))
        numy = np.random.randint(100,200)
        f = open(root + str(i) + ".txt","a")
        f.write(str(numx) + " " + str(numy) + "\n")

The numbers 36 41 etc are the coordinates of the polygon of interest on the image. It is fixed that the polygon will always be marked by these coordinates.

I couldn't run your code, so I can't say how much faster the following will be.

My suggestion is to use NumPy's loadtxt function to get the array of the necessary coordinates. With this function, you can specify skiprows and max_rows parameters to get the necessary rows, 36-45. This should be more efficient than reading all the file in memory.

Here:

areaAr.append(PolyArea(x[36:41],y[36:41]))
distance = max(np.abs(x[36]-x[39]),np.abs(x[42]-x[45]))
modifiedarea.append((PolyArea(x[36:41],y[36:41]))/distance)

you calculate PolyArea two times, but it is enough to calculate it only once and then reuse the result.

The final code could lool like this:

for filepath in df['filepath'].iloc[:10708]:
    values = np.loadtxt(filepath,
                        skiprows=35,
                        max_rows=10)
    x = values[:, 0]
    y = values[:, 1]
    area = PolyArea(x[:5], y[:5])
    areaAr.append(area)
    distance = max(np.abs(x[0] - x[3]), np.abs(x[6] - x[9]))
    modifiedarea.append(area / distance)


Text search in Python Whilst self-studying algorithms, I came across the Karp-Rabin rolling hash search algorithm here. I decided to have a go at implementing it in Python:

For ease of reading; the data-structure description and formulas embedded in append() and skip() are:

import random
from time import process_time

def is_prime(n):
    if n <= 1:
        return False
    elif n <= 3:
        return True
    elif (n % 2 == 0) or (n % 3 == 0):
        return False
    i = 5
    while (i*i) <= n:
        if (n % i == 0) or ((n % (i + 2)) == 0):
            return False
        i += 6
    return True

def find_prime_above(x):
    x = int(x)
    if x < 0:
        x = 0
    if x > 100:
        interval = int(x / 10)
    else:
        interval = x + 1
    count = 0
    found = False
    while not found:
        if (x % 2) == 0:
            start = x + 1
        else:
            start = x
        n = random.randrange(start, start + interval, 2)
        if is_prime(n):
            found = True
            return n
        count += 1
        if count > (interval / 2):
            interval *= 2
            count = 0

class hash_div(object):
    def __init__(self, size):
        if not is_prime(size):
            ValueError("Use a prime as the base")
        self.mod = size

    def h(self, num):
        return num % self.mod

class rolling_hash(hash_div):
    # built for strings
    def __init__(self, base, size):
        self.a = base
        self.uModP = 0
        self.size_x = 0
        self.ax = 1
        super(rolling_hash, self).__init__(size)

    def r(self):
        return self.uModP

    def update_ax(self, up_down):
        if up_down == "up":
            self.size_x += 1
        elif up_down == "down":
            self.size_x -= 1
        self.ax = self.h(self.a**(self.size_x - 1))

    def append(self, char):
        self.uModP = self.h((self.uModP*self.a) + ord(char))
        self.update_ax("up")

    def skip(self, char):
        self.uModP = self.h(self.uModP - (ord(char) * self.h(self.ax)))
        self.update_ax("down")

def search_file(fileStr, term):
    size = find_prime_above(len(fileStr))
    rs = rolling_hash(256, size)
    rt = rolling_hash(256, size)

    for c in term:
        rs.append(c)

    for c in fileStr[:len(term)]:
        rt.append(c)

    for i in range(len(term), len(fileStr)):
        rt.skip(fileStr[i - len(term)])
        rt.append(fileStr[i])
        if rs.r() == rt.r():
            # Found 1st instance, now print index of occurance
            print(i)
            # print rest of line
            ind = i - len(term) + 1
            ch = fileStr[ind]
            while ch != '\n':
                print(ch, end = "")
                ind += 1
                ch = fileStr[ind]
            print("\n")
            return i

test = input("Do you want to run in test mode?: ")

if test in ["yes", "y"]:
    fileName = "Shakey.txt"
    searchTerms = []
    with open(fileName, "r") as fp:
        words = fp.read().split()
        for i in range(100):
            searchTerms.append(random.choice(words))
else:
    fileName = input("Type File Name: ")
    searchTerms = [input("Type search term: ")]

total_t = 0

with open(fileName, "r") as fp:
    fileStr = fp.read()
    for term in searchTerms:
        t0 = process_time()
        search_file(fileStr, term)
        t = process_time() - t0
        total_t += t
        print(term, "took:", t, "s")
        print("----")

print("Average Time: ", total_t/len(searchTerms))

I'm using the works of Shakespeare as a test case, and it takes on average 0.5s to find a particular word (based on my test case embedded in code). My is_prime() function is verbatim from here, and I know that my find_prime_above() function is a bit of a dogs dinner.

But I have a few main questions:

Is there anything in my implementation that could be done to improve the constant factors (using the Karp-Rabin algorithm) and make it run faster?
How should I structure my tests (I am self taught, so I don't have anyone to tell me best practices)? Should they be in a separate file?

Computing hash with Python built-in

    pow(self.a, self_size - 1, self.mod)

is much faster than ** and % done separately.
I don't see the reason of passing string argument to update_ax. Passing 1 and -1 directly is much cleaner and likely faster:

def update_ax(self, up_down):
    self.size_x += up_down
    self.ax = self.h(....)

Finding a prime is indeed unconventional. I recommend to run a standard sieve (Chebyshov' theorem aka Bertrand postulate guarantees a prime in [n, 2n] range).


Simple singly linked list in Java The list is pretty simple, here is my code:
ILinkedList.java

package datastructures;

public interface ILinkedList<T> {
    public enum posForOperation { BEGGINIG,BEFORE ,AFTER ,END }
    public class Node<T>{
        T data;
        Node next;
        public Node(T data){
            this.data = data;
            this.next = null;
        }
    }
    public Node newNode(T data);
    public void add(posForOperation insert_at, T data);
    public void add(posForOperation insert_at, T data, Node node);
    public void delete(posForOperation delete_at);
    public void delete(posForOperation delete_at, Node node);
    public void deleteAtPos(int pos);
    public Node search(T data);
    public void print(); // for debugging
}

LinkedList.java

package datastructures;

public class LinkedList<T> implements ILinkedList<T> {
    private Node head;
    private Node end;
    public LinkedList(T data){
        Node new_node = new Node(data);
        head = new_node;
        end  = new_node;
    }
    @Override
    public Node newNode(T data) {
        return new Node(data);
    }

    @Override
    public void add(ILinkedList.posForOperation insert_at, T data) {
        Node new_node = newNode(data);
        if(insert_at == ILinkedList.posForOperation.BEGGINIG){
            new_node.next = head;
            head = new_node;
        }
        else if(insert_at == ILinkedList.posForOperation.END){
            end.next = new_node;
            end = new_node;
        }
    }

    @Override
    public void add(ILinkedList.posForOperation insert_at, T data, Node node) {
        if(insert_at == ILinkedList.posForOperation.BEFORE){
            Node tmp = head;
            while(tmp.next != node && tmp.next != null){
                tmp = tmp.next;
            }
            Node new_node = newNode(data);
            new_node.next = node;
            tmp.next = new_node;
        }
        else if(insert_at == ILinkedList.posForOperation.AFTER){
            Node new_node = newNode(data);
            new_node.next = node.next.next;
            node.next = new_node;
        }
        else // in case of misuse
            add(insert_at, data);
    }

    @Override
    public void delete(ILinkedList.posForOperation delete_at) {
        if(delete_at == ILinkedList.posForOperation.BEGGINIG){
            head = head.next;
        }
        if(delete_at == ILinkedList.posForOperation.END){
            Node tmp = head;
            while(tmp.next != end && tmp != end){ // the second condition is in case that head = end
                tmp = tmp.next;
            }
            tmp.next = null;
            end = tmp;
        }
    }

    @Override
    public void delete(ILinkedList.posForOperation delete_at, ILinkedList.Node node) {
        if(node.next == null)
            delete(ILinkedList.posForOperation.END);
        else if(delete_at == ILinkedList.posForOperation.AFTER){
            node.next = node.next.next;
        }
        else if(delete_at == ILinkedList.posForOperation.BEFORE){
            Node tmp = head;
            while(tmp.next != node){
                tmp = tmp.next;
            }
            tmp.next = node.next;
        }
        else //in case of misuse
            delete(delete_at);
    }

    @Override
    public ILinkedList.Node search(T data) {
        Node tmp = head;
        while(tmp.data != data && tmp != null){
            tmp = tmp.next;
        }
        return tmp;
    }

    @Override
    public void deleteAtPos(int pos) {
        Node tmp = head;
        for (int i = 0; i < pos-1 && tmp != null; i++){
            tmp = tmp.next;
        }
        delete(ILinkedList.posForOperation.AFTER, tmp);
    }

    @Override
    public void print() {
        Node tmp = head;
        while(tmp != end){
            System.out.println(tmp.data);
            tmp = tmp.next;
        }
    }
}

Initial impressions:

public Node newNode(T data) shouldn't be on the interface, why would anything outside of the list need to construct one?
print shouldn't be on the interface, I know you say it's for debugging, but a better approach would be to provider an iterator so that something outside the list could iterate the items and print them.
I don't like the fact that Node is visible outside of the list class.  It reveals too much of the underlying functionality.  What happens if I call 'newNode' then pass the contents of it to the delete method?
One of your delete methods takes in a 'delete_at' parameter, then ignores it in certain conditions and deletes the last member of the list instead...

public void delete(ILinkedList.posForOperation delete_at, ILinkedList.Node node) {
        if(node.next == null)
            delete(ILinkedList.posForOperation.END);
        else if(delete_at == ILinkedList.posForOperation.AFTER){

void deleteAtPos(int pos), there's no way for a caller to really know where in the list an item is (unless they count as they insert them?), so what's the purpose of this method?


Sum to zero of all triples in a list - n^2 running time As part of an interview, I had to submit a code sample to solve the classical "triples sum to 0" problem. The reviewer said the algorithm needed to be in n2 time, and I was later informed that the code I wrote did not accomplish this.

Can you guys help me identify where I went wrong? I've written comments explaining my thought process.

# Small struct to hold the values we need for computing unique sums
DoubleSum = namedtuple('DoubleSum', 'arg_sum int1 int2 int1_index int2_index')

def sum_zero(integers: [int]) -> [(int, int, int)]:
    """
    Given a list of integers, compute all triples that sum to 0
    :param integers: The integers to arrange
    :return: All triples that sum to 0, or [] if there are no sums
    """
    # Check for trivial issues
    if integers is None or len(integers) < 3:
        raise ValueError("Must have an input of at least 3 integers to check.")

    s_integers = sorted(integers)

    # Compute all unique possible sums of two integers
    # Should run in n^2
    sums = []
    for i in range(0, len(s_integers)):
        for j in range(i+1, len(s_integers)):
            int1 = s_integers[i]
            int2 = s_integers[j]
            sums.append(DoubleSum(int1+int2, int1, int2, i, j))

    # For each integer, find all two-element sums that would equal 0
    # Should be n^2 - for each integer, find all double sums that match it
    triples = []
    for i in range(0, len(s_integers)):
        current = s_integers[i]
        matches = filter(lambda s: s.arg_sum == -current, sums)
        for match in matches:
            test_triple = (i, match.int1_index, match.int2_index)
            # If the current index isn't below both indices in the sum,
            # we have come across another permutation of a previous sum to 0
            if i < match.int1_index and i < match.int2_index:
                triples.append(test_triple)

            # We could reduce the runtime if we added a break statement to the
            # else clause, but that seems to introduce errors after maintenance
            # when nobody quite remembers what the break did in the first place

    # Map the indices in `triples` to the actual values
    return [(s_integers[t[0]],
             s_integers[t[1]],
             s_integers[t[2]]) for t in triples]

Your first pair of loops builds the list sums. The length of this list is \$O(n^2)\$ in the length of the input.

In your second set of loops for each element in s_integers you filter all of sums to find those elements which match it. The runtime of this filter process is linear in the length of sums, and hence quadratic in the length of the input. You perform this quadratic process once for each member of the input list; the search loop is therefore cubic in the length of the input.

Your algorithm as a whole is therefore \$O(n^3)\$ in the length of the input.

To make the algorithm as a whole quadratic, you need to make the second (match) stage linear in the length of sums. Natural approaches would include:

Using a dictionary or some other map structure to lookup elements in the original either s_integers or sums by magnitude, in constant time; the match stage is then linear in the length of the other list. (Probably fastest on real input; it might be slightly tricky to check that there are no pathological cases, depending on which list you do lookup on).
Sorting sums (\$O(n \log n)\$), then effectively 'merging' sums and s_integers, (\$O(n)\$ in the length of the larger). This is easiest to prove to be \$O(n^2)\$


Returning the results of four $resource calls as a JSON array in AngularJS Title pretty much says it. I need a way to elegantly handle multiple $resource calls in AngularJS. Right now, I just calling each other call on the success function and calling a callback function to spit the data out when it's down.

Here's what I have so far.

// DataService.js
var resource = $resource('/app/data/event/:id/:ext', {id:'@id',ext:'@ext'}, {"getAll": {method: "GET", isArray: false}});
getAllEvents: function (successcb) {
    var combinedJSON = "[";
    // First Call
    var firstFile = resource.get({ id: 1, ext: '.json' });
    firstFile.$promise.then(function (data) {
        combinedJSON += JSON.stringify(data) + ",";
        // Second Call
        var secondFile = resource.get({ id: 2, ext: '.json' });
        secondFile.$promise.then(function (data) {
            combinedJSON += JSON.stringify(data) + ",";
            // Third Call
            var thirdFile = resource.get({ id: 3, ext: '.json' });
            thirdFile.$promise.then(function (data) {
                combinedJSON += JSON.stringify(data) + ",";
                // Fourth Call
                var fourthFile = resource.get({ id: 4, ext: '.json' });
                fourthFile.$promise.then(function (data) {
                    combinedJSON += JSON.stringify(data) + "]";
                    successcb(combinedJSON); // This is the success call back
                }, function (data) {
                    console.log(data);
                });
            }, function (data) {
                console.log(data);
            });
        }, function (data) {
            console.log(data);
        });
    }, function (data) {
        console.log(data);
    });
}

My callback function just spits out the data

// Controller.js
eventData.getAllEvents(function successcb(events) {
    $scope.foo = events;
});

Is there a better way to handle these types of situations?

Never, and I mean NEVER, manually construct JSON. That's just asking for trouble. Construct the object then use JSON.stringify. FYI, arrays are valid JSON so you can construct an array and pass it to JSON.stringify.

Next, it doesn't seem like your calls  depend on each other. You can just launch them all in parallel and use Promise.all (or Angular's equivalent API) listen to know when all of them have resolved. The resolved value is an array of values in the same order as the promises. That guarantees that the first call's result is the first item in the resolved value.

Lastly, since you're already using promises, just return a promise from your function. Using callbacks in the presence of a promise defeats the entire purpose of promises.

One more thing, just pointing out that you are returning JSON, a string, from getAllEvents and not an object. Not sure why you're doing that exactly, but if you aim to get the object for manipulation, you can skip that part.

const resource = $resource('/app/data/event/:id/:ext', {id:'@id',ext:'@ext'}, {"getAll": {method: "GET", isArray: false}})

getAllEvents(){
  const promise1 = resource.get({ id: 1, ext: '.json' }).$promise
  const promise2 = resource.get({ id: 2, ext: '.json' }).$promise
  const promise3 = resource.get({ id: 3, ext: '.json' }).$promise
  const promise4 = resource.get({ id: 4, ext: '.json' }).$promise

  return $q.all([ promise1, promise2, promise3, promise4 ])
}

// Usage
someService.getAllEvents().then(values => {
  // values[0] = your first file
  // values[1] = your second file
  // values[2] = your third file
  // values[3] = your fourth file
});