texts:
I'm implementing basic sorting algorithms to learn them, and coding, better. Criticisms and possible optimizations welcome.

import unittest
import random

def merge_sort(seq):
    """Accepts a mutable sequence. Utilizes merge_sort to sort in place, return
    a sorted sequence"""
    if len(seq) == 1:
        return seq
    else:
        #recursion: break sequence down into chunks of 1
        mid = len(seq)/2
        left = merge_sort(seq[:mid])
        right = merge_sort(seq[mid:])

        i, j, k = 0, 0, 0 #i= left counter, j= right counter, k= master counter

        #run until left or right is out
        while i < len(left) and j < len(right):
            #if current left val is < current right val; assign to master list
            if left[i] < right[j]:
                seq[k] = left[i]
                i += 1; k += 1
            #else assign right to master
            else:
                seq[k] = right[j]
                j += 1; k += 1

        #handle remaining items in remaining list
        remaining = left if i < j else right
        r = i if remaining == left else j

        while r < len(remaining):
            seq[k] = remaining[r]
            r += 1; k += 1

        return seq

class test_mergesort(unittest.TestCase):
    def test_mergesort(self):
        test = [random.randrange(0, 10000) for _ in range(2000)]
        self.assertEqual(merge_sort(test), sorted(test))

if __name__ == '__main__':
    unittest.main()


texts:
This function (find_prefix) is supposed to find words starting with a given prefix in a container. The container is sorted. This function is a fairly performance-critical part of the code, so I am open for any optimization suggestions. Here is a brief usage case; test_in is a file with \n separated English words:

#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
#include <iterator>
#include <tuple>
#include <fstream>

template <typename It_beg, typename It_end, typename Prefix>
auto find_prefix(const It_beg beg,
                 const It_end end,
                 Prefix prefix)
{
  auto low = std::lower_bound(beg, end, prefix);
  ++prefix.back();
  auto up = std::lower_bound(beg, end, prefix);
  return std::make_tuple(low, up);
}

int main()
{
  std::string s;
  std::fstream file("test_in");
  if (!file)
  {
    std::cerr << "Failed to open the file\n";
    return -1;
  }

  std::vector<std::string> svec;
  svec.reserve(470000);

  while (file >> s)
  {
    svec.push_back(s);
  }

  std::sort(svec.begin(), svec.end());

  while (std::cin >> s)
  {
    auto [beg, end] = find_prefix(svec.cbegin(), svec.cend(), s);
    std::copy(beg, end, std::ostream_iterator<std::string>(std::cout, "\n"));
  }

  return 0;
}

When the input is "stack" we get this output:

stack
stack's
stack-garth
stackable
stackage
stacked
stackencloud
stacker
stackering
stackers
stacket
stackfreed
stackful
stackgarth
stackhousiaceous
stacking
stackless
stackman
stackmen
stacks
stackstand
stackup
stackups
stackyard


texts: Calculating the joint probability of n events from a sample sequence of occurrences

texts:
I'm writing an algorithm to take in a sample list of sequences of events, calculate 1-step transitional probabilities from the sequences, forward or in reverse, then calculate the joint probability of n events occurring from those conditional probabilities.

Eg. if the sample list of sequences is:

  ['TTAGCAGTCAGT', 'TCAGCGTTCGACTGA']

cond_probs() produces a dictionary {'AT': n1, 'AG': n2, 'AA': n3, 'AC': n4, ... , 'TC': n16}, where, for one, n1 + n2 + n3 + n4 = 1, from those sequences. In reverse, the transitional probabilities are calculated with the sequences in reverse.

With that dictionary, exp_joint_probs() produces another dictionary which, when n = 3, looks like {'TTA': m1, 'TTC': m2, ..., 'GAC': m64}, where 'TTA' is calculated by P('T') * P('TT') * P('TA'). In reverse, it is P('A') * P('AT') * P('TT'), but the dictionary entry should still be 'TTA'.

I'm wondering if my algorithm could be cleaner. I feel that perhaps using Numpy would make it much nicer, so a word from a Numpy expert would be great. I'm also looking for help double-checking the math.

from collections import Counter
from itertools import product

def exp_joint_probs(seqList, n, reverse = 0):
    probs = {}
    counts = Counter(''.join(seqList))
    states = counts.keys()
    sumv = sum(counts.values())
    initProbs = {c: counts[c] / float(sumv) for c in counts}
    condProbs = cond_probs(seqList, reverse)
    paths = product(counts.keys(), repeat = n)
    for p in paths:
        p = ''.join(p)
        if reverse == 0:
            probs[p] = initProbs[p[0]]
            for i in range(n - 1):
                probs[p] = probs[p] * condProbs.get((p[i], p[i + 1]), 0)
        else:
            probs[p] = initProbs[p[2]]
            for i in range(n)[::-1][:-1]:
                probs[p] = probs[p] * condProbs.get((p[i], p[i - 1]), 0)
   return probs

def cond_probs(seqList, reverse = 0):
    counts = {}
    probs = {}
    for seq in seqList:
        if reverse:
            for i in range(len(seq))[::-1][:-1]:
                counts[seq[i],seq[i - 1]] = counts.get((seq[i], seq[i - 1]), 0) + 1
        else:
            for i in range(len(seq) - 1):
                counts[seq[i],seq[i + 1]] = counts.get((seq[i], seq[i + 1]), 0) + 1
    states = list(set(k[0] for k in counts.keys()))
    for s in states:
        if reverse:
            sCounts = dict((k,v) for (k,v) in counts.items() if k[1] == s)
        else:
            sCounts = dict((k,v) for (k,v) in counts.items() if k[0] == s)
        sumv = sum(sCounts.values())
        probs.update({(k,float(v)/sumv) for (k, v) in sCounts.items()})
    return probs


texts:
Looking for feedback on any bad practices and general advice on how I might better structure my code.

$(function() {
    // Load song on page load
    var song = new Audio('./songs/DJ Snake - Middle (Bad Royale Remix).mp3');
    song.load();

    // Update song duration display
    song.addEventListener('timeupdate', function(){
        updateTime(song);
    });

    // Set the play/pause button to play when song ends
    song.onended = function() {
        $('#play-pause').toggleClass('fa-play').toggleClass('fa-pause');
    };

    // Play or pause song when play/pause button pressed
    $('#play-pause').click(function() {
        togglePlay(song);
    });

    // Play song that was clicked
    $('.song').click(function() {
        if (!song.paused) {
            togglePlay(song);
        }
        song.src = "./songs/" + $(this).data('audio-src');
        $('#current-artist').text($(this).find('.artist').text() + " - ");
        $('#current-title').text($(this).find('.title').text());
        $('#current-artwork').attr('src', $(this).find('.artwork').attr('src'));
        song.load();
        song.currentTime = 0;
        togglePlay(song);
    });

    // Marquee scrolling for current song info
    setInterval(function() {
        var $elmt = $('.current-song-info');
        if ($('h1', $elmt).prop('scrollWidth') > $elmt.width()) {
            if (typeof mq === 'undefined') {
                mq = $('.marquee').marquee({
                    duration: 15000,
                    delayBeforeStart: 0,
                    pauseOnHover: true,
                    startVisible: true,
                    gap: 15,
                    duplicated: true
                });
            }
        } else if (typeof mq !== 'undefined') {
            mq.marquee('destroy');
            mq = undefined;
        }
    }, 1000);
});

function togglePlay(song) {
    if (song.paused) {
        song.play();
    } else {
        song.pause();
    }
    $('#play-pause').toggleClass('fa-play').toggleClass('fa-pause');
}

function updateTime(song) {
    var currentMinutes = Math.floor(song.currentTime / 60);
    var currentSeconds = (Math.floor(song.currentTime % 60) < 10 ? '0' : '' ) + Math.floor(song.currentTime % 60);

    $('#current-time').text(currentMinutes + ":" + currentSeconds);
    $('#progress').css('width', song.currentTime / song.duration * 100 + '%');
}


texts:
I've been trying to learn how to use the TPL for quite some time now.
Basically I'm trying to fire off a group of Tasks, wait for them to complete and then fire off another group of tasks, waiting for them to complete before firing off the tasks that update form elements on the UI Thread.

Here's what I got. I think I'm probably overcomplicating it however it does seem to work as I want it too.
Please could I have some advice on how I could simplify this based on what I want to achieve?

private async Task PrepareData()
{
    Task[] FirstTasks = new Task[] { TaskOne(), TaskTwo() };    // Do First group of Tasks
    await Task.WhenAll(FirstTasks); // Wait for First group of Tasks

    Task[] SecondTasks = new Task[] { TaskThree(), TaskFour() }; // Do Second group of Tasks
    await Task.WhenAll(SecondTasks).ContinueWith(c => // Wait for Second group of Tasks
        {
            GuiTaskOne();
            GuiTaskTwo();
        }, TaskScheduler.FromCurrentSynchronizationContext());  // Then update the form on the UI Thread
}

private async Task TaskOne()
{
    someVariable = await Task.Run(() => DoSomething());
}

private async Task TaskTwo()
{
    someVariable = await Task.Run(() => DoSomething());
}

private async Task TaskThree()
{
    someVariable = await Task.Run(() => DoSomething());
}

private async Task TaskFour()
{
    someVariable = await Task.Run(() => DoSomething());
}

private async Task GuiTaskOne()
{
    someControl.Text = await Task.Run(() => DoSomething());
}

private async Task GuiTaskTwo()
{
    someControl.Text = await Task.Run(() => DoSomething());
}


texts: Simplifying constructing native SQL query with nested if-else's

texts:
I've a method which is used to build a native sql query. I've 4 String builder as input and based on different conditions, I need to build my query.

Here is the code

private void appendConditions(StringBuilder query, StringBuilder condition, StringBuilder condition2,
    StringBuilder condition3) {
if (StringUtils.isNotEmpty(condition.toString())) {
    query.append(ApplicationConstants.AND+"(");
    query.append("( " + condition + " )");
    if (StringUtils.isNotEmpty(condition2.toString())) {
        query.append(ApplicationConstants.AND);
        query.append("( " + condition2 + " )");
        if (StringUtils.isNotEmpty(condition3.toString())) {
            query.append(ApplicationConstants.AND);
            query.append("( " + condition3 + " )");
        }

    } else {
        if (StringUtils.isNotEmpty(condition3.toString())) {
            query.append(ApplicationConstants.AND);
            query.append("( " + condition3 + " )");
        }
    }
    query.append(" )");
} else {
    if (StringUtils.isNotEmpty(condition2.toString())) {
        query.append(ApplicationConstants.AND+"(");
        query.append("( " + condition2 + " )");
        if (StringUtils.isNotEmpty(condition3.toString())) {
            query.append(ApplicationConstants.AND);
            query.append("( " + condition3 + " )");
        }
        query.append(" )");
    } else {
        if (StringUtils.isNotEmpty(condition3.toString())) {
            query.append(ApplicationConstants.AND+"(");
            query.append("( " + condition3 + " )");
            query.append(" )");
        }
    }
}

}

When I run my Sonar report, it says the Cognitive complexity is higher for this method. Can I simplify this methods avoiding many if-else loops


texts:
This is my first real attempt at unit testing. This is an area I'm currently focused on improving.

I say this because I would greatly appreciate any and every improvement!

Stack code:

