texts: Generating a day event calendar based on an array of objects

texts:
I wanted to get some eyes on some code that I wrote, and see if anyone can help improve what I did. Just looking for some constructive feedback to help make my code more performant, and more elegant.

From a high level my code needs to accomplish the following:

  Create a function that takes an array of objects that each represent an event. Each object in the array has a start and end time represented in minutes. The start and end times are represented as minutes after 9am. For example {start:30, end: 60} represents an event that starts at 9:30am and ends at 10am. The function takes the objects, and plots them as events on a vertical timeline. Events that have crossover will split the container in half, while events that don’t crossover will take the whole container width.

Here is the JS that I wrote to accomplish the above task:

//sample data - array of objects that represent events
var myArray = [
{start: 30, end: 130},
{start: 140, end: 147},
{start: 145, end: 155},
{start: 150, end: 175},
{start: 200, end: 250},
];

var myFunc = function(a) {
  //sort the input array from earliest start time to latest. Items with identical start times will compare end times - the longer duration item resolves with lower index. Assumes no exact duplicate items.
  var sortedDates = a.sort(function(a,b) {
    var caseOne= (a.end>b.end) ? -1 : 1,
        caseTwo= a.start - b.start;

    return (a.start===b.start) ? caseOne : caseTwo;
  });

  for(var i=0; i<sortedDates.length; i++) {
    var currentItem = sortedDates[i],
        itemDuration = currentItem.end-currentItem.start,
        itemTop = currentItem.start,
        prevItem = sortedDates[i-1],
        nextItem = sortedDates[i+1],
        newDiv = document.createElement('div');

    //set a default direction to each item
    currentItem.direction = 'left';

    //determine which items overlap and set a property to indicate
    if(nextItem !== undefined && (currentItem.end - nextItem.start > 0)) {
      currentItem.overlap = true;
      nextItem.overlap = true;
    }

    //ensure items flow in UI by staggering overlapping items
    if(prevItem !== undefined && (prevItem.direction === 'left')) {
      currentItem.direction = 'right';
    }

    //set class names on new DOM element based on overlap
    if(currentItem.overlap === true) {
      if(currentItem.hasOwnProperty('direction')) {
        newDiv.setAttribute('class', 'split '+currentItem.direction);
      }
      else {
        newDiv.setAttribute('class', 'split');
      }
    }

    //set the size and position based on computed duration and start time
    newDiv.setAttribute('style', 'height:'+itemDuration+'px; top:'+itemTop+'px');

    //insert new element into DOM
    document.getElementById('stuff').appendChild(newDiv);
  }
};

Here is a rough working example.


texts: A running gene crossover function for a Genetic Algorithm

texts:
I'm writing a Genetic Algorithm, and need to write a function that crosses two gene sequences. Basically, I want it to work like this:

(running-cross [1 2 3 4 5 6 7 8 9] ; Gene sequence 1
               [11 22 33 44 55 66 77 88 99] ; Gene sequence 2
               [2 5]) ; The "cross points"
=> [1 2 33 44 55 6 7 8 9]

Note how it crosses over to the second sequence at index 2, and back to the first sequence at index 5. See the related PPCG challenge for more examples.

I have two main concerns with my implementation:

It's ugly. The reducing function is atrocious, but I don't know what can be improved. The short names don't help, but longer names would add significant bloat which wouldn't be great either.
It's inefficient. It requires iterating the entire gene sequence, even if there are few, or even no cross over points. Of course I could add a special case and check if the points are empty first, but that still doesn't help much. Say there's a single cross over point at the end of the genes. It will require a full iteration regardless. I can't tell if O(n) is the best I'm going to get, but I'd prefer n be the number of cross-over points, not the number of genes per sequence.

(defn running-cross [genes other-genes cross-points]
  (let [cp-set (set cross-points)]
    (->> (map vector (range) genes other-genes)

      (reduce (fn [[g1? acc] [i g1 g2]]
                (let [g1?' (if (cp-set i) (not g1?) g1?)]
                  [g1?' (conj acc (if g1?' g1 g2))]))
              [true []])

      (second))))


texts:
I am writing a method to create a folder tree. I am getting the data from a database and creating the list of nodes. Is there a way to get the method to execute quicker? Perhaps using parallel task library?

Each node looks like this:

public class Node : INode
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string DisplayText { get; set; }
    public bool DefaultState { get; set; }
    public List<Node> ChildItems { get; set; }
}

The fastest implementation I have been able to come up with has been just two for loops using recursion:

/// <summary>
/// For loop incrementing: 00:00:28.2218157
/// </summary>
/// <param name="folderRepo"></param>
/// <param name="folders"></param>
private void GetChildFoldersIncrement(IRepository<Folder> folderRepo, List<Node> folders)
{
    for (var i = 0; i < folders.Count; i++)
    {
        var folderId = folders[i].Id;
        var childFolders = folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToList();
        if (childFolders.Count == 0) continue;
        for (var j = 0; j < childFolders.Count; j++)
        {
            var node = new Node
            {
                Id = childFolders[j].FolderID,
                ParentId = childFolders[j].ParentFolderID,
                DisplayText = childFolders[j].FolderName,
                DefaultState = false,
                ChildItems = new List<Node>()
            };

            if (folders[i].ChildItems == null) folders[i].ChildItems = new List<Node>();
            folders[i].ChildItems.Add(node);
        }

        if (folders[i].ChildItems.Count > 0) GetChildFoldersIncrement(folderRepo, folders[i].ChildItems);
    }
}

I've attempted to optimize the loops by decrementing them but it was actually slightly slower:

/// <summary>
/// For loop decrement: 00:00:28.3496396
/// </summary>
/// <param name="folderRepo"></param>
/// <param name="folders"></param>
private void GetChildFoldersDecrement(IRepository<Folder> folderRepo, List<Node> folders)
{
    if (folders == null) return;
    var maxFolders = folders.Count();
    for (var i = maxFolders - 1; i >= 0; --i)
    {
        var folderId = folders[i].Id;
        var childFolders = folderRepo.FindByExp(f => f.ParentFolderID == folderId).ToList();
        var maxChildFolders = childFolders.Count();
        for (var j = maxChildFolders - 1; j >= 0; --j)
        {
            var node = new Node
            {
                Id = childFolders[j].FolderID,
                ParentId = childFolders[j].ParentFolderID,
                DisplayText = childFolders[j].FolderName,
                DefaultState = false,
                ChildItems = new List<Node>()
            };

            if (folders[i].ChildItems == null) folders[i].ChildItems = new List<Node>();
            folders[i].ChildItems.Add(node);
        }

        GetChildFoldersDecrement(folderRepo, folders[i].ChildItems);
    }
}


texts:
I have devised a novel sorting algorithm, named Oracle Sort, which I believe is far superior to all currently known sorting algorithms (under certain assumptions). It utilizes an oracle to achieve a constant time complexity with regard to both the length of the input sequence and the number of distinct elements in the input sequence.

However, it seems that current computing is not yet ready for such an advanced algorithm, and therefore certain compromises had to be made and the algorithm had to be altered. As a result of these alterations, the performance of the provided algorithm has been much degraded. Therefore, I ask for any advice regarding the improvement of the time complexity of the algorithm as it stands.

Given below is an example implementation of the algorithm in Python 3.

from itertools import count, product

def oraclesort(input_seq):
  """
  Find a sequence (via enumeration), with is equal the sorted input sequence.

  Under ideal circumstances the enumeration would be done in parallel for all
  sequences of length up to at least the length of the input, and enumerating
  each of these sequences would take constant time. However, currently we are
  not able to achieve such results, so we have to resort to a less efficient
  sequential enumeration.

  The equality of enumerated candidate sequence and the sorted input sequence
  is determined by an oracle (the oracle_equals_sorted() function), which can
  tell in (assumed) constant time, whether the given candidate is equal to the
  sorted input. This, combined with the constant time needed to generate the
  candidates, gives us a total time complexity of O(1); the best known time
  complexity of an arbitrary-input sorting algorithm.
  """
  for i in count():
    for candidate_seq in product(input_seq, repeat=i):
      if oracle_equals_sorted(candidate_seq, input_seq):
        return candidate_seq

def oracle_equals_sorted(candidate_seq, input_seq):
  """
  Oracle which checks whether candidate_seq equals the sorted input_seq.

  The oracle should work in constant time (or ideally, in no-time), but we are
  limited to deterministic Turing Machines, and therefore, we are limited
  to certain implementations of the oracle, and these implementations happen
  to have non-optimal (eg. nonzero) time complexity.

  Despite being suboptimal, this implementation of the oracle is very elegant
  in that it internally uses the oracle sort to determine whether the given
  candidate sequence is equal to the sorted input sequence, hence completing
  a beautiful cycle of mutual recursion.
  """
  candidate_lst = list(candidate_seq)
  input_lst = list(input_seq)

  if not candidate_lst and not input_lst:
    return True

  if not candidate_lst or not input_lst:
    return False

  _, min_idx = min((val, idx) for idx, val in enumerate(input_lst))
  input_lst_without_min = input_lst[:min_idx] + input_lst[min_idx+1:]

  return candidate_lst[0] == input_lst[min_idx] and \
         candidate_lst[1:] == list(oraclesort(input_lst_without_min))


texts: Linq group by with multiple where, sum clauses in select causes a timeout

texts:
I have  linq query that extracts a summary of my sales quantities item group wise. This query causes an sql timeout. From the what i have found out, timeout indicates that my query is poorly designed and needs to be optimized.

Below is the linq query:

 (from inv in Dbcontext.tblSalesInvoices
    join det in Dbcontext.tblSalesInvoiceDetails on inv.SalesInvoiceId equals det.SalesInvoiceId
    join item in Dbcontext.tblItems on det.ItemId equals item.ItemId
    join itemGroup in Dbcontext.tblItemGroups on item.ItemGroupId equals itemGroup.ItemGroupId
    join loc in Dbcontext.tblLocations on inv.LocationId equals loc.LocationId
    where inv.InvoiceDate >= FeedSearchCriteria.FromDate && inv.InvoiceDate <= FeedSearchCriteria.ToDate
    && inv.InvoiceStatusId != Constants.REVERSED_INVOICE
    group new { det.Quantity, itemGroup.ItemGroupCode, item.Weight, item.ItemCode, det.LineTotal } by loc.LocationName into g
    select new LocationCount()
    {
    LocationName = g.Key,
    FeedBagCount = (int?)g.Where(x => x.ItemGroupCode == "FEED").Sum(x => x.Quantity),
    SupremeKg = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.Weight * x.Quantity),
    SupremeValue = (decimal?)g.Where(x => x.ItemGroupCode == "ABATTOIR").Sum(x => x.LineTotal),
    DocCount = (int?)g.Where(x => x.ItemCode == "DOC").Sum(x => x.Quantity)
    }).OrderBy(x=>x.LocationName).ToListAsync();

I think my issue arises because of the where/sum clause in select. How can i re-write below query in more optimized manner.

Edit

Time out occurs when a date range is more than or equal to 1 month of transactions.


texts: Getting columns from lines of uneven length

texts:
I am given pasted data from a table, so I have spaces as delimiters and in some of the fields I don't care about. I want the first field and the last three fields, and got them using this code:

testdata = """8/5/15 stuffidontneed custid locid 55.00
8/9/15 stuff i really dont need with extra spaces custid otherlocid 79.00"""
rows = testdata.split('\n')
tupls = [row.split(' ') for row in rows]
dates = [tupl[0] for tupl in tupls]
custids, locids, amounts = ([tupl[i] for tupl in tupls] for i in range (-3, 0))
print(dates, custids, locids, amounts)
# ['8/5/15', '8/9/15'] ['custid', 'custid'] ['locid', 'otherlocid'] ['55.00', '79.00']

