texts: Notifying view controller of changes to any of five types of models

texts:
I have a swift 3 project with a code that's look like very generic, but I don't know if I can reduce a method like this one :

var pages: [Page] // List of page object

func RefreshList(){
        guard let currentIndex = currentIndex else { return }

        if let listTableViewController: listTableViewController<ModelA> = pages[currentIndex].viewController as? listTableViewController<ModelA> {
            listTableViewController.didRefreshNodesList()
        }
        else if let listTableViewController: listTableViewController<ModelB> = pages[currentIndex].viewController as? listTableViewController<ModelB> {
            listTableViewController.didRefreshNodesList()
        }
        else if let listTableViewController: listTableViewController<ModelC> = pages[currentIndex].viewController as? listTableViewController<ModelC> {
            listTableViewController.didRefreshNodesList()
        }
        else if let listTableViewController: listTableViewController<ModelD> = pages[currentIndex].viewController as? listTableViewController<ModelD> {
            listTableViewController.didRefreshNodesList()
        }
        else if let listTableViewController: listTableViewController<ModelE> = pages[currentIndex].viewController as? listTableViewController<ModelE> {
            listTableViewController.didRefreshNodesList()
        }
    }

The only things that change is the Model(LETTER) is there a way to reduce that ?


texts: Applying an id attribute based on a variable's value

texts:
I have the following code that checks the value of a variable and then applies the correct id attribute accordingly. The value of menuLink will have the same value of one of the parts of .mainmenu a href path name.

Is there a way to simplify this so it can search the href path of .mainmenu a instead of explicitly stating each one?

if (menuLink == "whatsnew") {
    $('.mainmenu a:eq(1)').attr('id', 'active').addClass("disable");
} else if (menuLink == "products") {
    $('.mainmenu a:eq(2)').attr('id', 'active').addClass("disable");
} else if (menuLink == "contact") {
    $('.mainmenu a:eq(3)').attr('id', 'active').addClass("disable");
} etc.....


texts: Truncating an integer from left to right and right to left

texts:
Project Euler problem 37 says:

  The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.

Going right to left is trivial enough as you just keep dividing by 10:

IEnumerable<long> RTL (long x)
{
    while(x > 10) {
        x /= 10;
        yield return x;
    }
}

Going left to right was a little trickier. Just wondering if there's a more optimal way to do this.

IEnumerable<long> LTR (long x)
{
    while(x > 10)
    {
        long y = x;        //take a copy of current value of x;
        int powerten = 0;  //variable to count what the 10^n value is

        while(y > 10){     //calculate powerten by repeated dividing y / 10
            y /= 10;       // for 3797 this would be '3' i.e. 3.797 * 10^3
            powerten++;
        }

        long p = (long)Math.Pow(10, powerten); // 10 ^ 3 = 1000
        long z = (x/p)*p;                      // 3797/1000*1000 = 3000
        x = (x - z);                           // subtract from x
        yield return x;
    }
}

It runs pretty fast but I'm just wondering is there a more optimal way to remove the leftmost significant digit of a number on each iteration without all the "gymnastics".


texts: Displaying member information from a CSV file

texts:
The code is about displaying membership information of all clients from database.  I was just wondering what I could do to improve/change it.

def optionA():
    global DoAnother
    while DoAnother == True:
        print("")
        member = input("Please enter the member number: ")
        if len(member) !=4:
            print ("")
            print("The member number is not valid")
            DoAnother = True
        else:
            global memberfile
            memberfile = open("members.txt","r+")
            searchMem = True
            for line in memberfile.readlines():
                listed = line.split(",")
                if member in listed:
                    print("")
                    print("Team Code: {0}".format(listed[0]))
                    print("Member number: {0}".format(listed[2]))
                    print("Date of joining: {0}".format(listed[1]))
                    print("Membership type: {0}".format(listed[3]))
                    print("Amount paid: {0}".format(listed[5]))
                    searchMem = False
                    nextchoice()
            if searchMem == True:
                optionA()

def optionB():
    print("")
    print("Team Code  Member No           Fee      Amount Paid      Amount Outstanding")
    print("----------------------------------------------------------------------------------------")
    global memberfile
    memberfile=open("members.txt","r+")
    amountOut = 0
    for line in memberfile.readlines():
        listed = line.split(",")

        if listed[3] =="F" and listed[5].strip('\n')<listed[4]:
            difference = (int(listed[4])-int(listed[5]))
            amountOut = (amountOut + difference)
            print("{0}          {1}             £{2}            £{3}          £{4}".format(listed[0], listed[2], listed[4], listed[5].strip('\n'), difference))
    print("")
    print("                                                         Total Outstanding: £{0}".format(amountOut))
    nextchoice()


texts: Express a number as a sum of powers of 2

texts:
This is my function:

def two_powers(num):
    powers = []
    i = 1
    while i <= num:
        if i & num:
            powers.append(i)
        i <<= 1
    return powers

I have python 3.6(Windows 10 64-bit). I want the result in the form of a list. My problem statement is to express a integer(num) in the form of sum of powers of 2.

Do I have to create a list in the beginning and then append to it each time ? Can I return a list directly without creating it in the beginning ?

This will will speed up my execution time, right ?


texts: iterating over json object in Jekyll to render pages with different variables