class Stack:
    def __init__(self):
        self.items = []
        self.size = 0

    def is_empty(self):
         return not self.items

    def get_size(self):
         return self.size

    def pop(self):
        if self.is_empty():
            raise IndexError, 'Stack Empty'
        else:
            self.size =- 1
            return self.items.pop()

    def push(self, item, *args):
        if isinstance(item, list):
            self._push_list(item)
        else:
            self.items.append(item)
            self.size +=  1

        if args:
            for a in args:
                self.items.append(a)
                self.size +=  1

    def _push_list(self, l):
        for item in l:
            self.items.append(item)
        self.size += len(l)

    def get_stack(self):
        while not self.is_empty():
            return self.pop()

    def peek(self):
        if self.size == 0:
            return None
        else:
            return self.items[self.size - 1]

Unit Test Code:

import unittest

from extras import Stack

class TestStackMethods(unittest.TestCase):

    def setUp(self):
        self.s = Stack()
        self.l = [] # a generic list to append to

    def tearDown(self):
        while not self.s.is_empty():
            self.s.pop()

    def test_test(self):
        self.assertEqual(2, (4/2))

    def test_empty_function_with_items_in_stack(self):
        self.s.push(1)
        self.failIf(self.s.is_empty())

    def test_empty_function_on_empty_stack(self):
        self.failUnless(self.s.is_empty())

    def test_pop_function_with_items_in_stack(self):
        temp = 1
        self.s.push(temp)
        x = self.s.pop()
        self.assertEqual(temp, x)

    def test_pop_function_on_empty_stack(self):
        with self.assertRaises(IndexError) as c :
            self.s.pop()
        self.assertTrue('Stack Empty' in c.exception)

    def test_peek_function_with_items_in_stack(self):
        self.s.push(1)
        self.s.push(2)
        self.assertTrue(self.s.peek() == 2)

    def test_peek_function_on_empty_stack(self):
        self.assertIs(self.s.peek(), None)

    def test_push_function_for_one_item(self):
        self.s.push(10)
        self.assertTrue(self.s.size == 1)

    def test_push_function_on_a_list_arg(self):
        args = [1,2,3,4]
        self.s.push(args)
        self.assertTrue(self.s.size, 4)

    def test_push_function_on_multiple_args(self):
        self.s.push(1,2,3,4)
        self.assertTrue(self.s.size, 4)

    def test_lifo_functionality(self):
        self.s.push(1,2,3,4)
        while not self.s.is_empty():
             self.l.append(self.s.pop())

        self.assertEqual(self.l, [4,3,2,1])

if __name__ == '__main__':
     unittest.main()


texts:
I'm new to C and I've been working on some code for a project for school. This was the finished result and now that I'm done it, I came back and tried making it better. So I was wondering, how would I make this printAvgCalPerGroup simplified?

#include "diary.h"

void printTotalCal(Food * list)
{
     int total = 0;
     Food * temp = list;

     while (!isEmpty(temp))
     {
          total += (int)temp->calories;
          temp = temp->next; // change to the next list item
     }

     printf("%d\n", total);
     return;
}

void printAvgCalPerGroup(Food * list)
{
     double vegCount = 0.0;
     double meatCount = 0.0;
     double dairyCount = 0.0;
     double grainsCount = 0.0;
     double fatCount = 0.0;

     double vAmnt = 0.0;
     double mAmnt = 0.0;
     double dAmnt = 0.0;
     double gAmnt = 0.0;
     double fAmnt = 0.0;

     Food * temp = list;

     while (temp!= NULL)
     {
          if (temp->foodGroup[0] == 'v')
          {
               vAmnt+=1.0;
               vegCount+=temp->calories;
          }
          else if (temp->foodGroup[0] == 'm')
          {
               mAmnt+=1;
               meatCount+=temp->calories;
          }
          else if (temp->foodGroup[0] == 'd')
          {
               dAmnt+=1;
               dairyCount +=temp->calories;
          }
          else if (temp->foodGroup[0] == 'g')
          {
               gAmnt+=1;
               grainsCount+=temp->calories;
          }
          else if (temp->foodGroup[0] == 'f')
          {
               fAmnt+=1;
               fatCount+=temp->calories;
          }
          temp = temp->next;
     }
     printf("%.2f\n", calcAvg(vegCount,vAmnt));
     printf("%.2f\n", calcAvg(meatCount,mAmnt));
     printf("%.2f\n", calcAvg(dairyCount,dAmnt));
     printf("%.2f\n", calcAvg(grainsCount,gAmnt));
     printf("%.2f\n", calcAvg(fatCount,fAmnt));

}

double calcAvg(double x, double y)
{
     double ans = x/y;
     if (ans != ans) return 0.0;
     return ans;
}

void run(char * argv)
{
     Food * f = getDiary(argv);
     printTotalCal(f);
     printAvgCalPerGroup(f);
     printList(f);
     destroyList(f);
}


texts: An ES6 array of numbers - Double last number, delete the first number

texts:
I'm writing a JavaScript function for an array, based on a geographic sequence. \$[1, 2, 4, 8, 16]\$, etc.

  This function needs to populate the next number in the sequence
  $$item_n = item_{n-1} * 2$$
  If there are more than \$10\$ items in the array, remove the first
  (smallest) number.

  If the array reaches \$2^{15}\$ (no idea what this is), reset the array to
  its original contents - \$[1, 2, 4, 8, 16]\$.

I have it working, but I feel this could be written more efficiently...

updateSequence() {
  var sequence = this.get("geometricSequence");

  // Modify the sequence here
  function* values(sequence) {
    for (let prop of Object.keys(sequence))
    yield sequence[prop];
  }
  let arr = Array.from(values(sequence));

  const lastIndex = arr.length - 1;
  const lastValue = parseInt(arr[lastIndex]) * 2;
  arr.push(lastValue);
  if (lastIndex > 9) {
    arr.slice(0, 1);
  }
  if (lastValue > 32768) {
    arr = [1, 2, 4, 8, 16];
  }
  this.set('geometricSequence', arr);
}


texts:
I'm working in an application where there's a long unordered list of items that have to be paginated. New items are added to the list regularly, and the items come from a database.

The only control I have is via the front end. I cannot control how they are all loaded in the DOM before page load.

I was able to work this out using Ben Everard's jqPagination plugin.

All list items are hidden with display:none. Then, when the next/previous buttons are clicked, a group of items are given the 'active' class - which sets them to display:block.

  //get the total number
      var maxItems = $('li').length,
          numPages = maxItems / 5,
          oldSet,
          pageSet = 5;

      function showPages(s,c) {
        $('li').slice(s, c).addClass('active');
        pageSet = c;
      }

    $(document).ready(function() {

      //Show first set of items
      showPages(0, pageSet);

      $('.pagination').jqPagination({
        max_page  : Math.ceil(numPages),
        paged     : function(page) {

          //Remove the active class from previously active items
          $('.active').removeClass('active');

          //Reset the pageSet number
          pageSet = 5 * page;
          oldSet = pageSet - 5;

          showPages(oldSet, pageSet);

        }
      });

    });

This works pretty fast as is, but I'm concerned about whether it will run slow once the list grows (say to 1200 items).

How could I prevent any performance issues? Is it unavoidable?


texts: Rendering function for total player points

texts:
I have a render function:

render: function(playerId) {
    this.getTotalPoints(playerId);
    // and some other code after this;
}

This render function may be executed with or without a playerId.

This is the getTotalPoints function:

getTotalPoints: function(playerId) {
     if (playerId) {
         this.allplayers[playerId].totalPoints = this.calculatePoints(this.allplayers[playerId].cards);
     } else {
         this.allplayers.forEach(function(element, index) {
             element.totalPoints = this.calculatePoints(element.cards);
         }.bind(this));
     }
 }

And the third function that actually calculates the points:

calculatePoints: function(cards) {
    points = 0;

    for (var i = 0; i < cards.length; i++) {
        points += cards[i].points;
    };

    return points;
}

I am repeating myself in getTotalPoints, where I have a call to this.calculatePoints - one for a single player and then one for all the players, depending on whether the playerId is set or not.

Is there any chance I can avoid this and simplify the code?


texts: Reduce database touches for one to many data pull

texts:
I have the following function which works properly and returns all of the rows from a specific table, then loops through each row to add data related to it as a subarray.
public function fetch_products() {
    $return = $this->db->all("SELECT * FROM consumables_products");

    foreach($return as &$r) {
        $r['consumables'] = $this->db->all("SELECT A.*, B.description FROM consumables_product_consumables as A, consumables_consumables as B WHERE product_id=? AND B.uid=A.consum_id", [$r['uid']]);
    }

    return $return;
}

The result looks like this:
Array
(
    [0] => Array
        (
            [uid] => 1
            [description] => Test
            [consumables] => Array
                (
                    [0] => Array
                        (
                            [uid] => 1
                            [consum_id] => 186
                            [product_id] => 1
                            [amount] => 5
                            [description] => 3 X 1" GREEN Direct Thermal
                        )

                    [1] => Array
                        (
                            [uid] => 2
                            [consum_id] => 185
                            [product_id] => 1
                            [amount] => 1
                            [description] => 3 X 1" ORANGE Direct Thermal
                        )

                )

        )

)

This could get very inefficient with hundreds or thousands of rows in my consumables_products table, and an undefined number of rows in the consumables_product_consumables table.
I'm wondering if there is a way that I can do this in a single query, so that I don't have to do a separate call for every row in my consumables_products table.


texts: Custom sorting algo / optimized bubble sort

texts:
I'm a novice and started diving into data structures and algorithms recently. I was taught bubble sort recently and I found that the original bubble sort algorithm is so inefficient, so I wrote a modified, yet simple version of it.

Algorithm:

Loop through the provided array and store the index of the max element
Swap the last element with the max element
Decrease the total looping length by 1 and repeat

Code:

import java.util.Scanner;

