texts: Asynchronously assembling a complex object

texts:
Sanity check needed, as I'm still very unfamiliar with the nuances behind async/await and how they relate to more traditional Task / TPL code.
I have a high-level repository layer which is assembling a business object from various lower-level repositories.  As a business decision, we are doing keyed lookups at the data layer and assembling the composite object in code.  In the following code, "Account" is the business object, and the various _tAccountXXXRepo objects are all patterned similarly to this (we are using NPoco):
public class T_AccountMapperRepository : BaseNPocoRepository<T_AccountMapper>
    , IRetrieveMany<T_AccountMapper>
    , IRetrieve<AccountId, T_AccountMapper>
{
    public T_AccountMapperRepository(IDatabase database) : base(database)
    {
    }

    public async Task<T_AccountMapper> Retrieve(AccountId input)
    {
        return await Database.QueryAsync<T_AccountMapper>()
            .First(x => x.AccountId == input)
            .ConfigureAwait(false);
    }
}

The code to fetch the different values can be logically executed in parallel, and I am wondering if this implementation is the correct pattern to do so:  (the various methods being called on the Account object are thread-safe as well)
public async Task<Account> Retrieve(AccountId input1, DateTime input2)
{
    var account = new Account();

    await Task.WhenAll(
        _tAccountMapperRepo.Retrieve(input1)
            .ContinueWith(async result => account.SetAccountMap(await TranslateAccountMap(result))),

        _tPaymentRedirectionRepo.Retrieve(input1, input2)
            .ContinueWith(async result => account.ChangePayerToAccount(await TranslatePaymentRedirection(result))),

        _tAccountAncestorRepo.Retrieve(input1, input2)
            .ContinueWith(async result => await _tAccountMapperRepo.Retrieve((await result).AncestorId))
            .ContinueWith(async result => account.MoveAccountToNewParentAccountMap(await TranslateAccountMap(await result))),

        _tAccountRepo.Retrieve(input1)
            .ContinueWith(async result => await _tAccountTypeRepo.Retrieve((await result).TypeId))
            .ContinueWith(async result => account.SetAccountType(await TranslateAccountType(await result)))
    );

    return account;
}

Any method that is labelled with TranslateXXX all look similar to this:
private static async Task<AccountMap> TranslateAccountMap(Task<T_AccountMapper> mapTask)
{
    if (!mapTask.IsCompletedSuccessfully)
        throw new InvalidOperationException(nameof(mapTask), mapTask.Exception);

    var map = await mapTask;

    return new AccountMap(map.AccountId, map.Login, map.Namespace);
}

My main concerns are mixing Task and async/await, and whether or not my async & awaiting is re-introducing an element of synchronicity in what I'm hoping to make a very asynchronous process.  My end goal is that as many various properties as possible are fetched in parallel and assembled


texts: Sum data that needs to be joined and grouped by

texts:
I have a list of patients, Patient class has Prescriptions property, which is a list of Prescription objects. Prescription has 3 important attributes, Medicament,Amount and Type(which is basically a key for joining).

I need to join a list of Prescription types, as a prescription type has an attribute Influence which servers as multiplier for the amount.

var prescriptions = (from prs in
                        (from p in patients
                             from pr in p.Prescriptions
                             join type in DatabaseService.PrescriptionTypes
                                 on pr.Type equals type.Value
                         select new { Med = pr.Medicament,Amount = pr.Amount * (int)type.Influence })
                    group prs by prs.Med into prgs
                    select new { Medicament = prgs.Key,Amount = prgs.Sum(prg => prg.Amount) }).ToList();

Basically what I do (from inner to outer queries)

Join prescriptions with prescription types, get Medicament and the multiplied Amount
Group the records by the Medicament
Run one more select to get the overall sum from all patients

Is there any simpler way?

EDIT:

So I realised couple things and simplified the query quite a bit, I think it's much more readable now. The things I missed the first time were:

SelectMany that lets me get rid of the outter select, since prescriptions are all I care about
Being able to create new objects within group statement, hence one more select can be avoided

The new code looks like

    var prescriptions = from p in patients.SelectMany(p => p.Prescriptions)
                        join type in DatabaseService.PrescriptionTypes
                            on p.Type equals type.Value
                        group new { Amount = p.Amount * (int)type.Influence } by p.Medicament into prs
                        select new { Medicament = prs.Key,Amount = prs.Sum(pr => pr.Amount) };

With that I'm pretty happy and I doubt you can simplify it anymore.


texts: Prime numbers with array and OpenMP in C

texts:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <omp.h>

#define MAXN 10*1000*1000

int fillarray(unsigned maxn, int *p, int psize) {

    int i, top = 1;
    int n;
    p[0] = 3;
    printf(" 2\n 3\n");

    for (n = 5;; n += 2)

        for (i = 0; n % p[i] != 0; i++)

            if (p[i] * p[i] > n) {

                printf("%6d\n", n);
                p[top] = n;

                if (n * n > maxn)
                    return top;

                if (++top == psize) {
                    printf("Array too short\n");
                    return -1;
                }

                break;
           }
}

int main() {

    unsigned n, maxn = MAXN;
    int sum;

    /* Prime Number Theorem formula (x/logx) to find approx.
       size of array p[]. Needs some safety margin. */
    int psize =  10 + 1.2 * sqrt(maxn) / log(sqrt(maxn));
    int p[psize], *pp;

    int lastp = fillarray(maxn, p, psize);
    if (lastp < 0)
        return 1;

    /* "3" is p[0], plus the "2" */
    sum = lastp + 2;

    #pragma omp parallel for private(pp) schedule(guided) reduction(+:sum)

    for (n = p[lastp] + 2; n <= maxn; n += 2)

        for (pp = p; n % *pp > 0; pp++)

            if (*pp * *pp > n) {
                printf("%d\n", n);
                sum++;
                break;
            }

    printf("SUM %d (%.2f%%)\n", sum, (double) 100*sum / maxn) ;
    double lnx = maxn / log(maxn);
    printf("LnX %.2f (%f)\n",  lnx, sum / lnx);
    printf("psize %d\n", psize);
    printf("p[0] p[1]...p[%d] %d %d...%d\n", lastp, p[0], p[1], p[lastp]);

    return 0;
}

Compile with -fopenmp. And -lm for clang. But it works also without openmp.
Output:
# time ./a.out |tail
9999971
9999901
9999931
9999973
9999991
9999937
SUM 664579 (6.65%)
LnX 620420.69 (1.071175)
psize 480
p[0] p[1]...p[445] 3 5...3163

real    0m0.274s
user    0m1.497s
sys     0m0.402s

It takes 445 primes to reach 3163, whose square is > 10 million. The array size is 480. The output is not sorted, the threads print them directly.
The first (single-threaded) phase i.e. fillarray() takes no time compared to second, multi-threaded phase.
In main() the prime test is inlined, and written with pointers.


texts:
In my previous Watir question I was making a module with session_FF accepting a block.
Now I want to make the same but via RSpec. Here is my try:

require "rspec"
require "watir"

module Session_FF
  def method_missing m, *args, &block
    @browser.send m, *args, &block
  end
  def element *args
    elements = @browser.elements *args
    case elements.size
    when 1 ; elements.first
    when 0 ; raise "found no nodes using search args: #{args}"
    else   ; raise "found #{es.size} nodes -- use #elements method or improve args"
    end
  end
end

RSpec.configure do |config|
  config.include Session_FF
  config.before{ @browser ||= Watir::Browser.new :ff}
  config.after{ @browser.quit }
end

describe "it" do
  it "is alive" do
    goto "http://example.com/"
    element(class: "userpanel").click
  end
end

I see a problem, that previously I was defining method_missing in my own module but now include may redefine RSpec::Core::ExampleGroup or smth's #method_missing if it already exists or may appear in RSpec implementation. What is a better way for method_missing approach to forward browser interaction methods into @browser?


texts:
The point of this code snippet is to calculate and compare an MD5 obtained from a USB device connected to the computer against a database to check its validity.

var md5String = string.Empty;
using (var md5 = MD5.Create())
{
    var md5CRC = md5.ComputeHash(File.ReadAllBytes(destinationFilename));
    foreach (byte b in md5CRC)
        md5String += b.ToString("X2");
}

// here I check the MD5 against the database to check the usb device is valid

The code meets its purpose, but I want to know how I can improve this code.


texts: Cryptographically secure token generation in C#

texts:
Is the following a cryptographically secure way to generate a random token? Does it have any of the predictability risks that are theoretically associated with using a GUID as a token?

using System;
using System.Security.Cryptography;

namespace myApp
{
    class Program
    {
        static void Main(string[] args)
        {
            byte[] bytes = new byte[32];
            using (var rng = new RNGCryptoServiceProvider()) {
                rng.GetBytes(bytes);
            }

            string hexToken = BitConverter.ToString(bytes).Replace("-", "").ToLower();
            Console.WriteLine(hexToken);
        }
    }
}


texts: Circular buffer offsets and sorted set of offsets sorted on their index

texts:
Consider the following C++03 code:

#include <algorithm>
#include <deque>
#include <boost/iterator/counting_iterator.hpp>

const unsigned int _count = 0x10000;

struct recentFunctor {
  recentFunctor(const int base, const int firstOffset)
    : _base(base),
      _firstOffset(firstOffset) {
  }

  int getIndex(const int offset) const {
    return _base + _normalize(offset - _firstOffset);
  }

  bool operator()(const int offsetA, const int offsetB) const {
    return getIndex(offsetA) < getIndex(offsetB);
  }

private:
  int _normalize(const int offset) const {
    // Make negative offsets positive like math modulo.
    // Assumes _count is 0x10000.
    return int(static_cast<uint16_t>(offset));
  }

  const int _base;
  const int _firstOffset;

};

// Insert the inclusive range [beginOffset, lastOffset] into the recentItems
// ordered deque of offsets.  The offsets are into a circular array of 65,536
// items, so the range may wrap around.  The ordering of the offsets is based
// upon the index that corresponds to each offset.  For example, a beginOffset
// of 65,000 and a lastOffset of 100 means to insert the range of offsets
// [65000, 65535] into the deque at insertionPoint followed by the range of
// offsets [0, 100] and the beginOffset of 65,000 may correspond to an index of
// 65,000 but the lastOffset of 100 could correspond to an index of 65636 for
// the first time the circual buffer to which these offsets refer wraps around.

void
insertRecentRange(const int beginOffset,
                  const int lastOffset,
                  const int currentBase,
                  const int currentFirstOffset,
                  std::deque<int>::iterator insertionPoint,
                  std::deque<int> &recentItems)
{
  // The recentItems is an ordered set of offsets that have been noted.

  if (beginOffset <= lastOffset) {
    recentItems.insert(insertionPoint,
                       boost::counting_iterator<int>(beginOffset),
                       boost::counting_iterator<int>(lastOffset + 1));
  } else {
    // Fix this in C++11, for now insert() does not return what we want so we
    // must call lower_bound() to compute it:
    recentItems.insert(insertionPoint,
                       boost::counting_iterator<int>(beginOffset),
                       boost::counting_iterator<int>(int(_count)));

    std::deque<int>::iterator firstInsert
      = std::lower_bound(recentItems.begin(), recentItems.end(), beginOffset,
                         recentFunctor(currentBase, currentFirstOffset));

    recentItems.insert(firstInsert + (int(_count) - beginOffset),
                       boost::counting_iterator<int>(0),
                       boost::counting_iterator<int>(lastOffset + 1));
  }
}

While working in C++03, is there any way to perform the insert() and not have to call lower_bound() to compute a follow on insertion point for the remaining offsets?  Can this code be made easier to understand without changing the underlying data structures?  Any other suggestions to improve this?


texts:
I wrote a program for a problem in Harvard's CS50 course, Vigenere (week 2).