I just thought there might be a more elegant way to do things, maybe capturing the data in the middle as a single field.

Edit: I have attempted to add delimiters using re.finditer, but I can't replace the matches easily.


texts: Simplifying dictionary of constant values

texts:
I have the following code:

    public string GetRefStat(string pk) {
        return RefStat[pk.Substring(2, 2)];
    }
    private readonly Dictionary<String, int> RefStat =
    new Dictionary<string, int>
    {
        {"00", REF.MenuType,       } // Menu
        {"01", REF.ReferenceStatus,} // Article
        {"02", REF.ReferenceStatus,} // Favorites List
        {"03", REF.ReferenceStatus,} // Content Block
        {"06", REF.ReferenceStatus } // Topic
    };

GetRefStat and the dictionary are always used together.

Is there a way I could simplify and combine these? I was wondering if I could put the information in a static class and then have a get method that returned the information I needed.


texts:
I created a "2-player" rock-paper-scissors game in Python mainly using if statements and a single while loop. The program is really simple, but I was wondering if using switch statements or perhaps another format would make it less cluttered/quicker/etc.
again = 'y'

while (again == 'y'):

    p1 = input("Player 1 --> Rock, Paper, or Scissors? ")
    p1 = p1.lower()

    print()

    p2 = input("Player 2 --> Rock, Paper, or Scissors? ")
    p2 = p2.lower()

    print()

    if (p1 == "rock"):
        if (p2 == "rock"):
            print("The game is a draw")
        elif (p2 == "paper"):
            print("Player 2 wins!")
        elif (p2 == "scissors"):
            print("Player 1 wins!")
    elif (p1 == "paper"):
        if (p2 == "rock"):
            print("Player 1 wins!")
        elif (p2 == "paper"):
            print("The game is a draw")
        elif (p2 == "scissors"):
            print("Player 2 wins!")
    elif (p1 == "scissors"):
        if (p2 == "rock"):
            print("Player 2 wins!")
        elif (p2 == "paper"):
            print("Player 1 wins!")
        elif (p2 == "scissors"):
            print("The game is a draw")
    else:
        print("Invalid input, try again")

    again = input("Type y to play again, anything else to stop: ")

    print()


texts:
I have a Queue class that is basically a single linked list. It has 2 remove methods. What would be the cleanest way to avoid duplication of the code? Only the comparisons in methods are different.

int Queue::remove(const string& substring)
{
    // Loop through the queue list
    size_t found;
    found = current_job->description.find(substring)
    if (found != string::npos) {
        // Remove job.
    }
    // Return the amount of removed jobs.
}

int Queue::remove(int priority)
{
    // Loop through the queue list
    if (current_job->priority == priority) {
        // Remove job.
    }
    // Return the amount of removed jobs.
}

I thought a template solution as answered here, but in this case, the comparison function has different arguments.


texts:
From Code Wars:

  This kata is part of a series on the Morse code. After you solve this kata, you may move to the next one.

  In this kata you have to write a simple Morse code decoder. While the Morse code is now mostly superceded by voice and digital data communication channels, it still has its use in some applications around the world.
  The Morse code encodes every character as a sequence of "dots" and "dashes". For example, the letter A is coded as ·−, letter Q is coded as −−·−, and digit 1 is coded as ·−−−−. The Morse code is case-insensitive, traditionally capital letters are used. When the message is written in Morse code, a single space is used to separate the character codes and 3 spaces are used to separate words. For example, the message HEY JUDE in Morse code is ···· · −·−− ·−−− ··− −·· ·.

  NOTE: Extra spaces before or after the code have no meaning and should be ignored.

  In addition to letters, digits and some punctuation, there are some special service codes, the most notorious of those is the international distress signal SOS (that was first issued by Titanic), that is coded as ···−−−···. These special codes are treated as single special characters, and usually are transmitted as separate words.

  Your task is to implement a function that would take the morse code as input and return a decoded human-readable string.

  For example:

decodeMorse('.... . -.--   .--- ..- -.. .')
#should return "HEY JUDE"

  NOTE: For coding purposes you have to use ASCII characters . and -, not Unicode characters.

  The Morse code table is preloaded for you as a dictionary, feel free to use it:

  Coffeescript/C++/Go/JavaScript/PHP/Python/Ruby/TypeScript: MORSE_CODE['.--']
  C#: MorseCode.Get(".--") (returns string)
  Elixir: morse_codes variable
  Haskell: morseCodes ! ".--" (Codes are in a Map String String)
  Java: MorseCode.get(".--")
  Kotlin: MorseCode[".--"] ?: "" or MorseCode.getOrDefault(".--", "")
  Rust: self.morse_code
  All the test strings would contain valid Morse code, so you may skip checking for errors and exceptions. In C#, tests will fail if the solution code throws an exception, please keep that in mind. This is mostly because otherwise the engine would simply ignore the tests, resulting in a "valid" solution.

  Good luck!

  After you complete this kata, you may try yourself at Decode the Morse code, advanced.

I wrote a program that works, but it was essentially done with ad hoc patches to cover the edge cases/exceptions the program initially didn't cover. I'd appreciate a critique of my code, such as best practices and the program logic itself.

# "Code Wars: Decode the Morse Code"

def decodeMorse(morse_code):
    clear_text = ''
    char = ''
    index = 0
    length = len(morse_code)
    delim1 = " "    # Next character delimiter.
    delim2 = "   "  # Next word delimiter.
    while index < (length):
        if morse_code[index] != delim1:
            # Build the character to be added to the clear text.
            char += morse_code[index]
        else:
            # When the delimiter is encountered.
            if char != '':
                # To cover the program encountering erroneous whitespace.
                clear_text += MORSE_CODE[char]
                    # Add said character to clear text
                char = ''
                    # Reset "char".
                if index < (length-2):
                    # If it is possible to encounter a space.
                    if morse_code[index:(index+3)] == delim2:
                        # When a space is encountered.
                        clear_text += " "
                        index += 2
                        if index == length-1:
                            # If the last character in the code is a space, assign a control value to "char"
                            char = ""
        index += 1

    if char != "":
        # If the last character isn't a space.
        clear_text += MORSE_CODE[char]
            # Add the final character to the clear text.
    return clear_text


texts: Does this ugly code fit into a design pattern?

texts:
I'm trying to figure out a pattern to best accommodate this pretty ugly code:

var userDiscounts = _discountRepository.GetUserDiscountsForUsersWithDiscounts(new List<int> { buyerUserId, sellerUserId }).ToList();

// Buyer.
var buyerHasFreeCommission = false;
var buyerDiscounts = userDiscounts.Where(ud => ud.UserId == buyerUserId);
foreach(var userDiscount in buyerDiscounts)
{
    switch (userDiscount.Discount.Type)
    {
        case DiscountTypes.SingleFreeCommisionPerUser:
            buyerHasFreeCommission = true;
            break;
    }
}

var sellerHasFreeCommission = false;
var sellerDiscounts = userDiscounts.Where(ud => ud.UserId == sellerUserId);
foreach(var userDiscount in sellerDiscounts)
{
    switch (userDiscount.Discount.Type)
    {
        case DiscountTypes.SingleFreeCommisionPerUser:
            sellerHasFreeCommission = true;
            break;
    }
}

if (!sellerHasFreeCommission)
{
    var sellerCommisionChargeTransaction = new Transaction
    {
        AccountId = sellerAccountId,
        Type = TransactionTypes.Fee,
        Amount = -2
    };

    var sellerTransferFeeTransaction = new Transaction
    {
        AccountId = 5020,
        Type = TransactionTypes.Fee,
        Amount = 2
    };

    _accountRepository.AddTransaction(sellerCommisionChargeTransaction);
    _accountRepository.AddTransaction(sellerTransferFeeTransaction);
}

if (!buyerHasFreeCommission)
{
    var buyerCommisionChargeTransaction  = new Transaction
    {
        AccountId = buyerAccountId,
        Type = TransactionTypes.Fee,
        Amount = -2
    };

    var buyerTransferFeeTransaction = new Transaction
    {
        AccountId = 5020,
        Type = TransactionTypes.Fee,
        Amount = 2
    };

    _accountRepository.AddTransaction(buyerCommisionChargeTransaction);
    _accountRepository.AddTransaction(buyerTransferFeeTransaction);
}

if (!buyerHasFreeCommission || !sellerHasFreeCommission)
    _accountRepository.SaveChanges();

This won't be very maintainable when I need to add a new discount... I was thinking maybe somehow I could use the strategy pattern?


texts:
How could the following function (the for loop) be transformed to a lambda expression or refactored to be cleaner:

public static Collection<AccessRuleTemplate> getCaRules(String roleName, Collection<Integer> currentcas) {
    Collection<AccessRuleTemplate> result = new ArrayList<AccessRuleTemplate>();
    boolean allcafound = false;
    List<AccessRuleTemplate> carules = new ArrayList<AccessRuleTemplate>();
    for (Integer caId : currentcas) {
        if (caId.equals(Integer.valueOf(BasicAccessRuleSet.CA_ALL))) {
            allcafound = true;
            break;
        }
        carules.add(new AccessRuleTemplate(StandardRules.CAACCESS.resource() + caId.toString(), AccessRuleState.RULE_ACCEPT, false));
    }
    if (allcafound) {
        carules.clear();
        carules.add(new AccessRuleTemplate(StandardRules.CAACCESSBASE.resource(), AccessRuleState.RULE_ACCEPT, true));
    }
    result.addAll(carules);
    return result;

}

In particular i don't like the use of boolean flag and would like to avoid it. The idea with the function is to traverse list of ids and if a particular id found it breaks the loop and sets a flag to true and then checks the flag later and clears idlist and only adds something to list. Otherwise all other ids are added to list.


texts:
The following is a problem I found on this wiki. What can I do to optimize my algorithm, and make this code more C++11?

  Write a program to discover the answer to this puzzle:"Let's say men
  and women are paid equally (from the same uniform distribution). If
  women date randomly and marry the first man with a higher salary, what
  fraction of the population will get married?"

#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
//#include <cstdlib>

using std::cin;
using std::cout;
using std::endl;
using std::random_shuffle;

const int MIN = 1;
const int MAX = 1000000;
const int MALES = 100;
const int FEMALES = 100;

class Female{
public:
    Female(){isMarried = false;}

    bool isMarried;
    int salary;
};

class Male{
public:
    Male(){isMarried = false;}

    bool isMarried;
    int salary;
};

void marriageTest(std::vector<double> &results){

    double count = 0;
    bool done = false;

    Male male[MALES];
    Female female[FEMALES];

    //Fill array of Females and Males with random salaries ranging from 1 to 10
    for(int i=0; i<100; i++){
        int output = MIN + (rand() % (int)(MAX - MIN + 1));
        i[male].salary = output; //( ͡° ͜ʖ ͡°)
    }
    for(int i=0; i<100; i++){
        int output = MIN + (rand() % (int)(MAX - MIN + 1));
        i[female].salary = output;
    }

    //Start dating
    //Keep dating until the maximum salary of males is lower than minimum salary of females

    do{
        random_shuffle(&male[0], &male[MALES]);               //Shuffle array of males
        random_shuffle(&female[0], &female[FEMALES]);           //Shuffle array of females

        for(int i=0; i<100; i++){                              //Compare a female and male from both arrays
            if(female[i].salary < male[i].salary)
                if(!female[i].isMarried && !male[i].isMarried){
                    count++;
                    female[i].isMarried = true;
                    male[i].isMarried = true;
                }
        }

        //Check for Maximum Male Salary
        int maxMen = MIN;
        for(int i=0; i<100; i++){
            if(male[i].salary > maxMen && !male[i].isMarried)
                maxMen = male[i].salary;
        }

        //Check for Minimum Female Salary
        int minWomen = MAX;
        for(int i=0; i<100; i++){
            if(female[i].salary < minWomen && !female[i].isMarried)
                minWomen = female[i].salary;
        }

        if(maxMen <= minWomen)
            done = true;

    }while(!done);

    results.push_back(count/100);
}