texts:
This is a fairly standard project based on Jekyll/Liquid.  I'm trying to iterate over data object to include pages with different variables.
And since {% include %} and %{ include_relative }% tags are not permissive in terms of different symbols. This approach doesn't work:
{% include_relative _components/ranking.html rank=ranking['rank']
So I had to use a {% capture %} hack for {% include_relative %} to work.
<ul class="list-unstyled" style="column-count: 3;">
{% for ranking in site.data.infra-fund['scorecard']['rankings'] %}
  {% capture rank %} {{ranking['rank']}} {% endcapture %}
  {% capture name %} {{ranking['name']}} {% endcapture %}
  {% capture size %} {{ranking['size']}} {% endcapture %}

  <li>
    {% include_relative _components/ranking.html rank=rank name=name size=size%}
   </li>
{% endfor %}
</ul>

I have a feeling, that this is common problem and there should be a cleaner way to write this. Maybe anyone can advise?


texts: Mutex Protected Object (scoped object wrapper)

texts:
This is a class that holds mutex and associated object. On checkout/access the mutex is locked while the stack object lives and a reference to object is obtained. Any suggestions or improvements is welcomed.

#include <mutex>

template<class T>
class MutexProtectedObject {
  //this relies on benign use and it is just a helper rather than a foolproof solution - ie. anyone may still save a pointer to obj etc. and access it later
public:
  class Access {
  public:
    Access(std::mutex& m, T& obj) : sl_(m), obj_(obj) {
    }
    T& obj_;
  private:
    std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
  };

  Access access() {
    return Access(mutex, obj);
  }

  MutexProtectedObject(const MutexProtectedObject&) = delete;
  MutexProtectedObject& opreator=(const MutexProtectedObject&) = delete;

private:
  std::mutex mutex;
  T obj;
};


texts:
I was trying to implement a deque using a singly LL when I realized that eject() (popping the tail element) wasn't going to work without a pointer to the previous element.

A few implementations I've seen online seem to use a node struct as well as a queue struct, so I'm starting to think I might've really messed this thing up (although it somehow seems to work).

I'm only including the 4 main functions; push() pop() inject() and eject().

Any feedback is welcome. A few things on my mind besides optimization issues: how would you test the robustness of something like this? I ran tests "manually" but clearly nothing exhaustive. Also I wanted to return an actual value for pop() and eject() instead of just printing it, but I'm not sure what to do when the list is empty. As of right now I end up returning zero with a message, but that feels...not amazing.

EDIT: This is obviously a lot of code butpop()/eject() and push()/inject() are very similar; so if you don't have time to look at the whole thing, feedback on pop() and push() would already be great, or even just one of them.

typedef struct node{
    int value;
    struct node* next;
    struct node* previous;
}node;

node* head = NULL;
node* tail = NULL;

int head_value();
int tail_value();
void push(int);
int pop();
void inject(int);
int eject();

int size = 0;

void push(int value)
{
    if (head == NULL)
    {
        head = malloc(sizeof(node));
        head->value = value;
        head->next = NULL;
        head->previous = NULL;
        tail = head;
        size++;
    }
    else
    {
        node* new_node = malloc(sizeof(node));
        new_node->value = value;
        new_node->next = head;
        new_node->next->previous = new_node;
        head = new_node;
        new_node->previous = NULL;
        size++;
    }
}

int pop()
{
    if (head == NULL)
    {
        printf("List Empty\n");
        return 0;
    }

    node* temp = head;
    int value = temp->value;
    head = head->next;
    free(temp);
    if (head != NULL)
        head->previous = NULL;
    size--;
    if (size == 0)
        tail = NULL;
    return value;
}

void inject(int value)
{
    if (tail == NULL)
    {
        tail = malloc(sizeof(node));
        tail->value = value;
        tail->next = NULL;
        tail->previous = NULL;
        head = tail;
        size++;
    }
    else
    {
        node* new_node = malloc(sizeof(node));
        new_node->value = value;
        tail->next = new_node;
        new_node->previous = tail;
        tail = new_node;
        new_node->next = NULL;
        size++;
    }
}

int eject()
{
    if (tail == NULL)
    {
        printf("List Empty\n");
        return 0;
    }

    int value = tail->value;
    node* temp = tail;
    tail = temp->previous;
    free(temp);
    if (tail != NULL)
        tail->next = NULL;
    size--;
    if (size == 0)
        head = NULL;
    return value;
}


texts: Circular doubly linked list implementation in Cython

texts:
This is a follow-up from my previous question.
In summary, I am trying to implement a BVH module with Cython and need a way to keep track of the volumes during the construction of the hierarchy.

I was going to use a Doubly linked list for that purpose as it allows for efficiently inserting and popping items from either side, but a user pointed that many APIs use a circular version of the list to avoid problems.

I decided to implement such a list, also tried to make it more general so it can be useful for further projects.

cdef struct CDLinkedList:
    ListNode* head
    int length

cdef struct ListNode:
    ListNode** links #[0] = previous, [1] = next or vice versa, doesn't matter.
    void* data

cdef ListNode* list_node_create(void* data) nogil:
    cdef ListNode* n = <ListNode *> malloc(sizeof(ListNode))
    n.links = <ListNode **> malloc(sizeof(ListNode*) * 2)
    n.data = data
    return n

cdef void list_node_free(ListNode* node) nogil:
    free(node.links)
    free(node)

cdef CDLinkedList* list_create() nogil:
    cdef CDLinkedList* lst = <CDLinkedList *> malloc(sizeof(CDLinkedList))
    lst.head = list_node_create(NULL)
    lst.head.links[0] = lst.head
    lst.head.links[1] = lst.head
    lst.length = 0
    return lst

cdef void list_free(CDLinkedList* lst) nogil:
    while lst.length > 0:
        list_pop(lst, 0)
    list_node_free(lst.head)
    free(lst)

cdef void list_insert(CDLinkedList* lst, void* data, int link_side) nogil:
    cdef:
        int next = link_side
        int prev = 1 - link_side
        ListNode* next_node = lst.head.links[next]
        ListNode* new_node = list_node_create(data)
    next_node.links[prev] = new_node
    lst.head.links[next] = new_node
    new_node.links[prev] = lst.head
    new_node.links[next] = next_node
    lst.length += 1

cdef void* list_pop(CDLinkedList* lst, int link_side) nogil:
    if lst.length <= 0:
        return NULL
    cdef:
        int next = link_side
        int prev = 1 - link_side
        ListNode* next_node = lst.head.links[next]
        ListNode* next_next_node = next_node.links[next]
        void* data = next_node.data
    lst.head.links[next] = next_next_node
    next_next_node.links[prev] = lst.head
    list_node_free(next_node)
    lst.length -= 1
    return data


texts: Use parent class to declare a child object or how compiler allocates memory

texts:
I'm working with C# and .NET Framework 4.0 and Windows Forms.

On my project I have three custom objects that inherits from MyControl class (MyControl class inherits from UserControl).

I have this code:

private void ShowControlForBatchStatus(BatchStatus batchStatus)
{
    MyControl control = null;

    panelContainer.Controls.Clear();

    if (batchStatus == BatchStatus.NoBatch)
    {
        control = new InicializeLevel();
    }
    else if ((batchStatus == BatchStatus.BatchRunning) ||
                (batchStatus == BatchStatus.BatchPaused))
    {
        control = new Stadistics();
    }
    else if (batchStatus == BatchStatus.BatchFinish)
    {
        control = new FinishBatch();
    }

    panelContainer.Controls.Add(control);
}

Now I think that if it is correct to declare a MyControl control variable when I'm going to use bigger control like FinishBatch. I think that if compiler allocate memory for a MyControl object, and now I use a bigger one for that variable, is that a problem?

Maybe, I'm confuse and the compiler only allocate memory when I do new FinishBatch();.

Does the compiler allocate memory when I declare a variable?


texts: __repr__ for a binary tree whose constructor has default arguments

texts:
I recently have been working on a BinaryTree class, and looked into creating a proper __repr__ which when eval'ed would recreate the exact binary tree as the original.

The following code for __repr__ works as expected, but I'm wondering if there is a better way to handle the removal of values which already has a default parameter in the __init__ method of the class. That is, avoiding to use replace() to remove the None cases at the end of __repr__.

class BinaryTree(object):
    """Structure to hold a binary tree."""

    def __init__(self, value, left = None, right = None):
        self.value = value
        self.left = left
        self.right = right

    def __repr__(self):
       """Return a string which when eval'ed will rebuild tree"""

       return '{}({}, {}, {})'.format(
                 self.__class__.__name__,
                 repr(self.value),
                 repr(self.left) if self.left else None,
                 repr(self.right) if self.right else None) \
                      .replace(', None, None)', ')') \
                      .replace(', None)', ')')

    def __eq__(self, other):
        """Check if both trees exists, and have same value and subtrees."""

        # Return early if only one of the tree exists
        #   or if only one of them has a right tree
        #   or if only one of them has a left tree
        if (bool(self) ^ bool(other)
            or (bool(self.right) ^ bool(other.right))
            or (bool(self.left) ^ bool(other.left))):

            return False

        # Otherwise compare the values, and that sub trees are equal
        return (self.value == other.value
                and self.right == other.right
                and self.left == other.left)

    def __ne__(self, other):
        """Negated version of BinaryTree.__eq__"""
        return not self.__eq__(other)

Some test code verifying that it actually works:

trees = []
trees.append(('balanced manual', BinaryTree('D', BinaryTree('B', BinaryTree('A'), BinaryTree('C')),
                            BinaryTree('F', BinaryTree('E')))))

trees.append(('alphalevel manual', BinaryTree('A', BinaryTree('B', BinaryTree('D'), BinaryTree('E')), BinaryTree('C', BinaryTree('F')))))
trees.append(('integer_tree manual', BinaryTree(4, BinaryTree(2, BinaryTree(1), BinaryTree(3)), BinaryTree(6, BinaryTree(5)))))
trees.append(('strange_tree manual',
               BinaryTree('G',
                 BinaryTree('C',
                   BinaryTree('B',
                     BinaryTree('A')),
                   BinaryTree('F',
                     BinaryTree('D',
                       None,
                       BinaryTree('E')))),
                 BinaryTree('H',
                   None,
                   BinaryTree('I')))))

for tree_name, tree in trees:
    print('Treename: {}, equal to __repr__ version: {}'.format(tree_name,
                tree == eval(repr(tree))))

I do know that it doesn't hurt to explicitly specify the default parameters when eval'ing the repr version, but I'm contemplating on using some the repr-versions in tests and so on, and the version without None looks a little nicer than the one with:

BinaryTree('D', BinaryTree('B', BinaryTree('A'), BinaryTree('C')), BinaryTree('F', BinaryTree('E')))
BinaryTree('D', BinaryTree('B', BinaryTree('A', None, None), BinaryTree('C', None, None)), BinaryTree('F', BinaryTree('E', None, None), None))


texts: Better way of calculating Project Euler #2 (Fibonacci sequence)

texts:
Even Fibonacci numbers

  Problem 2

  Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

  By considering the terms in the Fibonacci sequence whose values do not
  exceed four million, find the sum of the even-valued terms.

object Problem_2 extends App {
    def fibLoop():Long =
    {
        var x = 1L
        var y = 2L
        var sum = 0L
        var swap = 0L

        while (x < 4000000)
        {
            if (x % 2 ==0) sum += x
            swap = x
            x = y
            y = swap + x
        }
        sum
    }
    def fib:Int = {
        lazy val fs: Stream[Int] = 0 #:: 1 #:: fs.zip(fs.tail).map(p => p._1 + p._2)
        fs.view.takeWhile(_ <= 4000000).filter(_ % 2 == 0).sum
    }

    val t1 = System.nanoTime()
    val res = fibLoop
    val t2 = (System.nanoTime() - t1 )/1000
    println(s"The result is: $res time taken $t2 ms ")
}

Is there a more functional way of calculating the Fibonacci sequence and taking the sum of the even values below 4 million?

Is the imperative method 1000x faster?


texts:
Please check if this date filtering function is inefficient code. It seems so to me, but I can't figure out the other way around it.

function makeTime () {
    /////////////////////////////////
    //Create a filtered Time/////////
    var timesStamp = new Date();
    var time = timesStamp.toLocaleTimeString();
    var timeArray = time.split(":");
    var spaceDeliTime = timeArray.join(" ");
    var rawTime = spaceDeliTime.split(" ");
    var extrTime = rawTime.splice(2,1);
    var AMPM = rawTime.splice(2,1);
    return rawTime.join(":")+' '+AMPM;
}


texts: Using volatile instead of synchronized for a simulation

texts:
I want to know if using volatile in this scenario will give better performance than using synchronized, specifically for the paused and running instance variable in the SimulationManager class.

public class SimulationManager {

    private List<SimulationPanel> simulations;
    private boolean paused = false;
    private boolean running = false;
    private volatile PausableStopabbleThread observer;

    public SimulationManager() {
        simulations = new ArrayList<>();
    }

    public SimulationManager(List<SimulationPanel> simulations) {
        this.simulations = Collections.unmodifiableList(simulations);
    }

    public void start() {
        if (isRunning()) {
            return;
        }
        for (SimulationPanel sim : simulations) {
            sim.tableInsertion.start();
        }
        setRunning(true);
        observer = new SimulationsObserver();
        observer.start();

    }

    public void play() {
        if (!isRunning() && !isPaused()) {
            return;
        }
        setPaused(false);
        for (SimulationPanel sim : simulations) {
            sim.tableInsertion.play();
        }
        observer.play();

    }

    public void reset() {
        if (!isRunning()) {
            return;
        }
        setRunning(false);
        setPaused(false);
        observer.stopWork();
        observer = null;
        for (SimulationPanel sim : simulations) {
            sim.tableInsertion.stopWork();
        }

    }

    public void pause() {
        if (!isRunning() && isPaused()) {
            return;
        }
        setPaused(true);
        observer.pause();
        for (SimulationPanel sim : simulations) {
            sim.tableInsertion.pause();
        }

    }

    private synchronized void setPaused(boolean b) {
        this.paused = b;

    }

    private synchronized boolean isPaused() {
        return paused;
    }

    public synchronized boolean isRunning() {
        return running;
    }

    private synchronized void setRunning(boolean running) {
        this.running = running;
    }

    /**
     * Specifies when the simulations has finished
     *
     * @author Victor J.
     *
     */
    class SimulationsObserver extends PausableStopabbleThread {

        private final int nSimulations = simulations.size();

        @Override
        public void run() {
            int finished = 0;
            while (!stopRequested()) {
                for (SimulationPanel sim : simulations) {
                    if (!sim.tableInsertion.isAlive()) {
                        finished++;
                    }
                }
                if (finished == nSimulations) {
                    setRunning(false);
                    return;

                } else {
                    finished = 0;
                }
                pausePoint();
            }

        }

    }

}


texts: Ruby selenium script waiting for an element to disappear

texts:
I'm a Java developer, I'm new to Ruby and I'm worried that I'm forcing or not-so-well using the goodness of the Ruby syntax.

What do you think about the Exception catching and how to print it in error messages?
What about the code block (closure?) I'm passing to the "until" method?
Is it ok to implicitly rely on what the last executed sentence of the block will be, regarding what would be its returned value?

def waitUntilDisappears(type, name) #Waits for a particular element to disappear
  begin
    puts "Waiting for element #{name} to disappear..."
    wait = Selenium::WebDriver::Wait.new(:timeout => 5)
    wait.until do
      element = driver.find_element(type, name)
      if element != nil
        displayValue = element.css_value("display")
        puts "Element #{name} has displayValue #{displayValue}."
        displayValue != "block"
      end
    end
    puts "Element #{name} disappeared or not present. OK."
  rescue Exception => e
    puts "Error: Could not wait for element #{name} to disappearDetails: #{e.inspect}"
  end
end


texts: Get list of the executables in the current directory

texts:
This is what I've done;

import Control.Applicative
import Control.Monad
import qualified System.Directory as SD
main = do
    files <- SD.getDirectoryContents =<< SD.getCurrentDirectory
    exes <- filterM (liftA SD.executable <$> SD.getPermissions) files
    print exes

This works fine, but I can't help feeling that this code is somewhat redundant --- with filterM, liftA, <$> and =<< all present at once, things seem unnecessarily complicated.

How can I improve this piece of code?

For a quick reference:

SD.getCurrentDirectory :: IO FilePath
SD.getDirectoryContents :: FilePath -> IO [FilePath]
SD.executable :: Permissions -> Bool
SD.getPermissions :: FilePath -> IO Permissions

and I want to filter the contents of the current directory based on its being executable or not.


texts: Determining if a check box has been checked or not

texts:
I have a block of code that checks to see if a check box is checked or not, and assigns a value to a variable for saving to a MySQL table.  There are approximately 8 of these boxes.

if ($("#amOld").is(":checked")) {
    var amOldGuide=1;
} else {
    var amOldGuide=0;
}
if ($("#folOld").is(":checked")) {
    var folOldGuide=1;
} else {
    var folOldGuide=0;
}
if ($("#tichOld").is(":checked")) {
    var tichOldGuide=1;
} else {
    var tichOldGuide=0;
}
if ($("#bookOld").is(":checked")) {
    var bookOldGuide=1;
} else {
    var bookOldGuide=0;
}
if ($("#nebOld").is(":checked")) {
    var nebOldGuide=1;
} else {
    var nebldGuide=0;
}
if ($("#sterOld").is(":checked")) {
    var sterOldGuide=1;
} else {
    var sterOldGuide=0;
}
if ($("#byteOld").is(":checked")) {
    var byteOldGuide=1;
} else {
    var byteOldGuide=0;
}
if ($("#ingOld").is(":checked")) {
    var ingOldGuide=1;
} else {
    var ingOldGuide=0;
}

I am using something similar for another set of check boxes later on in the project as well.  As it sits, this works, but it is ugly. I feel that there must be a better way to write this that will be easier to maintain, and without having to repeat it later on.  Should I be using a class or objects?


texts:
I needed a node app that:

reads a list in text file format from URL
parses the rows on the list. (fields: id, name, longitude, latitude)
finds names of the people who live maximum 100 kms away from a set location.
sorts the list by user id

Could you take a look and let me know what I could have done better here?

To run:

nodejs scriptname.js

 var ClientsNearby = (function(){
  'use strict';
  var contacts = [],
    dublinOffice = {
      latitude: 53.3381985,
      longitude: -6.2592576
    };
  var request = require('request');
  function getDistanceFromLatLonInKm(lat2,lon2) {
    var R = 6371; // Radius of the earth in km
    var dLat = toRadians(lat2-dublinOffice.latitude);  // toRadians below
    var dLon = toRadians(lon2-dublinOffice.longitude);
    var a =
      Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRadians(dublinOffice.latitude)) * Math.cos(toRadians(lat2)) *
          Math.sin(dLon/2) * Math.sin(dLon/2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    var d = R * c; // Distance in km
    return d;
  }

  function toRadians(deg) {
    return deg * (Math.PI/180);
  }
  function processClients(contacts) {
    // saving clients living in a 100km radius
    var distanceIncludedClientList =
      contacts.map(client => {
        return {
          latitude: client.latitude,
          longitude: client.longitude,
          user_id: client.user_id,
          name: client.name,
          distance: getDistanceFromLatLonInKm(client.latitude, client.longitude)
        };
      });

    var closeByClients = distanceIncludedClientList.
        filter(client => client.distance <= 100);
    function compareUserID(a,b) {
      if(a.user_id > b.user_id)
        return 1;
      if(a.user_id < b.user_id)
        return -1;
      return 0;
    }
    var closeByClientsSorted = closeByClients.sort(compareUserID);

    report(closeByClientsSorted);
  }
  function report(contacts) {
    console.log('Clients who live max 100 Kms from our office: \n');
    contacts.map(contact => {
      console.log(` id: ${contact.user_id}, Name: ${contact.name}, Distance: ${contact.distance.toFixed(1)}Km`);
    });
  }

  function init() {
    var textFileUrl = 'https://gist.githubusercontent.com/brianw/19896c50afa89ad4dec3/raw/6c11047887a03483c50017c1d451667fd62a53ca/gistfile1.txt';

    request.get(textFileUrl, function (error, response, body){
      if (!error && response.statusCode === 200) {
        contacts = body.split('\n');

        contacts = contacts.map(function(elm){
          elm = JSON.parse(elm);
          return elm;
        });
      }
      processClients(contacts);
    });

  }
  return {
    init: init,
    toRadians: toRadians,
    processClients: processClients,
    getDistanceFromLatLonInKm: getDistanceFromLatLonInKm
  };
})();

ClientsNearby.init();
module.exports = ClientsNearby;


texts: remove_prefix and remove_suffix functions

texts:
If the prefix/suffix does not match the beginning or the end of a string, then, depending on how I call these functions, they should either raise an exception or return the original text unmodified.

I am using these inside of a simple script for now, so there was no need to make these member functions of some class. I am hoping to find a way to simplify the logic, extract any common code into private function(s), improve the code style (although I think there are several different standards).

def remove_prefix(text, prefix, raise_if_no_match=True):
    exc_msg = 'Text "{}" does not start with a prefix "{}".'.format(text, prefix)
    if not prefix or not text:
        if not raise_if_no_match:
            return text
        if len(prefix) == len(text):
            return ''
        raise ValueError(exc_msg)
    if text.startswith(prefix):
        return text[len(prefix):]
    if raise_if_no_match:
        raise ValueError(exc_msg)
    return text

def remove_suffix(text, suffix, raise_if_no_match=True):
    exc_msg = 'Text "{}" does not end with a suffix "{}".'.format(text, suffix)
    if not suffix or not text:
        if not raise_if_no_match:
            return text
        if len(suffix) == len(text):
            return ''
        raise ValueError(exc_msg)
    if text.endswith(suffix):
        return text[:-len(suffix):]
    if raise_if_no_match:
        raise ValueError(exc_msg)
    return text

print remove_prefix('Hello, World', 'Hello, ')
# ValueError: Text "Hello, World" does not start with a prefix "Hello, Hello".
#print remove_prefix('Hello, World', 'Hello, Hello')
print remove_prefix('Hello, World', 'Hello, Hello', raise_if_no_match=False)

print remove_suffix('I am singing in the rain', ' in the rain')
# ValueError: Text "I am singing in the rain" does not end with a suffix "swinging in the rain".
#print remove_suffix('I am singing in the rain', 'swinging in the rain')
print remove_suffix('I am singing in the rain', 'swinging in the rain', raise_if_no_match=False)

Output:

World
Hello, World
I am singing
I am singing in the rain


texts:
This is my first bowling kata solution in java. I would be very grateful if you say something about that. I want to learn from you to become a better programmer.
I think the score method is quite small, but is it clear enough as well?
How can I improve it more?

public class BowlingGame {

  int[] rolls = new int[21];
  int currentRollIndex = 0;

  public void roll(int roll) {
      if (currentRollIndex < 21) {
          rolls[currentRollIndex++] = roll;
      }
  }

  public int score() {
      int score = 0;
      int index = 0;
      for (int i = 0; i < 10; i++) {
          score += rollIndex(index++);
          if (isStrike(index - 1)) score += rollIndex(index, index + 1);
           else {
              score += rollIndex(index++);
              if (isSpare(index - 2)) score += rollIndex(index);
          }
      }
      return score;
  }

  private boolean isStrike(int index) {
      return rolls[index] == 10;
  }

  private boolean isSpare(int index) {
      return rolls[index] + rolls[index + 1] == 10;
  }

  private int rollIndex(int... indexes) {
      int sum = 0;
      for (int i = 0; i < indexes.length; i++) sum += rolls[indexes[i]];
      return sum;
  }
  }

JUnit test:

public class BowlingKataTest {

    public BowlingKataTest() {
    }
    Bowling bowling;

    @BeforeClass
    public static void setUpClass() {
    }

    @AfterClass
    public static void tearDownClass() {
    }

    @Before
    public void setUp() {
        bowling = new Bowling();
    }

    @After
    public void tearDown() {
    }

    @Test
    public void NullTest() {
        bowling.roll(0);
        assertEquals(0, bowling.score());
    }

    void setRolls(int n, int pin) {
        for (int i = 0; i < n; i++) {
            bowling.roll(pin);
        }
    }

    void set2Rolls(int n, int pin1, int pin2) {
        for (int i = 0; i < n; i++) {
            bowling.roll(pin1);
            bowling.roll(pin2);
        }
    }

    void setArrayRolls(int[] n) {
        for (int i = 0; i < n.length; i++) {
            bowling.roll(n[i]);

        }
    }

    @Test
    public void OnesTest() {
        setRolls(20, 1);
        assertEquals(20, bowling.score());
    }

    @Test
    public void OnesBonusTest() {
        setRolls(10, 1);
        bowling.roll(10);
        setRolls(8, 1);
        assertEquals(30, bowling.score());
    }

    @Test
    public void FullBonusTest() {
        setRolls(12, 10);
        assertEquals(300, bowling.score());
    }

    @Test
    public void FullHalfBonusTest1() {
        set2Rolls(10, 3, 7);
        bowling.roll(10);
        assertEquals(137, bowling.score());
    }
    @Test
    public void FullHalfBonusTest2() {
        setRolls(21, 5);
        assertEquals(150, bowling.score());
    }
    @Test
    public void RealTest() {
        int[] rolls = {0,10,5,5,3,2,10,10,3,7,7,1,4,2,9,1,8,2,5};
        setArrayRolls(rolls);
        assertEquals(140, bowling.score());
    }
}


texts: Confirmation to delete items using a jQuery modal dialog

texts:
I'm looking for suggestions on how to clean up JavaScript/jQuery code that looks like the example in the Before snippet.

I'm a backend developer so some of the constructs in JavaScript are foreign to me. I took a stab at it in the After block but I'm not sure if there is a name for that design pattern.

Most of the JS code we have are click handlers and DOM table manipulation. There are also situations where we need to keep state like rows visible, etc.

In order to easily toggle console logging, I added a log() function that checks the debug flag.

Before

$(function() {

  // Delete button handler
  $('.delete-button').click(function(e) {
    e.preventDefault();
    var id = $(this).closest('tr').data('id');
    var name = $(this).prop('name');
    var modal = $('#delete-modal');
    modal.find('.modal-body').html("You've chosen to delete " + name + "");
    modal.data('id', id);
    modal.modal('show');
    console.log('Showing modal');
  });

  // Confirm delete button handler
  $('#confirm-delete-button').click(function(e) {
    var modal = $('#delete-modal');
    var id = modal.data('id');

    modal.modal('hide');

    console.log('Deleting id ' + id);

    // Build form for submission
    var $form = $('<form action="" method="POST"></form>');
    $form.append('<input type="hidden" name="id" value="' + id + '">');
    $form.append('<input type="hidden" name="reqType" value="Delete">');
    $(document.body).append($form);
    $($form).submit();

  });
});

After

var App = {

  rowCount: 0,
  visibleCount: 0,
  debug: true;

  onReady: function () {
    App.initHandlers();
  },

  log: function (message) {
    if (App.debug) {
      console.log(message);
    }
  },

  initHandlers: function () {
    $('.button-delete').click(App.showDeleteModal);
    $('#button-confirm-delete').click(App.deleteRow);
  },

  showDeleteModal: function (event) {
    event.preventDefault();
    var id = $(this).closest('tr').data('id');
    var name = $(this).prop('name');
    var modal = $('#delete-modal');
    modal.find('.modal-body').html("You've chosen to delete " + name + "");
    modal.data('id', id);
    modal.modal('show');
    App.log('Showing modal');
  },

  deleteRow: function () {
    var modal = $('#delete-modal');
    var id = modal.data('id');

    modal.modal('hide');

    App.log('Deleting id ' + id);

    // Build form for submission
    var $form = $('<form action="" method="POST"></form>');
    $form.append('<input type="hidden" name="id" value="' + id + '">');
    $form.append('<input type="hidden" name="reqType" value="Delete">');
    $(document.body).append($form);
    $($form).submit();
  },

  updateToolbar: function () {
    App.visibleCount = $('.product-row:visible').length;
    App.rowCount = $('.product-row').length;

    if (App.visibleCount === App.rowCount) {
      $('div.toolbar').html('
Showing ' + App.visibleCount + ' of ' + App.rowCount + ' rows
');
    } else {
     $('div.toolbar').html('
Showing ' + App.visibleCount + ' of ' + App.rowCount + ' rows
');
    }
  },
};

$(document).ready(App.onReady);


texts:
Code review for best practices, optimizations, code cleanup etc. Also requesting verification of the complexity: O(row*row*col).

/**
 * Contains coordinates of the
 * topMost left, of matrix, obtained by getRowOne and colRowOne
 * bottomMost right, of matrix, obtained by getRowTwo and getColTwo
 *
 * @author javadeveloper
 */
final class RectangleCoord {
    private final int rowOne;
    private final int colOne;
    private final int rowTwo;
    private final int colTwo;

    public RectangleCoord(int rowOne, int colOne, int rowTwo, int colTwo) {
        this.rowOne = rowOne;
        this.colOne = colOne;
        this.rowTwo = rowTwo;
        this.colTwo = colTwo;
    }

    public int getRowOne() {
        return rowOne;
    }

    public int getColOne() {
        return colOne;
    }

    public int getRowTwo() {
        return rowTwo;
    }

    public int getColTwo() {
        return colTwo;
    }
}

/**
 * Returns the maximum rectangle in the matrix
 *
 * Complexity:
 *  O(row2 * col)
 *
 * @author javadeveloper
 */
public final class MaximumSumRectangeInMatrix {

    // made this utility class non-instantiable
    private MaximumSumRectangeInMatrix() { }

    private static class MaxSubArray {
        int start;
        int end;
        int maxSum;

        public MaxSubArray(int start, int end, int maxSum) {
            this.start = start;
            this.end = end;
            this.maxSum = maxSum;
        }
    }

    private static MaxSubArray maxSubArraySum(int[] a) {
        assert a != null && a.length > 0;

        int max = a[0];
        int currSum = a[0];

        int start = 0;
        int end = 0;

        for (int i = 1; i < a.length; i++) {
            currSum = currSum + a[i];
            if (a[i] > currSum) {
                start = i;
                currSum = a[i];
            }
            if (currSum > max) {
                max = currSum;
                end = i;
            }
        }
        return new MaxSubArray(start, end, max);
    }

    /**
     * Returns the RectangleCoord object containing the maximum
     * rectangle in the matrix.
     *
     * @param  The input matrix.
     * @return The rectanglecoor object containing the coordinates of the maximum sub matrix
     */
    public static RectangleCoord calMaxRectangle(int[][] m) {
        if (m.length == 0 || m[0].length == 0) {
            throw new IllegalArgumentException("The matrix should be non empty");
        }

        int max = Integer.MIN_VALUE;
        int rowOne = 0;
        int colOne = 0;
        int rowTwo = 0;
        int colTwo = 0;

        for (int fromRow = 0; fromRow < m.length; fromRow++) {
            int[] temp = new int[m[0].length];
            for (int toRow = fromRow; toRow < m.length; toRow++) {
                for (int col = 0; col < m[0].length; col++) {
                    temp[col] = temp[col] + m[toRow][col];
                }

                MaxSubArray maxSubArrayCoord = maxSubArraySum(temp);

                if (maxSubArrayCoord.maxSum > max) {
                    max = maxSubArrayCoord.maxSum;
                    rowOne = fromRow;
                    colOne = maxSubArrayCoord.start;
                    rowTwo = toRow;
                    colTwo = maxSubArrayCoord.end;
                }
            }
        }

        return new RectangleCoord(rowOne, colOne, rowTwo, colTwo);
    }

    public static void main(String[] args) {

        int[][] m = {  {-20, -30, -40, -50},
                       { 10,  20,  30,  50},
                       { 50,  60,  70,  80},
                       {-10, -20, -30, -40},
                    };

        RectangleCoord r = calMaxRectangle(m);
        System.out.println(r.getRowOne() + " : " + r.getColOne());
        System.out.println(r.getRowTwo() + " : " + r.getColTwo());

    }

}


texts:
I've been trying to understand the original MVC implementation (the Xerox Parc's one). I'm sure it has flaws, but it's simple code to practice/learn the original MVC.

Working example

View (index.html):

<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Person</title>

Birth Date:

Age:

Model (model-person.js):

var ModelPerson = (function () {
    'use strict';

    var ModelPerson = function (name, birthDate) {
        this.name = name;
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getName = function () {
        return this.name;
    };

    ModelPerson.prototype.setName = function (name) {
        this.name = name;
    };

    ModelPerson.prototype.getBirthDate = function () {
        return this.birthDate;
    };

    ModelPerson.prototype.setBirthDate = function (birthDate) {
        this.birthDate = birthDate;
    };

    ModelPerson.prototype.getAge = function () {
        var dateDifference = new Date(Date.now() - this.birthDate.getTime());
        return Math.abs(dateDifference.getFullYear() - 1970);
    };

    return ModelPerson;
}());

Controller (controller-person.js):

var ControllerPerson = (function () {
    'use strict';
    var controller;

    var ControllerPerson = function (modelPerson) {
        controller = this;
        controller.modelPerson = modelPerson;
    };

    ControllerPerson.prototype.initialize = function () {
        document.getElementById('person-name').addEventListener('blur', function () {
            controller.modelPerson.setName(this.textContent);
            controller.updateView();
        });

        document.getElementById('person-birth-date').addEventListener('blur', function () {
            controller.modelPerson.setBirthDate(new Date(this.textContent));
            controller.updateView();
        });

        controller.updateView();
    };

    ControllerPerson.prototype.updateView = function () {
        document.getElementById('person-name').textContent = this.modelPerson.getName();
        document.getElementById('person-birth-date').textContent = this.modelPerson.getBirthDate();
        document.getElementById('person-age').textContent = this.modelPerson.getAge();
        document.getElementById('json-model-representation').textContent = JSON.stringify(controller.modelPerson);
    };

    return ControllerPerson;
}());

Instantiation (main.js):

(function () {
    'use strict';
    var modelPerson = new ModelPerson('John Doe', new Date('1987-09-11')),
        controllerPerson = new ControllerPerson(modelPerson);

    controllerPerson.initialize(); }());

My model is the mental object model. My controller handles events and update the Model. The view is "dumb" and just presents the content.

Do you think it's like the original MVC? What's wrong? What am I missing?


texts:
I have implemented a HashMap which supports insertions of integer key value pairs. The approach uses an array for simplicity and uses a standard hash function. Please give a review on the coding approach used in the program.

import junit.framework.Assert;
import org.junit.Test;

public class HashMapImpl {
class HashMap {
    int SIZE_OF_TABLE = 128;
    HashEntry[] table;
    HashMap() {
        table = new HashEntry[SIZE_OF_TABLE];
        for (int i = 0; i < SIZE_OF_TABLE; i++) {
            table[i] = null;
        }
    }

    public void put(int key, int value) {
        int index = hashCodeNew(key);
        System.out.println(index);
        HashEntry hashEntry = new HashEntry(key, value);
        if (table[index] == null) {
            table[index] = hashEntry;
        } else {
            HashEntry runner = table[index];
            while (runner.next != null) {
                if (runner.key == hashEntry.key) {
                    runner.value = hashEntry.value;
                    break;
                } else {
                    runner = runner.next;
                }
            }
            if (runner.next == null) {
                if (runner.key == hashEntry.key) {
                    runner.value = hashEntry.value;
                } else {
                    runner.next = hashEntry;
                }
            }
        }

    }

    public int get(int key) {
        int index = hashCodeNew(key);
        if (table[index] == null) {
            return -1;
        } else {
            HashEntry runner = table[index];
            if (runner.key == key) {
                return runner.value;
            }
            while (runner.next != null) {
                if (runner.key == key) {
                    return runner.value;
                }
            }
            return -1;
        }
    }

    public int hashCodeNew(int h) {
        h ^= (h >>> 20) ^ (h >>> 12);
        int hashCode = h ^ (h >>> 7) ^ (h >>> 4);
        return hashCode % SIZE_OF_TABLE;
    }
}

class HashEntry {
    int key;
    int value;
    HashEntry next = null;

    HashEntry() {
    }

    public HashEntry(int key, int value) {
        this.key = key;
        this.value = value;
    }

    public int getKey() {
        return this.key;
    }

    public int getValue() {
        return this.value;
    }
}

@Test
public void testBasic() {
    HashMap hashMap = new HashMap();
    hashMap.put(10, 20);
    hashMap.put(20, 11);
    hashMap.put(21, 1);
    hashMap.put(20, 10);

    int value = hashMap.get(20);
    Assert.assertEquals(10, value);

}
}


texts: Python script to identify regex matches in all subdirs and write dict of matches to MongoDB

texts:
I've been attempting to teach myself Python over the past couple of months and have been setting myself practical challenges to learn different aspects of the language.

I have a deep structure of subdirectories containing .rtf files. The objectives of the following code are as follows:

Examine every file in every subdirectory to identify "flagged words" defined in expression.
For each instance a flagged word is identified in a file, capture the file name and the line within that file in which the flagged word appears.
Construct a dictionary, in which flagged words are keys and filenames and lines are stored as values.
Insert each key/value pair in the dictionary into a MongoDB collection

The code is as follows:

from pymongo import MongoClient
import os
import re
import json

# connect to mongodb

client = MongoClient('localhost', 27017)
db = client['test-database']
restrictions = db['restrictions']

# create empty dictionary

d = {}

# setup regular expressions

expression = "sexual offences|reporting restriction|reporting restrictions|anonymous|anonymously|secret"
pattern = re.compile(expression)

# read the source files

for dname, dirs, files in os.walk("path/to/top/level/directory"):

    for fname in files:
        fpath = os.path.join(dname, fname)

        with open(fpath, 'r') as f:
            source = f.readlines()

            for i, line in enumerate(source):

                for match in re.finditer(pattern, line):
                # set the matched flagword as the key and the filename and line as the value
                    d.setdefault(match.group(0), [])
                    file_instance = fname, line
                    print file_instance
                    d[match.group(0)].append(file_instance)

# Update the restrictions database

for key, value in d.iteritems():
    xref_id = db.restrictions.insert_one({'flagged_word': key, 'instance': value})

An example document in MongoDB generated by this code:

    {
        "_id" : ObjectId("5925e0d94fb263cb1417bb73"),
        "flagged_word" : "restriction",
        "instance" : [
            [
                "Family3.txt ",
                "ii)\tAn application for a reporting restriction order (\"reporting restriction order\") to restrict or prohibit the publication of:\n"
            ]
    }

The code works as expected, but I have a nagging feeling that the same objectives could be achieved with a far less clunky approach in the code (particularly where all of the for loops are concerned).

In the spirit of wishing to learn how to write clearer, more Pythonic code, I wonder if anyone could offer some advice on how this code could be improved. Many thanks in advance for taking the time to read my code.


texts: Array-based stack data structure in Java

texts:
I've recently been writing simple data structures, even though they exist in the library it helps me understand them a lot better.

public class Stack<E>
{
    private int capacity;
    private E[] data;
    private int top;

    /**
     * Default Constructor where the stack size is initially
     * set to 1000 elements.
     */
    public Stack(int capacity) {
        this.capacity = capacity;
        this.data = (E[])new Object[capacity];
        top = -1;
    }
    public Stack() {
        this(1000);
    }

    public int size() {
        return top + 1;
    }

    public boolean isEmpty() {
        return top == -1;
    }

    public E top() throws EmptyADTException {
        if(isEmpty())
            throw new EmptyADTException("Nothing in the stack!");
        return data[top];
    }

    public void push(E obj) {
        if(data.length == size())
            throw new IllegalStateException("Stack is full!");
        data[++top] = obj;
    }

    public E pop() throws EmptyADTException {
        if(isEmpty())
            throw new EmptyADTException("Nothing in the stack!");
        E popObj = data[top];
        data[top--] = null;
        return popObj;
    }
}

I know that there are drawbacks to using an array-based stack, because of the limited size. Although, in the long run, it is more efficient if the time per operation isn't an issue, when compared to a linked-list implementation. I've also heard of people now using something called a VList.

I was wondering, is there any way I can improve this code whilst still using an array-based stack?


texts: Build a combinatorial matrix from two vectors

texts:
I want to define a matrix of values with a very simple pattern. I've achieved it with the code below but it's ugly - very difficult to read (I find) and surely not as optimal, in terms of performance, as it could be. The former is really what I'm trying to address here. I feel this can be done much more elegantly and would love some guidance from the community.

Here is an example of what I am hoping to achieve, from x and y I want to get points:

y =

    10    30    50    70

x =

    10    30    50

points =

    10    10
    30    10
    50    10
    10    30
    30    30
    50    30
    10    50
    30    50
    50    50
    10    70
    30    70
    50    70

x and y are, of course, no always those exact vectors. They are, however, very simply created. Something like so:

scale = 20;
max_x = 85;
max_y = 62;

y_count = floor(max_x / scale);
x_count = floor(max_y / scale);

y = ((1:y_count) * scale) - scale / 2;
x = ((1:x_count) * scale) - scale / 2;

Here's my brute force approach:

y = repmat(y, x_count, 1);
y = reshape(y, 1, size(y, 1) * size(y, 2));
y = y';

x = repmat(x, y_count, 1);
x = x';
x = reshape(x, 1, size(x, 1) * size(x, 2));
x = x';

points = [x y];

It works, but it isn't very elegant.


texts: Check whether address criteria contain only certain fields or more

texts:
I have a method that checks whether an addressCriteria contains only certain fields or more.  If it contains more fields, it should return false, otherwise true.

I'm uncertain what the best way to write my if statement is. As far as I can tell, I see 2 options:

Write them in 1 if statement
Write each check in a different if statement

Single if statement:

private boolean isShortAddress(AddressCriteria addressCriteria) {
  if((null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) ||
      (null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) ||
      (null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) ||
      (null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty())) {
    return false;
  }

  return true;
}

Multiple if statements:

private boolean isShortAddress(AddressCriteria addressCriteria) {
  if(null != addressCriteria.getCity() && !addressCriteria.getCity().isEmpty()) {
    return false;
  }

  if(null != addressCriteria.getNumber() && !addressCriteria.getNumber().isEmpty()) {
    return false;
  }

  if(null != addressCriteria.getState() && !addressCriteria.getState().isEmpty()) {
    return false;
  }

  if(null != addressCriteria.getZipCode() && !addressCriteria.getZipCode().isEmpty()) {
    return false;
  }

  return true;
}

Maybe there's a 3rd or 4th option that I am unaware of?


texts: Triggering methods that change instance state on other objects using a Dictionary

texts:
I've been reading up on Actions and delegates for the last couple of days, and I think I'm finally starting to understand, but I wanted to check that I was using them correctly, or at least using them in a way that isn't totally insane.

I'm using a text-based game (as such) as a platform for learning about what I suspect is called event-oriented programming. For a really terrible example, imagine the player has a torch that can set things on fire. I don't want the torch to do target.ChangeState(States.OnFire), that's giving the torch way too much power over other objects - nothing is preventing an action like nonFlammableRock.ChangeState(States.OnFire) I COULD have the torch tell the game manager entity that it wants to set something on fire, and then let the game manager decide if it's allowed to do so... but instead, I came up with this:

TestObject

internal class TestObject
{
    private string instanceVar;
    private Dictionary<string, Action> eventHandlers;

    public TestObject(string newInstanceVar)
    {
        this.instanceVar = newInstanceVar;
        eventHandlers = new Dictionary<string, Action>();
        eventHandlers.Add("event0", PrintInstanceVar);
        eventHandlers.Add("event1", InstanceVarToUpper);
        eventHandlers.Add("event2", ChangeOwnInstanceVar);
    }

    public void PrintInstanceVar()
    {
        Console.WriteLine(instanceVar);
    }

    public void InstanceVarToUpper()
    {
        instanceVar = instanceVar.ToUpper();
    }

    public void Event(string eventName)
    {
        eventHandlers[eventName].Invoke();
    }

    public void ChangeOwnInstanceVar()
    {
        instanceVar = "Object has changed its instance variable";
    }
}

Program

private static void Main(string[] args)
    {
        var test1 = new TestObject("First test obejct");

        test1.Event("event2");
        test1.Event("event0");
        test1.Event("event1");
        test1.Event("event0");

        Console.ReadKey();
    }

In short, I want to tell an object what has happened to it, and then let the object itself decide what to do. In this way, a torch can send a message "ignite" to any object, and the target object itself looks up "ignite" in its dictionary of behaviours, and reacts accordingly. So for a Rock, eventHandlers["ignite"] = () => Console.WriteLine("The rock isn't flammable, the torch had no effect"), whereas for HayBale, eventHandlers["ignite"] = () => Console.WriteLine("The bale of hay catches alight").

Is this a sane approach? Are there any traps I've missed that will come back to haunt me later? Is there a better way of doing this? I know that C# Events exist, but I don't fully understand them yet, and I don't know how to use them to achieve what I'm trying to do here - but if using Events would be better, how would I change this?

Note:

I know individual entities shouldn't be responsible for printing to console - if I made this whole thing, they'd be sending updates as to their state, strings containing action text etc to the game manager, which would be responsible for displaying messages for the player.


texts:
Question

How can the following implementation of fractionParse be made
less ugly? (Preserving unreduced numerators and denominators is supposed to be a feature---as shown in the second example---so using readMaybe s :: Maybe (Ratio Int) doesn't really help.)

Things that irked me in the process of writing it, include:

Not being able to find a way to use do-notation in conjunction with Maybe in a way that would return as soon as Just appears rather than when the first Nothing appears. In other words a Maybe monad instance that emulates or rather than and.
case and pattern matching colliding in unhelpful ways, forcing me to write nested if-then-elses.

Usage examples

λ> fractionParse "2/3"
Fraction 2 3
λ> fractionParse "12 / 6"
Fraction 12 6
λ> fractionParse "23"
Whole 23
λ> fractionParse "a"
Rubbish
λ> fractionParse "2/3/4"
Rubbish
λ> fractionParse "2%3"
Rubbish

Implementation

import Text.Read (readMaybe)
import Data.String.Utils (split)
import Data.Maybe (isJust, fromJust)

data FractionParse = Fraction Int Int
                   | Whole Int
                   | Rubbish deriving (Show, Eq)

fractionParse :: String -> FractionParse
fractionParse s = let i = maybeInt s
                      r = maybeNumDenom s in
  if isJust r
  then let (Just (n,d)) = r in Fraction n d
  else if isJust i
       then Whole (fromJust i)
       else Rubbish

maybeInt :: String -> Maybe Int
maybeInt s = readMaybe s

maybeNumDenom :: String -> Maybe (Int, Int)
maybeNumDenom s = do
  if containsExactlyOneSlash s then Just () else Nothing
  let [ns,ds] = split "/" s
  n <- readMaybe ns
  d <- readMaybe ds
  return (n,d)

containsExactlyOneSlash s = (length $ filter (=='/') s) == 1


texts:
As a little standard exercise, I wrote an integer to roman numerals converter in F03. The result looks already neat enough, for my standards, but I wonder whether it could be made snappier without sacrificing clarity. For folks not familiar with the simple syntax of modern Fortran, I suggest the following quick modern Fortran tutorial.
module mRomanStrings

  implicit none
  private
  character(len=*), parameter :: RM_CHARS  = "IVXLCDMvxlcdm_"
  integer         , parameter :: MAX_ORDER = len(RM_CHARS)/2-1
  character(len=4)            :: ROMAN_STRING(0:9,0:MAX_ORDER)
  logical                     :: mRomanStringsIsNotInitialized = .TRUE.
  public :: IntegerToRoman

contains

  function IntegerToRoman(i) result(rm)
    integer         , intent(in)  :: i
    character(len=:), allocatable :: rm
    integer :: n
    if( mRomanStringsIsNotInitialized ) call mRomanSring_init()
    rm = " "
    do n = min(MAX_ORDER,int(log(dble(i))/log(10.d0)+1.d-10)), 0, -1
       rm = trim(rm)//trim(ROMAN_STRING(mod(i/10**n,10),n))
    enddo
  end function IntegerToRoman

  subroutine mRomanSring_init()
    character :: a0, a1, a2, a3
    integer :: n
    do n = 0, MAX_ORDER
       a0 = " "
       a1 = RM_CHARS(2*n+1:2*n+1)
       a2 = RM_CHARS(2*n+2:2*n+2)
       a3 = RM_CHARS(2*n+3:2*n+3)
       ROMAN_STRING(0:9,n) = [&
            a0//a0//a0//a0, a1//a0//a0//a0, a1//a1//a0//a0, a1//a1//a1//a0, a1//a2//a0//a0, &
            a2//a0//a0//a0, a2//a1//a0//a0, a2//a1//a1//a0, a2//a1//a1//a1, a1//a3//a0//a0 ]
    enddo
    mRomanStringsIsNotInitialized = .FALSE.
  end subroutine mRomanSring_init

end module mRomanStrings

program ConvertIntegersToRoman
  use, intrinsic :: iso_fortran_env
  use mRomanStrings
  implicit none
  integer :: i
  do i=1,10000
     write(OUTPUT_UNIT,"(i6,x,a)") i, IntegerToRoman(i)
  enddo
end program ConvertIntegersToRoman


texts:
I've been writing classic ASP.NET web services for a while now, and this is my first time writing a PHP based web service. I'm rather new to PHP as well.

In ASP.NET, you directly call the web method that you wish to be executed, but I'm not sure if PHP has a similar functionality.

Instead I'm calling a PHP page, and to it I'm passing the method name to be executed. Following is my code -

PHP Web Service

<?php
    require_once 'classes/CommonFunctionality.php';

    // Getting the json data from the request
    $json_data = json_decode(file_get_contents("php://input"));
    $response = '';

    // Checking if the data is null..
    if(is_null($json_data))
    {
        $response = json_encode(array("status" => -1, "message" => "Insufficient parmaters!"));
    }
    else
    {
        // Checking if it's null or if it exists...
        if(!property_exists($json_data, "MethodName") || is_null($json_data->MethodName) || function_exists($json_data->MethodName . "()"))
        {
            $response = json_encode(array("status" => 0, "message" => "Invalid function name."));
        }
        else
        {
            // Get method name...
            $methodName = $json_data->MethodName;
            // Call the method...
            $response = $methodName();
        }
    }
    header('Content-type: application/json');
    echo $response;

    /****************************
     * Methods defined for use. *
     ****************************/
    function GetAllCrmUsers()
    {
        // Adding crm users class.
        $userArray = CrmUsers::GetAllUsers();
        return json_encode(array("status" => 200, "value" => json_encode($userArray)));
    }
?>

AJAX call

// URL, Data to send, Call back function.
AjaxCall($("#hdnWbUrl").val() , {MethodName : 'GetAllCrmUsers'}, BindData);

Generic jQuery ajax method

function AjaxCall(url, data, callBack){
    $.ajax({
        url : url,
        type : 'POST',
        data : JSON.stringify(data),
        contentType : 'application/json utf-8',
        dataType : 'json',
        success : function(data, textStatus, jqxhr){
            callBack(data);
        },
        error : function (jqxhr, textStatus, errorMessage){
            console.log(argument);
        }
    })
}

Now my question is if there is a better way to do this, something that I might be unaware of.


texts:
I needed to impose on a Python method the following locking semantics: the method can only be run by one thread at a time. If thread B tries to run the method while it is already being run by thread A, then thread B immediately receives a return value of None.

I wrote the following decorator to apply these semantics:

from threading import Lock

def non_blocking_lock(fn):
    fn.lock = Lock()

    @wraps(fn)
    def locker(*args, **kwargs):
        if fn.lock.acquire(False):
            try:
                return fn(*args, **kwargs)
            finally:
                fn.lock.release()

    return locker

This works in my testing so far. Does anyone notice any gotchas or have any suggestions for improvements?

Revised version

After the suggestions by @RemcoGerlich, I have added a docstring and kept the lock local to the decorator:

from threading import Lock

def non_blocking_lock(fn):
    """Decorator. Prevents the function from being called multiple times simultaneously.

    If thread A is executing the function and thread B attempts to call the
    function, thread B will immediately receive a return value of None instead.

    """
    lock = Lock()

    @wraps(fn)
    def locker(*args, **kwargs):
        if lock.acquire(False):
            try:
                return fn(*args, **kwargs)
            finally:
                lock.release()

    return locker


texts:
I'm having trouble optimising the project euler #50 exercise, it runs for around 30-35 seconds, which is terrible performance.

  The prime 41, can be written as the sum of six consecutive primes:

  41 = 2 + 3 + 5 + 7 + 11 + 13
  This is the longest sum of consecutive primes that adds to a prime below one-hundred.

  The longest sum of consecutive primes below one-thousand that adds to a prime, contains 21 terms, and is equal to 953.

  Which prime, below one-million, can be written as the sum of the most consecutive primes?

The catch here is that it's not necessary to start from 2, the sum of consecutive primes which add to 953 are starting from 7.

Here's my code :

    static void Main(string[] args)
    {
        int max = 0;
        int maxCount = 1;
        List<int> primes = new List<int>();
        Stopwatch sw = Stopwatch.StartNew();
        bool[] allNumbers = SetPrimes(1000000);
        for (int i = 0; i < allNumbers.Length; i++)
        {
            if (allNumbers[i])
            {
                primes.Add(i);
            }
        }
        foreach (int prime in primes)
        {
            int startingIndex = 0;
            while (primes[startingIndex] < prime/maxCount)
            {
                int n = prime;
                int j = startingIndex;
                int sum = 0;
                int count = 0;
                while (n > 0)
                {
                    sum += primes[j];
                    n -= primes[j];
                    j++;
                    count++;
                }
                if (sum == prime)
                {
                    if (count > maxCount)
                    {
                        maxCount = count;
                        max = prime;
                    }
                }
                startingIndex++;
            }
        }
        sw.Stop();
        Console.WriteLine(max);
        Console.WriteLine($"Time to calculate : {sw.ElapsedMilliseconds}");
        Console.ReadKey();
    }

    private static bool[] SetPrimes(int max)
    {
        bool[] localPrimes = new bool[max + 1];
        for (int i = 2; i <= max; i++)
        {
            localPrimes[i] = true;
        }
        for (int i = 2; i <= Math.Sqrt(max); i++)
        {
            if (localPrimes[i])
            {
                for (int j = i * i; j <= max; j += i)
                {
                    localPrimes[j] = false;
                }
            }
        }
        return localPrimes;
    }


texts: Using dapper Unit of Work in 3-tier architecture

texts:
The Unit of Work:

public class UnitOfWork : IUnitOfWork
{
    private IDbConnection _connection;
    private IDbTransaction _transaction;

    private bool _disposed;
    private _repository;
    private UnitOfWork(string connectionString)
    {
        _connection = new SqlConnection(connectionString);
        _connection.Open();
        _transaction = _connection.BeginTransaction();
    }

    public static IUnitOfWork Create(string connectionString)
    {
        return new UnitOfWork(connectionString);
    }
   public IRepository Repository
    {
        get { return _repository ?? (_repository = new Repository(_transaction)); }
    }

    public void Commit()
    {
        try
        {
            _transaction.Commit();
        }
        catch
        {
            _transaction.Rollback();
            throw;
        }
        finally
        {
            _transaction.Dispose();
            _transaction = _connection.BeginTransaction();
            resetRepositories();
        }
    }

    private void resetRepositories()
    {
        _repository = null;
    }

    public void Dispose()
    {
        dispose(true);
        GC.SuppressFinalize(this);
    }

    private void dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                if (_transaction != null)
                {
                    _transaction.Dispose();
                    _transaction = null;
                }
                if (_connection != null)
                {
                    _connection.Dispose();
                    _connection = null;
                }
            }
            _disposed = true;
        }
    }

    ~UnitOfWork()
    {
        dispose(false);
    }
}

It's not my code. I took it from Tim Schreiber repository. I need transactions for add/update operations in my project.
And I use the Unit of Work in business logic assembly like this:

public class DealService : Service, IDealService
{
    public DealService(string connectionString)
        : base(connectionString)
    {

    }

    public async Task<User> GetUserAsync()
    {
        var user = null;
        using (var uow = UnitOfWork.Create(_connectionString))
        {
            user = await uow._repository.GetFirstAsync();
        }
        throw new NotImplementedException();
        //business logic here.
    }
}

Service.cs is an abstract class that has protected field _connectionString. And DI composition root I have in ASP.NET Core layer:

public IConfigurationRoot Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc();
        string connectionString = Configuration.GetConnectionString("default");

        services.AddTransient<IDealService, DealService>(service => new DealService(connectionString));

    }

I'm feeling that I do something wrong so I have several questions:

As you can see in current realization I have to pass connection string to each Service and then pass to UnitOfWork constructor. Is it right way or exists solution where I can set connection once?
I use Unit Of Work without injection and don't like it. But how can I do injection if I need to use Dispose()?

I will be very glad to any help and advice.


texts:
In order to test some software I've written, I need to write values to a test harness with OLE for Process Control (OPC).  The problem is, for a larger range of values I'm generating points for (say 10000), this code can take 15 seconds to execute.  I need it to work in under 1 second.

import OpenOPC
import argparse
import sys
import time
from random import randint

def get_args():
    parser = argparse.ArgumentParser(description='Record data value changes')
    parser.add_argument('range', type=int, help='range of values to record')
    parser.add_argument('time', type=int, help='time to update values in seconds')
    return parser.parse_args()

def get_range_list(amount, val, end):
    return [
        ('flcon1:DataValue~Osiris_Test_Data_' + str(i + 1) + end, randint(0, val))
        for i in range(amount)
    ]

def get_time_list(amount, end):
    return [
        ('flcon1:DataValue~Osiris_Test_Data_' + str(i + 1) + end, time.strftime('%m/%d/%Y %H:%M:%S'))
        for i in range(amount)
    ]

def main():
    args = get_args()
    opc = OpenOPC.open_client('localhost')
    opc.connect('SISCO.AXS4ICCP.3')

    print('Logging test harness value changes')
    while True:
        try:
            t0 = time.clock()
            value_list = get_range_list(args.range, 9, '.Value')
            time_list = get_time_list(args.range, '.TimeStamp')

            opc.write(value_list)
            opc.write(time_list)

            print('Wrote values')

            with open(str(args.range) + '.' + str(args.time) + '_1-iccp_harness.log', 'a') as f:
                for i in xrange(0, args.range):
                    f.write('Osiris_Test_Data_' + str(i + 1) + ', realQTimetagExtended' +
                            ', %g, %s, %s\n' % (value_list[i][1], 00, time_list[i][1]))

            t1 = time.clock()
            print t1-t0

            print('Logged values')
            time.sleep(args.time)

        except KeyboardInterrupt:
            opc.close()
            print('Closing down logger')
            sys.exit()

if __name__ == '__main__':
    main()


texts:
I've written a short web scraper in Lua (run in LuaJIT for speed) to download every post from a specific forum (not general purpose... yet). It takes about 12 hours to run and download 500,000 posts and there are no errors. I'm wondering how I can make it faster. I know different places where the code can be better in readability and structure, but not how it could be better in speed.

local https = require("ssl.https")
local tcount, pcount = 0,0
local threads = {}
local posts = {}
local root = --the forum url

local output = io.open("output.txt", "a")

function scrape(address, p)
    local request_body = [[]]
    local response_body = {}

    local res, code, response_headers = https.request{
        url = address,
        method = "GET",
        source = ltn12.source.string(request_body),
        sink = ltn12.sink.table(response_body),
    }

    if res ~= 1 or code ~= 200 then print(res, code) end

    if type(response_headers) == "table" and p then --if the function is called with a p param, print the response headers
        for k,v in pairs(response_headers) do
            print(k, v)
        end
    end
    if code == 301 then
        print("Location", response_headers["location"])
    end

    if type(response_body) == "table" then
        response_body = table.concat(response_body) --every response in this instance is a table, so I would probably be able to take out this if statement.
    else
        print("Not a table:", type(response_body))
    end
    return response_body
end

function parse_posts(response_body)
    for match in string.gmatch(response_body, '
.-
') do
        local m = string.gsub(match, '.-', ""):gsub([[</?[^>q]+>]], ""):gsub("\n", "
")
        output:write(m..'\n')
        pcount = pcount+1
    end
end

function get_threads(response_body)
    string.gsub(response_body, [[(%d+)]], function (m) if tonumber(m) > p then p = tonumber(m) end end)
    for i = p, 1, -1 do
        parse_posts(scrape(url.."/?page="..tostring(i)))
        --print("Scraping", url.."/?page="..tostring(i))
    end
end

do
    print("Getting threads")
    for i = 1528, 1, -1 do
        local url = root .. '/threads/?page='..tostring(i)
        get_threads(scrape(url))
    end
end

do
    print("Getting pages on each thread")
    for id,url in pairs(threads) do
        print("Writing for id", id)
        if id ~= 1121 and id ~= 1217 and id ~= 441 then     --exclude three specific large threads, i intend to remove this next iteration in favor of just removing them: threads[1121] = nil, but i do not believe that will improve speed at all.
            get_pages(scrape(url), url)
        end
        tcount = tcount+1
    end
end

print(string.format("Finished scraping %d posts across %d threads.", pcount, tcount))
output:close()
```


texts:
I actually feel bad posting "yet another singleton"... I wrote the following one many years ago and had recently found another application for it. We had many threads, each running the same function that requires the use of a boost::asio::io_service instance. It was best that all threads shared the same io_service instance and also that that instance be destroyed before main returned. That last requirement (whose validity I now question, but, whatever..) meant no global or static object.

Here's a function that returns an instance of an object wrapped in a shared_ptr. What's special about it though is that we keep an additional reference count so the singleton is eagerly destructed when the last shared_ptr is gone.

For example, if you call the function twice, you have two shared_ptrs, each with a ref-count of 1, but our singleton's ref-count is 2. On the other hand, if you call the function only once and copy the returned shared_ptr, the shared_ptr has a ref-count of 2 but our singleton's ref-count is at one. Either way, the singleton instance gets destructed when the last shared_ptr is destructed.

One disadvantage of this code is that the class is instantiated from its default constructor.

#include <memory>
#include <mutex>

// Deleter function given to the shared_ptr returned by get_shared_singleton.
template<typename T>
void release_shared(std::mutex& m, int& n, T*& p)
{
    std::lock_guard<std::mutex> lg(m);
    if(!--n)
    {
        delete p;
        p = 0;
    }
}

template<typename T>
std::shared_ptr<T> get_shared_singleton()
{
    static std::mutex m;

    std::lock_guard<std::mutex> lg(m);

    static int n = 0;   // Ref count.
    static T* p = 0;

    if(!p) p = new T();
    ++n;

    return std::shared_ptr<T>(p, std::bind(release_shared<T>, std::ref(m), std::ref(n), std::ref(p)));
}

The requirements, more clearly stated:

You wrote a function foo() that requires an instance of object X to perform its duty.
foo() can be invoked concurrently from different threads.
Concurrent foo()s must share the same instance of object X.
If no foo() is running, there must be no instance of object X alive.
foo() is in a library, you have no control of main() or the lifetime of threads that invoke foo().

What is the best code to provide a shared instance of an object that is both lazily-constructed and eagerly-destructed?


texts: Is this Agent/Actor implementation issue free?

texts:
I implemented this Agent class for a project recently and was wondering if I could get some other eyes to look at it -- I'm currently the only developer where I work so I can't exactly ask someone here to do it.

I'm pretty sure it's correct, but then I'm too close to it.

public abstract class Agent<M> : IDisposable
{
    private Thread thread;
    private Queue<M> messageQueue;
    private bool quit;

    public Agent()
    {
        this.thread = new Thread(new ThreadStart(AgentThreadBody));
        this.messageQueue = new Queue<M>();
        this.quit = false;

        this.thread.Start();
    }

    /// <summary>
    /// Stops the message-handling thread.
    ///
    /// Do not call this method from within the message-
    /// handling method, or it will result in a deadlock
    /// (because this method waits for the message-handling
    /// thread to stop).
    /// </summary>
    public virtual void Dispose()
    {
        this.quit = true;
        this.thread.Interrupt();
        this.thread.Join();
        this.thread = null;
        // clear messageQueue before nulling?
        // (would do this to dispose queued items)
        this.messageQueue = null;
    }

    public void QueueMessage(M message)
    {
        lock (this.messageQueue)
        {
            this.messageQueue.Enqueue(message);
            this.thread.Interrupt();
        }
    }

    private void AgentThreadBody()
    {
        while (!this.quit)
        {
            M message = default(M);
            bool messageAvailable = false;

            lock (messageQueue)
            {
                if (messageQueue.Count > 0)
                {
                    message = messageQueue.Dequeue();
                    messageAvailable = true;
                }
            }

            try
            {
                if (!messageAvailable)
                {
                    // if the Interrupt() method was
                    // called before we sleep or is
                    // called while we're sleeping,
                    // this will throw:
                    // ThreadInterruptedException
                    Thread.Sleep(Timeout.Infinite);
                }
            }
            catch (ThreadInterruptedException)
            {
                // we have a new message to handle,
                // so get it, or we've been told
                // to quit.
                continue;
            }

            ProcessMessage(message);
        }
    }

    protected abstract void ProcessMessage(M message);
}

Also, are there any special considerations you can think of that should be made by a class inheriting from this base class? (I can't think of any.)

I could add start/stop methods, but at the moment they're not needed.

Btw, I have to use .NET 3.5.


texts: this is my realloc version, is it good ? any suggestion are welcomed

texts:
I am trying to recode some c functions myself.
This is an my implementation of realloc function, any updates or suggestion about how to improve it are welcomed.
void    *ft_realloc(void *old_ptr, size_t old_size, size_t size) {
    void *new_ptr;

    if (size == 0 && old_ptr != NULL)
    {
        free (old_ptr);
        return (NULL);
    }
    else if (old_ptr == NULL)
    {
        if (!(old_ptr = malloc (size)))
            return (NULL);
        ft_memset(old_ptr, 0, size);
        return (old_ptr);
    }
    else if (size >= old_size) {
        if (!(new_ptr = malloc (size)))
            return (NULL);
        ft_memset(new_ptr, 0, size);
        ft_strncpy (new_ptr, old_ptr, old_size);
        free (old_ptr);
        return (new_ptr);
    }
    else if (size < old_size)
    {
        if (!(new_ptr = malloc(size)))
            return (NULL);
        ft_memset(new_ptr, 0, size);
        ft_strncpy (new_ptr, old_ptr, size);
        free (old_ptr);
        return (new_ptr);
    }
    return (NULL);
}

ft_memset and ft_strncpy are just my implementation of memset and strncpy they behave the same way!


texts: Validation of Identification card fields (string and array)

texts:
I am validating two variables of an Identification card (cedula in the code). The first one is a string and the second is an array.

My inputs are:

1- e.g. 3-728-2208
2- e.g. array('1' => '3-728-2208', '2' => '1-728-2208')

My method is :

public function validateId($cedula)
{
    $rules = ['cedula' => 'cedula'];

    $input = ['cedula' => $cedula];
    if(is_array($cedula))
    {
        $validator = $this->validateIdIsArray($cedula);
    } else {
        $validator = Validator::make($input, $rules);
    }

    return !($validator->fails());
}

public function validateIdIsArray($cedula)
{
    $rules = ['cedula' => 'cedula'];

    foreach ($cedula as $ids) {
        $input = ['cedula' => $ids];
        $validator = Validator::make($input, $rules);
    }

    return !($validator->fails());
}

My method from Rule:

public function passes($attribute, $value)
{
   return preg_match('/^((\d{1,2}|N|E|PE|\d{1,2}PI)-\d{1,5}-\d{1,6})$/u', $value);
}


texts: Better container for tracking number of string elements?

texts:
I'm looking for the most simple and efficient way to track the number of string elements in a container.

I'm currently using std::vector but I wonder if there's a better container which is more suitable for my purpose.

My Code :

#include <iostream>
#include <string>
#include <vector>

class Table
{
public:
    void insert(const std::string &name)
    {
        data.push_back(name);
    }
    void remove(const std::string &name)
    {
        auto it = std::find(data.begin(), data.end(), name);
        if (it != data.end())
            data.erase(it);
    }
    /* get the number of occurrences */
    int count(const std::string &name)
    {
        auto num = std::count(data.begin(), data.end(), name);
        return static_cast<int>(num);
    }
private:
    std::vector<std::string> data;
};

int main(int argc, const char * argv[])
{
    Table table;
    table.insert("Apple");
    table.insert("Apple");
    table.insert("Orange");
    table.insert("Orange");
    table.remove("Orange");
    std::cout << "Number of Apples : " << table.count("Apple") << std::endl;
    std::cout << "Number of Oranges : " << table.count("Orange") << std::endl;
    std::cout << "Number of Lemons : " << table.count("Lemon") << std::endl;
    return 0;
}

The Result :

Number of Apples : 2
Number of Oranges : 1
Number of Lemons : 0
Program ended with exit code: 0

Is there a way to improve the class Table so my program can be more efficient?

And would you recommend a different container than std::vector for the class Table?

P.S: Usually, from 50 to 500 strings will be stored to a container in my program.


texts: Changing the environment if it sees the incorrect environment in the setting

texts:
I am using the function below to change the environment. If it sees the wrong environment values, it clicks on it and it changes the environment.
In this function, I am just using if and else statement. Is this a good code practice? This does the job however it does not seem clean.
class SettingsPage extends Page {

changeEnvironment(appName) {
        if (appName.$(PreferenceScreen.environmentProduction).isDisplayed()) {
            appName.$(PreferenceScreen.environmentProduction).click();
        }
        else if
            (appName.$(PreferenceScreen.environmentDevelopment).isDisplayed()) {
             appName.$(PreferenceScreen.environmentDevelopment).click();
        }
    }
}


texts:
I've always been bothered by the fact that there weren't any built-in functions that could replace multiple substrings of a string in Python, so I created this function. Essentially, you supply it with a string, a dictionary of keys (substrings) and values (replacements), and then a few additional options.

def keymap_replace(
        string: str,
        mappings: dict,
        lower_keys=False,
        lower_values=False,
        lower_string=False,
    ) -> str:
    """Replace parts of a string based on a dictionary.

    This function takes a string a dictionary of
    replacement mappings. For example, if I supplied
    the string "Hello world.", and the mappings
    {"H": "J", ".": "!"}, it would return "Jello world!".

    Keyword arguments:
    string       -- The string to replace characters in.
    mappings     -- A dictionary of replacement mappings.
    lower_keys   -- Whether or not to lower the keys in mappings.
    lower_values -- Whether or not to lower the values in mappings.
    lower_string -- Whether or not to lower the input string.
    """
    replaced_string = string.lower() if lower_string else string
    for character, replacement in mappings.items():
        replaced_string = replaced_string.replace(
            character.lower() if lower_keys else character,
            replacement.lower() if lower_values else replacement
        )
    return replaced_string

Here's some example usage:

print(keymap_replace(
    "Hello person. How is your day?",
    {
        "hello": "goodbye",
        "how": "what",
        "your": "that",
        "day": ""
    },
    lower_keys=False,
    lower_values=False,
    lower_string=True
))


texts: Return sizeof a struct containing members ordered like given template parameters

texts:
template<typename... T>
constexpr std::size_t sizeof_struct()
{
    // Helper
    auto alignto = [](auto x, auto a) { return (x + a - 1) / a * a; };
    // Algorithm
    std::size_t max_align{0};
    std::array<std::pair<std::size_t, std::size_t>, sizeof...(T)> arr{{
        {alignof(T), sizeof(T)}...
        }};
    auto sum = std::accumulate(
        std::begin(arr), std::end(arr), std::size_t{0},
        [&max_align, alignto] (auto s, auto&& it) {
            max_align = std::max(it.first, max_align);
            return alignto(s, it.first) + it.second;
        });
    return max_align ? alignto(sum, max_align) : 1;
}

Is there any type I can put in the parameter pack T... that can break this code?  Anything else that doesn't look right?  Anything I can clean or make more concise?


texts:
I'm new to OOP PHP and I created a simple input helper class. And was wondering if it's good? Are my dependencies good?

Also the reason I'm not throwing an exception with the get method is that I will mainly use this class for form validation purposes.

I'll take any suggestion for improvement!

class Input {
    private $_get,
            $_post;

    public function __construct(Array $get, Array $post) {
        $this->_get  = $get;
        $this->_post = $post;
    }

    public function exists($type = 'POST') {
        switch($type) {
            case 'POST':
                return (!empty($this->_post)) ? true : false;
            break;
            case 'GET':
                return (!empty($this->_get)) ? true : false;
            break;
            default:
                return false;
            break;
        }
    }

    public function get($input, $source = 'POST') {
        if($source == 'POST' && isset($this->_post[$input])) {
            return $this->_post[$input];
        } elseif($source == 'GET' && isset($this->_get[$input])) {
            return $this->_get[$input];
        }
        return false;
    }
}

I figured I could made my code shorter:

class Input {
    private $_source;

    public function __construct(Array $source) {
        $this->_source = $source;
    }

    public function exists() {
        return !empty($this->_source);
    }

    public function get($input) {
        return (isset($this->_source[$input])) ? $this->_source[$input] : false;
    }
}


texts:
I came up with a solution for the InterviewStreet problem "Triplet"

In short, there is an integer array d which does not contain more than two elements of the same value. How many distinct ascending triples (d[i] < d[j] < d[k], i < j < k) are present?

It successfully passes 9 test cases of 15. but my solution exceeds time limit in other test cases.

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;

/**
 *
 * @author Dumindu
 */
public class Triplets {
    public static void main(String args[])
    {
        int[] arr,helper;
        Scanner scn=new Scanner(System.in);
        int x=scn.nextInt();
        arr=new int[x];
        helper=new int[x];
        for(int i=0;i<x;i++)
        {
            arr[i]=scn.nextInt();
        }
        int triplets=0;
        helper[0]=0;
        Map<Integer,Integer> map1=new HashMap<Integer,Integer>();

        for(int i=0;i<x;i++)
        {
            int minVals=0;

            Set<Integer> set=new HashSet<Integer>();
            int tempTrip=0;
            for(int j=i-1;j>=0;j--)
            {
                if(arr[j]<arr[i] && !set.contains(arr[j]))
                {
                    minVals++;
                    tempTrip+=helper[j];
                    set.add(arr[j]);
                }
            }
            helper[i]=minVals;
            if(!map1.containsKey(arr[i]))
            {
                triplets+=tempTrip;
                map1.put(arr[i],tempTrip);
            }
            else
            {
                triplets=triplets-map1.get(arr[i])+tempTrip;
            }
        }
        System.out.println(triplets);
    }

}

If there is a way to optimize this solution or approach it differently, please let me know.


texts: Finding word acronyms for telephone numbers

texts:
Having read most of Learn You a Haskell as well as parts of Real World Haskell, I decided to embark on an easy project to see if I can apply the Haskell that I've learned.

{-# LANGUAGE OverloadedStrings #-}

import Data.Maybe
import Text.Regex.TDFA
import qualified Data.ByteString.Char8 as B

main = do
       dictionary <- B.readFile "words.txt"
       putStrLn "What is your phone number?"
       phoneNumber <- getLine
       B.putStrLn (outputMessage (getMatches dictionary (toPattern phoneNumber)))

outputMessage :: Maybe [B.ByteString] -> B.ByteString
outputMessage Nothing   = "Some input was incorrect. Make sure no letters or numbers with 0 or 1 are being used."
outputMessage (Just []) = "Sorry. No matches were found."
outputMessage (Just x)  = "Matching words: \n" `B.append` ( B.unlines x)

getMatches _       Nothing        = Nothing
getMatches _       (Just "")      = Just []
getMatches words   (Just pattern) = if (words == B.empty)
                                    then error "Was not able to read dictionary file."
                                    else Just (getAllTextMatches (words =~ (B.pack ("\\b" ++ pattern  ++ "\\b")) ))

toPattern = parseList . map toRegex . readNumber

parseList list
    | Nothing `elem` list = Nothing
    | otherwise = Just (concat . catMaybes $ list)

toRegex :: (Data.String.IsString a1, Num a, Eq a) => a -> Maybe a1
toRegex 2 = Just "(a|b|c)"
toRegex 3 = Just "(d|e|f)"
toRegex 4 = Just "(g|h|i)"
toRegex 5 = Just "(j|k|l)"
toRegex 6 = Just "(m|n|o)"
toRegex 7 = Just "(p|q|r|s)"
toRegex 8 = Just "(t|u|v)"
toRegex 9 = Just "(w|x|y|z)"
toRegex _ = Nothing

readNumber :: [Char] -> [Integer]
readNumber = map $ read . (:"")

I'm interested in any suggestions for making my code more efficient/idiomatic.


texts:
I'm learning object oriented programming and am still trying to understand the best way to structure a class for modularity and attempting to follow DRY principles. I currently created a class containing multiple requests that share the same self.reponse block repeatedly. I am not sure the best way to abstract this outside of each function call since I am also returning the response object within each method.

My code currently looks like this:

import requests
import urllib3
import logging
import re
from itertools import zip_longest

log = logging.getLogger()

server = "https://example.com"
organization = "/example/"
username = "example@example.com"
PAT = "xxxxxxxxxxxxxxxxxxxxx"

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

class InvokeRequest():
    def __init__(self):
        self.server = server + organization

    # Get All Repositories
    def getRepositories(self, project):
        self.URL = self.server + project + "/_apis/git/repositories"
        self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
        return self.response.json()

    # Get All Build Definitions
    def getBuildDefinitions(self, project):
        self.URL = self.server + project + "/_apis/build/definitions/"
        self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
        return self.response.json()

    # Get Specific Build Definition
    def getBuildDefinitionID(self, project, ID):
        self.URL = self.server + project + "/_apis/build/definitions/" + str(ID)
        self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
        return self.response.json()

    # Get All Release Definitions
    def getReleaseDefinitions(self, releaseID):
        self.URL = self.server + releaseID + "/_apis/git/releaseID"
        self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
        return self.response.json()

request = InvokeRequest()

repos = request.getRepositories("DevOps")

list_of_repos = []
for repo in repos["value"] or []:
    list_of_repos.append(repo["name"])

buildDefinitions = request.getBuildDefinitions("DevOps")

build_definition_IDs = []
build_pipeline_names = []
for build in buildDefinitions["value"]:
    if build["queueStatus"] == "enabled":  # Skip over disabled builds
        build_definition_IDs.append(build["id"])
        build_pipeline_names.append(build["name"])

associated_build_repos = []  # Repos containing an associated build pipeline
for ID in build_definition_IDs:
    buildDefinition = request.getBuildDefinitionID("DevOps", ID)
    log.debug(buildDefinition["repository"].get("name"), "has pipeline")
    try:
        associated_build_repos.append(buildDefinition["repository"].get("name"))
    except KeyError as e:
        log.error(e)

For now, I am only passing a single project "DevOps", however, this will change in the future. I want to find a way to prevent repeating this specific block of code:

self.response = requests.get(self.URL, auth=(username, PAT), verify=False)
return self.response.json()

I have considered creating a base class called InvokeRequestConfig() or something similar to create the setup of the server and response object, that way I could inherit that class in InvokeRequest(). however I think that adds a lot of complexity that might not be necessary.

What is the best way to reuse the code above to make it more modular and follow best practices of OOP and DRY?


texts: Populating a list of all .wtv files across 4 hard drives

texts:
I am using Vba excel to populate a list of all my .wtv files using the .GetDetailsOf method. There are some 3000 files across 4 hard drives filed in a b c... subdirectories.

This sends my memory usage from just over 4 (normal) to nearly the full 8 GB available and halts my computer for a short time.

Is there a better method or something else i can set that doesn't force windows to open every file?

(This is a mash up of two codes on the net found here and here

Option Explicit
Sub GetDetails()

Cells.Select
Selection.ClearContents
Range("A1").Select

Dim fso, oFolder, oSubfolder, queue As Collection 'removed oFile,

Dim dirs As Variant
Dim oShell As Object
Dim oFile As Object
Dim oFldr As Object
Dim lRow As Long
Dim iCol As Integer

Dim fArray As Variant
fArray = Array("K:\Video_Store\Movies_a_k", "I:\Video_Store\Movies_j_r", "J:\Video_Store\Movies_The", "H:\Video_Store\Movies_s_z")
Dim vArray As Variant
vArray = Array(0, 21, 27, 1, 260, 15, 253, 261, 16, 259, 177, 19) 'removed
'0=Name, 21=Title, 27=length, 01=size, 260=recordingtime, 15=year, 253=channelno,
'261=stationcallsign, 16=genre, 259=progdesc, 177=path, 19=rating

Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection

lRow = 1

For dirs = LBound(fArray) To UBound(fArray)
    queue.Add fso.GetFolder(fArray(dirs)) 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue

            Set oShell = CreateObject("Shell.Application")
            Set oFldr = oShell.Namespace(CStr(oSubfolder))
                With oFldr
'                    For iCol = LBound(vArray) To UBound(vArray)
'                        Cells(lRow, iCol + 1) = .GetDetailsOf(.Items, vArray(iCol))
'                    Next iCol
                    For Each oFile In .Items
                        lRow = lRow + 1
                        For iCol = LBound(vArray) To UBound(vArray)
                            Cells(lRow, iCol + 1) = .GetDetailsOf(oFile, vArray(iCol))
                        Next iCol
                    Next oFile
                End With

        Next oSubfolder
'        For Each oFile In oFolder.Files
'            '...insert any file processing code here...
'        Next oFile
    Loop

Next dirs

End Sub