Here is a description of what the program needs to do:

  Design and implement a program that encrypts messages using Vigenère’s cipher.

  Implement your program in a file called vigenere.c in a directory
  called vigenere.
  Your program must accept a single command-line argument: a keyword, k, composed entirely of alphabetical characters.
  If your program is executed without any command-line arguments, with more than one command-line argument, or with one command-line argument that contains any non-alphabetical character, your program should print an error (of your choice) and exit immediately, with main returning 1 (thereby signifying an error).
  Otherwise, your program must proceed to prompt the user for a string of plaintext, p, (as by a prompt for plaintext:) which it must then encrypt according to Vigenère’s cipher with k, ultimately printing the result (prepended with ciphertext: and ending with a newline) and exiting, with main returning 0.
  With respect to the characters in k, you must treat A and a as 0, B and b as 1, …, and Z and z as 25.
  Your program must only apply Vigenère’s cipher to a character in p if that character is a letter. All other characters (numbers, symbols, spaces, punctuation marks, etc.) must be outputted unchanged. Moreover, if your code is about to apply the jth character of k to the ith character of p, but the latter proves to be a non-alphabetical character, you must wait to apply that jth character of k to the next alphabetical character in p; you must not yet advance to the next character in k.
  Your program must preserve the case of each letter in p.

I received full credit for my answer, but I still want to clean up the code if possible. I am new to programming, so I enjoy seeing what changes more experienced programmers would make.

#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

int check(string argv);
int shift(char c);

int main(int argc, string argv[])
{
    //check for valid key and save
    int valid = 0;
    if (argc == 2)
    {
        valid = check(argv[1]);
    }
    else
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }

    //begin encryption
    int key;
    int index = -1;
    int new_code;
    if (valid == 1)
    {
        //get plaintext to encrypt
        string plaintext = get_string("plaintext: ");
        printf("ciphertext: ");

        //iterate through each char of plaintext
        for (int j = 0, l = strlen(plaintext); j < l; j++)
        {
            if (isalpha(plaintext[j]))
            {
                //iterate through the keyword only when there is an alpha in the plaintext
                index++;
                key = shift(tolower(argv[1][index % strlen(argv[1])]));
                new_code = (int) plaintext[j] + key;
                if ((int) tolower(plaintext[j]) + key > 122)
                {
                    new_code = new_code - 26;
                    printf("%c", (char) new_code);
                }
                else
                {
                    printf("%c", (char) new_code);
                }
            }
            else
            {
                printf("%c", (char) plaintext[j]);
            }
        }
        printf("\n");
    }
    else
    {
        printf("Usage: ./vigenere keyword\n");
        return 1;
    }
}

//create key
int shift(char c)
{
    int key = (int) c - 97;
    return key;
}

//decide if key is valid
int check (string argv)
{
    int val = 0;
    for (int i = 0, n = strlen(argv); i < n; i++)
    {
        if (isalpha(argv[i]))
        {
            val = 1;
        }
        else
        {
            val = 0;
            break;
        }
    }
    return val;
}


texts: Bank account model implementation in Django

texts:
There is a draft of my models.py. What can I do for code quality and readability increase?

from datetime import timedelta

from django.contrib.auth.models import User
from django.db import models
from django.utils import timezone

class Rule(models.Model):
    start_date = models.DateField()
    end_date = models.DateField()

    deposit_percent = models.FloatField()
    credit_percent = models.FloatField()

    @staticmethod
    def on_date(_date):
        return Rule.objects.get(start_date__lte=_date, end_date__gte=_date)

class BankAccount(models.Model):

    LEGAL = 1
    NATURAL = 2

    DEBET = 1
    CREDIT = 2

    owner_type = models.PositiveSmallIntegerField(choices=(
        (LEGAL, 'Физическое лицо'),
        (NATURAL, 'Юридическое лицо'),
    ))

    method = models.PositiveSmallIntegerField(choices=(
        (DEBET, 'Дебет'),
        (CREDIT, 'Кредит'),
    ))

    name = models.CharField(max_length=254)
    owner = models.ForeignKey(User, related_name='w_accounts')
    spectators = models.ManyToManyField(User, related_name='r_accounts')
    when_opened = models.DateField()

    @property
    def balance(self):
        assert self.method == self.DEBET
        today = timezone.now()
        rule = Rule.on_date(self.when_opened)
        result = 0
        current_date = self.when_opened
        while current_date <= today:
            result -= sum(x.total for x in self.cashing_set.on_date(current_date))
            result -= sum(x.total for x in self.outcome_transfers.on_date(current_date))
            result += sum(x.total for x in self.deposit_set.on_date(current_date))
            result += sum(x.total for x in self.income_transfers.on_date(current_date))
            result *= 1 + rule.deposit_percent * 0.01
            current_date += timedelta(days=1)
        return result

    @property
    def debt(self):
        assert self.method == self.CREDIT
        today = timezone.now()
        rule = Rule.on_date(self.when_opened)
        result = 0
        current_date = self.when_opened
        while current_date <= today:
            result += sum(x.total for x in self.cashing_set.on_date(current_date))
            result += sum(x.total for x in self.outcome_transfers.on_date(current_date))
            result -= sum(x.total for x in self.deposit_set.on_date(current_date))
            result -= sum(x.total for x in self.income_transfers.on_date(current_date))
            result *= 1 + rule.credit_percent
            current_date += timedelta(days=1)
        return result

class OperationManager(models.Manager):

    def on_date(self, date):
        return (super(OperationManager, self).get_queryset()).filter(when__gte=date, when__lte=date)

class MoneyTransfer(models.Model):
    sender = models.ForeignKey(BankAccount, related_name='outcome_transfers')
    receiver = models.ForeignKey(BankAccount, related_name='income_transfers')
    when = models.DateTimeField()
    total = models.FloatField()
    comment = models.CharField(max_length=255)

    objects = OperationManager()

class Deposit(models.Model):
    account = models.ForeignKey(BankAccount)
    total = models.FloatField()
    banker = models.ForeignKey(User)
    when = models.DateTimeField()

    objects = OperationManager()

class Cashing(models.Model):
    account = models.ForeignKey(BankAccount)
    total = models.FloatField()
    banker = models.ForeignKey(User)
    when = models.DateTimeField()

    objects = OperationManager()


texts: Refactoring conditions in text parsing method

texts:
I am writing a generic text parser and have come up with the following text parsing algorithm, which works fine. I'm wondering how to refactor the following method to make it easily understandable and maintainable for the future. It has chains of conditions and nested if-else blocks to compare with each text line to find matching criteria. Any ideas or comments would be highly appreciated ...

private void seekContents (String currentLine, String fontCurrentLine, String pdfContentPageNumber, String currentSearchToken) throws Exception

{
boolean isTokensToSkip=regCompare.isTokensToSkip(currentLine);
boolean isLinesToSkip=regCompare.isLinesToAvoid(currentLine);
boolean isTokensToStop=regCompare.isTokensToStop(currentLine);
boolean isKeywordToSeekAfterToken= regCompare.isKeywordPatternsToSeekAfterToken(currentLine);

boolean isKeywordPatternToSeekAfterTokenExists=regCompare.isKeywordPatternToSeekAfterTokenExists();

boolean hasFont=regCompare.hasLineFont(fontCurrentLine);
boolean isFileHeader=regCompare.isFileHeader(currentLine);
boolean isFileFooter=regCompare.isFileFooter(currentLine);

String pageNumber=regCompare.hasPageNumber(currentLine);
String hasContentPatternToSeekAfterToken = regCompare.hasContentPatternsToSeekAfterToken(currentLine);
String hasRegexTokensToSkip=regCompare.hasRegexTokensToSkip(currentLine);
String hasRegexTokenToStop=regCompare.hasRegexTokensToStop(currentLine);
String hasRegexTokenToAvoid = regCompare.hasRegexTokensToAvoid(currentLine);

if(isFileHeader||isFileFooter||isLinesToSkip)
{
    //System.out.println("Skipped the header/footer/lines to skip!");
}
else if(hasRegexTokenToAvoid!=null)
{
    //System.out.println("Skipped the Regex line!");
}

else if(pageNumber!=null)
{
    //System.out.println("Found the page#");
}
else if(isTokensToSkip)
{
    isSearchTokenFound=false;
}
else if(hasRegexTokensToSkip!=null)
{
    //System.out.println("Did i found regex stopper?");
    isSearchTokenFound=false;
}
else if(isTokensToStop)
{
    isSearchTokenFound=false;
    isParserEngineStop=true;
}
else if(hasRegexTokenToStop!=null)
{
    isSearchTokenFound=false;
    isParserEngineStop=true;
}
else
{
    //check for content pattern match

    if(hasContentPatternToSeekAfterToken!=null)
    {
        isContentPatternFound=true;

        if(isKeywordPatternToSeekAfterTokenExists)
        {
            contentPattern=hasContentPatternToSeekAfterToken;
            isKeywordAfterPatternFound=false;
        }
        else
        {
            keepRecordsNoKeywordPatternToSeekAfterTokenExists(hasContentPatternToSeekAfterToken,pdfContentPageNumber,currentSearchToken,currentLine);
        }
    }
    else
    {
        if(isContentPatternFound)
        {
            if(isKeywordPatternToSeekAfterTokenExists)
            {
                if(isKeywordToSeekAfterToken)
                {
                    keepRecordsKeywordToSeekAfterToken(contentPattern,pdfContentPageNumber,currentSearchToken,currentLine);
                    isKeywordAfterPatternFound=true;
                }
                else
                {
                    if(isKeywordAfterPatternFound)
                    {
                        desiredContents.add(currentLine);
                    }
                }
            }
            else
            {
                desiredContents.add(currentLine);
            }
        }
    }
}

}


texts:
I want to improve this code. How to enter all elements in linked list simultaneously? I have not written code to delete a node becauseI want to only merge list for learning purpose.

#include <iostream>
#include <utility>

template<class T>
class LinkedList
{
  struct Node
  {
    T data;
    Node * next = nullptr;
    Node()          : data(), next(nullptr) {}
    Node(T&& value) : data(std::move(value)), next(nullptr) {}
  };

  Node *head;
public:
  LinkedList() : head(nullptr) {}
  LinkedList(const LinkedList& ll) = delete; //copy constructor
  LinkedList& operator=(const LinkedList& ll) = delete; //copy assignment
  ~LinkedList()
  {
    Node *tmp = nullptr;
    while(head)
    {
      tmp = head;
      head = head->next;
      delete tmp;
    }
    head = nullptr;
  }

   void insert(T&& value)
   {
    Node *node = new Node(std::move(value));
    Node *tmp = head;
    if(tmp == nullptr)
    {
      head = node;
    }
    else
    {
      while(tmp->next != nullptr)
      {
        tmp = tmp->next;
      }
      tmp->next = node;
    }
  }

  void mergeSortedList(LinkedList<T>& ll2)
  {
    Node *node = new Node();
    node->next = nullptr;
    Node *tmp = nullptr;
    tmp = node;

    Node *head1 = head;
    Node *head2 = ll2.head;

    while(head1 != nullptr && head2 != nullptr)
    {
      if(head1->data <= head2->data)
      {
        tmp->next = head1;
        tmp = tmp->next;
        head1 = head1->next;
      }
      else
      {
        tmp->next = head2;
        tmp = tmp->next;
        head2 = head2->next;
      }
    }
    while(head1 != nullptr && head2 == nullptr)
    {
      tmp->next = head1;
      tmp = tmp->next;
      head1 = head1->next;
    }
    while(head2 != nullptr && head1 == nullptr)
    {
      tmp->next = head2;
      tmp = tmp->next;
      head2 = head2->next;
    }
    tmp = tmp->next;
    delete tmp;

    // head of the new list
    head = node->next;
  }

  void printList()
  {
    Node *node = head;
    if(node == nullptr)
    {
      std::cout << "Empty List \n";
    }
    while(node != nullptr)
    {
      std::cout << node->data << " ";
      node = node->next;
    }
    std::cout << "\n";
  }
};