void runTrials(int num_trials, std::vector<double> &results){

    for(int i=0; i<num_trials;i++)
        marriageTest(results);
}

double Percentage(std::vector<double> &results){

    double final = 0;
    int trials = 0;
    for(auto i : results){
        final += i;
        ++trials;
    }

    return final/trials;
}

int main()
{
    int num_trials;
    std::vector<double> results;

    srand(time(NULL));

    cout << "Number of trials: ";
    cin >> num_trials;

    runTrials(num_trials,results);

    double final = Percentage(results);

    cout << "Percentage: " << final << endl;

    return 0;
}


texts: Check all permutations of generic type parameters

texts:
I have a function that takes an object ("token") and three additional parameters of different types ("obj1", "obj2", "obj3").  The object "token" has an 'IsSatisfied' method that may take none, 1, 2, or 3 paremeters of types matching "obj1", "obj2", "obj3".  Versions of "token" that have 1 or more parameters are generic.  Right now, I have an inelegant solution of pattern matching the "token" against every permutation of 0, 1, 2, or 3 parameters, as shown in the code sample below.

Is there a more elegant way to write this?  It works as is, but I might go to 4 parameters ("obj1", "obj2", "obj3", "obj4") in which case the list of permutations gets really long. Perhaps a solution that uses 'params' for an indefinite number of parameters.  I would also be happy to drop the generic parameters  on the Tokenizer class.

public class Tokenizer <T1, T2, T3>
{