class Methods extends Main
  {
    int[] getArray(int len)
      {
        int[] array = new int[len];

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

    int [] pushMaxSort(int[] arr)
      {
        int len = arr.length;

        while (len>0)
          {
            int max=arr[0];
            int index=0;
            for(int i=0; i<len;i++)
              {
                if(arr[i]>max)
                  {
                    max = arr[i];
                    index = i;
                  }
              }
            int temp = arr[len-1];
            arr[len-1] = arr[index];
            arr[index] = temp;
            len--;
          }

        return arr;
      }

    void printArr(int []arr)
      {
        System.out.println("sorted array :");
        for(int i=0;i<arr.length;i++)
          {
            System.out.print("\t" +arr[i]);
          }
      }

  }

class Main
  {
    static Scanner sc = new Scanner(System.in);

    public static void main(String[] args)
      {
        long t = System.currentTimeMillis();
        Methods o = new Methods();
        o.printArr(o.pushMaxSort(o.getArray(sc.nextInt())));
        long t2 = System.currentTimeMillis();
        System.out.println("\n\n time " + (t2-t));
      }
  }

Also, I need to learn to describe complexity (using Big O notation). I am vaguely guessing this has \$O(n \log{n})\$ but please let me know of the exact running time.


texts:
Prompted by a meta answer, here is an HTML page I'm deliberating over in JSBIN and I would like your review, please.

I am not looking to implement the logic, just please focus on HTML & CSS.
Are tables a good candidate to mark up purchase items? I've seen this implemented as a list in each column, which I thought was worse.
How can I best add markup and style to the final total?

There is a known issue with the CSS border. I'm not asking for you to fix that, but I'm telling you because there is a comment in my code that could possibly make it sound broken. Any other good tips or examples would be great.

td, th { text-align: right; }
tr th:first-child, tr td:first-child { text-align: left; }
tbody tr:last-child td { font-weight: bold;  }
table { border-collapse: collapse; }
tbody tr:last-child { border-top: thick black solid; }

      Description
      Quantity
      Rate
      Amount

      Moon cakes
      5
      100
      500

      Super biscuits
      1
      500
      500

 Total value

 1000


texts: Serialize data into one byte array using ByteBuffer

texts:
I have a class in which I am passing certain parameters through the constructor and then using those parameters to make one final byte array with a proper format (header + data):

public final class Frame {
  private final byte addressedCenter;
  private final byte version;
  private final Map<byte[], byte[]> keyDataHolder;
  private final long location;
  private final long locationFrom;
  private final long locationOrigin;
  private final byte partition;
  private final byte copy;

  public Frame(byte addressedCenter, byte version,
      Map<byte[], byte[]> keyDataHolder, long location, long locationFrom,
      long locationOrigin, byte partition, byte copy) {
    this.addressedCenter = addressedCenter;
    this.version = version;
    this.keyDataHolder = keyDataHolder;
    this.location = location;
    this.locationFrom = locationFrom;
    this.locationOrigin = locationOrigin;
    this.partition = partition;
    this.copy = copy;
  }

  public byte[] serialize() {
    // All of the data is embedded in a binary array with fixed maximum size 70000
    ByteBuffer byteBuffer = ByteBuffer.allocate(70000);
    byteBuffer.order(ByteOrder.BIG_ENDIAN);

    int numOfRecords = keyDataHolder.size();
    int bufferUsed = getBufferUsed(keyDataHolder); // 36 + dataSize + 1 + 1 + keyLength + 8 + 2;

    // header layout
    byteBuffer.put(addressedCenter); // byte
    byteBuffer.put(version); // byte
    byteBuffer.putInt(numOfRecords); // int
    byteBuffer.putInt(bufferUsed); // int
    byteBuffer.putLong(location); // long
    byteBuffer.putLong(locationFrom); // long
    byteBuffer.putLong(locationOrigin); // long
    byteBuffer.put(partition); // byte
    byteBuffer.put(copy); // byte

    // now the data layout
    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
      byte keyType = 0;
      byte keyLength = (byte) entry.getKey().length;
      byte[] key = entry.getKey();
      byte[] data = entry.getValue();
      short dataSize = (short) data.length;

      ByteBuffer dataBuffer = ByteBuffer.wrap(data);
      long timestamp = 0;

      if (dataSize > 10) {
        timestamp = dataBuffer.getLong(2);
      }

      byteBuffer.put(keyType);
      byteBuffer.put(keyLength);
      byteBuffer.put(key);
      byteBuffer.putLong(timestamp);
      byteBuffer.putShort(dataSize);
      byteBuffer.put(data);
    }
    return byteBuffer.array();
  }

  private int getBufferUsed(final Map<byte[], byte[]> keyDataHolder) {
    int size = 36;
    for (Map.Entry<byte[], byte[]> entry : keyDataHolder.entrySet()) {
      size += 1 + 1 + 8 + 2;
      size += entry.getKey().length;
      size += entry.getValue().length;
    }
    return size;
  }
}

I would like to know if it can be improved in any way. As you can see right now, I am allocating ByteBuffer with predefined size of 70000. Is there a better way by which I can allocate the size I am using while making ByteBuffer instead of using a hardcoded 70000?