int main()
{
  LinkedList<int> ll1;
  ll1.insert(5);
  ll1.insert(10);
  ll1.insert(18);
  ll1.insert(25);
  std::cout << "List 1 : ";
  ll1.printList();

  LinkedList<int> ll2;
  ll2.insert(6);
  ll2.insert(8);
  ll2.insert(11);
  ll2.insert(20);
  ll2.insert(23);
  ll2.insert(28);
  ll2.insert(40);
  std::cout << "List 2 : ";
  ll2.printList();

  ll1.mergeSortedList(ll2);
  std::cout << "Merged List : ";
  ll1.printList();
}


texts: Custom event trigger and listener module

texts:
I am working on a data collection JavaScript library, and would like other members of my organization to be able to write loosely coupled plugins to extend its core functionality. I've been working on a trigger\listener (or publish\subscription) module for it and would love some feedback.

Particularly any potential unexpected pitfalls or performance gotchas I might be missing. This has the potential to be on a very heavily trafficked site and need some more eyes on it.

var eventDispatcher = (function() {
    var eventListeners = {};

    var _listener = function(eventKey, listener) {
        // Create the event's object if not yet created.
        eventListeners[eventKey] = eventListeners[eventKey] || [];

        // Add the listener to the queue
        var index = eventListeners[eventKey].push(listener) - 1;

        return {
            remove: function() {
                delete eventListeners[eventKey][index];
            }
        }
    }

    var _trigger = function(eventKey, info) {
        // If the event doesn't exist then there are no listeners in the queue, just leave.
        if(!eventListeners[eventKey]) return;

        // Cycle through event queue and fire listeners.
        eventListeners[eventKey].forEach(function(item) {
            item(typeof info !== 'undefined' ? info : {});
        });
    }

    return {
        'on'        : _listener
      , 'trigger'   : _trigger
    }
})();


texts:
I thought of doing the following to mock/test functions in Go and wanted some advice. Let's say you have an interface for a repository:
    type Creator interface {
        CreateUser(User) (*User, error)
    }

    type Updater interface {
        UpdateUser(User) (*User, error)
    }

    type Retreiver interface {
        GetUserByEmail(string) (*User, error)
        GetUserByID(uint) (*User, error)
    }

    type Repository interface {
        Creator
        Updater
        Retreiver
    }

The mock interface implements the Repository interface. It provides mock functions that can be swapped out depending on the test:
type MockUserRepo struct {
    CreateUserMock     func(user.User) (*user.User, error)
    UpdateUserMock     func(user.User) (*user.User, error)
    GetUserByEmailMock func(string) (*user.User, error)
    GetUserByIDMock    func(uint) (*user.User, error)
}

func (m *MockUserRepo) CreateUser(u user.User) (*user.User, error) {
    return m.CreateUserMock(u)
}

func (m *MockUserRepo) UpdateUser(u user.User) (*user.User, error) {
    return m.UpdateUserMock(u)
}

func (m *MockUserRepo) GetUserByEmail(s string) (*user.User, error) {
    return m.GetUserByEmailMock(s)
}

func (m *MockUserRepo) GetUserByID(i uint) (*user.User, error) {
    return m.GetUserByIDMock(i)
}

Then in the test function, you can create a mock for the single function that can be called. This can sometimes cause a nil pointer error if the function wasn't implemented/mocked by the testcase.
mockUserRepo := &MockUserRepo{
    GetUserByEmailMock: func(s string) (*user.User, error) {
        return nil, user.ErrUserDoesNotExist
   },
}

Any thoughts on if this is a bad/good practice?


texts: Calculate expiration date based on server data

texts:
This code yet is not really optimize and I know that . But for now this is all I have.

What this code does is that it computes the expiration date of an account.

By the way I need to do the swapping workaround because the date that the server gives to me are inverted so I need to do a lil workaround about that.

    /// <summary>
    /// Add revalidation text and how many days the agents account will expire
    /// </summary>
    public async void RevalidateAccount()
    {
        //Get Stored Persistent Data of Date
        string _expDateFromPersistent = await SecureStorage.GetAsync("ExpirationDate");

        //Check if empty or not
        //because if it is empty we need to hide the validation text first
        //then show it after relogging in
        if (!string.IsNullOrEmpty(_expDateFromPersistent))
        {
            IsVisibleValidationText = true;
            //Convert string date to DateTime
            DateTime expDate = Convert.ToDateTime(_expDateFromPersistent);
            DateTime todayDate = DateTime.Now;
            //Change Format
            string _dateToday = todayDate.ToString("yyyy/MM/dd", CultureInfo.InvariantCulture);

            //Swap workaround
            string day = expDate.Day.ToString();
            string month = expDate.Month.ToString();
            string year = expDate.Year.ToString();
            string _expirationDate = year + "/" + day + "/" + month;
            //Calculation
            TimeSpan expirationDate = DateTime.Parse(_expirationDate) - DateTime.Parse(_dateToday);
            //Business Rule: 7 days prior to 30 days show the revalidation text
            if (expirationDate.Days <= 7)
            {
                if (IsVisibleValidationText)
                {
                    //Formatted Text for validation text
                    Revalidate = new FormattedString();
                    Revalidate.Spans.Add(new Span { Text = "You have ", ForegroundColor = Color.FromHex(_textColor), FontSize = 15 });
                    Revalidate.Spans.Add(new Span { Text = $"{expirationDate.Days} days", ForegroundColor = Color.FromHex(_textColor), FontSize = 15, FontAttributes = FontAttributes.Bold });
                    Revalidate.Spans.Add(new Span { Text = " left before you need \n to re-validate your login credentials.", ForegroundColor = Color.FromHex(_textColor), FontSize = 15 });
                    await _pageDialogService.DisplayAlertAsync("NOTICE", "You have " + expirationDate.Days + " days left before you need to re-validate your login credentials.", "OK");
                }
            }
        }
        else
        {
            IsVisibleValidationText = false;
        }
    }

What my code does is that it gets the data(Expiration Date) from the server then I just need to differ the DateTime.Now and the date(expiration date) from the server to have an expiration date.


texts: Advent of Code 2016 Day 1 "No Time for a Taxicab"

texts:
I already solved it in JavaScript, where I'm more comfortable. I pretty much ported the algorithm from there.

I wanted to try the first Advent of Code puzzle in a new language and I picked Racket.

It's a taxicab geometry navigation problem. Given input R3, L5 you:

turn right 90 degrees
move forward 3 steps
turn left 90 degrees
move forward 5 steps

The goal: at the end of the instructions:

  how far are you from the start?

It's my first Racket program. I've read around Lisps but not written much. How could I improve it?

#lang racket

; convert "L1" to '(#\L 1)
(define (parse step)
  (let ([dir (string-ref step 0)]
        [distance (string->number (substring step 1))])
    (list dir distance)))