    public void Test(IBoolToken token, T1 obj1, T2 obj2, T3 obj3)
    {
        if (token is IBooleanTokenable tokenable0P) tokenable0P.IsSatisfied();
        else if (token is IBooleanTokenable<T1> tokenable1P1) tokenable1P1.IsSatisfied(obj1);
        else if (token is IBooleanTokenable<T2> tokenable1P2) tokenable1P2.IsSatisfied(obj2);
        else if (token is IBooleanTokenable<T3> tokenable1P3) tokenable1P3.IsSatisfied(obj3);
        else if (token is IBooleanTokenable<T1, T2> tokenable2P1) tokenable2P1.IsSatisfied(obj1, obj2);
        else if (token is IBooleanTokenable<T1, T3> tokenable2P2) tokenable2P2.IsSatisfied(obj1, obj3);
        else if (token is IBooleanTokenable<T2, T3> tokenable2P3) tokenable2P3.IsSatisfied(obj2, obj3);
        else if (token is IBooleanTokenable<T2, T1> tokenable2P4) tokenable2P4.IsSatisfied(obj2, obj1);
        else if (token is IBooleanTokenable<T3, T1> tokenable2P5) tokenable2P5.IsSatisfied(obj3, obj1);
        else if (token is IBooleanTokenable<T3, T2> tokenable2P6) tokenable2P6.IsSatisfied(obj3, obj2);
        else if (token is IBooleanTokenable<T1, T2, T3> tokenable3P1) tokenable3P1.IsSatisfied(obj1, obj2, obj3);
        else if (token is IBooleanTokenable<T1, T3, T2> tokenable3P2) tokenable3P2.IsSatisfied(obj1, obj3, obj2);
        else if (token is IBooleanTokenable<T2, T1, T3> tokenable3P3) tokenable3P3.IsSatisfied(obj2, obj1, obj3);
        else if (token is IBooleanTokenable<T2, T3, T1> tokenable3P4) tokenable3P4.IsSatisfied(obj2, obj3, obj1);
        else if (token is IBooleanTokenable<T3, T1, T2> tokenable3P5) tokenable3P5.IsSatisfied(obj3, obj1, obj2);
        else if (token is IBooleanTokenable<T3, T2, T1> tokenable3P6) tokenable3P6.IsSatisfied(obj3, obj2, obj1);
    }

}
```


texts: Caling AJAX Method for multiple hidden ids aspx

texts:
I am calling a ajax method for a number of hidden client ids on an aspx page.  The ajax method returns some html to a div provided.

So the code looks like below:

<asp:HiddenField runat="server" ID="hdnSomeProperty" Value="False"/>
<asp:HiddenField runat="server" ID="hfMyIndex" Value="0" />
<asp:HiddenField runat="server" ID="hfCustId" />
<asp:HiddenField runat="server" ID="hfCarId" />
<asp:HiddenField runat="server" ID="hfVanId" />
<asp:HiddenField runat="server" ID="hfTruckId" />
<asp:HiddenField runat="server" ID="hfMotorCycleId" />

var carNode = "<%=VechileNodeTypeEnum.Car.ToString() %>";
var selectedCarIds = $('#<%=hfCarId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: carNode, selectedIds: selectedCarIds }, '#carDiv');

var vanNode = "<%=VechileNodeTypeEnum.Van.ToString() %>";
var selectedVanIds = $('#<%=hfVanId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: vanNode, selectedIds: selectedVanIds }, '#vanDiv');

var truckNode = "<%=VechileNodeTypeEnum.Truck.ToString() %>";
var selectedTruckIds = $('#<%=hfTruckId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: truckNode, selectedIds: selectedTruckIds }, '#truckDiv');

var motorcycleNode = "<%=VechileNodeTypeEnum.MotorCycle.ToString() %>";
var selectedMotorcycleIds = $('#<%=hfMotorCycleId.ClientID %>').val();
ajaxMethod('/MyPage/MyMethod', { custId: custId, vechileNodeType: motorcycleNode, selectedIds: selectedMotorcycleIds }, '#motorcycleDiv');

Everything works as expected however I dont like the pattern of repeating the code 4 times with just a few of the proerties changed - I was think I could perhaps use a for loop and loop round 4 times - not sure how I would pass the changed properties dynamically though?


texts:
Learn You a Haskell shows the insert function.

  insert takes an element and a list of elements that can be sorted and
  inserts it into the last position where it's still less than or equal
  to the next element. In other words, insert will start at the
  beginning of the list and then keep going until it finds an element
  that's equal to or greater than the element that we're inserting and
  it will insert it just before the element.

ghci> insert 4 [3,5,1,2,8,2]
[3,4,5,1,2,8,2]
ghci> insert 4 [1,3,4,4,1]
[1,3,4,4,4,1]

How's my implementation?

insert' :: (Ord a) => a -> [a] -> [a]
insert' x []     = [x]
insert' x yys@(y:ys) = if x <= y then x : yys else y : insert' x ys


texts:
Suppose the following example unit test for an ASP.NET MVC controller:

[Test]
public void Delete_Will_Redirect_To_Index_1()
{
    bookRepository.Add(someBook);
    var result = booksController.Delete(someBook.Id) as RedirectToRouteResult;
    Assert.That(result, Is.Not.Null);
    Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}

Resharper unwittingly complains on the fourth line of code that result.RouteValues may cause a possible NullReferenceException. I hate those squiggly lines, so I figured I could just as easily write it as follows:

[Test]
public void Delete_Will_Redirect_To_Index_2()
{
    bookRepository.Add(someBook);
    var result = (RedirectToRouteResult)booksController.Delete(someBook.Id);
    Assert.That(result.RouteValues["Action"], Is.EqualTo("Index"));
}

This has some advantages:

One LoC less;
More to the point;

It also has one main disadvantage:

Code will fail with a cast exception if the result is of unexpected type. This seems(?) less clear than a failed assert.

Some other alternatives I've considered include :

[Test]
public void Delete_Will_Redirect_To_Index_3()
{
    bookRepository.Add(someBook);
    var result = booksController.Delete(someBook.Id);
    Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
    var redirectResult = (RedirectToRouteResult)result;
    Assert.That(redirectResult.RouteValues["Action"], Is.EqualTo("Index"));
}

This is five lines of code, but has two very clear asserts.

I've even considered this version:

[Test]
public void Delete_Will_Redirect()
{
    bookRepository.Add(someBook);
    var result = booksController.Delete(someBook.Id);
    Assert.That(result, Is.InstanceOf<RedirectToRouteResult>());
}

[Test]
public void Delete_Will_Redirect_To_Index_4()
{
    bookRepository.Add(someBook);
    var redirectResult = (RedirectToRouteResult)booksController.Delete(someBook.Id);
    Assert.That(redirectResult.RouteValues["Action"], Is.EqualTo("Index"));
}

All in all I see the following points in play to judge the various forms:

number of lines of code;
readability of the code;
clarity of failing-unit-test feedback;
how pragmatic and painless it is to write a test;

Did I miss any important points? Did I miss a scenario that has the best of all points? What can I do to get the best of all scenarios?

PS. I'd prefer a framework-agnostic answer, but if it matters, I'm using C# NUnit tests for an ASP.NET MVC5 controller.


texts: Extracting meta data from nupkg file with F# looks like C# Linq

texts:
The code snippet below examines a nuget package file (zip file with meta) and extracts all file names referenced inside. The final result should be a Set<string> with all file names. My problem is that the code looks like a nested Linq query in c# and the usage of Seq.iter blocks me to build the Set collection. Can you please give me some kind of advice how to improve the F# code? Am I missing some fundamental concept?

getDependencies nugetPackagesFile
                |> Seq.iter(fun (name,ver) ->
                    name + "." + ver
                    |> fun pkgName ->
                        !! ("./src/packages/*/" + pkgName + ".nupkg")
                        |> Seq.iter(fun pkg ->
                            global.NuGet.ZipPackage(pkg).GetFiles()
                            |> Seq.iter(fun file -> filename file.Path |> printfn "%s")))

Current output:

Elders.Cronus.dll
Elders.Cronus.pdb
Elders.Cronus.DomainModeling.dll
Elders.Cronus.DomainModeling.pdb
log4net.dll
log4net.xml
log4net.dll
log4net.xml
log4net.dll
log4net.xml
log4net.dll
log4net.xml
log4net.dll
log4net.xml
log4net.dll
log4net.xml
log4net.dll
log4net.xml
Elders.Multithreading.Scheduler.dll
Elders.Multithreading.Scheduler.pdb
protobuf-net.dll
protobuf-net.pdb
protobuf-net.xml
protobuf-net.dll
protobuf-net.pdb
protobuf-net.xml
protobuf-net.dll
protobuf-net.pdb
protobuf-net.xml


texts:
I have a dictionary self.indexList = {} filled with 3-item-lists values = [lineId, nominalLineId, vertex] for each dictionary key (its a supplement to a QgsSpatialIndex in PyQGIS, btw).

I need to reverse-search this dictionary for matching tuples of lineId and vertex. This function is the dealbreaker in a larger PyQGIS algorithm; called multiple times (almost 40.000 with a large test dataset) and causing 2/3 of total running time.

def get_idx_from_values(instance, lineID, vertex):
    """Searches the indexList for a lineID and a vertex number (= unique line segment).
    Returns dic index (=fid)."""
    items = instance.indexList.items()
    for idx, values in items:
        if values[0] == lineID and values[2] == vertex:
            return idx
    print("No index entry found for line " + str(lineID) + ", Vertex " + str(vertex))
    return None

I already found Search in a big dictionary Python where a second dictionary with a reversion of key and value is suggested.

I consider this, but I'm open for other suggestions how to speed up the code above, as my case - matching two values with a certain key - adds complexity to the simple key/value reversion.


texts:
I just started to learn C++ and I decided to make a Rock Paper Scissors game. It works fine but I would like to know how can I improve it further.
In particular I couldn't find an efficient way to implement a play again feature. Thanks in advance.

#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>

using namespace std;

int main() {

srand(static_cast<unsigned int>(time(NULL)));

string userChoice;
int computerNumber = rand() % 3 + 1;
string computerChoice;
string userName;

if (computerNumber == 1) {
    computerChoice = "rock";
} else if (computerNumber == 2) {
    computerChoice = "paper";
} else {
    computerChoice = "scissors";
}

std::cout << "Welcome to rock, paper, scissors! What is your name?" << endl;
getline(cin, userName);
std::cout << "Hello " << userName << "! What do you choose?" << endl;
getline (cin,userChoice);

for (int i=0;i<userChoice.length();i++){
    userChoice[i]=tolower(userChoice[i]);
}

while (userChoice != "rock" && userChoice != "paper" && userChoice != "scissors") {
    std::cout << "Sorry! Didn't get that. Please enter again." << endl;
    getline(cin, userChoice);
    for (int i=0;i<userChoice.length();i++){
        userChoice[i]=tolower(userChoice[i]);
    }
}

std::cout << "Press enter to continue..." << endl;
std::cin.ignore();

if(computerChoice == "rock" && userChoice == "rock") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "rock" && userChoice == "scissors") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else if (computerChoice == "paper" && userChoice == "paper") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "paper" && userChoice == "rock") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else if (computerChoice == "scissors" && userChoice == "scissors") {
    std::cout << "It was a tie!" << endl;
} else if (computerChoice == "scissors" && userChoice == "paper") {
    std::cout << "The computer won! Better luck next time!" << endl;
} else {
    std::cout << "Congrats! You won!" << endl;
}

return 0;
}


texts: Implementing binary-heap in x86-64 assembly

texts:
I'm trying to implement some of the simplest classical data-structures in x86-64 assembly on linux.

PRIMARY GOAL: Reduce memory consumption and increase performance (maybe using x86-64 architecture specific tricks).

Also any advises about style and design are highly appreciated! I'm also trying to adhere to x86-64 Linux ABI. Here is what I currently have:

binary-heap.asm:

SYS_mmap equ 0x09
SYS_munmap equ 0x0B

ELEMENT_SIZE equ 0x08
PAGE_SIZE equ 0x8000

section .text
    ;rdi = size
    global _create_heap
    ;rdi = pointer to the binary heap, rsi = element to insert
    global _add
    ;rdi = pointer to the binary heap, rsi = element number to retrieve
    global _get
    ;rdi = pointer to the binary heap
    global _clear
    ;rdi = pointer to the bionary heap
    global _size
    ;rdi = pointer to the binary heap
    global _delete

_create_heap:
    mov rcx, ELEMENT_SIZE
    mov r10, PAGE_SIZE

    ;Checking if the memory required to hold the elements of tree is enough
    mov rax, rdi
    add rax, 2 ; we need to store elements number and current index which are 8 bytes long
    mul rcx
    jo too_many_elemenents

    xor rdx, rdx ;clearing rdx so unsigned division is not affected
    div r10

    mov rbp, rdi ;ommiting frame pointer and storing elements number as a temporary
    test rdx, rdx
    ;we need to increment rax only in case rdx is not equal to zero
    jz allocate_memory
    inc rax

    allocate_memory:
        mul r10
        ;calling mmap with rax len
        mov rsi, rax
        mov rax, SYS_mmap
        mov rdi, 0x00 ; NULL pointer
        mov rdx, 0x03 ; PROT_READ | PROT_WRITE
        mov r10, 0x22 ; MAP_PRIVATE | MAP_ANANONYMOUS
        mov r9, 0x00  ; OFFSET = 0
        syscall

        test rax, -1
        js cannot_allocate_memory

        mov [rax], rbp ; maxmimum allowed elements in this binary heap
        mov [rax + ELEMENT_SIZE], dword 0 ; at the creation time there is no elements stored in the binary heap
        ret

    too_many_elemenents:
        mov rax, -2
        ret
    cannot_allocate_memory:
        ret

_add:
    mov rcx, 0x02 ;dividor
    mov rax, [rdi + ELEMENT_SIZE] ; storing current number of elements in this binary heap
    cmp [rdi], rax
    jz binary_heap_size_overflow

    inc rax
    mov [rdi + ELEMENT_SIZE], rax
    mov [rdi + ELEMENT_SIZE + rax * ELEMENT_SIZE], rsi

    up_heap:
        xor rdx, rdx ; for division

        ;store offset and value of the element being swapped
        mov rbp, rax
        mov r10, rsi
        ;...

        div rcx
        test rax, rax
        jz exit ;We reached the root of this binary heap. Exiting

        mov rsi, [rdi + ELEMENT_SIZE + rax * ELEMENT_SIZE] ;updating rsi with the parent element
        cmp rsi, r10
        jnl exit ; Binary heap have consistent ordering. Exiting

        ;The actual swap of the parent and the child
        mov [rdi + ELEMENT_SIZE + rax * ELEMENT_SIZE], r10
        mov [rdi + ELEMENT_SIZE + rbp * ELEMENT_SIZE], rsi
        ;...

        jmp up_heap

    exit:
        xor rax, rax
        ret

    binary_heap_size_overflow:
        mov rax, -1
        ret

_get:
    mov rax, [rdi + ELEMENT_SIZE + ELEMENT_SIZE * rsi]
    ret

_size:
    mov rax, [rdi + ELEMENT_SIZE]
    ret

_clear:
    mov [rdi + ELEMENT_SIZE], dword 0 ; setting stored elements count to 0
    ret

_delete:
    mov rcx, ELEMENT_SIZE
    mov rax, [rdi]
    add rax, 2
    mul rcx

    mov rsi, rax
    mov rax, SYS_munmap
    syscall
    ret

main.asm (To test the binary-heap data structure implemented before):

section .text
    global _start
    extern _create_heap
    extern _add
    extern _get
    extern _size

_start:
    mov rdi, 0x03; Size of the binary heap
    call _create_heap
    mov r12, rax ; according to linux x64-ABI, r12 is callee-saved

    mov rdi, r12
    mov rsi, 0xFFABB1
    call _add

    mov rdi, r12
    mov rsi, 0x11
    call _add

    mov rdi, r12
    mov rsi, 0xFFFABB1
    call _add

    mov rdi, r12
    mov rsi, 0x12
    call _add

    mov rdi, r12
    call _size

    mov rax, 60
    syscall


texts:
Q1. Can the following code be made more efficient and simple?

Q2. How is the general structure of the code?

Q3. Would this be better written in def/classes? If yes, what would the code look like?

Any other opinions/ tips are completely welcome. Thank you.

# Challenge 3 // Chapther 5 Python for The Absolute Beginner Book
# Python 3.4.3 // MAC 0SX (Latest) // 01.08.2017
from time import sleep

pool_points = 30
menu_option = None
attribute_words = ("Strength, Health, Wisdom & Dexterity")
attributes = {"strength": 0,
              "health": 0,
              "wisdom": 0,
              "dexterity": 0}
GENERAL_MENU = ("""\t\tMENU
    0 = Exit and Final Result
    1 = Add Points to Attributes
    2 = Remove Points from Attributes
    3 = Print Menu
    """)

print("Welcome to Character Builder!")
print()
print(GENERAL_MENU)

while menu_option != "0":
    print()
    sleep(1) #provides user friendly reading
    menu_option = input("Please select an option: ")
    print()

    #exit
    if menu_option == "0":
        print("Creating Character Profile... ")

    #add
    elif menu_option == "1":
        print("ADD Points To An Attribute!")
        print("Attributes Available:", attribute_words)
        print("Points Available:", pool_points)
        print()
        attribute_name = input("Attribute Name: ").lower()
        if attribute_name in attributes:
            value_points = int(input("Value: "))
            if value_points <= pool_points and value_points >= 0:
                pool_points -= value_points
                attributes[attribute_name] += value_points
                print("Points ADDED to,", attribute_name.title())
            else:
                print(value_points, "is an incorrect value. Try again...")
        else:
            print("Unfortunately,", attribute_name, "doesn't exist!")

    #remove
    elif menu_option == "2":
        print("REMOVE Points From An Attribute!")
        print("Attributes Available:", attribute_words)
        print("Points Available:", pool_points)
        print()
        attribute_name = input("Attribute Name: ").lower()
        if attribute_name in attributes:
            value_points = int(input("Value: "))
            if value_points <= int(attributes[attribute_name]) and value_points >= 0:
                pool_points += value_points
                attributes[attribute_name] -= value_points
                print("Points REMOVED from,", attribute_name.title())
            else:
                print(value_points, "is an incorrect value. Try again...")
        else:
            print("Unfortunately,", attribute_name, "doesn't exist!")

    #print menu
    elif menu_option == "3":
        print(GENERAL_MENU)

    #if all else fails!
    else:
        print("INVALID! Select an option from the menu... ")
        print()
        print(GENERAL_MENU)

#final results
sleep(1)
print("-----------------------")
print("Points Remaining", "=>", pool_points, "|")
print("-----------------------")
for i in attributes.keys():
    print(i.title(), "=>", attributes[i], "\t       |")
    print("-----------------------")

input()


texts:
Last night in The 2nd Monitor there was a discussion about postless users - I wanted to see how many there are, whether they're one-timers that showed up once, registered and never came back, and whether they vote at all.

So I whipped up this query on SEDE, showing voters and their post count, as well as other information:

with sub as (

  select distinct
    Users.Id
   ,Users.DisplayName
   ,Users.CreationDate
   ,Users.LastAccessDate
   ,datediff(day, cast(Users.CreationDate as date), cast(Users.LastAccessDate as date)) MembershipDays
   ,case when cast(Users.CreationDate as date) = cast(Users.LastAccessDate as date) then 1 else 0 end IsOneTimer
   ,sum(case when Posts.Id is null then 0 else 1 end) over (partition by Users.Id) PostCount
   ,Users.Reputation
   ,Users.UpVotes + Users.DownVotes TotalVotes
   ,Users.UpVotes
   ,Users.DownVotes
  from Users
  left join Posts on Users.Id = Posts.OwnerUserId
  where Users.Id > 0

), agg as (

  select
     Id
    ,DisplayName
    ,CreationDate
    ,LastAccessDate
    ,IsOneTimer
    ,MembershipDays
    ,case when MembershipDays = 0 then TotalVotes else TotalVotes / cast(MembershipDays as decimal) end VotesPerDay
    ,PostCount
    ,Reputation
    ,TotalVotes
    ,UpVotes
    ,DownVotes
  from sub
  where TotalVotes > 0)

select
     Id
    ,DisplayName
    ,CreationDate
    ,LastAccessDate
    ,IsOneTimer
    ,MembershipDays
    ,round(VotesPerDay, 3) VotesPerDay
    ,PostCount
    ,Reputation
    ,TotalVotes
    ,UpVotes
    ,DownVotes
from agg
order by
  PostCount
 ,cast(VotesPerDay as int) desc
 ,cast(LastAccessDate as date) desc
 ,TotalVotes desc
 ,Reputation
 ,IsOneTimer
 ,CreationDate

Returns 26740 rows returned in 211 ms (cached). Is there any way it could be improved, performance or otherwise?

Postless Users query on SEDE.


texts:
I am trying to implement squarelist by using iteration that points to the head element.  I've create this iterator class to make my iterator id directional.  I just want to see if I implemented it correctly.

class iterator : public std::iterator<std::bidirectional_iterator_tag , Object , int>
    {

    public:
        iterator(Node* p=nullptr) : _node(p){}
        ~iterator(){}

        Node* getNode(){return _node;}

        Object operator * () { return _node->data; }
        iterator & operator ++()
        {
            _node = _node->next;
            return *this;
        }

        iterator operator ++(int)
        {
            iterator  retVal = *this;
            ++this;
            return retVal;
        }
        bool operator < (iterator const& rhs) const
        {
            return _node < rhs._node;
        }
        bool operator != (iterator const& rhs) const
        {
            return _node != rhs._node;
        }
        bool operator == (iterator const& rhs) const
        {
            return _node == rhs._node;
        }
    };


texts: uplifitng return value error reporting to Exception based error reporting

texts:
In Framework Design guideline book there is a chapter about Exception and they talk about return-value-based error reporting and exception based error reporting and the fact that we in a O.O language like C# we should avoid return-value-based error reporting and use exceptions. With that in mind I was looking at our code that eight years ago was written in Visual Basic and last year with a automatic tool got converted to C#!

So here is a method I am looking at, I was wondering if the advice from that book applies to such a method and if yes, then what would be a better approach for rewriting this method?

public int Update(CaseStep oCaseStepIn)
{
    int result = 0;
    //Update the master object with the passed in object

    result = UCommonIndep.gnUPDATE_FAILED;
    if (Validate(oCaseStepIn) == UCommonIndep.gnVALIDATE_FAILED)
    {
        return result;
    }

    CaseStep oCaseStep = get_ItemByObjectKey(oCaseStepIn.CopyOfObjectKey);
    if (oCaseStep == null)
    {
        return result;
    }

    if (oCaseStep.Update(oCaseStepIn) == UCommonIndep.gnUPDATE_SUCCESSFUL)
    {
        //*******************************
        //FYI - Insert code here to update any Key values that might have changed.
        result = UCommonIndep.gnUPDATE_SUCCESSFUL;
    }
    return result;
}


texts:
I am learning Haskell and I am doing 99 Haskell problems. There is a problem to check if a list if a palindrome. It's obvious solution is

isPalindrome x = x == reverse x

There are several other solutions with some kind of reverse. All of them use two passes -- one for building reverse list and one more for ==. I wanted to write a single pass palindrome check.

walk :: (Eq a) => [a] -> Int -> Either (Either Int [a]) Bool
walk (x:xs) n = case walk xs (n + 1) of
    Left (Left back) | (back + 1) == n -> Left (Right xs)
                     | back == n -> let (y:ys) = xs in if y == x then (if null ys then Right True else Left (Right ys)) else Right False
                     | otherwise -> Left (Left (back + 1))
    Left (Right (y:ys)) -> if y == x then (if n > 0 then Left (Right ys) else Right True) else Right False
    Left (Right []) -> error "Impossible"
    Right ans -> Right ans

walk [] _ = Left (Left (-1))

isPalindrome :: (Eq a) => [a] -> Bool
-- isPalindrome x = x == reverse x
isPalindrome [] = True
isPalindrome [_] = True
isPalindrome x = ans where (Right ans) = walk x 0

This looks quite ugly. Is there a better way to check if a string is a palindrome using only one pass? Is it worth trying to write a single pass check?


texts: Wrapper classes for objects returned by 3rd party APIs

texts:
I am building a WPF application which uses a third party library to fetch objects which I want to allow the user to interact with.

The objects are returned as interface types. Am I right in thinking it is good practise to create wrapper classes for these objects instead of binding directly to the interface returned e.g (ICustomer)?

If so, what is the best way to do this? My current thinking is to inject the service into my view model. Then create my own version of the customer class (ClientCustomer) on the client. When I call get customers on the service it will return a list of ICustomer.

For each of these, I will create a new instance of ClientCustomer passing in the ICustomer object and client customer can simply return the underlying properties. This will leave me with a list of ClientCustomer objects which I can bind to instead of binding directly to the List of ICustomer:

public class ClientCustomer
{
  public ClientCustomer(ICustomer c)
  {
    this.customer = c;
  }

  public string Name
  {
    get { return this.customer.Name;}
  }

  //Other properties in a similar way to Name
}

public class CustomerViewViewModel : ViewModelBase
{
  ICustomerService svc;

  public ViewModel(ICustomerService svc)
  {
    this.svc = svc;
    Customers = new List<ClientCustomer>();
    var custs = svc.GetCustomers();
    custs.ForEach(c => Customers.Add( new ClientCustomer(c));
  }

 public List<ClientCustomer> Customers {get;}
}

Is this a good approach?

I'm also unsure how to handle complex types which ICustomer contains. For instance ICustomer has a List of Bank accounts IBankAccount.
Do I need to wrap the Bank Account object in a similar way as well?


texts: Batch file to delete calling program and then itself

texts:
There are times when I want to run a one-off executable on an end-user's machine that cleans up after itself, i.e. deletes itself without a trace. An exe can't delete itself because an exe can't be deleted while it's running. However, a batch file can delete itself, presumably because its contents get copied so the file can close before the code gets run.

So what if there was a general-purpose batch file that deletes the calling executable and then deletes itself? I couldn't find such a batch file so I made one, thinking maybe it could be useful to others. And obviously I want to see if it can be improved upon, of course.

This is particularly useful for an NSIS installer because the batch file can be embedded in the exe and then extracted.

Make sure you copy the batch file before you test it because it will delete itself!

@ECHO OFF

SET filename=%~nx1

IF "%filename%"=="" GOTO:EOF

TASKKILL /IM "%filename%" /F

:LOOP
TASKLIST | FIND /I "%filename%" >NUL 2>&1
IF ERRORLEVEL 1 (
  GOTO CONTINUE
) ELSE (
  ECHO %filename% is still running
  PING -n 6 127.0.0.1>NUL
  GOTO LOOP
)

:CONTINUE

DEL /F "%~f1"
DEL /F "%~f0"

I figured the easiest way to get the path of the calling program is to just have it passed in as a parameter. The IF "%filename%"=="" GOTO:EOF is very important because if the first parameter isn't defined then DEL /F "%~f1" will automatically act like a * is there and try to delete the contents of the whole folder.


texts: Ruby method that is validating the payload received

texts:
What is a cleaner and/or clearer way of writing the following method

def disbursements
  @invoice = Invoice.find(params[:id])
  utc_time = Time.parse.now.utc

#check if invoice_id is not nil
  if @invoice.invoice_id == nil
    @invoice.errors[:invoice_id] << "invoice_id can not be blank"
  end
#check if trip date is now or past
  if utc_time <= @invoice.trips.first
    @invoice.errors[:trips] << "Funds can not be disbursed yet."
  end
#check if trip had been cancelled
  if @invoice.cancelled == true
    @invoice.errors[:cancelled] << "This invoice was already been cancelled."
  end
#check if this invoie has been processed before
  if @invoice.service_rendered == true
    @invoice.errors[:service_rendered] << "This invoice has already been disbursed."
  end
#check all is well
  if @invoice.errors.empty? == false
    render json: @invoice.errors, status: :unprocessable_entity
    return
  end

...


texts:
Recently I made simple hangman game in Java.

Main.java

package com.company;

import java.util.Arrays;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System.out.println("Type a passwords");
        String word = input.nextLine();
        char[] password = word.toCharArray();
        char[] passwordView = new char[password.length];
        for (int w = 0; w < passwordView.length; w++) {
            passwordView[w] = '_';
        }

        int badAnswers = 0;
        char letter = 'x';
        String guess;
        boolean success;
        String answers = "";

        while (badAnswers < 11) {
            success = false;
            System.out.println("Type a char.");
            while (!success) {
                guess = input.nextLine();
                if (guess.length() == 1 && !(answers.contains(guess))) {
                    letter = guess.charAt(0);
                    success = true;
                    answers = answers + letter + ", ";
                } else if (!(guess.length() == 1)){
                    System.out.println("Type exactly one char!");
                }
                else if (answers.contains(guess)){
                    System.out.println("You have already typed that symbol!");
                }

            }

            CheckingIfPasswordContainsLetter checker = new CheckingIfPasswordContainsLetter();
            if (checker.cointans(password, letter)) {
                for (int i = 0; i < password.length; i++) {
                    if (password[i] == letter) {
                        passwordView[i] = letter;
                    }
                }
            } else {
                badAnswers++;
                System.out.println("Bad");
            }

            if (!(Arrays.equals(password, passwordView))) {
                System.out.println("Already used symbols: " + answers);
                System.out.print("Current password is ");
                new PrintingArray(passwordView);
                System.out.print("\n");
            }

            if (Arrays.equals(password, passwordView)) {
                System.out.print("You won! the password was ");
                new PrintingArray(password);
                break;
            }

            if (badAnswers == 11) {
                System.out.print("You lose! Sorry!");
                break;
            }
        }

    }
}

PrintingArray.java

package com.company;

public class PrintingArray {

    public PrintingArray(char[] a){
        for (char z : a) {
            System.out.print(z);
        }
    }

}

CheckingIfPasswordContainsLetter.java

package com.company;

public class CheckingIfPasswordContainsLetter {
    public boolean cointans(char[] a, char b) {
        for (int i = 0; i < a.length; i++) {
            if (a[i] == b) {
                return true;
            }
        }
        return false;
    }
}


texts: Array to map based on object property containing array items

texts:
If i have a object like following
result  = [
 {
   phones : ["ABC", "DEF"],
   name: "Simon"
 },
 {
   phones : ["ABC", "XZY"],
   name: "John"
 }
]

Expected output
Map of key, value
{ABC,     ["Simon", "John"]}
{DEF,     ["Simon"]}
{XYZ,     ["John"]}

My try
map: Map = new Map();
for ( r of result ) {
   for( phone of r.phones) {
      if(map.get(phone)){
        map.set(phone, map.get(phone).concat(r.name))
      } else {
        map.set(phone, r.name);
      }
   }
}

Is there a ES6 way to perform the above double iteration in a minimised way ?


texts: Performance Test and Idea: Initialize a widget

texts:
I want to extend an app object with a widget that initializes itself immediately.

Immediately-Invoked Function Expression:

var app = {};

(function() {
  app.widget = {
    init: function() {
      return true;
    }
  };

  app.widget.init();
}());

Immediately-Invoked Object Expression:

var app = {};

({
  init: function() {
    app.widget = this;

    return true;
  }
}.init());

Please take a look: http://jsperf.com/iife-vs-iioe


texts:
I've written this rather naïve branch-and-bound based IP solver.

Are there any obvious JavaScript optimisations that could speed it up?  I am not looking for asymptotically better algorithms, just simple speed optimisations effective on problem sizes with 5-6 variables and minSize values up to about 500.

/** Represents a simple 1-dimensional
 * IP (Integer Programming) problem.
 * @constructor
 * @param {Array<size: Number, cost: Number>} priceList
 *   List of costs for given sizes.
 *   Note that this list will be sorted by this constructor.
 */
function Prices (priceList) {
  this.prices = priceList;
  this.prices.sort (PriceCompare);
  this.minimise = PricesMinimise;
  this.pricesBB = PricesBB;
}

/** Solves the simple 1-dimensional IP problem:
 * Minimise Sum_i cost_i * x_i
 *    where Sum_i size_i * x_i >= minSize
 *      and cost_i, size_i are positive reals,
 *      and x_i is a nonnegative integer. (i = 0..prices.length - 1)
 *
 * cost_i = this.prices[i].cost and size_i = this.prices[i].size.
 *
 * @param {Number} minSize  The minimum size that must be supplied.
 * @return {xs: Array, cost: Number}  [x_0, x_1, ...] and total cost.
 */
function PricesMinimise (minSize) {
  this.minSize = minSize;
  this.incumbent = Number.POSITIVE_INFINITY;
  this.maxCost = Number.POSITIVE_INFINITY;
  var xsCost = this.pricesBB (0, 0, 0, 0);
  xsCost.xs.reverse ();
  return xsCost;
}

/** Solves a sub problem using only price list elements with
 * index >= i.  It uses instance fields
 * minSize: the minimum required size sum,
 * incumbent: lowest full solution cost seen so far,
 * maxCost: upper bound on full solution cost.
 * @param {Number} i        Minimum price list index.
 * @param {Number} sizeSum  Size sum already selected.
 * @param {Number} costSum  Cost sum already spent.
 * @param {Number} minCost  Lower bound on full solution cost in this
 *                          subtree.
 * @return {xs: Array, cost: Number}  A minimum candidate
 *   solution, or null if none better than the incumbent were
 *   found.
 */
function PricesBB (i, sizeSum, costSum, minCost) {
  var price = this.prices [i];
  var size = price.size;
  var cost = price.cost;
  var xReal = (this.minSize - sizeSum) / size;
  var x = Math.ceil (xReal);
  var localCostSum;
  if (size == Number.POSITIVE_INFINITY) {
    x = 1;
    size = 0; // Avoid NaN in recursive call
    localCostSum = cost;
  } else {
    localCostSum = costSum + cost * x;
    var localMinCost = costSum + cost * xReal;
    minCost = Math.max (minCost, localMinCost);
    if (localMinCost >= this.incumbent) return null;
  }
  this.maxCost = Math.min (this.maxCost, localCostSum);
  var localMin = {'xs': [x], 'cost': localCostSum};
  if (localCostSum < this.incumbent) this.incumbent = localCostSum;
  if (localCostSum == minCost) return localMin;
  if (i < this.prices.length - 1)
    for (x--; x >= 0; x--) {
      var xsCost =
        this.pricesBB (i + 1, sizeSum + size * x, costSum + cost * x, minCost);
      if (xsCost == null) continue;
      xsCost.xs.push (x);
      localMin = xsCost;
      if (localMin.cost == minCost) return localMin;
    }
  if (localMin.cost == this.incumbent)
    return localMin;
  else
    return null;
}


texts: Adding blank rows for every skipped value in a DataTable

texts:
So I have a DataTable that returns results within a month to month range when available.  However, when I format the return, I need to still show skipped months as blanks.

I have a working solution, but it's a little verbose and I think it can be done cleaner.

Here's a setup to the problem

Dim startMonth As Date = #5/1/2011#
Dim endMonth As Date = #6/1/2012#
Dim dr As DataRow

Dim dtData As New DataTable
With dtData.Columns
    .Add("MonthDate", GetType(Date))
    .Add("OtherInfo", GetType(String))
    'other columns...
End With

With dtData.Rows
    .Add(#6/1/2011#, "Info")
    .Add(#7/1/2011#, "Info")
    .Add(#7/1/2011#, "Info")
    .Add(#1/1/2012#, "Info")
End With

This part will loop through the date ranges and generate a DataTable with one blank row per possible date

'get all dates
Dim dtAllTimes As DataTable = dtData.Clone()

Do While startMonth <= endMonth
    dr = dtAllTimes.NewRow()
    dr("MonthDate") = startMonth
    dtAllTimes.Rows.Add(dr)
    startMonth = startMonth.AddMonths(1)
Loop

This part will create a blank DataTable with one date per found value

'get used dates
Dim dtUsedTimes As DataTable = dtData.Clone()

For Each usedDate As Date In
        From row As DataRow In dtData.AsEnumerable Select CDate(row("MonthDate")) Distinct
    dr = dtUsedTimes.NewRow()
    dr("MonthDate") = usedDate
    dtUsedTimes.Rows.Add(dr)
Next

Finally I combine those two tables to get the unused dates and add them onto the original data

'subtract used dates from all dates
Dim unusedDates As IEnumerable(Of DataRow)
unusedDates = dtAllTimes.AsEnumerable.Except(dtUsedTimes.AsEnumerable(), DataRowComparer.Default)

'add subtraction back into all
dtData = dtData.AsEnumerable.Union(unusedDates).CopyToDataTable()

Any suggestions would be great.

Update...

Implementing my own custom comparison class helps to shave off a couple lines of code and processing time by not having to compare every column in the entire row against every other column and also helps skip the step of finding used rows since that was only done to put them into a DataTable that could be used with the Default DataRowComparer.

Here's the custom DataRowComparer

Public Class DataRowDateComparer : Implements IEqualityComparer(Of DataRow)

    Public Function Equals(x As DataRow, y As DataRow) As Boolean _
            Implements IEqualityComparer(Of DataRow).Equals
        Return x("MonthDate") = y("MonthDate")
    End Function

    Public Function GetHashCode(obj As DataRow) As Integer _
            Implements IEqualityComparer(Of DataRow).GetHashCode
        Return obj.ToString.GetHashCode
    End Function

End Class

Here's the code after creating a DataTable with every date

'only add rows that aren't already in datatable
dtData = dtData.AsEnumerable _
               .Union(dtAllTimes.AsEnumerable, New DataRowDateComparer) _
               .CopyToDataTable()

Also, sorting by MonthDate in a DataView can help view the results more easily

Dim dv As New DataView(dtData)
dv.Sort = "MonthDate"


texts: Faster way to determine largest prime factor

texts:
Project Euler problem 3 asks:

  What is the largest prime factor of the number 600851475143?

The first step I took is to determine the highest value number I should be looking at as a possibility (600851475143 / 2). Next I wanted to check each prime number as I go to see if it is a factor of 600851475143. If so, I store it in a variable denoting the highest prime factor encountered so far.

On running the program, the prime factor '6857' is the last output I am seeing for several minutes in my output. I entered this as the answer and it was correct. My problem is finding a way to streamline the algorithm to greatly reduce the processing time.

public class Euler3 {

    public static void main(String[] args) {
        long max = 600851475143L / 2;
        long lgstPrime = 1;
        boolean isPrime = true;

        for (int i=2; i<max; i++){
            for (int j=2; j<=i; j++){
                if ((i % j == 0) && (j != i))
                    isPrime = false;
            }

            if ((isPrime) && (600851475143L % i == 0))
                lgstPrime = i;

            isPrime = true;     //reset
        }

        System.out.println("\n" + "the largest prime factor of the number 600851475143 is " + lgstPrime);
    }
}


texts:
I got this question during my interview:

  Given an integer N, output an N x N spiral matrix with integers 1 through N.

  Examples: Input:  3

  Output: [[1, 2, 3],
           [8, 9, 4],
           [7, 6, 5]]

  Input: 1

  output: matrix filled out as a spiral  [[1]]

/*PSEUDO:
rowMin = 0
rowMax = n - 1
colMin = 0
colMax = n - 1
counter = 1
matrix = []
create the matrix:
loop from 0 to n - 1
  array
  loop from 0 to n-1
    push 0 into array
while rowMin <= rowMax and colMin <= colMax
  loop on rowMin from colMin to colMax.  col
    matrix[rowMin][col] becomes counter++
  rowMin++
  loop on colMax and from rowMin to rowMax.  row
    matrix[row][colMax] becomes counter++
  colMax--
  loop on rowMax from colMax to colMin.  col
    matrix[rowMax][col] becomes counter++
  rowMax--
  loop on colMin from rowMax to rowMin.  row
    matrix[row][colMin] becomes counter++
  colMin++
return matrix
*/

const spiralMatrix = (n) => {
  const matrix = [];
  let rowMin = 0,
    rowMax = n - 1,
    colMin = 0,
    colMax = n - 1,
    counter = 1;

  for (let i = 0; i < n; i++) {
    matrix.push(new Array(n).fill(0));
  }

  while (rowMin <= rowMax && colMin <= colMax) {
    for (let col = colMin; col <= colMax; col++) {
      matrix[rowMin][col] = counter++;
    }
    rowMin++;
    for (let row = rowMin; row <= rowMax; row++) {
      matrix[row][colMax] = counter++;
    }
    colMax--;
    for (let col = colMax; col >= colMin; col--) {
      matrix[rowMax][col] = counter++;
    }
    rowMax--;
    for (let row = rowMax; row >= rowMin; row--) {
      matrix[row][colMin] = counter++;
    }
    colMin++;
  }

  return matrix;
}

console.log(spiralMatrix(10));


texts: Newton-Pepys, common birthdays and other probability simulations in Python 3

texts:
I have been learning Probability from Statistics 110 and trying to simulate problems that have an unintuitive answer

from numpy import cumsum
from statistics import mean
from numpy.random import exponential
from random import randint, sample, uniform
from bisect import bisect_left

def mean_of_experiments(experiment_func, N=100000):
    '''Decorator to repeat any Bernoulli trial N times and return probability of success'''
    def wrapper(*args, **kwargs):
        return round(mean(experiment_func(*args, **kwargs) for _ in range(N)), 3)
    return wrapper

@mean_of_experiments
def common_birthday(k):
    '''Simulates an experiment to generate k independent uniformly random birthdays and check if there are any repeat birthdays'''
    rands = [randint(1, 365) for _ in range(k)]
    return len(rands) != len(set(rands))

@mean_of_experiments
def matching(k=52):
    '''Simulates an experiment to permute 'k' cards and check if any jth card's value is j'''
    idx_labels = enumerate(sample(range(k), k))
    return any(idx == label for idx, label in idx_labels)

@mean_of_experiments
def dice(n, c):
    '''Simulates an experiment to roll 'n' dice and and check if count of 6's is at least c'''
    return [randint(1, 6) for _ in range(n)].count(6) >= c

def boardings(scale=5.0, N=1_00_000):
    '''Simulates an experiment where arrival of buses at stop follows a Poisson process and finds avg. inter-arrival time at a random instant'''
    arrivals = cumsum([exponential(scale=scale) for _ in range(N)])

    @mean_of_experiments
    def wait():
        boarding_idx = bisect_left(arrivals, uniform(0, arrivals[-1]))
        missed_bus = 0 if boarding_idx == 0 else arrivals[boarding_idx - 1]
        return arrivals[boarding_idx] - missed_bus

    return wait()

Probability Problems:

common_birthday: Given k people, what's the probability that any 2 people share a birthday? For 23 people, it's >50% and for 50 people, >97%.
matching: Given 52 cards with a unique label in 0...n-1, they are shuffled. What's the probability that any j^th card's label is j? Answer's very close to 1-1/e
dice: Problem posed by a gambler to Newton; dice(6, 1) > dice(12, 2) > dice(18, 3)
boardings: Given that a bus company's buses follow a Poisson process, if a person visits a stop at some random time, what was that inter-arrival time? From Tsitsiklis' lectures; answer is 2*scale for any value of scale.

What I wish I could do in my code is dynamically set the value of N in the decorator mean_of_experiments. Is that possible?


texts: Hide menu during user inactivity with jQuery, setInterval performance

texts:
I created a script to hide a menu during user inactivity and when the position of my page is left < 2.

I would like to know if I use a good method regarding the performances. It's not too heavy ? Should I optimize my code ?

var interval = 1;

setInterval(function(){
    var posx=$("#page").offset();
    if (interval == 30 && posx.left < 2) {
    $('#menu').fadeOut(1000);
       interval = 1;
   }
   interval = interval+1;
    console.log(interval);
    },1000);

$(document).bind('mousemove keydown scroll touchstart', function() {
    var posx=$("#page").offset();
    if($('#menu').is(':hidden') && posx.left < 2) {
        $('#menu').fadeIn(1000);
        interval = 1;
    }
});


texts: Showing "open" or "closed" based on the current time

texts:
I'm using this code to have a site show either "Open" or "Closed" depending on what the current time  is.
I'm a junior developer and I want to show this to my boss but one of the Senior Developers said to make it more robust/reusable before I do.

var currentDate = new Date();
var currentMonth = currentDate.getMonth();
var currentDay = currentDate.getDay();
var currentHour = currentDate.getHours();
var currentMinute = currentDate.getMinutes();

function openClose() {
  if(currentDay >= 1 && currentDay <= 4) {
    document.getElementById("friday").style.display = "none";
    if (currentHour >= 8 && currentHour <= 21) {
      document.getElementById("closed").style.display = "none";
    }
  else {
    document.getElementById("open").style.display = "none";
  }
}
if (currentDay === 5) {
  document.getElementById("mon-thurs").style.display = "none";
  if (currentHour >= 8 && currentHour <= 17.5) {
    document.getElementById("closed").style.display = "none";
  }
  else {
    document.getElementById("open").style.display = "none";
  }
}
if (currentDay === 0 || currentDay === 6) {
  document.getElementById("open").style.display = "none";
  document.getElementById("friday").style.display = "none";
}
};

setInterval(openClose(), 5000);
.layout-header .header-one #open,
.layout-header .header-one #closed,
.layout-header .header-one #friday,
.layout-header .header-one #mon-thurs {
   display: inline-block;
   color: #000;
}

Open

Closed

Sales: 8am - 8pm

Sales: 8am - 5:30pm


texts: "Invert" a JavaScript object hash whose values are arrays to produce a new object hash with keys as the elements of those original value vectors

texts:
Background

lodash and underscore have an invert function that takes an object hash and converts it to a new one, which has keys as the input object's values and values as the input object's keys. As such, if the values in the input object aren't unique, this non-unique input value will, when it's a key in the output object, have as its value only one of the input object's keys.

An example:

_.invert({a: 1, b: 2, c: 2})
// { 1 : "a", 2 : "c" }

The twist

I frequently work with object hashes whose values are one-dimensional arrays (vectors). I've written a function using lodash/underscore (NB. only tested with lodash) that performs an array-aware invert, whose output object has keys that are the unique elements of the input object's value vectors, and values that are the input object's keys.

function arrayAwareInvert(obj) {
    return _.object(_.flatten(_.map(obj, function(valVec, key) {
        return valVec.map(function(val) { return [ val, key ]; });
    })));
}

I'd appreciate feedback on this function.

(NB. I can't use lodash/underscore's built-in invert with an object hash with array-valued keys because the resulting object has keys which simply stringify the arrays—an output object key might be [1, 2, 3].toString(), and entirely useless.)

Example use

Just to confirm that it works:

arrayAwareInvert({a: [1, 2], b: [3, 4]})
// { 1: "a", 2: "a", 3: "b", 4: "b" }

Per the original invert's behavior, if the elements of the input object's value vectors aren't unique (that is, if multiple value vectors contain the same element), the output object's value for those non-unique elements will be one of the input object keys:

arrayAwareInvert({a: [1, 2], b: [3, 4, 2]})
// { 1: "a", 2: "b", 3: "b", 4: "b" } // NB: 2: "b" here

Implementation notes

My implementation seems as brute-force as possible: it's effectively a doubly-nested loop, with the outer loop going over all input object keys and the inner loop going over the contents of each input object value (which is a vector).

A [key, value] tuple is built for each iteration of the inner-most loop, where "key"/"value" refer to the output object.

flatten is used to remove one level of nesting, i.e., transform [[[k1, v1]], [[k2, v2], [k3, v3]]] to [[k1, v1], [k2, v2], [k3, v3]].

Finally object is called to convert this list of 2-tuple key-value pairs into an object hash.

Summary

Are there implementations that occupy more advantageous positions in the clarity-speed-elegance phase space?

Does this operation have a more general name?

Analyses of solutions

reduce

I can simplify? @Flambino's solution a bit with _.merge:

function arrayAwareInvert(obj) {
  return _.reduce(obj, function (result, values, key) {
    return _.merge(result,
                   _.mapValues(_.object(values), function(v) { return key; }));
  }, {});
}

I like using merge here because it describes what's happening very well. But I don't really like how much code is needed to combine a vector and a string into an object hash with keys as elements of the vector and values as the string:

_.mapValues(_.object(values), function(v) { return key; })

As one (of many) alternatives, you could do this instead:

_.object(values, values.map(function(v) { return key; }))

but both of these seem obfuscated, compared with how clear the reduce and merge steps are.


texts:
I was trying to solve a problem on de-arrangements (Number of partial derangement such that exactly  prime number discs are found away from their natural positions? (Any number of non-prime K disks may also be found in or out of their natural positions)).

Somehow solved it using recursion but my code fails (taking long time to show output sometimes it gets freezes) on larger inputs for parameter move like (1000, 1000000), working fine for smaller inputs. Any approach to optimize this recursive function with Dynamic Programming with better time complexity.

static BigDecimal derangements(int move, int dontCare) {

        if (move < 1)
            return factorial(dontCare);

        // recursion
        move--;
        BigDecimal result = derangements(move, dontCare).multiply(BigDecimal.valueOf(dontCare));
        if (move > 0) {
            result = (derangements(move - 1, dontCare + 1).multiply(BigDecimal.valueOf(move))).add(result);
        }

        return result;
}

I tried something like this but failed to correctly implement it. I know it's wrong. Any correct approach or implementation would do.

static BigDecimal derangements(int move, int dontCare) {
  BigDecimal[] moveResult = new BigDecimal[move + 1];

  moveResult[0] = factorial(dontCare);

  for (int i = 1; i < move; i++) {
      moveResult[i] = moveResult[i - 1].multiply(BigDecimal.valueOf(dontCare));
  }

  while ( move  > 1) {
      int i = 1;
      moveResult[i] = moveResult[i - 1].multiply(BigDecimal.valueOf(dontCare))

              .multiply(BigDecimal.valueOf(move)).add(moveResult[i]);
      move--;
      i++;
  }

  return moveResult[move-1];
}


texts:
I have the following scenario - i have a grid on web page that is populated with data.  User can check a check-boxes in grid and data is saved to DB on navigating to next page.  If they then navigate back to the page and remove a selection the data is deleted from the DB and also if the original selection is still checked the data is not saved to the DB twice.  It is a MVC 5 application with SQL server db using Entity Framework - this particular logic is contained in my Web API controller.

The following is my code for the API method:

 public HttpResponseMessage SaveCarModelSelect(CarModelSelectViewModel model)
    {
        var car = _carService.GetById(model.carId);

        var splitSelectedCars = model.SelectedCars.Split(',').Select(sValue => sValue.Trim()).ToList();

        // We only need to check if there are Car Models saved in the DB
        if (car.CarModels.Count > 0)
        {
            var carsToRemove = CarModelsToRemoveFromDb(car, splitSelectedCars);

            foreach (var carToRemove in carsToRemove )
            {
                var carIdToDelete = car.RemoveCar(carToRemove);
                _carService.Delete(carIdToDelete);
            }
        }

        foreach (var singleSelectedCar in splitSelectedCars)
        {
            var savedCarsInDb = car.CarModels.Select(c=> c.ModelId)
              .ToList();

            if (!savedCarsInDb.Contains(singleSelectedCar))
            {
                riskAppraisal.AddCar(singleSelectedCar);
            }
        }

        _carService.Update(car);

        return Request.CreateResponse(HttpStatusCode.OK);
    }

The private method for CarModelsToRemoveFromDb is below

    private static IEnumerable<string> CarModelsToRemoveFromDb (Car car, IEnumerable<string> splitSelectedCars)
    {
        var savedCarsInDb = car.CarModels.Select(c=> c.ModelId)
              .ToList();

        return savedCarsInDb.Except(splitSelectedCars, StringComparer.OrdinalIgnoreCase);
    }

I'm guessing has anyone got suggestions to improve this - all the functionality is working as expected.  Where I call the AddCar method I suppose the checking database logic could be wrapped in another if the .Count is > 0 but then if I had the AddCar(singleSelectedCar) outside that it would get added twice.  The Goal I am trying to get to is make my API method thin and separate out other logic into their own methods.

Any suggested improvements appreciated.


texts: The CRUD interface I created for my new app. Creates, updates, deletes, reads and lists

texts:
Here is the Interface I am using in my working app.

<?php

declare(strict_types=1);

namespace midorikocak\nano;

use Exception;

interface CrudInterface
{

    /**
     * @param array $data Array data of an Item.
     * @return array Array data of an Item with id.
     * @throws Exception if the data does not pass validate
     */
    public function create(array $data): array;

    /**
     * @param string $id
     * @return array Returns the array of New Item.
     * @throws Exception if something bad happens
     */
    public function read($id): array;

    /**
     * @param string $id Can be an integer or a string
     * @param array $data Accepts Array data of an Item with or without id.
     * @return array Returns the array of Updated Item.
     * @throws Exception if something bad happens
     * @todo Is it ok to have id in array data?
     */
    public function update(string $id, array $data): array;

    /**
     * @param string $id Can be an integer or a string
     * @return void Returns nothing. Simple Command Query separation.
     * @throws Exception if id not found or something bad happens
     * @todo Should create different exceptions for negative outcomes
     */
    public function delete(string $id): void;

    /**
     * @return array[] Should return an array of arrays that contain Item Data.
     */
    public function list(): array;

    /**
     * We have to validate data in every operation that receives item array.
     * @param array $data Accepts Array data of an Item with or without id.
     * @todo How can we be sure that this runs in every method that acceps item data?
     * @todo Maybe an abstract class?
     *
     * @return bool
     */
    public function validateData(array $data): bool;
}

I have some questions.

In update method, is it ok to have id in array data?
Should I create different exceptions for negative outcomes? Instead of returning false or null, when something is wrong, I prefer to throw exceptions.
How can we be sure that In validateData method runs in every method that accepts item data? Maybe an abstract class?
Are there any violations or can it be some better?


texts: Convertors converting unconverted objects

texts:
In my app, I have several convertors, like these two:

public class ThemeToTableStripeConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((int)value == 1) { return new SolidColorBrush(Color.FromArgb(255, 34, 34, 34)); }
        return new SolidColorBrush(Color.FromArgb(255, 238, 238, 238));
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return null;
    }
}

public class ThemeToLBStyleConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        if ((int)value == 1) { return Application.Current.Resources["LBDark"]; }
        else if ((int)value == 2) { return Application.Current.Resources["LBGold"]; }
        else { return Application.Current.Resources["LBLight"]; }
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        return null;
    }
}

In the first, I have an int representing a theme style, with 0, 1, and 2 being the three themes I support.  Themes 0 and 2 are identical in the part affected by this (white background), while 1 has a black background.  In the second, I want theme 0 to always be the default, no matter the value, and themes 1 and 2 to return different items.

Beyond the general comments, there are a couple things I would like specific feedback on.  Both of these convertors are one-way convertors, and always will be; however, that return null; looks a little off - should I replace that with throw new NotImplementedException();?  Instead of formatting my code like this:

if (condition) { return val1; }
return val2;

Should I write that as:

if (condition) { return val1; }
else { return val2; }


texts: Temporarily block API calls when server sends a 503 response

texts:
I have a scenario in which I call many APIs throughout my application lifecycle.

In case the server sends me a 503 response code, it will also send a lockdown object which has a timestamp associated in one of the fields. The reason of this being that I have to block further calls to the server till the timestamp expires.

My solution consists of a retrofit client coupled with an okhttp Interceptor

Here are the steps of execution:

Interceptor (Sentinel) intercepts the request
Interceptor checks a global exception value which is held by an object class (Singelton - LockDownManager ) returns a true or false based on the current timestamp. The LockDownManager is also responsible for memoizing the exception, incase the server is still locked down it helps in rethrowing the same exception.

below is my implementation, I am only including the relevant parts from Sentinel:

   class Sentinel : Interceptor {

        override fun intercept(chain: Interceptor.Chain): Response {
            // Check with global counter if request can be executed
            val canClientMakeRequest = LockDownManager.isServerAvailable()
            if (!canClientMakeRequest) {
                throw LockDownManager.ex as HttpStatusDetailedException
            } else {
                // Mark exception null
                LockDownManager.ex = null
            }
       //....... Continue execution
       // Response received
       // Check if response contains 503 object
       // Done by checkIfHasToMemoize(...)
    }

Here is how exception is memoized and parsed:

fun checkIfHasToMemoize(resp: Response) {
    // Parse response and derive errorObj - excluded
    val errorObj = httpResult.httpError
    if (errorObj != null) {
        val detailedException =
            HttpStatusDetailedException(httpStatusCode, "Unexpected HTTP(S) result:" +
                " $result", errorObj)
        // Set LockDown -> isServerAvailable
        if (detailedException.httpCode == 503 && null != LockDownManager.ex)
            LockDownManager.ex = detailedException

        throw detailedException

    }

Finally here is my singleton Manager:

object LockDownManager {

    @Volatile
    var ex: HttpStatusDetailedException? = null

     fun isServerAvailable(): Boolean {
        if (ex == null) {
             return true
        }
        val serverAvailableTimestamp = ex?.blockUntil ?: 0L
        if (serverAvailableTimestamp == 0L) {
            return true
        }
        val c = Calendar.getInstance()
        c.timeZone = TimeZone.getTimeZone("UTC")
        val currentTime = c.timeInMillis
        return currentTime > serverAvailableTimestamp
    }
}

This is a multithreaded environment and more than the semantics of my variable names I am concerned about the veracity of thread safety.


texts:
I've created a second 'calculator-like' program, this time using the JOptionPane rather than typing in the console.  At the moment the code looks to have a lot of repetition so I'm looking to simplify it; any advice and suggestions would be great!

import javax.swing.JOptionPane;

public class SaveCalc {

    public static void main(String[] args) {

        //Text prompts to collect data
        String carCost = JOptionPane.showInputDialog("What is the total cost of the car?");

        String insCost = JOptionPane.showInputDialog("What is the yearly cost of the insurance?");

        String manCost = JOptionPane.showInputDialog("How much would you like to save for maintenance?");

        String saveMonth = JOptionPane.showInputDialog("How much will you be saving each month?");

        //Converts string inputs to Doubles
        double carCostP = Double.parseDouble(carCost);
        double insCostP = Double.parseDouble(insCost);
        double manCostP = Double.parseDouble(manCost);
        double saveMonthP = Double.parseDouble(saveMonth);

        //Calculates the total cost and the months to save
        double costTotal = carCostP + insCostP + manCostP;
        double months = costTotal / saveMonthP;

        //Converts the months value to an integer
        int monthsP = (int) months;

        System.out.printf
        ("With a saving of \u00A3%5.2f each month and a total cost of \u00A3%5.2f it will take "
        + monthsP
        + " months to save up.",saveMonthP,costTotal);
    }
}


texts:
I wrote this script to backup some important files.  It backs up the files to a local folder as well as to an external hard drive.  It creates a new subdirectory which has its name constructed with the current date and time.  Works perfectly, but I'm just wondering if there are any Python best-practices I'm missing or if there's any way I could've made it better!

import datetime
import os
import shutil

GOOGLE_DRIVE_DIRECTORY = 'C:\\Users\\Jeff\\Google Drive\\Manifest_Destiny'
MAIN_BACKUP_DIRECTORY = 'C:\\Users\\Jeff\\Desktop\\Manifest_Destiny_Backups\\md_backup_{0}'
EXTERNAL_DRIVE_DIRECTORY = 'F:\\My Files\\Manifest_Destiny_Backups\\md_backup_{0}'

def get_backup_directory(base_directory):
    date = str(datetime.datetime.now())[:16]
    date = date.replace(' ', '_').replace(':', '')
    return base_directory.format(date)

def copy_files(directory):
    for file in os.listdir(GOOGLE_DRIVE_DIRECTORY):
        file_path = os.path.join(GOOGLE_DRIVE_DIRECTORY, file)
        if os.path.isfile(file_path):
            shutil.copy(file_path, directory)

def perform_backup(base_directory):
    backup_directory = get_backup_directory(base_directory)
    os.makedirs(backup_directory)
    copy_files(backup_directory)

def main():
    perform_backup(MAIN_BACKUP_DIRECTORY)
    perform_backup(EXTERNAL_DRIVE_DIRECTORY)

if __name__ == '__main__':
    main()


texts: Pretty printing degrees input to radians

texts:
I'm mostly concerned about edge cases, although I think I dealt with them all. Improvements on code quality would also be much appreciated.

/*
    printRadian(90) -> π/2
    printRadian(-90) -> -π/2
    printRadian(180) -> π
    printRadian(-180) -> -π
    printRadian(270) -> 3π/2
*/

function printRadian(degrees) {

    if(degrees % 180 == 0) {
        if(degrees == 180) {
            return "π";
        }
        else if(degrees == -180){
            return "-π";
        }else{
            return degrees / 180 + "π";
        }
    }

    var frac = degrees / 180;

    // 10 ** number of decimal places
    var multiplier = Math.pow(10, frac.toString().split(".")[1].length);
    var numerator = frac * multiplier;
    var denominator = multiplier;

    //http://stackoverflow.com/a/17445304/896112 - Euclid's Algorithm
    function gcd(a, b) {
        return (!b)?a:gcd(b, a%b);
    }

    var g = gcd(numerator, denominator);

    numerator = numerator/g;
    denominator = denominator/g;

    if(numerator == 1){
        numerator = "π";
    }else if(numerator == -1){
        numerator = "-π";
    }else{
        numerator += "π"
    }

    if(denominator < 0){
        denominator = Math.abs(denominator);
        numerator = "-"+numerator;
    }

    return numerator +"/"+ denominator;
}


texts: Single word CAS tagged pointer for algorithms susceptible to the ABA problem

texts:
I've been looking for a solution to the ABA problem for a lock-free stack. Searching the Web revealed patented and complicated hazard pointers and tagged pointers using double compare-and-swap (DCAS, CAS2). I would settle for the DCAS, but it's not available on some older AMD CPUs. So I came up with this helper class:

class TaggedPtrBase {
    typedef unsigned int tag_t;
    static const tag_t INVALIDATED = 1;
public:
    TaggedPtrBase() {
        tag.store(0, std::memory_order_relaxed);
        ptr = 0;
    }
    TaggedPtrBase & operator=(const TaggedPtrBase & other) {
        tag.store(other.tag.load(std::memory_order_acquire), std::memory_order_relaxed);
        ptr = other.ptr;
        return *this;
    }
    operator void *() const {
        return get();
    }
    void * get() const {
        return ptr;
    }
    bool compare_and_swap(const TaggedPtrBase & oldval, void * newptr) {
        uintptr_t old_tag = oldval.tag.load(std::memory_order_relaxed);
        if (old_tag & INVALIDATED) {
            return false;
        }
        if (tag.compare_exchange_strong(old_tag, old_tag | INVALIDATED, std::memory_order_acquire)) {
            ptr = newptr;
            tag.store(old_tag + 2, std::memory_order_release);
            return true;
        } else {
            return false;
        }
    }
private:
    std::atomic<tag_t> tag;
    void * ptr;
};
...
void push(Node * node) {
    void * newptr = reinterpret_cast<void *>(node);
    TaggedPtrBase old;
    do {
        old = ptr;
        node->next = static_cast<Node *>(old.get());
    } while (!ptr.compare_and_swap(old, newptr));
}

It appears to be working, but it's simplicity suggests that I'm missing something.
So I wonder if this is a proper solution, or is it just a glorified spin-lock? Any issues on non-x86 platforms?


texts:
(See the next iteration.)

I have this small program for sorting a stack using mergesort. Basically, the aim was to use as little aid from JDK library as possible. See what I have:

StackMergesort.java:

import java.util.Collections;
import java.util.Random;
import java.util.Stack;
import java.util.stream.IntStream;

public class StackMergesort {

    public static <E extends Comparable<? super E>>
        void sort(final Stack<E> stack) {
        if (stack.size() < 2) {
            // Trivially sorted.
            return;
        }

        if (stack.size() == 2) {
            final E element1 = stack.pop();
            final E element2 = stack.pop();

            if (element1.compareTo(element2) < 0) {
                stack.push(element2);
                stack.push(element1);
            } else {
                stack.push(element1);
                stack.push(element2);
            }

            return;
        }

        final int size = stack.size();
        final int auxStackLength = size / 2;
        final Stack<E> aux1 = new Stack<>();
        final Stack<E> aux2 = new Stack<>();

        for (int i = 0; i < auxStackLength; ++i) {
            aux1.push(stack.pop());
        }

        while (!stack.isEmpty()) {
            aux2.push(stack.pop());
        }

        sort(aux1);
        sort(aux2);

        Collections.<E>reverse(aux1);
        Collections.<E>reverse(aux2);

        // Merge.
        while (!aux1.isEmpty() && !aux2.isEmpty()) {
            if (aux1.peek().compareTo(aux2.peek()) > 0) {
                stack.push(aux1.pop());
            } else {
                stack.push(aux2.pop());
            }
        }

        while (!aux1.isEmpty()) { stack.push(aux1.pop()); }
        while (!aux2.isEmpty()) { stack.push(aux2.pop()); }
    }

    public static <E extends Comparable<? super E>> boolean isSorted(final Stack<E> stack) {
        if (stack.size() < 2) {
            // Trivially sorted.
            return true;
        }

        E previous = stack.pop();

        while (!stack.isEmpty()) {
            E current = stack.pop();

            if (previous.compareTo(current) > 0) {
                return false;
            }

            previous = current;
        }

        return true;
    }

    public static void main(final String[] args) {
        final long seed = System.nanoTime();
        final Random random = new Random(seed);
        final Stack<Integer> stack = createRandomIntegerStack(20, random);

        // Note: the topmost element of a stack is the rightmost
        // one in the output.
        System.out.println("Seed = " + seed);
        System.out.println("Before: " + stack);
        sort(stack);
        System.out.println("After:  " + stack);
        System.out.println("Sorted: " + isSorted(stack));
    }

    private static Stack<Integer>
        createRandomIntegerStack(final int size, final Random random) {
        final Stack<Integer> stack = new Stack<>();
        IntStream.range(0, size)
                 .forEach((e) -> { stack.add(random.nextInt(100));});
        return stack;
    }
}

Any critique much appreciated.


texts: Find the largest contiguous sum of two or more integers in an array of positive or negative integers?

texts:
I received an interview question: Find the largest contiguous sum of two or more integers in an array of positive or negative integers.
I wrote a brute force solution, which is slow at O(n^2). Is there a faster solution? Sorry in advance if this question was already asked. I couldn't find an answer that accounts for the sum being at least 2 integers, and having negative numbers.
static int maxSum(int[] nums, int minArrayLen = 1) {
  int maxSum = Int32.MinValue;
  int curSum = 0;
  for (int i = 0; i < nums.Length; i++) {
    curSum = nums[i];
    for (int j = i + 1; j < nums.Length; j++) {
      curSum += nums[j];
      maxSum = Math.Max(curSum, maxSum);
    }
  }
  return maxSum;
}