texts:
I have implemented a merge sort in Ruby. (Yes, I know, there's Array#sort) I would like to get feedback on code quality and optimization.

def merge(a, b)
  result = []

  while !a.empty? && !b.empty?
    if a[0] <= b[0]
      result << a.shift
    else
      result << b.shift
    end
  end

  result += a += b

  return result
end

def merge_sort(m)
  if m.length <= 1
    return m
  end

  left, right = [], []
  m.each_with_index do |x, i|
    if i < m.length / 2
      left << x
    else
      right << x
    end
  end
  left = merge_sort(left)
  right = merge_sort(right)

  return merge(left, right)
end

input = [*1..100].shuffle

p input

p merge_sort input


texts: Turning an array of words into a random license plate

texts:
This is an assignment question from school:

  Write a method called licencePlate that takes an array of objectionable words and returns a random licence plate that does not have any of those words in it. Your plate should consist of four letters, a space, then three numbers.

import java.util.*;

class MethodAssign5{
static String licensePlate(String[] a){
    char[] lchars={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
    char[] nchars={'0','1','2','3','4','5','6','7','8','9'};
    boolean contain = true;
    char[] license = new char[8];
    license[4]=' ';
    Random generator = new Random();
    do{
        for(int i=0;i<4;i++){
            license[i]=lchars[generator.nextInt(26)];
        }
        for(int i=0;i<3;i++){
            license[i+5]=nchars[generator.nextInt(10)];
        }
        contain = false;
        for(String s:a){
            boolean same = true;
            char[] wchars = s.toCharArray();
            for(int i=0;i<4;i++){
                if(license[i]!=wchars[i]){
                    same = false;
                }
            }
            if(same==true){
                contain = false;
            }
        }
    }while(contain==true);
    String ans = new String(license);
    return ans;
}
public static void main(String[]args){
    String[] words ={"HAHA","GORD"};
    System.out.println(licensePlate(words));
}
}

As you can see, I have no idea if my solution is right. It's such a low probability.

What do you think about my solution? What should I do if this was an in-class test and had the same problem where the probability of getting the error is low?


texts:
I am using the SICP book. There is an exercise in which you need to create a function that will receive a list as an argument and return a list with the same elements in a reverse order.

I know there are more efficient solutions than the one I am going to present. However, I really learn by analyzing things that came up naturally from my mind.

I would like to improve my suboptimal solution in its own nature.

First, I created my own list-ref (I like building built-in functions as a matter of practice):

(define (list-ref lista n)
  (if (= n 1)
      (car lista)
      (list-ref (cdr lista) (- n 1))))

Second, I created my own function to count the length of a list:

(define (list-len lista)
  (if (null? lista)
      0
      (add1 (list-len (cdr lista)))))

After that, I created the core of the reverse process:

(define (reverse-exe lista n)
  (if (= n 0)
      empty
      (cons (list-ref lista n) (reverse-exe lista (- n 1)))))

On the code above, the parameter n needs to be the length of the list (considering the first element as 1, and not zero).

As the question asks us to build a function that will receive only a list as an input, I created another function which turns "n" as the length:

(define (reverse lista)
  (reverse-exe lista (list-len lista)))

Is there a better way to organize these procedures?


texts:
I have a class which is responsible for waiting until a message is added to a message list and then sending it off to get processed.

withdrawMessages waits for a message. I wait for a total of 2 minutes for a message to appear. I do this to keep the connection alive on my browser.
depositMessage adds a message to the message list.

The process flow I am aiming for is:

Deposit a message into the list
Wait is notified and the whole list gets passed to the processor object (IUpdater)

If processMessages is about to get executed and a new message is added to the list I want to make sure this new message is also sent when calling responseUpdater.sendResponse

I need it to be thread-safe so when responseUpdater.sendResponse(messageList); is actually getting processed, then nothing else can be added to the list. It needs to wait until sendResponse is completed before adding it.

sendResponse basically sends the list to browser then the browser sends back a request to call withdrawMessages. So if a new message is added when sendResponse is getting executed, it has to wait until withdrawMessages is called again. At that point it will process the messages.

public class MessagePusher {

    private static final int TWO_MINUTE_WAIT = 120 * 1000;
    private volatile boolean notified = false;
    private final ArrayList<String> messageList = new ArrayList<String>();

    private void waitOnMessages(int duration) throws InterruptedException {
        messageList.wait(duration);
    }

    private void notifyWaitingThreads() {
        if (messageList.size() > 0) {
            notified = true;
            this.messageList.notify();
        }
    }

    public void depositMessage(String message) {
        synchronized (this.messageList) {
            this.messageList.add(message);
            notifyWaitingThreads();
        }
    }

    //IUpdater just processes the messages
    public void withdrawMessages(IUpdater updater) {
        boolean processRequired = false;
        synchronized (messageList) {
            //gets lock
            boolean timeout = false;
            try {
                //releases lock
                waitOnMessages(TWO_MINUTE_WAIT);
                //gets lock again
                if ((!notified)) {
                    timeout = true;
                }
            } catch (InterruptedException e) {
                ShipsLog.out.asWarning("Unexpected exception! Nested exception is:\n" + e);
            }
            if (notified || timeout) {
                notified = false;
                processRequired = true;
            }
        }
        if (processRequired) {
            processMessages(updater);
        }
    }

    public void processMessages(IUpdater responseUpdater) {
            synchronized (messageList) {
                responseUpdater.sendResponse(messageList);
                messageList.clear();
            }
    }
}


texts: Java and C++ stack implementations with dramatically different performance

texts:
I'm developing a small programming language for use in any project I have where I feel a small scripting language could be used well. I've written two emulators for the language, one in C++ and one in Java. The C++ performs faster except for any recursion in the language, in which it suddenly performs terribly!

Here is the code from my language that I am running which runs in 1.5s on the Java emulator and 4s on the C++ emulator:

dec i = 0;
recurse();
print i;

def recurse:
    if i < 10000000:
        i++;
        recurse();
    return;

This compiles down into the following instructions:

% i = 0; #define the alias i as being variable 0;
# i needs to be initialised;
STOREINT i 0;
CALL @recurse; #call the label recurse, push this line onto the stack;
PRINTINTLN $i;
END; #end of program;

@recurse; #define the function recurse;
# if i is < 10000000 then inc i;
GEQ $i 10000000;
JCMP @return; #jump to the return statement
INC i;
CALL @recurse;
@return;
RETURN; #return back to the line on the top of the stack;

The C++ implementation differs slightly from the Java implementation in that it uses an array of unions to store each "typeless" object, whereas Java just uses Object. Other than that, the code is almost identical (with C++ not needing to do any casting because from the instructions we can be sure which field  in the union we are using, and therefore we access the correct field instead of casting the Object to the correct type in Java. C++ also doesn't need to use & 0xFF in order to fix sign problems with the java byte type, as we can make unsigned chars). The main difference between them seems to be the performance of the call stacks, which are implemented in each case as follows:

Java

public class ArrayStack<T> implements Stack<T>
{
    private static final long serialVersionUID = 1L;
    protected Object[] stack;
    protected int capacity;
    protected int pointer;

    public ArrayStack(int capacity)
    {
        stack = new Object[capacity];
        this.capacity = capacity;
        clear();
    }

    public void push(T value)
    {
        stack[pointer++] = value;
    }

    public T pop()
    {
        return (T) stack[--pointer];
    }

    public T peek()
    {
        return (T) stack[pointer-1];
    }

    public boolean isEmpty()
    {
        return pointer == 0;
    }

    public boolean isFull()
    {
        return pointer == capacity;
    }

    public void clear()
    {
        pointer = 0;
    }

    public int size()
    {
        return pointer;
    }

    public int capacity()
    {
        return capacity;
    }
}

C++

template <class T> class ArrayStack
{
    private:
        T* stack;
        int capacity;
        int pointer;

    public:
        ArrayStack(int capacity)
        {
            this->capacity = capacity;
            stack = new T[capacity];
            clear();
        }

        ~ArrayStack() { delete stack; }
        void push(T value) { stack[pointer++] = value; }
        T pop() { return stack[--pointer]; }
        T peek() const { return stack[pointer-1]; }
        bool isEmpty() const { return pointer == 0; }
        void clear() { pointer = 0; }
        int size() const { return pointer; }
        int getCapacity() { return capacity; }
};

I'll provide the case statements running during this program below if anybody wants to see them, but for now I'll leave them out to keep this post a little shorter!

To my eyes, the C++ looks like it should be either faster than or equal to the Java one, as even if new was the slow part of the C++ code, that isn't taken into account in the timing of the program execution, which starts timing as soon as the first instruction is executed. Could it be that I'm storing the stack as a member variable in the Emulator class, and not as a pointer or something like that, or something the JIT compiler can do that the static C++ compiler (on O3) can't?


texts: Rearranging array elements depending on their indexes

texts:
I am (still!) going through these CodingBat exercises for Java. Here is the one I have just done:

  Return an array that contains the exact same numbers as the given array, but rearranged so that all the zeros are grouped at the start of the array. The order of the non-zero numbers does not matter. So {1, 0, 0, 1} becomes {0 ,0, 1, 1}. You may modify and return the given array or make a new array.

And here is my code:

    public int[] zeroFront(int[] nums){

    int zeroCount = 0;
    int[] resultantArray = new int[nums.length];
    int[] noZerosArray = new int[nums.length];

    //Count zeros
    for (int i = 0; i < nums.length; i++) {
        if (nums[i] == 0) {
            zeroCount++;
        }
    }

    //Make an array without any zeros
    int j = 0;
    for (int i = 0; i < nums.length; i++) {
        if(nums[i] != 0){
            noZerosArray[j] = nums[i];
            j++;
        }
    }

    //To resultant array, add zeros first, then add remaining numbers of original
    for (int i = 0; i < resultantArray.length; i++) {
        if (i < zeroCount) {
            resultantArray[i] = 0;
        } else {
            resultantArray[i] = noZerosArray[i-zeroCount];
        }
    }

    return resultantArray;
}

Please bear in mind I am doing it without importing anything extra like java.util.Arrays etc., as , primarily, this is not accepted by the assessor and, secondarily, I want to get to grips with arrays without importing anything extra yet.

Regarding my code, I would like to know how this can be improved. Is this a good solution? It feels like it could be more efficient, bearing in mind I have three for loops and creating three extra arrays.

Even though this one seems trivial, I found it really difficult!


texts: Displaying contacts in PHP, with options to omit some information

texts:
I am currently changing some PHP code. The old code looked like:

<div class="contact<?php echo $this->pageclass_sfx; ?>" itemscope itemtype="https://schema.org/Person">
 <?php if ($tparams->get('show_page_heading')) : ?>

   <?php echo $this->escape($tparams->get('page_heading')); ?>

 <?php endif; ?>

 <?php if ($this->contact->name && $tparams->get('show_name')) : ?>

    <?php if ($this->item->published == 0) : ?>
     <?php echo JText::_('JUNPUBLISHED'); ?>
    <?php endif; ?>
    <?php echo $this->contact->name; ?>

 <?php endif; ?>

 <?php $show_contact_category = $tparams->get('show_contact_category'); ?>

 <?php if ($show_contact_category === 'show_no_link') : ?>

   <?php echo $this->contact->category_title; ?>

 <?php elseif ($show_contact_category === 'show_with_link') : ?>
  <?php $contactLink = ContactHelperRoute::getCategoryRoute($this->contact->catid); ?>

   <a href="<?php echo $contactLink; ?>">
    <?php echo $this->escape($this->contact->category_title); ?>

 <?php endif; ?>

I found this quite hard to follow and decided to try and rewrite the same piece of code. It ended up looking like this:

<?php
echo '
pageclass_sfx . '" itemscope itemtype="https://schema.org/Person">';

// show/hide heading
if ($tparams->get('show_page_heading')){
 echo '
'. $this->escape($tparams->get('page_heading')) . '
';
}

// show/hide contact name
if ($this->contact->name && $tparams->get('show_name')){
 echo '
';
 echo '
';
 if ($this->item->published == 0){
  echo '' . JText::_('JUNPUBLISHED') . '';
 }
 echo ''. $this->contact->name . '';
 echo '
';
 echo '
';
} ?>

I think the logic is much easier to follow when written like this.

I was wondering if anyone had some opinions / remarks / feedback on improvements for the second version of the code.
If anyone sees some advantages of the first version over the second I would love to hear what they are.


texts: Extract indices of visible nodes in a tree where only some nodes are expanded

texts:
A program that I work on constantly updates and modifies program state containing an arbitrarily deep and wide tree. The data looks something like this.

(defonce state
         (r/atom {:some  "program"
                  :state "here"
                  :tree  [{:topic    "Books"
                           :expanded true
                           :children [{:topic "Titles"}
                                      {:topic    "Authors"
                                       :expanded true
                                       :children [{:topic "Alice"}
                                                  {:topic "Bob"}
                                                  {:topic "Carol"}]}
                                      {:topic "Genres"}]}
                          {:topic    "CDs"
                           :children [{:topic "Genres"}
                                      {:topic "Albums"}
                                      {:topic "Artists"}]}
                          {:topic    "To Do"
                           :expanded true
                           :children [{:topic    "Spouse Birthday"
                                       :expanded nil
                                       :due-date "07/31/2025"
                                       :children [{:topic "Buy Card"}
                                                  {:topic "Buy Jewelry"}
                                                  {:topic "Buy Cake"}]}]}]}))

As the program runs, I need to extract the series of numeric vector indices to reach the visible topics (those that have :children where the :expanded flag is present and "truthy").

Here is a method that works.

;; This flattening function is from an idea presented in response to
;; this question:
;; https://stackoverflow.com/questions/5232350/clojure-semi-flattening-a-nested-sequence
(defn flatten-to-vectors
  [s]
  (mapcat #(if (every? coll? %) (flatten-to-vectors %) (list %)) s))

(defn visible-nodes
  [tree so-far]
  (flatten-to-vectors
    (map-indexed
      (fn [idx ele]
        (let [new-id (conj so-far idx)]
          (if (not (and (:children ele) (:expanded ele)))
            new-id
            (cons new-id (visible-nodes (:children ele) new-id)))))
      tree)))

;; The function can be called like this on the data above.
(println (visible-nodes (:tree @state) []))
;; => ([0] [0 0] [0 1] [0 1 0] [0 1 1] [0 1 2] [0 2] [1] [2] [2 0])

Although this works, it seems like I should be able to generate the correct result without creating nested sequences that require flattening. But I just can't come up with anything.

Any suggestions would be appreciated.


texts: Creating a Concentration memory-style game with CSS/HTML/JavaScript

texts:
I am doing a pre-cohort coursework for General Assembly and I am somewhat stuck. I have tried making several changes, but it never seems to work right. I am trying to use Career Karma to get assistance, but if you've ever worked with them, it is all dependent on how many people are online and who actually knows what they are doing.

Here's the instructions:

And here's what I have finished with so far. I have tried many different coding changes and none of them seem to work.

The if...else statements seem to be the worst.

const cards = ['queen', 'queen', 'king', 'king'];
console.log(cards.slice([0, 3]));
let cardOne = [[0]];
let cardTwo = [[1]];
let cardThree = [[2]];
let cardFour = [[3]];

cardsInPlay = [];
cardsInPlay.push(cards[0]);
console.log("User flipped " + cards[0]);
cardsInPlay.push(cards[1]);
console.log("User flipped " + cards[1]);

if(cardOne == cardTwo)
{
alert("You found a match!")
};
if (cardOne !== cardTwo)
{
alert("Sorry, try again.")
};


texts:
Please review my Adjacency Matrix class based on this code.

Since I use std::vector to create the matrix, I would like to store as many nodes as possible. Is it OK to use std::size_t all over the code?
Are using 1 for connected and 0 for not connected a bad idea?

class AdjMatrix {
public:
    AdjMatrix(const std::size_t& vertsize);
    std::size_t Vertices() const;
    std::size_t Edges() const;
    void addEdge(const std::size_t& a, const std::size_t& b);
    std::size_t degree(const std::size_t& v) const;
    std::size_t maxDegree() const;
    std::size_t minDegree() const;
private:
    std::size_t vertices;
    std::size_t edges;
    std::vector<std::vector<std::size_t>> matrix;
};

AdjMatrix::AdjMatrix(const std::size_t& vertsize) :vertices{vertsize < 0? throw std::out_of_range{"necgative values"} : vertsize}, edges{0}, matrix{vertsize} {
    for (auto& v : matrix) {
        v.resize(vertsize);
    }
}

std::size_t AdjMatrix::Vertices() const {
    return vertices;
}

std::size_t AdjMatrix::Edges() const {
    return edges;
}

void AdjMatrix::addEdge(const std::size_t& a, const std::size_t& b) {
    if (a < 0 || b < 0) {
        throw std::out_of_range{"negative values"};
    }
    if (matrix[a][b] == 0) {
        edges++;
    }
    matrix[a][b] = 1;
    matrix[b][a] = 1;
}

std::size_t AdjMatrix::degree(const std::size_t& v) const {
    std::size_t d = 0;
    for (std::size_t i = 0; i < matrix[v].size(); ++i) {
        if (matrix[v][i] == 1) {
            d++;
        }
    }
    return d;
}

std::size_t AdjMatrix::maxDegree() const {
    std::size_t max = 0;
    for (std::size_t i = 0; i < matrix.size(); i++) {
        std::size_t d = degree(i);
        max = d > max ? d : max;
    }
    return max;
}

std::size_t AdjMatrix::minDegree() const {
    std::size_t min;
    for (std::size_t i = 0; i < matrix.size(); i++) {
        std::size_t d = degree(i);
        if (i == 0) {
            min = d;
        } else {
            min = min < d ? min : d;
        }
    }
    return min;
}

How can I improve this code?


texts:
The goal is to

make an object that persists upon page reloads,
have an interface as close as possible to the Object class.

function PersistentObject(key,initial_value)
//use for(..in data.keys()) instead of for(..in data)
{
  var ret;
  if(localStorage[key]) ret=JSON.parse(localStorage[key]);
  if(!ret) ret = initial_value;
  if(!ret) ret = {};
  //JSON.stringify ignores put and keys functions
  ret.put=function() { localStorage[key]=JSON.stringify(this) };
  ret.keys=function()
  {
    var res = {};
    for(var prop in this) if(this[prop] !== this.put && this[prop] !== this.keys)
      res[prop]=true;
    return res;
  };
  return ret;
}

The code is used as follows:

var myPersistentObject = new PersistentObject('myPersistentObject');
var myPersistentArray  = new PersistentObject('myPersistentArray',[]);

Unfortunately there is AFAIK no way to get the name of the variable and therefore the name of the variable needs to be passed as first argument.

Also unfortunate is that the function keys needs to be called in order to iterate over the object. I'm aware of the defineProperty function that allow to add a propoerty that is not enumerable but AFAIK cross browser compability is an issue with defineProperty.


texts:
I have made my own MinHeap in Java. I would like to get review comments on the same.

package heap.minheap;

public class MinHeap {

private int[] heap;
private int size;
private int maxSize;
private static final int FRONT = 1;

public MinHeap(int maxSize){
    this.heap = new int[maxSize+1];
    heap[0] = Integer.MIN_VALUE;
    this.size = 0;
}

private int getParent(int position){
    return position/2;
}

private int getLeftChild(int position){
    return 2*position;
}

private int getRightChild(int position){
    return 2*position+1;
}

private void swap(int position1, int position2){
    int temp = heap[position1];
    heap[position1] = heap[position2];
    heap[position2] = temp;
}

private boolean isLeaf(int position){

    if(position > size/2){
        return true;
    }
    return false;
}

public void insert(int data){
    heap[++size] = data;
    int currentItem = size;
    while( heap[getParent(currentItem)] > heap[currentItem] ){
        swap(getParent(currentItem),currentItem);
        currentItem = getParent(currentItem);
    }
}

public int delete(){
    int itemPopped = heap[FRONT];
    heap[FRONT] = heap[size--];
    heapify(FRONT);
    return itemPopped;
}

private void heapify(int position){
    if(isLeaf(position)){
        return;
    }

    if ( heap[position] > heap[getLeftChild(position)] || heap[position] > heap[getRightChild(position)]){

        if(heap[getLeftChild(position)] < heap[getRightChild(position)]){
            swap(position , getLeftChild(position));
            heapify(getLeftChild(position));
        }
        else{
            swap(position , getRightChild(position));
            heapify(getRightChild(position));
        }
    }
}

@Override
public String toString(){
    StringBuilder output = new StringBuilder();
    for(int i=1; i<= size/2; i++){
        output.append("Parent :"+ heap[i]);
        output.append("LeftChild : "+heap[getLeftChild(i)] +" RightChild :"+ heap[getRightChild(i)]).append("\n");
    }
    return output.toString();
}
}


texts: Acceptable way of using jQuery methods in Angular directives

texts:
Here is my plunker example of what I am doing.

jQuery is a great way to use slide transitions and seem to work well with angular as long as you are only using the methods on the element object inside a directive.

Basically I am using a directive for divs I want to slide toggle which listens for a broadcast from the controller which happens when the click function is called in the controller.

I am not using jQuery selectors and am only calling slideToggle() on the angular element.

Is this an acceptable angular way of doing this?  If not, what is?

HTML

    <title></title>
    <link type="text/css" rel="stylesheet" href="style.css"/>

            <input type="text" placeholder="username" />
            <input type="password" placeholder="password" />
            <button class="btn-login">Login</button>

Click here

            <input type="text" placeholder="username" />
            <input type="email" placeholder="email" />
            <input type="password" placeholder="password" />
            <button class="btn-login">Sign up</button>

Click here again

            <button>X</button>

JavaScript

var myApp = angular.module("myApp", []);

myApp.controller('mainCtrl', function($scope, $rootScope) {
  $scope.toggleClick = function(){
    $rootScope.$broadcast("toogleDiv","");
  };
});

myApp.directive('toggle', function () {
    return {
        restrict:'C',
        link: function (scope, element, attrs) {
            scope.$on("toogleDiv", function(e, val){
              element.slideToggle();
            });
        }
    }
});


texts: C# lambda expressions as array extensions in JavaScript

texts:
I use a lot of lambda expressions in C#, so I've decided to create some similar functionality in JavaScript. Since jQuery is included in my projects, I'm using $.grep() instead of Array.prototype.filter() to support older browsers without including shims.

The two examples below corresponds to Where() and FirstOrDefault() in C#:

if(!Array.prototype.where){

    Array.prototype.where = function (func) {

        var that = this;

        switch (typeof func) {

            case 'function':
                return $.grep(that, func);

            case 'object':

                for(var prop in func){
                    that = $.grep(that, function(item){
                        return item[prop] === func[prop];
                    });
                }

                return that;

            default:
                throw new ReferenceError("no/wrong func type passed");
        }
    };
}

if(!Array.prototype.firstOrDefault){

    Array.prototype.firstOrDefault = function(func){
        return this.where(func)[0] || null;
    };
}

var persons = [{ name: 'foo', age: 1 }, { name: 'bar', age: 2 }];

var where1 = persons.where(function(p){
    return p.age === 1 && p.name === 'foo';
});

console.log(where1);

var where2 = persons.where({ age: 1, name: 'foo' });

console.log(where2);

var fod1 = persons.firstOrDefault(function(p){
    return p.age === 1 && p.name === 'foo';
});

console.log(fod1);

var fod2 = persons.firstOrDefault({ age: 1, name: 'foo' });

console.log(fod2);

Fiddle

I would have preferred to add the methods as non-enumerable using Object.defineProperty, but since I need to support IE >= 7, that's not an option.

However, the only downside with having the methods enumerable would be if someone is iterating an array using for..in, which they shouldn't do in the fist place.

In case of an object being passed as argument, one way to decrease the total iterations from array length * object property count to array length * 1 could be solved using the function constructor:

var o = { foo: 1, bar: true, s: 's' };

var str = Object.keys(o).reduce(function (prev, key) {

    if(typeof o[key] === 'string')
        o[key] = '\'' + o[key] + '\'';
    return (prev ? prev + ' && ' : '') + 'x.' + key + ' === ' + o[key];

}, '');

var f = new Function('x', 'return ' + str + ';');

// pass f to filter/$.grep
console.log(f);

Fiddle

I would like some feedback about possible performance improvements and what you think about the code in general (but not pros and cons with extending native objects).


texts: Generic Meyers Singleton implementation in C++

texts:
Is this a correct implementation of a generic Meyers Singleton in C++17? Any tips appreciated.
Singleton.h
#ifndef SINGLETON_H
#define SINGLETON_H

template<class T>
class Singleton
{
public:

    static T& get()
    {
        static T obj;
        return obj;
    }

protected:

    Singleton() = default;
    virtual ~Singleton() = default;
    Singleton(const Singleton&) = delete;
    Singleton(Singleton&&) = delete;
    Singleton& operator=(const Singleton&) = delete;
    Singleton& operator=(Singleton&&) = delete;

};

#endif

MySingleton.h
#ifndef MYSINGLETON_H
#define MYSINGLETON_H

class MySingleton : public Singleton<MySingleton>
{
    friend class Singleton<MySingleton>;

public:

    // public members

private:

    MySingleton() {};
    ~MySingleton() {};

};

#endif


texts: Sum Of Two Arrays element by element and arrays can be of unequal length

texts:
In this question, I need to find the sum of 2 arrays element by element.
Arrays can be of unequal length.
Explanation: Sum of [1, 0, 2, 9] and [3, 4, 5, 6, 7] is [3, 5, 5, 9, 6] and the first digit represents carry over , if any (0 here ).
Here's what I could come up with. Let me know if anything could be done better,or anything i did wrong.
Also earlier someone suggested me that I should split my code into smaller pieces that are easier to read and test individually. Perhaps if anyone could help with the method signatures that I should make(if any).
    private static void sum(int[] arr1, int[] arr2) {
    ArrayList<Integer> arraySum = new ArrayList<>();
    int[] largerArray, smallerArray;
    boolean flag;
    if (arr1.length == arr2.length) {
        largerArray = arr1;
        smallerArray = arr2;
        flag = true;
    } else if (arr1.length > arr2.length) {
        largerArray = arr1;
        smallerArray = arr2;
        flag = false;
    } else {
        largerArray = arr2;
        smallerArray = arr1;
        flag = false;
    }
    int sum = 0, carry = 0;
    int diff = largerArray.length - smallerArray.length;
    for (int i = smallerArray.length - 1; i >= 0; i--) {        //traverse through smaller array
        sum = largerArray[i + diff] + smallerArray[i] + carry;
        carry = 0;
        if (sum > 9) {
            int N = sum;
            while (N != 0) {
                int rem = N % 10;
                if (N < 10) {
                    carry = rem;
                } else {
                    arraySum.add(rem);
                }
                if (i == 0 && carry != 0 && flag) {     //if we are at last element & carry!=0 add carry as first digit
                    arraySum.add(carry);
                }
                N = N / 10;
            }
        } else {
            arraySum.add(sum);
        }
    }
    if (!flag) {
        for (int i = diff - 1; i >= 0; i--) {       // now sum remaining elements of larger array
            sum = arr1[i] + carry;
            carry = 0;
            if (sum > 9) {
                int N = sum;
                while (N != 0) {
                    int rem = N % 10;
                    if (N < 10) {
                        carry = rem;
                    } else {
                        arraySum.add(rem);
                    }
                    if (i == 0 && carry != 0) {     //if we are at last element & carry!=0 add carry as first digit
                        arraySum.add(carry);
                    }
                    N = N / 10;
                }
            } else {
                arraySum.add(sum);
            }
        }
    }
    display(arraySum);
}


texts: Convert an `int` to a C string with size limitation

texts:
Creating a textual version of an int to save as a C string to a buffer that is all ready allocated and maximum allowable size is determined seems common.  Thought I'd make a function to fulfill that.

If the destination size is too small or destination is NULL, return NULL.

Your critique of functionality, style, use, etc. is requested.

#include <stdlib.h>
#include <limits.h>
#include <string.h>

char *int_strnull(int x, char *dest, size_t dest_size) {
  if (dest != NULL) {
    // Size local buffer to x needs.  Note 10/33 just greater than log(2)
    char buf[sizeof x * CHAR_BIT * 10 / 33 + 3];
    char *p = &buf[sizeof buf - 1];
    // Work with negative absolute value to cope with INT_MIN
    int xna = x < 0 ? x : -x;

    // Form string
    *p = '\0';
    do {
      *--p = '0' - xna % 10;
      xna /= 10;
    } while (xna);
    if (x < 0) {
      *--p = '-';
    }

    // Copy string
    size_t src_size = &buf[sizeof buf] - p;
    if (src_size > dest_size) {
      // Not enough room
      return NULL;
    }
    memcpy(dest, p, src_size);
  }
  return dest;
}

Similar to snprintf(buf, sizeof buf, "%d", some_int); but without the printf() overhead.


texts:
I'm working on the problem:

  Given array with positive and negative values, return the maximum alternating slice size; two elements are alternating if they have different signs, zero is treated as both negative and positive.

  Time complexity: \$O(N)\$

  Space complexity: \$O(1)\$

I developed a working code and would like to know if there is any method to make the code shorter or faster.

public static int maxSizeAlterSlice(int[] a){
    int max_size_so_far = -1;
    int cur_max_size = -1;
    if(a.length == 1)
        return 1;
    int startInd = 0;
    int endInd = 0;
    int i=1;
    int compareInd=0;
    while(i<a.length){
        if((a[compareInd]>=0 && a[i]<=0)||(a[compareInd]<=0 && a[i]>=0)){
            compareInd=i;
            endInd++;
            i++;
        }else{
            cur_max_size = endInd-startInd+1;
            if(max_size_so_far<cur_max_size){
                max_size_so_far = cur_max_size;
            }
            startInd = i;
            compareInd=startInd;
            endInd=startInd;
            i=startInd+1;
        }
    }
    return max_size_so_far;
}


texts:
There are a plethora of streams and streambuffers available today, none are as fast as a memory streambuf, that you can use for testing. Shoot away!

#ifndef MEMSTREAMBUF_HPP
# define MEMSTREAMBUF_HPP
# pragma once

#include <cassert>

#include <cstring>

#include <array>

#include <iostream>

#include <streambuf>

template <::std::size_t N>
class memstreambuf : public ::std::streambuf
{
  ::std::array<char, N> buf_;

public:
  memstreambuf()
  {
    setbuf(buf_.data(), buf_.size());
  }

  ::std::streambuf* setbuf(char_type* const s,
    ::std::streamsize const n) final
  {
    auto const begin(s);
    auto const end(s + n);

    setg(begin, begin, end);
    setp(begin, end);

    return this;
  }

  pos_type seekpos(pos_type const pos,
    ::std::ios_base::openmode const which = ::std::ios_base::in |
    ::std::ios_base::out) final
  {
    switch (which)
    {
      case ::std::ios_base::in:
        if (pos < egptr() - eback())
        {
          setg(eback(), eback() + pos, egptr());

          return pos;
        }
        else
        {
          break;
        }

      case ::std::ios_base::out:
        if (pos < epptr() - pbase())
        {
          setp(pbase(), epptr());
          pbump(pos);

          return pos;
        }
        else
        {
          break;
        }

      default:
        assert(0);
    }

    return pos_type(off_type(-1));
  }

  ::std::streamsize xsgetn(char_type* const s,
    ::std::streamsize const count) final
  {
    auto const size(::std::min(egptr() - gptr(), count));

    ::std::memcpy(s, gptr(), size);

    gbump(size);

    return egptr() == gptr() ? traits_type::eof() : size;
  }

  ::std::streamsize xsputn(char_type const* s,
    ::std::streamsize const count) final
  {
    auto const size(::std::min(epptr() - pptr(), count));

    ::std::memcpy(pptr(), s, size);

    pbump(size);

    return epptr() == pptr() ? traits_type::eof() : size;
  }
};

template <::std::size_t N = 1024>
class memstream : public memstreambuf<N>,
  public ::std::istream,
  public ::std::ostream
{
public:
  memstream() : ::std::istream(this),
    ::std::ostream(this)
  {
  }
};

#endif // MEMSTREAMBUF_HPP


texts: Computing the Kronecker product over a tensor chain

texts:
I'm working on some Python code and have a few functions which do similar things, and the only way I've found of writing them is quite ugly and not very clear.
In the example below, the goal is to compute the Kronecker product over a tensor chain of length M, in which the mth tensor is R and every other tensor is J.
Is there any nice way to rewrite this?
def make_rotate_target(m, M, J, R):
    out = J
    if M == 1:
        return R
    else:
        for i in range(M):
            if i == 0:
                out = J
            else:
                if i + 1 == m:
                    out = np.kron(out, R)
                else:
                    out = np.kron(out, J)
    return out


texts:
I'm new to handling errors and am not sure how to do it, basically, in a speicific request err.code === 11000 is not actually an error, but expected behaviour. I want to output it but not like another error and I want the code to continue running. I don't think it looks nice.

(async () =>{
  let client;
  try {
    client = await MongoClient;
    let sales = await call(),
        collection = client.db("scraper").collection("sold");
        try {
          stored = await collection.insertMany(sales.sold, {ordered: false});
          console.log({completed: stored.result.n})
        }catch(err){
          if(err.code === 11000){log({completed: err.result.nInserted, duplicates: err.result.result.writeErrors.length})}
          else{log( {err} )}
        }
    //console.log(sales)
  } catch(err) {
    log(err)
  }
  client.close();
})()


texts: Concurrent access to data with QReadWriteLock

texts:
Using Qt, I've got this code in order to protect access to some shared data between threads. I'm pretty sure the idea is correct, but I don't know if RVO and/or RAII could potentially screw the get function. I'm much more used to C and while I understand the idea, I'm not totally familiar with all the "gotchas" for these two concepts.

class DataManager {
    Q_OBJECT

private:
    QVector<DataType> data;
    QReadWriteLock* rwLock;

public:
    DataManager() {
        rwLock = new QReadWriteLock();
    }
    ~DataManager() {
        delete rwLock;
    }
    Q_DISABLE_COPY(DataManager)

    QVector<DataType> getData() {
        QReadWriteLocker lock(rwLock);
        return data;
    }
    QVector<DataType>* beginModifyData() {
        rwLock->lockForWrite();
        return &data;
    }
    void endModifyData() {
        rwLock->unlock();
        emit dataChanged();
    }

signals:
    void dataChanged();
};

In the get function, is it possible that the RAII-type class QReadWriteLocker unlocks the lock before the return copy is made? Thus allowing some thread, that was waiting to write, to overwrite the data being returned.

Also, if somebody writes

QVector<DataType>& myData = dataManager->getData();

Is it possible, due to RVO, that they get a reference to the actual data?

Also, I'd like to receive comments on the code and idea itself. Below I've outlined the reasons why I chose this approach.

Simple to use. Since one can only read a copy of the data, they don't have to worry about synchronization and locking.
Taking advantage of the implicit sharing of Qt containers, no actual copies will ever be made when using getData(), thus making read-only access very fast.
Since, when modifying the data, one gets a pointer to the actual data, again, in most cases, no copies will be made, unless some thread is caching the data (or one of the copies has not yet gone out of scope of whatever got it).
Looking at the documentation and code, a non-recursive QReadWriteLock is ultra fast in the non-contended case, not doing any waiting or context-switching (uses atomic operations on an integer).
I could potentially do some data validation/fixup in the endModifyData function if needed.

Thanks.


texts: Parallel processing in different directories in Perl

texts:
I have some subroutines which I commonly copy & paste into much of my work.
I recently posted this on StackOverflow
and user simbabque suggested that I post my code here for reviews and comments:

#!/usr/bin/env perl

use strict; use warnings; use Cwd;
my $TOP_DIRECTORY = getcwd();
local $SIG{__WARN__} = sub {#kill the program if there are any warnings
    my $message = shift;
    my $fail_filename = "$TOP_DIRECTORY/$0.FAIL";
    open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
    printf $fh ("$message @ %s\n", getcwd());
    close $fh;
    die "$message\n";
};#http://perlmaven.com/how-to-capture-and-save-warnings-in-perl

sub execute {
    my $command = shift;
    print "Executing Command: $command\n";
    if (system($command) != 0) {
        my $fail_filename = "$TOP_DIRECTORY/$0.fail";
        open my $fh, '>', $fail_filename or die "Can't write $fail_filename: $!";
        print $fh "$command failed.\n";
        close $fh;
        print "$command failed.\n";
        die;
    }
}

sub run_parallel {
    my $command_array_reference = shift;
    unless ((ref $command_array_reference) =~ m/ARRAY/) {
        print "run_parallel requires an array reference as input.\n";
        die;
    }
    use Parallel::ForkManager;
    my $manager = new Parallel::ForkManager(4);
    my $START_DIRECTORY = getcwd();
    foreach my $command (0..scalar @{ $command_array_reference }-1) {
        $manager->start and next;
        my ($dir, $cmd) = @{ $command_array_reference->[$command] };
        chdir $dir or die "Can't chdir to $dir: $!";
        execute( $cmd );
        chdir $START_DIRECTORY or die "Can't chdir to $START_DIRECTORY: $!";
        $manager->finish;
    }
    $manager->wait_all_children;#necessary after all lists
}

my @commands;

$commands[0][0] = 'tmp1';#directory
$commands[0][1] = 'echo "ave Maria" > aveMaria.txt';#command

$commands[1][0] = 'tmp2';#directory
$commands[1][1] = 'echo "IN HOC SIGNO VINCES" > xp.txt';#command

run_parallel(\@commands);


texts:
I wrote the following code for this problem. The problem is to find the longest palindromic substring.
I think it is correct and is working correctly for all the test cases I entered myself. Now, the code is producing a Time Limit Exceeded Error. I know that there exists Manacher's Algorithm which does it in linear time but I thought of the following solution myself and wanted to implement it. I believe that it's time complexity is less as compared to \$\mathcal{O}(n^3)\$ and other \$\mathcal{O}(n^3)\$ solutions have been accepted which makes me feel that I am missing something important.

string = input()

longest = 0
position = 0
string = string.replace('', '^')
length = len(string)

##print(string)

for index, letter in enumerate(string):
##    print()
##    print('Index:', index, 'Letter:', letter)

    stretch = 1

    while string[index-stretch:index+stretch+1] == string[index-stretch:index+stretch+1][::-1]\
          and index - stretch >= 0 and index + stretch < length:
##        print('Matching Strings:', string[index-stretch:index+stretch+1], string[index-stretch:index+stretch+1][::-1], 'Stretch:', stretch)
        stretch += 1

##    print('Not Matched:', string[index-stretch:index+stretch+1], string[index-stretch:index+stretch+1][::-1], 'Stretch:', stretch)

    stretch -= 1

    if stretch > longest:
##        print('Highest Till Now')
        longest = stretch
        position = index - stretch

##print(position, longest)

print(string[position:position+(2*longest+1)].replace('^', ''))

stretch is the extension of the palindrome on either side of its center. longest stores the length of the longest substring found till then. position stores the index of the starting letter of longest. Please ask if you have any doubts.

What I want to know is that am I missing something which is causing the program to lose its efficiency? How can I overcome it? Can you suggest some improvements to the algorithm.

Thanks.


texts: Need help optimizing PHP/MySQL code snippet

texts:
I am sorry for the simple request, but I'm trying to figure out the best way to optimizing the following bit of code.  I hate using 20 lines of code when 12-15 will suffice.  I also don't like having to use intermediate variables if I don't need to.

$total_query_raw = "SELECT SUM( total ) AS total
                        FROM  `tblinvoices`
                        WHERE  `datepaid`
                            BETWEEN  '$start_date 00:00:00' AND  '$end_date 23:59:59'";

$total_query = mysqli_query($link, $total_query_raw);
    if (!$total_query) {
        echo "DB Error, could not query the database\n";
        echo 'MySQL Error: ' . mysqli_error();
        exit;
    }
$total_result = mysqli_fetch_array($total_query);
$grand_total = $total_result['total'];
echo "Grand Total: $" . number_format($grand_total,2) . "<br>";
mysqli_free_result($total_query);


texts: Function to calculate distances and nearest points between 2 GeoPandas dataframes

texts:
I have 2 geoPandas frames and want to calculate the distance and the nearest point (see functions below) from the geoSeries geometry from dataframe 1 (containing 156055 rows with unique POINT geometries) as to a geoSeries geometry in dataframe 2 (75 rows POINTS).

Question: How can the following code be optimized so as to make it quicker? As an example, I would love some code that uses the dask distributed dataframes  map_partitions solution to apply the below functions on a partitioned part of a (sub)-dataframe so as to speed things up. Optimized vector-based cython code would also be a solution etc..

A peak in both dataframes:

df1:

df2:

In the ah frame (df2) there are 75 points, around which I place a buffer of 1000 meters. In each buffer I calculate the distance (using the points of df1 representing households) and nearest point.

My code so far works but, as said, is slow:

import pandas as pd
import geopandas as gpd
from shapely import wkt, wkb
from shapely.geometry import Polygon, Point, LinearRing
from shapely.ops import nearest_points
from tqdm import tqdm, tqdm_notebook

# crs
crs= {'init': 'epsg:28992'}

def calculate_distance(row, dest_geom, src_col='geometry',
                  target_col='distance'):
    """
    Calculates distance between single Point geometry and GeoDF
    with Point geometries.

    Parameters
    ----------
    dest_geom : Point geometry to which distances will be calculated to
    src_col : column with Point objects from where the distances will be calculated from.
    target_col : name of target column where the result will be stored.
    """
    # calculate distances
    dist = row[src_col].distance(dest_geom)
    # to km
    dist_km = dist/1000
    # Assign the distance to the original data
    row[target_col] = dist_km
    return row

def find_nearest_point(row, geom_union, df1, df2, geom1_col='geometry',
            geom2_col='geometry', src_column=None):
    """Find nearest point,return corresponding value from specified
    column
    Parameters
    ----------
    geom_union = variable with unary union of points from second frame.
    df1 = dataframe 1 containing geometry column (points)
    df2 = dataframe 2 containing geometry column (points)
    geom1_col = geometry column name from df1
    geom2_col = geometry column name from df2
    src_column =  columns from df2 to be retrieved based on nearest match
    """
    # Find closest geometry
    nearest = df2[geom2_col] == nearest_points(row[geom1_col], geom_union)[1]
    # Get corresponding value from df2 (based on geometry match)
    value = df2[nearest][src_column].get_values()[0]
    return value

Here i apply the functions with a loop:

n=len(ah)

test = []
for i, row in enumerate(tqdm_notebook(list(ah['buffer'][:n]),
desc='distance_calc')):
    sub_df = df.loc[(df.geometry.within(ah['buffer'][i])), :]
    sub_df = (sub_df.apply(calculateDistance,
                       dest_geom= ah['geometry'][i],
             target_col= 'distance', axis=1))
    print ('shape sub_df {} = {}'.format(i, sub_df.shape))

    indices = (sub_df.apply(nearest,
                  geom_union=ah.unary_union,
                  df1=sub_df,
                  df2=ah,
                  geom1_col='geometry',
                  src_column='zaak_id',
                  axis=1))

    indices_frame = indices.to_frame()
    sub_df = pd.concat([sub_df, indices_frame], axis=1)

    test.append(sub_df)

test = pd.concat(test, axis=0)


texts: Making this reduce() Fibonacci generator better

texts:
I've recently discovered how cool reduce() could be and I want to do this:

>>> a = [1, 1] + [0] * 11
>>> count = 1
>>> def fib(x,n):
...     global count
...     r = x + n
...     if count < len(a) - 1: a[count+1] = r
...     count += 1
...     return r
>>>
>>> reduce(fib,a,1)
610
>>> a
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233]

But this just looks so messy and almost defeats the purpose of the last line:

reduce(fib,a,1)

What would be a better way to use Python to make a Fibonacci number with reduce()?


texts:
Given an array S of n integers, are there elements a, b, c in S such
  that a + b + c = 0? Find all unique triplets in the array which gives
  the sum of zero.

  Note: The solution set must not contain duplicate triplets.

a + b + c = 0

Solution is to just convert this into two pointer technique of solving 2SUM problem. Traverse the array and for each element check if rest of the array has 2 elements that sum up to -a.

class Solution(object):
    def threeSum(self, nums):
        def two_pointer(nums, target):
            '''two pointer technique and it is caller responsibility to pass proper nums'''
            first = 0
            second = len(nums) - 1
            two_sums = []
            while first < second:
                two_sum = nums[first] + nums[second]
                if two_sum < target:
                    first += 1
                elif two_sum > target:
                    second -= 1
                else:
                    two_sums.append([nums[first]] + [nums[second]])
                    while first+1 < len(nums) and nums[first] == nums[first+1]:
                        first += 1
                    while second-1 >= 0 and nums[second] == nums[second-1]:
                        second -= 1
                    first += 1
                    second -= 1
            return two_sums
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums = sorted(nums)
        three_sums = []
        i = 0
        while i < len(nums)-2:
            two_sums = two_pointer(nums[i+1:], -nums[i])
            for j in range(len(two_sums)):
                three_sums.append([nums[i]] + two_sums[j])
            while i+1 < len(nums) and nums[i] == nums[i+1]:
                i += 1
            i += 1
        return three_sums


texts: First-come first-serve job scheduling algorithm

texts:
I tried to make the code for implementation of first-come first-serve job scheduling algorithm as used by operating systems.

How can I make it better?

I am using turbo C++ compiler

#include<conio.h>
#include<iostream.h>
#include<dos.h>
struct process//contains information about processes in waiting queue
{
    int waitt;
    int etime;
    char name[32];
    struct process * next;
};

void inc( struct process * q)//increases wait time of all processes in wait queue
{
     while(q!=0)
     {
         q->waitt++;
         q=q->next;
     }
}

int pop(struct process** q)//remove process from wait queue to run state returns wait time of process
{
    int wait=(*q)->waitt;
    struct process* t=*q;
    *q=(*q)->next;
    delete t;
    return wait;
}

void addnode(struct process** q)//add new process to wait queue
{
   struct process *temp=new (struct process);
   cout<<"\nEnter process name ";
   cin>>temp->name;
   do
   {
        cout<<"\nEnter process execution time ";
        cin>>temp->etime;
   }while(temp->etime<=0);//to check valid input for process burst time
   temp->next=0;
   temp->waitt=0;
   if(*q==0)
   *q=temp;
   else
   {
        struct process* t=*q;
        while(t->next!=0)
        t=t->next;
        t->next=temp;
    }
}

int main(void)
{
    clrscr();
    int e=1,wait=0,p=0,tt=1;
    struct process* q=0,*t;
    //add first process
    addnode(&q);
    e=q->etime;//Burst time of runing process
    cout<<"\nProcess "<<q->name<<" startedafter a wait time of "<<q->waitt;
    cout<<" time units \n";
    p++;
    wait=pop(&q);
    do
    {
        //to check addition of new process
        if(kbhit())
        addnode(&q);
        //increase wait time of waiting processes
        inc(q);
        //decrement time left for finishing of process
        e--;
        if(e==0)//if process ended
        {
            if(q!=0)/*if process is left in wait queue remove next process from wait queue and add  its wait time to total time*/
            {
                e=q->etime;
                cout<<"\n"<<q->name<<" started after a wait time of "<<q->waitt<<"time units\n";
                p++;
                wait+=pop(&q);
             }
        }
        delay(100);
        cout<<tt++<<"  ";//to show total time units since start of first process
    }while(q!=0||e!=0);//if process ended also no process in wait queue end loop
    cout<<"\n\nTotal no. of prcesses executed ="<<p;
    cout<<"\nTotal wait time for all prcesses executed ="<<wait;
    cout<<"\nAverage wait time for prcesses executed ="<<wait/(float)p;
    getch();
    return 0;
}


texts:
I tried my hand at a contact-us PHP script. I came up with the following. First the markup, then a little client-side validation and then the email script. I just need to know if this is usable code.
I actually got to the point where I can make some cash developing websites. I just need to know if this is valid
HTML

function validateContactForm() {
  var valid = true;

  $(".info").html("");
  $(".input-field").css('border', '#e0dfdf 1px solid');
  var userName = $("#userName").val();
  var userEmail = $("#userEmail").val();
  var subject = $("#subject").val();
  var content = $("#content").val();

  if (userName == "") {
    $("#userName-info").html("Required.");
    $("#userName").css('border', '#e66262 1px solid');
    valid = false;
  }
  if (userEmail == "") {
    $("#userEmail-info").html("Required.");
    $("#userEmail").css('border', '#e66262 1px solid');
    valid = false;
  }
  if (!userEmail.match(/^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/)) {
    $("#userEmail-info").html("Invalid Email Address.");
    $("#userEmail").css('border', '#e66262 1px solid');
    valid = false;
  }

  if (subject == "") {
    $("#subject-info").html("Required.");
    $("#subject").css('border', '#e66262 1px solid');
    valid = false;
  }
  if (content == "") {
    $("#userMessage-info").html("Required.");
    $("#content").css('border', '#e66262 1px solid');
    valid = false;
  }
  return valid;
}
<form name="frmContact" id="frmContact" method="post" action="" enctype="multipart/form-data" onsubmit="return validateContactForm()">

    Name

    <input type="text" class="input-field" name="userName" id="userName" />

    Email
 <input type="text" class="input-field" name="userEmail" id="userEmail" />

    Subject
 <input type="text" class="input-field" name="subject" id="subject" />

    Message

    <textarea name="content" id="content" class="input-field" cols="60" rows="6"></textarea>

    <input type="submit" name="send" class="btn-submit" value="Send" />

      <?php if (!empty($message)) { ?>
      <p class='<?php echo $type; ?>Message'>
        <?php echo $message; ?>

      <?php } ?>

</form>

PHP
<?php if (!empty($_POST['send'])) {
    $name = $_POST['userName'];
    $email = $_POST['userEmail'];
    $subject = $_POST['subject'];
    $content = $_POST['content'];

    $toEmail = 'neilmeyermusic@gmail.com';
    $mailHeaders = 'From: ' . $name . '<' . $email . ">\r\n";
    if (mail($toEmail, $subject, $content, $mailHeaders)) {
        $message = 'Your contact information is received successfully.';
        $type = 'success';
    }
}
require_once "contact-view.php";
?>


texts: Uploading a .csv to a NoSQL cluster - batch faster than consumer/producer

texts:
I was tasked with making a program that uploads a .csv to a NoSQL cluster. The files are larger (typically 2-17GB). My program works in batch mode and can process a 17GB file in 6 hours.

I decided to make a consumer-producer multithreading structure. This caused it to be significantly slower. I want to know why the producer-consumer construct was slower than a batch produce, batch consume method.

The batch looks like this:

int count = 0;
        //
        Row r;

        while ((r = rm.getNextRow()) != null)
        {
            RowQueue.Enqueue(r);
            while (RowQueue.Count <= ROWMAX)
            {
                if ((r = rm.getNextRow()) != null)
                    RowQueue.Enqueue(r);
                else
                    break;
            } //

            int uniqueIdentifer = -1;
            if (count > 1000)
            {
                PrintAndSavePosition(count, rm, positionQueue, true);
                count = 0;
            }
            //give it some extra room to be safe
            while (RowQueue.Count != 0)
            {
                r = RowQueue.Dequeue();
                while (uniqueIdentifer == -1)
                {
                    uniqueIdentifer = nsqw.tryPut(r);
                    if (uniqueIdentifer == -1)
                        Thread.Sleep(1);
                }
                count++;
            }

            positionQueue.Add(new Tuple<int, long>(uniqueIdentifer, rm.Position));
         }

As compared to

public void produceLoop(){
            while (true)
            {

                while (RowQueue.Count <= ROWMAX && (r = rm.getNextRow()) != null){
                    RowQueue.Enqueue(r);
                }

            }
 }

public void consumeLoop(){
     while(true){
     while (RowQueue.Count != 0)
            {
                RowQueue.TryDequeue(out r);
                while (uniqueIdentifer == -1)
                {
                    uniqueIdentifer = nsqw.tryPut(r);
                    if (uniqueIdentifer == -1)
                        Thread.Sleep(1);
                }
                count++;
            }

            positionQueue.Add(new Tuple<int, long>(uniqueIdentifer, rm.Position));
         }
 }

}

The bottom half are infinite loops for a speed test.


texts:
I wrote this switch function for Python, as there isn't a built-in one and most of the Googlable ones doesn't execute code, but only return something (I admit I haven't looked much further than a single Stack Oveflow page to see what people use, but a lot of the solutions are unnecessarily complex):

def switch(variable, **cases):
    for case in cases.keys():
       if variable is case:
           exec(cases[case])

I use **cases, due to this syntax:

def switch(variable, **cases):
    for case in cases.keys():
       if variable is case:
           exec(cases[case])

some_string = "a"
switch(some_string,
       b="print('It is b!')",
       a="print('It is a!')")

some_string = "b"
switch(some_string,
       b="print('It is b!')",
       a="print('It is a!')")

some_string = "c"
switch(some_string,
       b="print('It is b!')",
       a="print('It is a!')")

Can this be optimized/made more pythonic?


texts:
I currently have the following class that takes a custom file object as an argument and makes a copy of the file locally.

class FileCopier
 def initialize(file_info_object)
  @file_info_object = file_info_object
 end

 def copy
  File.open(local_file_path, 'wb') do |f|
   read_file_in_chunks do |chunk|
     f.write chunk
   end
  end
 end

private

 def local_file_path
  File.join(Rails.root,'tmp/blah.txt')
 end

 def read_file_in_chunks(chunksize=10343)
  index = 0
  size = @file_info_object.size
  path = @file_info_object.path

  while index < filesize
   yield Client.read(path, offset: index, length: chunksize)
   index += chunksize
  end

 end

end

The copy method seems to be fairly straight forward but I was wondering if there is a way to simplify it. It seems difficult to test to me at the moment.


texts:
I have a few hundred mp4 files (thanks android =/) that I need to convert. I only want to convert videos that are too large (>= 1080p) and I do want to keep the exif Information so the timeline is not broken.

I hope someone can look over the script to point me to some grave mistakes or give some improvement.

Anything I am missing? Thanks in advance.

resize() {
    echo "Filename $1"
    filename=$(basename -- "$1")
    extension="${filename##*.}"
    filename="${filename%.*}"
    new_filename=${filename}.${timestamp}.${extension}
    ffmpeg -v quiet -stats -i $1 -map_metadata 0 \
    -vf scale=-1:720 -c:v libx264 -crf 23 \
    -c:a copy $new_filename < /dev/null
    exiftool -TagsFromFile $1 "-all:all>all:all" -overwrite_original     $new_filename
}

if [[ -d $1 ]]; then
    timestamp=$(date +%s)
    echo "Finding Video Files ..."
    exiftool $1/*.mp4 -if '$ImageHeight >= 1080' -p '$Filename' > /tmp/fl_$timestamp

    echo "Processing Video Files ..."
    while IFS= read -r line; do
        resize $line
    done < /tmp/fl_$timestamp
    rm /tmp/fl_$timestamp
elif [[ -f $1 ]]; then
    resize $1
else
    echo "Argument missing"
    exit 1
fi


texts: Cluster correlations for many (> 500k) features by threshold

texts:
I have a matrix with roughly 500,000 features that I'd like to correlate and find features that have correlations >= 0.90, then cluster these into one group. Is there an efficient algorithm to do this? R's cor() function will not work as this data is too large to compute a 500k x 500k matrix, let alone storing this in memory. I'm only interested in finding these features that satisfy a correlation threshold.

cluster_number <- 1
for (b in seq(1, 500000)) {

  # INIT
  b1 <- to_cluster[b]
  if(b == 1){ selected$R_CLUST[selected$BIN %in% b1] <- cluster_number }

  # COMPUTE COR
  sel <- subset(selected, R_CLUST != 0)
  sel <- sel[!duplicated(sel$R_CLUST), ]
  sel <- as.vector(sel$BIN)
  sel <- sel[! sel %in% b1]
  if(length(sel) == 0){ next }

  r2 <- round(cor(signal[, c(b1, sel)], method = "pearson", use = "everything"), 5)
  diag(r2) <- 0
  r2 <- subset(melt(r2), value >= r_cutoff & Var1 == b1)

  if(nrow(r2) > 0){
    correlate <- r2$Var2
    selected$R_CLUST[selected$BIN %in% b1] <- selected$R_CLUST[selected$BIN %in% correlate]
  } else {
    cluster_number <- cluster_number + 1
    selected$R_CLUST[selected$BIN %in% b1] <- cluster_number
  }
}

Here I am iterating through my features and placing correlated features aside in the selected data.frame if they satisfy a correlation threshold. This does not work though because the selected data.frame gets very large and computing cor() becomes computationally intensive. I should mention that the ultimate goal here is to cluster these features into groups such that the guarantee is that each group satisfies a correlation threshold. I'm also thinking about perhaps taking a nearest-neighbor approach by taking, say, the top 10 closest features to a given feature and create a graph based on this and find largely connected components, but I know the guarantee is not necessarily satisfied in this way.


texts: Getting information from URL efficiently

texts:
I wrote a dirty and ugly code to show in console how many bugs are left until the release of elementary codename Isis.
The code works but it's pretty inefficient. What it does is:

downloads the entire Launchpad site
writes it down to a temp file
scans for the appropriate lines in said file
stores the number of bugs still open
deletes the temp file
shows the total number of bugs left

How could I make this code more efficient? For example, is there a way to get that data without having to download the entire site each time? Or to scan the downloaded data for the still opened bugs, without having to write it down to a temp file first?

I'm running python 2.7.3.

import urllib
import os

"""
Retrieves the number of bugs left until the arrival of elementary OS Isis.
"""

# Get Launchpad data.
f = urllib.urlopen("https://launchpad.net/elementary/+milestone/isis-beta1")
s = f.read()
f.close()

# Write data to temp file.
ff = open("temp.del", "w")
ff.write(s)
ff.close()

# Find number of bugs left.
temp = open("temp.del", "r")
for i, line in enumerate(temp):

    # Incomplete bugs.
    if 'span class="statusINCOMPLETE">' in line and i < 450:
        a = temp.next()
        b = a.split('')
        c = b[1].split('')
        b_incomp = int(c[0])

    # Confirmed bugs.
    if 'span class="statusCONFIRMED">' in line and i < 450:
        a = temp.next()
        b = a.split('')
        c = b[1].split('')
        b_conf = int(c[0])

    # In progress bugs.
    if 'span class="statusINPROGRESS">' in line and i < 450:
        a = temp.next()
        b = a.split('')
        c = b[1].split('')
        b_inprog = int(c[0])

# Delete temp file.
os.remove('temp.del')

# Print to console.
bugs = b_incomp + b_conf + b_inprog
print '\n%d bugs left until Isis. Quit moaning.\n' % bugs


texts:
Is there a better way to optimize this code? It started with \$O(n^2)\$ (nested loops) then \$O(n)\$ (with index).

public static String getRelativePath(String from, String to) {
    String relative = "";
    String regexPath = "/";
    String regexLow = "..";

    List<String> toList = Arrays.asList(to.split(regexPath));
    List<String> fromList = Arrays.asList(from.split(regexPath));

    int toSize = toList.size();
    int fromSize = fromList.size();

    relative += regexPath;

    for(int index = 0; index < fromSize; index++) {
        if(index <= toSize-1) {
            String toValue = toList.get(index);
            String fromValue = fromList.get(index);

            if(toValue.equals(fromValue)) {
                relative += regexLow + regexPath;
            }
            else
                relative += fromValue + regexPath;
        }
        else {
            if(index != fromSize-1)
                relative += fromList.get(index) + regexPath;
            else
                relative += fromList.get(index);
        }
    }

    return relative;
}

Inputs:

  fromPath -> "/a/b/c" toPath -> "/a/b/d/f"

Output:

  relativePath -> "/../../d/f


texts: Avoiding "warning: Use of uninitialized value" when fetching an integer CGI parameter

texts:
I was using this code to fetch a CGI parameter:

$page = int(param('page'));

This sometimes results in:

warning: Use of uninitialized value in int

Is this a good solution to resolve this warning, or is better and more succinct code available?

if (defined param('page')) {
    $param_page = int(param('page'));
} else {
    $param_page = 1;
}


texts:
I have recently been brushing up on my statistics and calculus and wanted to implement Linear Regression, the code will be for a calculus/statistics library I am working on (I know there are libraries for this but I am trying improve my both coding and math skills).

The following code works as intended. However, I feel like it has some structural flaws and I can't put my finger on what it is

class LinearReg:

    x = []
    y = []

    x_mean = 0
    y_mean = 0

    b_zero = 0
    slope = 0

    def __init__(self,x,y):

        if len(x) != len(y):
            raise Error("Both axis must have the same number of values")

        self.x = x
        self.y = y
        self.x_mean = self.axis_mean(self.x)
        self.y_mean = self.axis_mean(self.y)

    def axis_mean(self,axis):
        return sum(axis) / len(axis)

    def sum_of_deviation_products(self):
        result = 0
        for i in range(len(self.y)):
            x_dev = (self.x[i] - self.x_mean)
            y_dev = (self.y[i] - self.y_mean)
            result += x_dev * y_dev
        return result

    def sum_of_x_deviation_squared(self):
        result = 0
        for i in range(len(self.x)):
            result += (self.x[i] - self.x_mean)**2
        return result

    def get_b_zero(self):
        return self.b_zero

    def get_slope(self):
        self.slope = self.sum_of_deviation_products() / self.sum_of_x_deviation_squared()
        return self.slope

    def fit_best_line(self):
        self.b_zero = self.y_mean - (self.get_slope() * self.x_mean)
        print("The best line equation is: " +
        "%.2f" % self.slope
         + "x + " +
         "%.2f" % self.b_zero)

My primary focus is now: structure and cleanliness,

How efficient would this play out in a large library?
How clean and readable is the code?
What kind of problems would I face if this class were to interact with other classes in the library?

Perhaps there is quicker way to do Linear Regression in Theory, but I'm not really interested in that right now.


texts:
Problem Statement: JNEXT

  DevG was challanged to find the just next greater number which can be formed using digits of a given number. Now DevG needs your help to find that just next greater number and win the challenge.

  Input

  The first line have t number of test cases (1 <= t <= 100). In next 2*t lines for each test case first there is number n (1 <= n <= 1000000) which denotes the number of digits in given number and next line contains n digits of given number separated by space.

  Output

  Print the just next greater number if possible else print -1 in one line for each test case.

  Note : There will be no test case which contains zero in starting digits of any given number.

  Example

  Input:

2
5
1 5 4 8 3
10
1 4 7 4 5 8 4 1 2 6

  Output:

15834
1474584162

My Solution is

public static void main(String[] argh) throws Exception{
        Reader br = new Reader();
        int t= br.nextInt();

        for(int aa=0; aa<t; aa++){
            int n= br.nextInt();
            int[] arr= new int[n];
            int breakPoint= -1;
            int mI= -1;

            for(int qq=0; qq<n; qq++){
                arr[qq]= br.nextInt();
                if(qq !=0 && arr[qq] > arr[qq-1]){
                    breakPoint= qq-1;
                }
                if(breakPoint != -1){
                    if(arr[breakPoint] < arr[qq]){
                        mI= qq;
                    }
                }
            }
            if(breakPoint == -1 || n == 1){
                System.out.println(-1);
                continue;
            }

            // swap
            arr[breakPoint]= arr[breakPoint] + arr[mI];
            arr[mI]= arr[breakPoint] - arr[mI];
            arr[breakPoint]= arr[breakPoint] - arr[mI];
            breakPoint++;

            for(int ii=0; ii<breakPoint; ii++){
                System.out.print(arr[ii]);
            }
            for(int ii=n-1; ii>=breakPoint; ii--){
                System.out.print(arr[ii]);
            }
            System.out.println("");
        }
    }

My solution is having O(N) time complexity but still I am getting TLE.
Can anyone point out issue?