; given a direction (#\L or #\R) and the last heading 0-3,
; compute the heading after the next step
(define (get-heading dir last-heading)
  (define raw
    (match dir
      [#\L (+ last-heading 1)]
      [#\R (- last-heading 1)]))
  (modulo raw 4))

; compute the x coordinate after the next step
(define (get-x heading last-x distance)
  (match heading
    [1 (+ last-x distance)]
    [3 (- last-x distance)]
    [_ last-x]))

; compute the y coordinate after the next step
(define (get-y heading last-y distance)
  (match heading
    [0 (+ last-y distance)]
    [2 (- last-y distance)]
    [_ last-y]))

; iterate over the instructions, computing
; x, y and heading after each step
(define (walk steps)
  (define-values (x y _)
    (for/fold
        ([x 0] [y 0] [heading 0])
        ([step steps])
      (match-define (list dir distance) step)
      (let* ([next-heading (get-heading dir heading)]
             [next-x (get-x next-heading x distance)]
             [next-y (get-y next-heading y distance)])
        (values next-x next-y next-heading))))
    (+ (abs x) (abs y))
  )

;;;; input
(define input "R3, L5, R1, R2, L5, R2, R3, L2, L5, R5, L4, L3, R5, L1, R3, R4, R1, L3, R3, L2, L5, L2, R4, R5, R5, L4, L3, L3, R4, R4, R5, L5, L3, R2, R2, L3, L4, L5, R1, R3, L3, R2, L3, R5, L194, L2, L5, R2, R1, R1, L1, L5, L4, R4, R2, R2, L4, L1, R2, R53, R3, L5, R72, R2, L5, R3, L4, R187, L4, L5, L2, R1, R3, R5, L4, L4, R2, R5, L5, L4, L3, R5, L2, R1, R1, R4, L1, R2, L3, R5, L4, R2, L3, R1, L4, R4, L1, L2, R3, L1, L1, R4, R3, L4, R2, R5, L2, L3, L3, L1, R3, R5, R2, R3, R1, R2, L1, L4, L5, L2, R4, R5, L2, R4, R4, L3, R2, R1, L4, R3, L3, L4, L3, L1, R3, L2, R2, L4, L4, L5, R3, R5, R3, L2, R5, L2, L1, L5, L1, R2, R4, L5, R2, L4, L5, L4, L5, L2, L5, L4, R5, R3, R2, R2, L3, R3, L2, L5")
(define steps
  (map parse
    (string-split input ", ")))

;;;; run
(walk steps)


texts: Google FooBar Level 3 - Shortest path to 1

texts:
I recently found the Google Foobar challenges and am having a problem with level 3. The goal of the task is the find the minimum number of operations needed to transform a group of pellets down into 1, while following these rules:

  1) Add one fuel pellet

  2) Remove one fuel pellet

  3) Divide the entire
  group of fuel pellets by 2 (due to the destructive energy released
  when a quantum antimatter pellet is cut in half, the safety controls
  will only allow this to happen if there is an even number of pellets)

My code is as follows:

from math import log, ceil, floor
def answer(n):
    steps = 0
    steps_taken = " => {}"
    all_steps = "{}".format(n)
    n = int(n)
    if n < 1:
        return 0
    while n > 1:
        if n == 3:
            n -= 1
            all_steps += steps_taken.format(n)
            steps += 1
        elif n % 2 == 1:
            if n + 1 == 2**closest_power(n+1):
                n += 1
                all_steps += steps_taken.format(n)
            elif n - 1 == 2**closest_power(n-1):
                n -= 1
                all_steps += steps_taken.format(n)
            else:
                n -= 1
                all_steps += steps_taken.format(n)
            steps += 1
        else:
            n = n / 2
            all_steps += steps_taken.format(n)
            steps += 1

    print all_steps
    return steps

def closest_power(x):
    possible_results = floor(log(x, 2)), ceil(log(x, 2))
    return int(min(possible_results, key= lambda z: abs(x-2**z)))

This manages to perform the two test cases provided:

Inputs:

(string) n = "4"

Output:

(int) 2

Inputs:

(string) n = "15"

Output:

(int) 5

But it fails on others, that Google doesn't make available. Since I don't have access to the failing test cases, I'm looking for performance suggestions.

Right now the code is making the following assumptions:

If the number is even, divide it by two. This should reduce the amount of space left to reach 1
If a number is odd, check if the next and previous numbers are a power of 2. If so, add or subtract one to get to that number. Since powers of 2 can be divided repeatedly, there will be no more adding/subtracting of pellets
If neither neighbor is a power of two, subtract one. I am betting this is the assumption that is causing problems. I don't have the mathematical background to provide it, but my thought was that moving closer to 1 is better.
If the number is 3, subtract 1. Since both of its neighbors are a power of two, this is a special case. Additionally, moving from 3->2->1 is shorter than 3->4->2->1.


texts:
The Task:

  Given a set of closed intervals, find the smallest set of numbers that
  covers all the intervals. If there are multiple smallest sets, return
  any of them.

  For example, given the intervals [0, 3], [2, 6], [3, 4], [6, 9], one
  set of numbers that covers all these intervals is {3, 6}.

My solution:

const intervalls = [[0, 3], [2, 6], [3, 4], [6, 9]];
const getLargestMinAndSmallestMax = (acc, intervall, _, src) => {
    if (src.length === 0) { return []; }
    if (src.length === 1) { return intervall; }
    if (acc[1] === undefined || intervall[0] > acc[1]) {
      acc[1] = intervall[0];
    }
    if (acc[0] === undefined || intervall[1] < acc[0]) {
      acc[0] = intervall[1];
    }
    return acc;
  };
const smallestIntervallCoveringAllIntervalls = list => list.reduce(getLargestMinAndSmallestMax, []);

console.log(smallestIntervallCoveringAllIntervalls(intervalls));

Is there a faster and cleaner version of it?


texts: Finding users with the highest Following vs. Friends ratio

texts:
I am trying to find the users who have the highest "Following vs. Friends" ratio in my Twitter timeline.

I have a SQLite database of the users in my Twitter timeline and each column contains data found in the user section of the tweet JSON.

Is there a better way that I could write this search query?

Why does it return zero when the user has a higher friends count than followers count?

Is there a way to shorten this search query?

SELECT CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL), screen_name FROM following
ORDER BY CAST(
    CAST(followers_count AS DECIMAL)/ CAST(friends_count AS DECIMAL)
AS INT)
DESC LIMIT 25;


texts: The Odin Project - Project Ruby: Translating from English to Pig Latin

texts:
I just finished the pig latin translator for The Odin Project and I would appreciate some honest feedback for my code. The code is intended to be "test-driven learning", and therefore emulates test driven development.

Here is the prompt:

Pig Latin is a made-up children's language that's intended to be confusing. It obeys a few simple rules (below) but when it's spoken quickly it's really difficult for non-children (and non-native speakers) to understand.

Rule 1: If a word begins with a vowel sound, add an "ay" sound to the end of the word.

Rule 2: If a word begins with a consonant sound, move it to the end of the word, and then add an "ay" sound to the end of the word.

(There are a few more rules for edge cases, and there are regional variants too, but that should be enough to understand the tests.)

Here is the test spec:

require "pig_latin"

describe "#translate" do

  it "translates a word beginning with a vowel" do
    s = translate("apple")
    expect(s).to eq("appleay")
  end

  it "translates a word beginning with a consonant" do
    s = translate("banana")
    expect(s).to eq("ananabay")
  end

  it "translates a word beginning with two consonants" do
    s = translate("cherry")
    expect(s).to eq("errychay")
  end

  it "translates two words" do
    s = translate("eat pie")
    expect(s).to eq("eatay iepay")
  end

  it "translates a word beginning with three consonants" do
    expect(translate("three")).to eq("eethray")
  end

  it "counts 'sch' as a single phoneme" do
    s = translate("school")
    expect(s).to eq("oolschay")
  end

  it "counts 'qu' as a single phoneme" do
    s = translate("quiet")
    expect(s).to eq("ietquay")
  end

  it "counts 'qu' as a consonant even when it's preceded by a consonant" do
    s = translate("square")
    expect(s).to eq("aresquay")
  end

  it "translates many words" do
    s = translate("the quick brown fox")
    expect(s).to eq("ethay ickquay ownbray oxfay")
  end

  # Test-driving bonus:
  # * write a test asserting that capitalized words are still capitalized (but with a different initial capital letter, of course)
  # * retain the punctuation from the original phrase

end

Finally, here is my code:

def translate(phrase) #translates individual words or multiple words into pig latin
  new_phrase = []
  if phrase.include? " "
    new_phrase = phrase.split(" ").map do |word|
      rearrange(word)
    end
    new_phrase = new_phrase.join(" ")
  else
    new_phrase = rearrange(phrase)
  end
  new_phrase
end

def rearrange(word) #rearranges individual words into pig latin
  vowels = ["a", "e", "i", "o", "u", "y"]
  new_word = word
  word.each_char do |char|
    if char == "u" && new_word[-1] == "q"
      new_word << "u"
      new_word.slice!(0)
      next
    elsif vowels.include? char
      new_word << "ay"
      break
    else
      new_word << char
      new_word.slice!(0)
      next
    end
  end
  new_word
end


texts:
My implementation of a binary-to-bits converting function:

#include <stdio.h>
#include <limits.h>

unsigned char *return_byte (unsigned char source)
{
    static unsigned char byte[CHAR_BIT];
    unsigned char *p = byte, i;

    for(i = 0; i < CHAR_BIT; i++)
        p[i] = '0' + ((source & (1 << i)) > 0);

    return p;
}

int main(void)
{
    unsigned char val = 200;

    printf("Value:\t%i\nBinary:\t%s", val, return_byte(val));

    return 0;
}

Output:

Value:  200
Binary: 00010011


texts: CodedUi method which checks all cells in certain column

texts:
I have the following extension method which checks all cells for values in a table column with the specified header name:

public static bool AllCellsInColumnHaveValue(this HtmlTable table, string columnName)
{
    // Find the columnindex of the specified column name
    var cell = new HtmlHeaderCell(table);
    cell.SearchProperties.Add(new PropertyExpression
        (UITestControl.PropertyNames.FriendlyName, columnName, PropertyExpressionOperator.Contains));
    var columnIndex = cell.ColumnIndex;

    // Check all cells in the column if they have a value
    foreach (var row in table.Rows)
    {
        var tableCells = row.GetChildren();

        if (string.IsNullOrWhiteSpace(tableCells[columnIndex].FriendlyName))
        {
            return false;
        }
    }

    // If we get here all rows in the column contain a value
    return true;
}

Is there a way to improve this method?


texts: Single consumer and single producer lock-free circular buffer

texts:
I'm pretty new to multithreading. The code below is a simple implementation of a single consumer/single producer circular buffer that does not use any locking, that I wrote for fun.

The question is, will this kind of container work in actual real world situation or would it crash miserably because of some data race that I have not noticed?

#include <array>
#include <memory>
#include <atomic>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <random>

template<typename T, int S=5>
class CircularBuffer{
public:
  CircularBuffer():start(0),end(0){
  }
  bool AddElement(std::unique_ptr<T> && obj,bool block=true){

    int end_idx=end.load();
    if(block)
      while(end_idx+1==start.load());//Busy wait until there is place
    else if(end_idx+1==start.load())
      return false;

    buffer[end_idx++]=std::move(obj);
    if(end_idx==buffer.size())
      end.store(0);
    else
      end.store(end_idx);
    return true;
  }
  std::unique_ptr<T> GetElement(bool block=true){
      int start_idx=start.load();
      if(block)
        while(end.load()==start_idx);
      else if(end.load()==start_idx)
        return std::unique_ptr<T>();

      auto ret_obj=std::move(buffer[start_idx]);
      start_idx++;
      if(start_idx==buffer.size())
    start.store(0);
      else
    start.store(start_idx);
      return ret_obj;
  }

private:
  std::array<std::unique_ptr<T>,S+1> buffer;
  std::atomic<int> start;
  std::atomic<int> end;

};

std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0,500);

void Producer(CircularBuffer<int> * buffer){

  int i=0;
  while(i<20){
    std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
    auto val=dis(gen);
    std::cout << "Adding " << val <<std::endl;
    buffer->AddElement(std::unique_ptr<int>(new int(val)));
    i++;
  }
}
void Consumer(CircularBuffer<int> * buffer){

  int i=0;
  while(i<20){
    std::this_thread::sleep_for(std::chrono::milliseconds(dis(gen)));
    std::cout << "Got " << *buffer->GetElement() << std::endl;
    i++;
  }

}

int main(){

  CircularBuffer<int> buffer;

  std::thread t[2];
  t[0]=std::thread(Producer,&buffer);
  t[1]=std::thread(Consumer,&buffer);

  t[0].join();
  t[1].join();
}


texts:
Given a list of words, this program outputs the starting letters of the words capitalized.

I was reviewing this question that solves the same task, but over time so many changes accumulated, that I think my programme bears little resemblance to the original one, so instead of posting it as an answer, I ask you for further improvement.

#include <stdio.h>
#include <ctype.h>
#include <stdbool.h>
#include <string.h>
#include <stdlib.h>

const int NAME_LEN = 160 + 1;

bool is_letter(char ch)
{
    return ch >= 'a' && ch <= 'z';
}

bool is_terminating_char(char ch)
{
    return ch == '\n' || ch == '\0';
}

const char * first_letters_only_capitalized(char words[NAME_LEN]) {

    char *capitals = malloc(sizeof(char) * NAME_LEN);
    int pos = -1;

    for(int i = 0; ! is_terminating_char(words[i]); i++)
    {
        capitals[++pos] = is_letter(words[i]) ? toupper(words[i]) : words[i];

        while (is_letter(words[i]))
        {
            i++;
        }
    }

    capitals[++pos] = '\0';

    return capitals;
}

int main()
{
    char user_name[NAME_LEN], user_initials[NAME_LEN];

    puts("Enter your name, I will output the initials capitalized: ");
    if ( ! fgets(user_name, NAME_LEN, stdin))
    {
        puts("Error reading input.");
        return 1;
    }

    strcpy(user_initials, first_letters_only_capitalized(user_name));
    printf("%s\n", user_initials);
}

Example session:

Enter your name, I will output the initials capitalized:
foo bar buz
FBB


texts:
I'm working on a project for an Intro to C/Python class and am looking to improve the efficiency of the program. The program is a lottery simulation where the user inputs the number of tickets they want to buy, then generates tickets, and finally outputs the total winnings and net gain (usually loss).

This is my code (in Python, as required):

def main():

    numb_tickets = int(input("How many tickets would you like to buy?\n"))

    #Calculate Winnings
    winnings = 0

    for i in range(numb_tickets):

        #For testing only, gives feedback progress of program
        print(i,"     ",winnings)

        #Creating winning ticket/your ticket, find number of matches
        win_tic = getRandomTicket(MAX_VALUE, TIX_SIZE)
        my_tic = getRandomTicket(MAX_VALUE, TIX_SIZE)
        numb_win = numMatches(win_tic, my_tic)

        #Add appropriate payout for number of matches
        if numb_win == 6:
            winnings += WIN_SIX
        elif numb_win == 5:
            winnings += WIN_FIVE
        elif numb_win == 4:
            winnings += WIN_FOUR
        elif numb_win == 3:
            winnings += WIN_THREE

    #Calculate cost of purchasing tickets
    cost_tics = numb_tickets * COST_TIC

    if winnings >= cost_tics:
        profit = winnings - cost_tics
        print("You won $",winnings,", for a net earnings of $",profit,".", sep="")
    elif winnings < cost_tics:
        loss = cost_tics - winnings
        print("You won $",winnings,", for a net loss of $",loss,".", sep="")

main()

Note: the getRandomTicket() and numMatches() functions were provided by the professor to generate a lottery ticket and check the number of matches it has, respectively.

My program works fine for smaller numbers of tickets, but when testing the required 1,000,000 tickets, takes a massive amount of time. It makes sense that the time increases rapidly as the range of the loop increases, but I don't know of a better way to loop this yet. Any input or suggestions are greatly appreciated.


texts: Transforming full names to surname and initial

texts:
I have a large data frame that I want to merge with another dataset. In order to do so I need to get the names of individuals into a certain format. The function below converts the name in 'column' to the desired format (mostly) and stores it in newColumn.

My question is, is there a better (faster and/or more pythonic) way to do this?

The main aim is to transform full names into surname and initials, such as:

Novak Djokovic = Djokovic N.
Jo-Wilfred Tsonga = Tsonga J.W.
Victor Estrella Burgos = Estrella Burgos V.
Juan Martin Del Potro = Del Potro J.M.

def convertNames(df,column, newColumn):
    df[newColumn] = 'none'

    for player in df[column]:

        names = player.split(' ')

        if len(names) == 2:

            if (len(names[0].split('-')) > 1):
                newName = names[1]+' '+names[0].split('-')[0][0]+'.'+names[0].split('-')[1][0]+'.'
            else:
                newName = names[1]+' '+names[0][0]+'.'

        elif len(names) == 3:
            newName = names[1]+' '+names[2]+' '+names[0][0]+'.'

        else:
            newName = names[2]+' '+names[3]+' '+names[0][0]+'.'+names[1][0]+'.'

        df[newColumn][df[column] == player] = newName

    return df


texts: Archiving content in SharePoint libraries

texts:
I have the following using statement, used specifically for the purpose of archiving content in SharePoint libraries. In this statement my objects are disposed in two places:

finally
{
    web.Dispose();
    site.Dispose();
}

and at the termination of my using statement.

The full using statement is:

using (var site = new SPSite(connectionString))
            {

                SPWeb web = site.OpenWeb(); // open the site
                Console.WriteLine("[{0}] Opened site: {1}", DateTime.Now.ToShortTimeString(), web);
                Console.WriteLine("[{0}] Web Relative URL is: {1}", DateTime.Now.ToShortTimeString(), web.ServerRelativeUrl);

                try
                {
                    // Get your source and destination libraries
                    var source = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales1");
                    var destination = web.GetList(web.ServerRelativeUrl + @"/Approval%20History%20%20Sales");

                    Console.WriteLine("[{0}] Source set to: {1}", DateTime.Now.ToShortTimeString(), source);
                    Console.WriteLine("[{0}] Destination set to: {1}", DateTime.Now.ToShortTimeString(), destination);

                    // Get the collection of items to move, use source.GetItems(SPQuery) if you want a subset
                    SPListItemCollection items = source.Items;

                    // Get the root folder of the destination we'll use this to add the files
                    SPFolder folder = web.GetFolder(destination.RootFolder.Url);

                    Console.WriteLine("[{0}] Moving {1} files from {2} to {3} - please wait...", DateTime.Now.ToShortTimeString(),
                                      items.Count, source, destination);

                    // Now to move the files and the metadata
                    foreach (SPListItem item in items)
                    {
                        //Get the file associated with the item
                        SPFile file = item.File;

                        // Create a new file in the destination library with the same properties
                        SPFile newFile = folder.Files.Add(folder.Url + "/" + file.Name, file.OpenBinary(), file.Properties, true);

                        // Optionally copy across the created/modified metadata
                        SPListItem newItem = newFile.Item;
                        newItem["Editor"] = item["Editor"];
                        newItem["Modified"] = item["Modified"];
                        newItem["Modified By"] = item["Modified By"];
                        newItem["Author"] = item["Author"];
                        newItem["Created"] = item["Created"];
                        newItem["Created By"] = item["Created By"];

                        // UpdateOverwriteVersion() will preserve the metadata added above.
                        newItem.UpdateOverwriteVersion();

                        // Delete the original version of the file
                        // todo: make local backup before deleting?
                        file.Delete();
                        fileCount++;
                    }

                    Console.WriteLine("[{0}] Completed moving {1} files to {2}", DateTime.Now.ToShortTimeString(), fileCount,
                                      destination);
                }
                catch (System.IO.FileNotFoundException)
                {
                    Console.WriteLine("[{0}] Unable to set a location. Please check that paths for source and destination libraries are correct and relative to the site collection.", DateTime.Now.ToShortTimeString());
                }
                finally
                {
                    web.Dispose();
                    site.Dispose();
                }
            }

Is my finally statement here redundant? Is there any reason that even if potentially it is redundant that I should retain it anyway?


texts: AIO programming challenge - Friendlist - Who has the most friends?

texts:
I attempted this sample question from the Australia Infomatics Competition. TL;DR - Each line of input contains two numbers, representing a mutual friendship relationship. The output needs to be the number representing the person who has the most friends (and if there is a tie, list them in numerical order).
Exact Words:

Input
The first line of input will contain the integer f, 1 <= f <= 1,000,000.
Each of the following f lines will be of the form a b, where a and b are different player IDs. This indicates that player #a is friends with player #b, and vice versa. All player IDs are integers between 0 and 1000 inclusive.
(Note that no friendship will ever be listed twice: for example, if "2 5" is one of the lines in the input, then neither "2 5" nor "5 2" will appear anywhere else in the input)
Output
Output should consist of all the player IDs that are tied for biggest friendlist. These IDs should be given in ascending order.
Sample Input:
6
5 6
0 1
1 4
5 4
1 2
4 0
Sample Output:
1
4

Here is my current code (in Python 2.6.6 as per the comp's requirements):
fileInput = open("listin.txt", "r")
InputList = map(int, fileInput.read().split())
fileInput.close()

input1 = InputList[1:]
friends_dict = {}

for each in xrange(int(InputList[0])+1):
    friends_dict[each] = input1.count(each)

highest = max(friends_dict.values())

biggest_nums = sorted([k for k, v in friends_dict.items() if v == highest])

Output = "\n".join([str(e) for e in biggest_nums])

fileOutput = open("listout.txt", "w")
fileOutput.write(str(Output))
fileOutput.close()

My Approach

First read in the whole file at once (is this a good idea? would it be better to do line by line?)

Count all occurrences of a friend ID and then assign it to a spot in the dictionary (thus works in theory as if A is friends with B and A is friends with C, if we were to count them, A appears 2x and that is how many friends A has, likewise with B = 1 and C = 1)

Find the maximum score(s)

The code seems to work alright (although the test machine did say one case failed - it works for the smaple input and some cases I made up, but I think that there are still flaws in the method) but the main issue seems to be that it is too slow. Over half the trial cases failed due to going over the 1 sec limit. I am open to any suggestions or even a new algorithm is general and suggestions to my coding in general.
I have been at this for a while now and I can't think of anything else to shave off. I suspect the bottleneck may be at the end which is simply finding the largest friend counts and ordering them.
I would appreciate any feedback whatsoever, be it from my coding practices to the implementation of or the actual algorithm. I would really like to be able to produce a faster and more efficient version of this code.


texts:
I have three functions, each assigned to an anchor tag which gets called onclick.

Is there a way to condense this code? It seems redundant to have three function calls which do the same thing except the value is different for each.

var winnings = 0;

function add20() {
    winnings += 20;
    document.getElementById("winnings").innerHTML = winnings;
}

function add40() {
    winnings += 40;
    document.getElementById("winnings").innerHTML = winnings;
}

function add60() {
    winnings += 60;
    document.getElementById("winnings").innerHTML = winnings;
}


texts: Converting time in number of minutes past midnight to HH:MM format

texts:
This program is a clock that only displays minutes passed since midnight. This program is supposed to be really simple but because of some "aesthetic bug", I wrote quite a lot if-else statements that I think can be simplified.

  Format Input

  The first line will contain an integer T, the number of test cases.
  Each test case will contain an number N, the number displayed by the
  strange clock.

  Format Output

  For each test case, print “Case X: “ (X starts with 1) and then print
  what time it is in 24 hours HH:MM format.

  Constraints

  1 <= T <= 1000

  0 <= N <= 1439

#include <stdio.h>

int main()
{
    int T;
    scanf("%d", &T);

    for (int i = 1; i <= T; i++) {

        int N;
        scanf("%d", &N);

        int hours = N / 60;
        int minutes = N % 60;

        printf("Case #%d: ", i);

        if (N < 10) {
            printf("00:0%d\n", N);
        } else if (N > 10 && N < 60) {
            printf("00:%d\n", N);
        } else if (N > 60 && N < 600) {
            if (minutes == 0) {
                printf("0%d:00\n", hours);
            } else if (minutes > 0 && minutes < 10) {
                printf("0%d:0%d\n", hours, minutes);
            } else {
                printf("0%d:%d\n", hours, minutes);
            }
        } else {
            if (minutes == 0) {
                printf("%d:00\n", hours);
            } else if (minutes > 0 && minutes < 10) {
                printf("%d:0%d\n", hours, minutes);
            } else {
                printf("%d:%d\n", hours, minutes);
            }
        }
    }
}


texts:
I have tried to make two buttons to be used for post navigation below each post on a blog:

It works, however - it feels like to much code and classes for so little. I'm using Bootstrap 4, alpha 6. Is there any easier way to make something like this?

HTML:

    <button type="button" class="btn btn-secondary btn-navigation mr-2 bg-gray-900 text-muted border-0 rounded-0">Previous

      The title of the previous post
   </button>

    <button type="button" class="btn btn-secondary btn-navigation bg-gray-900 text-muted border-0 rounded-0">Next

      The title of the next post. It might be long. Very very long
   </button>

CSS:

.wordwrap {
  white-space: normal;
}

.bg-gray-800 {
  background-color: #dfdfdf;
}

.bg-gray-900 {
  background-color: #efefef;

}

CodePen with the code


texts: Two Angular animations for modal dialogs

texts:
I'm using Ionic 4 and Angular animations to animate modals. I created the following two functions that control the animations but they share a lot of repeated code. Is there a way I can clean these up into a single function that just takes an array of parameters for the animations?

import { Injectable } from '@angular/core';
import { Animation } from '@ionic/core';

@Injectable({
  providedIn: 'root'
})
export class AnimationsService {
  modalLeave(AnimationC: Animation, baseEl: HTMLElement): Promise<Animation> {
    const baseAnimation = new AnimationC();

    const backdropAnimation = new AnimationC();
    backdropAnimation.addElement(baseEl.querySelector('ion-backdrop'));

    const wrapperAnimation = new AnimationC();
    const wrapperEl = baseEl.querySelector('.modal-wrapper');
    wrapperAnimation.addElement(wrapperEl);
    const wrapperElRect = wrapperEl!.getBoundingClientRect();

    wrapperAnimation
      .beforeStyles({
        opacity: 1
      })
      .fromTo('transform', 'translateX(0%)', 'translateX(100%)')
      .fromTo('opacity', 1, 0)
      .fromTo('-webkit-backdrop-filter', 'blur(7px)', 'blur(0px)');

    return Promise.resolve(
      baseAnimation
        .addElement(baseEl)
        .easing('ease-in')
        .duration(150)
        .add(backdropAnimation)
        .add(wrapperAnimation)
    );
  }

  modalEnter(AnimationC: Animation, baseEl: HTMLElement): Promise<Animation> {
    const baseAnimation = new AnimationC();

    const backdropAnimation = new AnimationC();
    backdropAnimation.addElement(baseEl.querySelector('ion-backdrop'));

    const wrapperAnimation = new AnimationC();
    const wrapperEl = baseEl.querySelector('.modal-wrapper');
    wrapperAnimation.addElement(wrapperEl);

    wrapperAnimation
      .beforeStyles({
        opacity: 1
      })
      .fromTo('transform', 'translateX(100%)', 'translateX(0%)')
      .fromTo('opacity', 0, 1)
      .fromTo('-webkit-backdrop-filter', 'blur(0px)', 'blur(7px)');

    return Promise.resolve(
      baseAnimation
        .addElement(baseEl)
        .easing('ease-in')
        .duration(150)
        .add(wrapperAnimation)
    );
  }
}


texts:
I'm introducing someone to JavaFX. It still feels relatively new and I don't take being someone's first exposure to something lightly. I want to know if there's anything I'm doing unconventionally, inefficiently, or just plain oddly in this code? Although it is relatively simple, If fresh eyes could discern something unaccounted or discern a should-be inclusion, I'd be remiss not to illuminate self before attempting to do so for another.

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.control.Tooltip;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

public class Hello extends Application {
    Scene scene;

    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        TextField entry = new TextField();
        entry.setPromptText("Enter your name");

        Button hello = new Button("Greeting");
        hello.setOnAction(e -> greet(entry));
        hello.setDefaultButton(true);
        hello.setTooltip(new Tooltip("Click me!"));

        HBox layout = new HBox();
        layout.getChildren().addAll(entry, hello);
        layout.setPadding(new Insets(2, 12, 2, 12));

        scene = new Scene(layout);

        stage.setScene(scene);
        stage.setTitle("Welcome to JavaFX");
        stage.show();
        hello.requestFocus();
    }

    public void greet(TextField entry) {
        String name = entry.getText();
        Label label = name.isEmpty() ? new Label("Hello user!") : new Label("How's it going, " + name + "?");
        scene.setRoot(label);
    }
}


texts: Function that calls a function with the terminal temporarily set to raw mode

texts:
I'm working through Build Your Own Text Editor, a walkthrough of the code to an extremely small text editor for a posix terminal in C, but I'm attempting to follow along in-the-spirit with OCaml.

I've put together a function that wraps an parameter function with termcap stuff to get the terminal into raw mode. This code works, but it feels ugly to me, specifically the let res stuff near the end. I feel like there should be a way to either get the second Unix.tcsetattr into a finally like block, or otherwise "wrap" the call to f ().

How could I make this code more idiomatic? I'm quite new to OCaml, so any suggestions for restructuring this code would be useful.

module TermIO = struct
  let in_raw_mode (f: unit -> _) =
    let termio  = Unix.tcgetattr Unix.stdin in
    let termio' = { termio with
                    Unix.c_echo   = false ;
                    Unix.c_icanon = false
                  } in
    Unix.tcsetattr Unix.stdin Unix.TCSAFLUSH termio' ;
    let res = f () in
    Unix.tcsetattr Unix.stdin Unix.TCSAFLUSH termio  ;
    res
end


texts: Convert cardinal abbreviations into full cardinal direction

texts:
I'm still learning Ruby and I made the following function to convert "N" or "SE" into "NORTH" or "SOUTH EAST" respectively.  The function works and the tests all pass, but the code seems to be overly complicated.  Any suggestions on how to clean it up and make it more Ruby-ish?

Code

module Example
  class Utils
    CARDINAL_PATTERN = /^([NS]?)([EW]?)$/
    CARDINAL_DB = {'N'=>'NORTH', 'S'=>'SOUTH', 'E'=>'EAST', 'W'=>'WEST' }
    def correct_cardinal word
      clean_word = word.gsub(/\p{Punct}/, '').upcase
      match = CARDINAL_PATTERN.match(clean_word)
      if match
        if (not match[1].empty?) and (not match[2].empty?)
          CARDINAL_DB[match[1]] + " " + CARDINAL_DB[match[2]]
        elsif (not match[1].empty?)
          CARDINAL_DB[match[1]]
        elsif (not match[2].empty?)
          CARDINAL_DB[match[2]]
        else
          ""
        end
      else
        word
      end
    end
  end
end

Tests

describe Example::Utils do
  let(:utils) { Example::Utils.new}

  describe '#correct_cardinal' do
    it 'should correct S' do
      expect(utils.correct_cardinal('S')).to eq "SOUTH"
    end

    it 'should correct N' do
      expect(utils.correct_cardinal('N')).to eq "NORTH"
    end

    it 'should correct E' do
      expect(utils.correct_cardinal('E')).to eq "EAST"
    end

    it 'should correct W' do
      expect(utils.correct_cardinal('W')).to eq "WEST"
    end

    it 'should strip single period' do
      expect(utils.correct_cardinal('W.')).to eq "WEST"
    end

    it 'should correct SE' do
      expect(utils.correct_cardinal('SE')).to eq "SOUTH EAST"
    end

    it 'should correct SW' do
      expect(utils.correct_cardinal('SW')).to eq "SOUTH WEST"
    end

    it 'should correct NE' do
      expect(utils.correct_cardinal('NE')).to eq "NORTH EAST"
    end

    it 'should correct NW' do
      expect(utils.correct_cardinal('NW')).to eq "NORTH WEST"
    end

    it 'should strip multiple periods' do
      expect(utils.correct_cardinal('N.W.')).to eq "NORTH WEST"
    end

    it 'should not correct 1' do
      expect(utils.correct_cardinal('1')).to eq "1"
    end

    it 'should not ordinalize eggs' do
      expect(utils.correct_cardinal('EGGS')).to eq "EGGS"
    end

  end

end


texts: How to transform true and false to 1 and 0?

texts:
I use the following code:

  var newValue = ($(event.target).is(":checked")) ? 1 : 0;
  var oldValue = (!$(event.target).is(":checked")) ? 1 : 0;
  sendMessage(this.name, oldValue, newValue);

Is there any better approach?


texts: Meta-circular interpreter for lambda calculus in Python

texts:
For learning purpose, I've written a simple lambda calculus interpreter (plus 'Add'). I would like it to be the cleanest and most idiomatic possible.

Can we make it as neat as the Haskell version?

# lambda interpreter example.

# Values: Num, Fun & Wrong.
# Terms: Cons, Var, Lam, App & Add.

class Num:
  def __init__(self, v):
    self.v = v
  def __str__(self):
    return str(self.v)

class Fun:
  def __init__(self, f):
    self.f = f
  def __call__(self, *args, **kargs):
    return self.f(*args, **kargs)
  def __str__(self):
    return 'function'

class Wrong:
  def __str__(self):
    return 'Wrong'

def add(v1, v2):
  return Num(v1.v + v2.v)

def apply(v1, v2):
  return v1(v2)

class Cons:
  def __init__(self, v):
    self.v = int(v)
  def interp(self, env):
    return Num(self.v)

class Var:
  def __init__(self, x):
    self.x = x
  def interp(self, env):
    return env[self.x]

class Lam:
  def __init__(self, arg, body):
    self.arg = arg
    self.body = body
  def interp(self, env):
    def f(v):
      env2 = env.copy()
      env2[self.arg] = v
      return self.body.interp(env2)
    return Fun(f)

class App:
  def __init__(self, fun, param):
    self.fun = fun
    self.param = param
  def interp(self, env):
    return apply(self.fun.interp(env),
                 self.param.interp(env))

class Add:
  def __init__(self, a, b):
    self.a = a
    self.b = b
  def interp(self, env):
    return add(self.a.interp(env), self.b.interp(env))

expr = App( Lam('x', Add(Var('x'), Var('x'))),
             Add(Cons(10), Cons(11)) )

print(expr.interp({}))


texts:
I need to compute the summation of:

$$\left\lfloor\frac{\text{sum of triplets}}{\text{product of triplets}}\right\rfloor$$

from integers of an array.

Input:

5

1 2 1 7 3

Output:

6

Explanation:

  The following triplets exists in the given array:

  1 2 1

  1 2 7

  1 2 3

  1 1 7

  1 1 3

  1 7 3

  2 1 7

  2 1 3

  2 7 3

  1 7 3

  Considering these triplets from the sample input:

  1 2 1 contributes 2 [floor{(1+2+1)/(1*2*1)} = floor{4/2}=2]

  1 2 3 contributes 1

  1 1 7 contributes 1

  1 1 3 contributes 1

  2 1 3 contributes 1

  All other triplets contribute 0 to the sum.

  Hence the answer is (2+1+1+1+1)=6.

What I tried has complexity \$O(n^3)\$:

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

int main()
{
    long t,n[300005],sum=0,mul=1,i,j,k,res=0;
    cin >> t;

    for(i=0;i<t;i++)
        cin >>n[i];

    for(i=0;i<t-2;i++)
    for(j=i+1;j<t-1;j++)
    for(k=j+1;k<t;k++)
    {
        sum = n[i]+n[j]+n[k];
        mul = n[i]*n[j]*n[k];
        res += floor(sum/mul);
    }

    cout << res << endl;
    return 0;
}

Is there any hint of better optimization?


texts:
To help with learning code in my class, I've been working on this text based game to keep myself coding (almost) every day. I have a class called BasicUnit, and in it I have methods to create a custom class. I use 2 methods for this, allowing the user to enter the information for the class. I'm just wondering if I can do this in a more simplified manner?

    public void buildCustomClass(int maxHP, int maxMP, int maxSP, int baseMeleeDmg, int baseSpellDmg, int baseAC, int baseSpeed) {

    this.maxHP = maxHP;
    this.maxMP = maxMP;
    this.maxSP = maxSP;
    this.baseMeleeDmg = baseMeleeDmg;
    this.baseSpellDmg = baseSpellDmg;
    this.baseAC = baseAC;
    this.baseSpeed = baseSpeed;
    lvl = 1;
    xp = 0;
    curHP = maxHP;
    curMP = maxMP;
    curSP = maxSP;

}

public void createCustomClass() {
    kb = new Scanner(System.in);

    System.out.println("Enter the information for your class: ");
    System.out.println("Enter HP: ");
    maxHP = kb.nextInt();
    System.out.println("Enter MP: ");
    maxMP = kb.nextInt();
    System.out.println("Enter SP: ");
    maxSP = kb.nextInt();
    System.out.println("Enter Base Melee Damage: ");
    baseMeleeDmg = kb.nextInt();
    System.out.println("Enter Base Spell Damage: ");
    baseSpellDmg = kb.nextInt();
    System.out.println("Enter AC: ");
    baseAC = kb.nextInt();
    System.out.println("Enter Speed: ");
    baseSpeed = kb.nextInt();

    buildCustomClass(maxHP, maxMP, maxSP, baseMeleeDmg, baseSpellDmg, baseAC, baseSpeed);
}


texts: all appointment based on interval distance

texts:
Currently with a given Date and an Interval in Day, I can calculate all of the appointment in the future. for example if you are supposed to have an appointment each 30 day starting '2020-09-24', all the future appointments would be calculated like this.
--Source Table Creation
DROP TABLE IF EXISTS #DimDate

CREATE TABLE #DimDate ( id INT PRIMARY KEY IDENTITY, GregorianDate DATE)
--Sample Data
INSERT INTO #DimDate(GregorianDate)
SELECT  TOP 2000 DATEADD(DAY, ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) , GETDATE())
FROM    sys.all_objects

--Calculation Code

;WITH cte_name --30.4375
AS ( SELECT GregorianDate,DATEADD(DAY,30,GregorianDate) next30, ((ROW_NUMBER() OVER (ORDER BY GregorianDate ASC)-1) + 30) % 30 AS r
     FROM   #DimDate
     WHERE GregorianDate >='2020-09-24'
)
SELECT  *
FROM    cte_name
WHERE r=0

Calculation is based on residual of this part the code ((ROW_NUMBER() OVER (ORDER BY GregorianDate ASC)-1) + 30) % 30 AS r, if residual is 0 then we are at the next interval.
What I am looking for

Is there any problem not yet considered?
Is there any other way? ( some playful way like window aggregate!)

Thank you

Update:
Some clarification:
I have a Date Dimension table in which all the related Calendar Conversion is stored like HijriCalendar, PersianCalendar and other needed data.
That is why even though generally speaking calculating nth appointment using (n * 30 (interval distance) ) + start is faster but overall because of other data needed from Dimension it'd be the same. (Greatly appreciated)


texts:
After taking into account answers for my questions here and here I created (well may-be) improved version of my wrapper. The key issue was what if an attacker is knowing what is encoded - he might then find the key and encode another messages. So I added XOR before encryption. I also in this version prepend IV to the data as was suggested.

SHA256 on key is only for making sure the key is as long as needed for the AES algorithm, but I know that key should not be plain text but calculated with many iterations to prevent dictionary attack

function aes192ctr_en($data,$key) {
    $iv = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM);
    $xor = mcrypt_create_iv(24,MCRYPT_DEV_URANDOM);
    $key = hash_hmac('sha256',$key,$iv,true);
    $data = $xor.((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1));
    $data = hash('md5',$data,true).$data;
    return $iv.mcrypt_encrypt('rijndael-192',$key,$data,'ctr',$iv);
}

function aes192ctr_de($data,$key) {
    $iv = substr($data,0,24);
    $data = substr($data,24);
    $key = hash_hmac('sha256',$key,$iv,true);
    $data = mcrypt_decrypt('rijndael-192',$key,$data,'ctr',$iv);
    $md5 = substr($data,0,16);
    $data = substr($data,16);
    if (hash('md5',$data,true)!==$md5) return false;
    $xor = substr($data,0,24);
    $data = substr($data,24);
    $data = ((string)$data ^ (string)str_repeat($xor,(strlen($data)/24)+1));
    return $data;
}

$encrypted = aes192ctr_en('secret text','password');
echo $encrypted;
echo aes192ctr_de($encrypted,'password');

Another question is: Is CTR mode is okay in this context, would it be better if I use CBC mode instead?

Again, by safe I mean, could an attacker derive the password if he knows which exact text was encrypted, and knows above method. I assume a random and long password here.

Maybe instead of XOR, will it be safer to use random initial data with another run of AES or other simpler algorithm like TEA or trivium?


texts: using system calls to compare text files

texts:
I am trying to make a script that compares 2 .txt files.

It works, but I wanted to double-check if there's something I missed about these system calls (since I'm new at this). Is there any improvement you would've done or anything else you think can help me improve with it (especially with this mmap thing)?

The script returns 2 if it's the same file and 1 otherwise.

#include<sys/stat.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main(int argc , char * argv[])
{
    if(argc != 3)
    {
        printf("something wrong with variables\n");
        exit(-1);
    }

    char* filename1 = argv[1];
    char* filename2 = argv[2];
    char* addr1;
    char* addr2;
    struct stat stat_p1;
    struct stat stat_p2;
    int fileSize1=0,fileSize2=0;

    if(stat(filename1,&stat_p1) == -1)
    {
        printf("error occurred while attempting to stat %s\n" , filename1);
        exit(-2);
    }

    if(stat(filename2,&stat_p2) == -1)
    {
        printf("error occurred while attempting to stat %s\n" , filename2);
        exit(-2);
    }

    if((fileSize1=stat_p1.st_size) != (fileSize2=stat_p2.st_size)) //checks if the size is different than its not the same file.
    {
        return 1;
    }
    else
    {
        int fd1,fd2;
        if((fd1 = open(filename1 ,O_RDONLY)) < 0)
        {
            printf("error opening file %s\n",filename1);
            exit(-3);
        }
        if((fd2 = open(filename2 ,O_RDONLY)) < 0)
        {
            printf("error opening file %s\n",filename2);
            exit(-3);
        }

        addr1 = mmap(NULL, fileSize1+ 1, PROT_READ,MAP_PRIVATE, fd1, 0);
        if (addr1 == MAP_FAILED)
        {
            printf("mmap failed\n");
            exit(-4);
        }

        addr2 = mmap(NULL, fileSize2+ 1, PROT_READ,MAP_PRIVATE, fd2, 0);
        if (addr2 == MAP_FAILED)
        {
            printf("mmap failed\n");
            exit(-4);
        }
        for(int i=0;i<fileSize1+1;i++)
        {
            if(addr1[i] != addr2[i])
            {
                return 1;
            }
        }
        close(fd1);
        close(fd2);
    }
    return 2;
}

(It's in the main file because it's meant to be used as part of testing program later.)


texts: Grouping array elements into batches of at most three

texts:
const items = ['a', 'b', 'c', 'd']

const reduced = items.reduce((acc, cur, index) => {
  const arrayIndex = Math.ceil((index + 1) / 3) - 1

  if (acc[arrayIndex]) {
    acc[arrayIndex].push(cur)
  } else {
    acc.push([cur])
  }

  return acc
}, [])

I'm taking an array of items, batching them into arrays of three at most and returning them as arrays of array. Here reduced yields the correct structure of [["a", "b", "c"], ["d"]]. How do I accomplish this without the if statement (which mutates the accumulated value directly)?


texts: Download the JSON from API and parse the data like Unique Voting Station Name and Councillors Name

texts:
Please give me some pointers on how I can improve this project with Python 2.7.

import json
import urllib
urls = ["https://data.calgary.ca/resource/kqmd-3dsq.json","https://data.calgary.ca/resource/4wni-k3sg.json"]
print " \nThis is Json Data Parser Program. \nThis program will print the Unique Voting Station Name from 2013 or 2017 City Elections from City of Calgary OpenData Portal"
CRED = '\033[91m'
CEND = '\033[0m'

try:
    year= int (raw_input("\nElection Year to Search [2013 or 2017]:"))

    if ( year not in range(2013,2018,4) ):
        year=int(raw_input("Invalid Year ! \nPlease type again Year to Search [2013 or 2017]:"))\

except (EOFError, KeyboardInterrupt, ValueError):
    year= int (raw_input("\nThe exception has occured !!\nPlease type again Year to  Search [2013 or 2017]:"))
else:
    print "You choose: {} year for Elections Results".format(year)

try:
    ward=int(raw_input("\nWard to Search:"))

    if ( ward not in range(0,14)):
        ward=int(raw_input("Ward does not exist in City of Calgary !\nPlease type again Ward to Search:"))

except (EOFError,ValueError,KeyboardInterrupt):
    ward=int(raw_input("\nThe exception has occured !!\nPlease type again Ward to Search:"))
else:
    print "\nYou choose ward: {} for Elections Results".format(ward)

def jsonUrl(year):
    global url
    if (year == 2017):
        url = urls[0]
        return url
    elif (year == 2013):
        url = urls[1]
        return url
    else:
        raise Exception('The City of Calgary only has data for 2013 and 2017')

jsonUrl(year)

response = urllib.urlopen(url)
data= json.loads(response.read())

def wardstnname(ward):
    wardwithscore = "{}".format(ward)
    wardstnresult = []
    for i in data:
        try:
            if (i["ward"] == wardwithscore and  i["voting_station_name"] not in wardstnresult):
                        wardstnresult.append(i["voting_station_name"])
        except KeyError:
            continue
    if len(wardstnresult) > 0:
        print "\nThere were total", len(wardstnresult),"unique voting stations in your ward"
        print "\nThe list of the Voting Station were as follows"
        for votingstnname,b in enumerate(wardstnresult,1):
            print '{} {}'.format(votingstnname,b)
    else:
        print CRED,"\nCity of Calgary has no Data on this Ward for Voting Station Name on Year", year,CEND

wardstnname(ward)

def wardOffice(ward):
    wardwithscore= "{}".format(ward)
    officeResult = []
    for i in data:
        if (i["ward"] == wardwithscore and i["office"] == "COUNCILLOR" and i["ballot_name"] not in officeResult):
            officeResult.append(i["ballot_name"])
    if len(officeResult) > 0:
        print "\nThere were total", len(officeResult),"councillors in your ward"
        print "\nThe list of the Councillors were as follows"
        for councillorname,b in enumerate(officeResult,1):
            print '{} {}'.format(councillorname,b)
    else:
        print CRED,"\nCity of Calgary has no Data on this Ward for Councillors on Year", year,CEND

wardOffice(ward)


texts: Multiple dice roll game with multiple players

texts:
I feel as if I did not write it efficiently. Any suggestions on slimming? I had trouble when player 2 would guess the number the first try, it would say player 2 won but keep continuing to the re-roll loop, hence the sys.exit().

import random
import time
import sys

diceNumber = random.randint(1,6)

print("lets play dice of destiny")

play1 = input("Player 1 name?")
play2 = input("Player 2 name?")
prize = input("What does the loser have to do?")

print("Hi " + play1 + " & " + play2 + ", let" + "'" + "s roll the dice
of destiny.")

play1Num = input(play1 + " choose a number 1-6.")
play2Num = input(play2 + " choose a number 1-6.")

play1Num = int(play1Num)
play2Num = int(play2Num)

if play1Num == diceNumber:
    print("The Dice rolled...")
    print(diceNumber)
    print(play1.upper() + " WINS!")
    print(play2 + " must: " + prize)
    sys.exit()

if play2Num == diceNumber:
    print("The Dice rolled...")
    print(diceNumber)
    print(play2.upper() + " WINS!")
    print(play1 + " must: " + prize)
    sys.exit()

while diceNumber != play1Num and play2Num:
    print("The Dice rolled...")
    print(diceNumber)
    print("both wrong, rolling again...")
    diceNumber = random.randint(1,6)
    time.sleep(1)

if play1Num == diceNumber:
    print("The Dice rolled...")
    print(diceNumber)
    print(play1.upper() + " WINS!")
    print(play2 + " must: " + prize)
    break

if play2Num == diceNumber:
    print("The Dice rolled...")
    print(diceNumber)
    print(play2.upper() + " WINS!")
    print(play1 + " must: " + prize)
    break


texts: Finding the difference between the estimated value and the true value in a reward task

texts:
I have this function called error, which estimates value based on previous value and rewards in trials. The difference between the estimated value and true value is then calculated, giving the error. I need to run this code 1000 times with different lists of trials, but currently it runs too slowly. How would I optimize this code?
Additional information: alpha is a parameter. Reward and true_value are lists. Value always starts at 0.5, but I remove this starting number before calculating error
def loopfunction(alpha, reward, true_value):
    difference = []
    value = [0.5]
    for index, lr in enumerate(reward):
        value.append(lever_update(alpha, value[-1], reward[index]))
    value.pop(0)
    zip_object = zip(value, true_value)
    for value_i, true_value_i in zip_object:
        difference.append(value_i-true_value)
    absdiff = [abs(number) for number in difference]

    return absdiff

The lever_update function, which calculates value is here:
def lever_update(alpha, value, reward):
   value += alpha * (reward - value)
return(value)


texts:
I'm working on my implementaion of the linux wc command. I finally have something that is working properly (with no options yet) but i think it needs a lot of "cleaning". I mean, i highly disrespect the "do not repeat yourself rule" and i want to hear some ideas on how can i polish this up a bit.

Here 's the code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>
#define BUF_SIZE 1024

typedef struct Total{ //stores the Total count of lines words and bytes
  int lines;
  int words;
  int bytes;
} Total;

Total* new_Total(int lines, int words, int bytes){ //constructor function for Total
  Total* t = (Total*)malloc(sizeof(Total));
  t->lines = lines;
  t->words = words;
  t->bytes = bytes;
  return t;
}

void updateTotal(Total *t, int lines, int words, int bytes){ //updates Total counters
  t->lines += lines;
  t->words += words;
  t->bytes += bytes;
}

void readStdin(Total* t, char c){ //reads from stdin, counts and prints
  int lines = 0, words = 0, bytes = 0, startWord = 0;
  char ch;
  while((ch=fgetc(stdin)) != EOF){//count the bytes, lines and words
    bytes++;
    if (ch == '\n'){
      lines++;
    }
    if (ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t'){ //if there's a visible char, there's a word
      startWord = 1;
    }
    if ((ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') && startWord == 1){ //when the word ends
      words++; //increment the word coutner
      startWord = 0; //reset word finder
    }
  }
  updateTotal(t, lines, words, bytes);
  if (c == '\0'){ //if the command was called with no arguments
    printf ("%d %d %d\n", lines, words, bytes);
  }
  else{
    printf ("%d %d %d %c\n", lines, words, bytes, c);
  }
}

void readFile(Total *t, char* filename, FILE* fp){
  int lines = 0, words = 0, bytes = 0, startWord = 0;
  char ch;
  if (fp == NULL){
    printf("%s: No such file or drectory\n", filename);
    exit(1);
  }
  while ((ch=fgetc(fp)) != EOF){ //count the bytes, lines and words
    bytes++;
    if (ch == '\n'){
      lines++;
    }
    if (ch != ' ' && ch != '\n' && ch != '\r' && ch != '\t'){
      startWord = 1;
    }
    if ((ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t') && startWord == 1){
      words++;
      startWord = 0;
    }
  }
  updateTotal(t, lines, words, bytes);
  printf("%d %d %d %s\n", lines, words, bytes, filename);
}

void readArgs(Total* t, int argc, char* argv[]){
  FILE* fp;
  for (int i=1; i<argc; i++){
    if (*argv[i] == '-'){//if a '-' is found, read from stdin
      readStdin(t, '-');
      clearerr(stdin);
    }
    else { //tries to read the file in argv[i]
      fp = fopen(argv[i], "r");
      readFile(t, argv[i], fp);
      fclose(fp);
    }
  }
  if (argc > 2){ //if there's more than one file, print the total in the end
    printf("%d %d %d total\n", t->lines, t->words, t->bytes);
  }
  else {
    exit(0);
  }
}

int main(int argc, char* argv[]){
  Total* t = new_Total(0,0,0);
  if (argc<2){ //no arguments
    readStdin(t,'\0'); //pass /0 to readstin because as it is the only time it is called, there's no need to append the name of the argument
    return 0;
  }
  readArgs(t, argc, argv);
  free(t);
  return 0;
}

As you can see, both in readStdin() and in readFile() i have the same piece of code that handles the counting. I've tried to make a function out of this using pointers but i gave up. Any suggestion would be much appreciated. Also, if you have any hint that has nothing to do with the problem that i mentioned, shoot it up!


texts: TLE on SPOJ for Prime Generator (PRIME1)

texts:
The objective is to find all primes between two given numbers. It is specified that the two numbers are \$\le\$ 1 billion and the difference between the two numbers is ~100,000. We are to repeat the whole process for a \$t\$number of times, where \$t\$ is given \$\le\$ 10.

Detail of the problem: PRIME1

The following code results in Time Limit Exceeded, so please suggest optimizations.

import java.lang.*;
import java.util.*;
import java.io.*;

class PRIME1 {
    static boolean[] primesUpto(){
        boolean[] isPrime =new boolean[31623];
        for(int i=2; i<isPrime.length; i++){
            isPrime[i]=true;
        }
        for(int i=2;i<isPrime.length;i++){
            for(int j=i;j*i<isPrime.length;j++){
                isPrime[j*i]=false;
            }
        }
        return isPrime;
    }
    static boolean[] isPrime=primesUpto();
    static void listPrimes(long m, long n){
        for(long i=m; i<n+1; i++){
            for(int j=2; j<isPrime.length;j++){
                if(isPrime[j] && i%j==0) break;
                if(j==31622) System.out.println(i);
            }
        }
    }
    public static void main(String args[])throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        byte t= Byte.parseByte(br.readLine());
        String[] in = new String[t];
        for(int i=0; i<t; i++){
            in[i]=br.readLine();
        }
        for(int i=0; i<t;i++){
            StringTokenizer st = new StringTokenizer(in[i]);
            listPrimes(Long.parseLong(st.nextToken()), Long.parseLong(st.nextToken()));
            System.out.println();
        }
    }
}


texts: Rounding ints division result to certain "granularity"

texts:
In my program I call "granularity" the "minimum step" for a number. For example, if granularity == 4 then I only work with numbers "0, 4, 8, 12 etc" (so normal integer has granularity == 1).

I need a function to round an integer number to a certain granularity. So for example, if granularity == 3, I want this map:

// I don't use negative number so don't care about negative results
0 -> 0
1 -> 0
2 -> 3
3 -> 3
4 -> 3
5 -> 6
6 -> 6
7 -> 6
8 -> 9
and so on

This is my implementation:

#include <iostream>
#include <stdint.h>

using namespace std;

typedef int64_t myDecimal;

myDecimal Round(myDecimal val, myDecimal granularity)
{
    myDecimal rest = val % granularity;
    myDecimal candidat = val / granularity;
    if (2 * rest < granularity) {
        return candidat * granularity;
    } else {
        return (candidat + 1) * granularity;
    }
}

int main()
{
    for (int i = -10; i < 10; i++){
        std::cout << "i = " << i << " " << Round(i, 3) << std::endl;
    }
    return 0;
}

How can you further improve it for better latency as I'm using this in HFT trading?


texts:
Simple code for getting documents that have a creationDate between two values in mongodb.
If the user provides only one of the values the code should still work and get the documents that have either a creationDate less than or bigger than the given value.
I'm mainly looking for more readability and simplicity.
interface mongoDateFilter {
  $gte?: Date;
  $lte?: Date;
}

export const getReportsForContent = async (
  contentId: ObjectId,
  beginDate: Date | undefined,
  endDate: Date | undefined,
): Promise<Report[]> => {
  const reportsCollection = await getCollection('reports');

  const creationDateMongoFilter: mongoDateFilter = {};

  if (beginDate) {
    creationDateMongoFilter['$gte'] = beginDate;
  }

  if (endDate) {
    creationDateMongoFilter['$lte'] = endDate;
  }

  let reportsForContent: Report[] = [];

  if (beginDate || endDate) {
    reportsForContent = await reportsCollection.find({ contentId, creationDate: creationDateMongoFilter }).toArray();
  } else {
    reportsForContent = await reportsCollection.find({ contentId }).toArray();
  }

  return reportsForContent;
};
```


texts:
I'd like to know if there's any better way to write this query:

(from a in Context.Pages
join b in Context.Visitors on a.PageID equals b.PageFK
join c in Context.Visits on b.VisitorID equals c.VisitorFK
join d in Context.Signups on c.VisitID equals d.VisitFK
where
d.DateOptinUtc.HasValue && a.UserFK == USER_ID
group d by new { a.PageID, a.DateCreated, a.BaseName, a.Name }
into g
select
new ListReport
 {
     DateCreated = g.Key.DateCreated,
     BaseName = g.Key.BaseName,
     Id = g.Key.PageID,
     Name = g.Key.Name,
     Optins = g.Count(),
     Views =
         (from h in Context.Visits
          where
              h.Visitors.PageFK == g.Key.PageID
          select h).Count()
 }).AsQueryable();

Are there any performance issues writing subqueries like these? I don't how I can get that value from the groupby.


texts:
Challenge: 2520 is the smallest number divisible by 1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by 1-20?

Solution:

public class Euler5 {
    public static void main(String[] args) {
        long startTime = System.nanoTime();
        int result = 0;

        for (int i = 2520; i > 0; i += 2520) {
            if (isSmallestMultiple(i)) {
                result = i;
                break;
            }
        }

        System.out.print("Result: " + result +
            ".\nTime used for calculation in nanoseconds: " +
            (System.nanoTime() - startTime) + ".");
    }

    public static boolean isSmallestMultiple(int i) {
        return i % 2 == 0 &&
            i % 3 == 0 &&
            i % 4 == 0 &&
            i % 5 == 0 &&
            i % 6 == 0 &&
            i % 7 == 0 &&
            i % 8 == 0 &&
            i % 9 == 0 &&
            i % 10 == 0 &&
            i % 11 == 0 &&
            i % 12 == 0 &&
            i % 13 == 0 &&
            i % 14 == 0 &&
            i % 15 == 0 &&
            i % 16 == 0 &&
            i % 17 == 0 &&
            i % 18 == 0 &&
            i % 19 == 0 &&
            i % 20 == 0;
    }
}

Example output:

 Result: 232792560.
Time Used for Calculation in nanoseconds: 11561136.

This is the first thing I tried. I started with a "should work" sentiment, and now that it has, I feel like it's an exceptional case.

Is incrementing by the given multiple, given its coverage of 1
through 10 more intuitive than I suspect? I'm wondering if this
situation is coincidental since they're not all primes.
Is there any obvious way of making this even faster?
Would this solution work for additional requirements? (i.e 1-25)


texts: Parallelized image transformations using GraphicsMagick

texts:
This is part of a script that I use for porting a TWRP theme from one resolution to another, respectively portrait to portrait and landscape to landscape. In this function entirely, it focuses on the images. What I am not showing is irrelevant since it focuses on porting the XML files.

I compiled GraphicsMagick for ARM and thus call on it when it is time to do the resizing of each image. GM can be a bit slow so I included a method which mimics the parallel concept to help speed up the process.

Is this sufficient or is there a better approach I can take given how this part of the script operates?

GOTOTWRPIMAGE() {

    NUM=0
    QUEUE=""
    MAX_NPROC=$(grep "processor :" < /proc/cpuinfo | wc -l) # default
    MAX_NPROC=$(($MAX_NPROC+1))

queue() {
    QUEUE="$QUEUE $1"
    NUM=$(($NUM+1))
}

regeneratequeue() {
    OLDREQUEUE=$QUEUE
    QUEUE=""
    NUM=0
    for PID in $OLDREQUEUE; do
        if [ -d /proc/$PID ]; then
            QUEUE="$QUEUE $PID"
            NUM=$(($NUM+1))
        fi
    done
}

checkqueue() {
    OLDCHQUEUE=$QUEUE
    for PID in $OLDCHQUEUE; do
        if [ ! -d /proc/$PID ]; then
            regeneratequeue # at least one PID has finished
            break
        fi
    done
}

    if [ ! -f "${P_IMAGES}"/image_dir.txt ]; then
        busybox touch "${P_IMAGES}"/image_dir.txt
    else
        rm -f "${P_IMAGES}"/image_dir.txt
        busybox touch "${P_IMAGES}"/image_dir.txt
    fi

    # Find the images to be ported.
    if output=$(find "${P_IMAGES}" -type f -iname "*.png" -o -iname "*.jpg"); then
        echo "${output}" > "${P_IMAGES}"/image_dir.txt
    fi

    filename="${P_IMAGES}"/image_dir.txt
    filelines=$(cat "${filename}")

    for line in $filelines; do
        # Remember the directory and filename
        local IMAGEFILE="$(basename "${line}")"
        local IMAGEFILEDIR="$(dirname "${line}")"

        # Remember width and height
        SIZEW=$(gm identify -format "%w" "${IMAGEFILEDIR}"/"${IMAGEFILE}")
        SIZEH=$(gm identify -format "%h" "${IMAGEFILEDIR}"/"${IMAGEFILE}")

        # Calculate old size for new size of each image.
        # Round fractions up and down for each image.
        FINALW=$(awk 'BEGIN{print int("'$BASEW'"/("'$PORTW'"/"'$SIZEW'")+0.5)}')
        FINALH=$(awk 'BEGIN{print int("'$BASEH'"/("'$PORTH'"/"'$SIZEH'")+0.5)}')

        # Inform user of the change and conduct the change
        echo " "
        echo Porting "${IMAGEFILE}" from $SIZEW'x'$SIZEH to $FINALW'x'$FINALH
        # Convert image to new sizes
        gm convert -size  $FINALW'x'$FINALH! "${IMAGEFILEDIR}"/"${IMAGEFILE}" -resize $FINALW'x'$FINALH! "${IMAGEFILEDIR}"/"${IMAGEFILE}" &

        PID=$!
        queue $PID

        while [ $NUM -ge $MAX_NPROC ]; do
            checkqueue
            #sleep 0.4
        done
    done
    wait # wait for all processes to finish before exit

    if [ -f "${P_IMAGES}"/image_dir.txt ]; then
        rm -rf "${P_IMAGES}"/image_dir.txt
    fi

    if [ $OPT == "1" ]; then
        HEADSUP
    fi
}


texts:
I need to write a method that will print the integers from [1, maxValue] in a pyramid where the nth row contains n numbers like so (for printChart(24)):

1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24

I am wondering if there is a way to optimize my code for functionality, simplicity, or computational complexity (although I doubt the latter, because I think this runs at \$O(n)\$ time).

It has one helper function, which returns a boolean value representing whether or not a given integer, n, is a perfect square.

public boolean isPerfectSquare(int n){
    int root = (int) Math.sqrt(n);
    return root * root == n;
}

public void printChart(int maxValue) {
    int number = 1;
    while (number <= maxValue) {

        System.out.print(number + " ");

        /* A number n can be determined to be triangular iff
         8n+1 is a perfect square;  if n is a triangular number,
         print a line after it*/
        if(isPerfectSquare(8*number+1)) { System.out.println(); }

        number++;
    }
}