texts: Python implementation of the longest increasing subsequence

texts:
Prompted by this question on Stack Overflow, I wrote an implementation in Python of the longest increasing subsequence problem.  In a nutshell, the problem is: given a sequence of numbers, remove the fewest possible to obtain an increasing subsequence (the answer is not unique).

Perhaps it is best illustrated by example:

>>> elems
[25, 72, 31, 32, 8, 20, 38, 43, 85, 39, 33, 40, 98, 37, 14]
>>> subsequence(elems)
[25, 31, 32, 38, 39, 40, 98]

The algorithm iterates over the input array, X, while keeping track of the length longest increasing subsequence found so far (L). It also maintains an array M of length L where M[j] = "the index in X of the final element of the best subsequence of length j found so far" where best means the one that ends on the lowest element.

It also maintains an array P which constitutes a linked list of indices in X of the best possible subsequences (e.g. P[j], P[P[j]], P[P[P[j]]] ... is the best subsequence ending with X[j], in reverse order).  P is not needed if only the length of the longest increasing subsequence is needed.

The code below works, but I am sure it could be made shorter and / or more readable. Can any more experienced Python coders offer some suggestions?

from random import randrange
from itertools import islice

def randomSeq(max):
  while True: yield randrange(max)

def randomList(N,max):
  return list(islice(randomSeq(max),N))

## Returns the longest subsequence (non-contiguous) of X that is strictly increasing.
def subsequence(X):
    L = 1     ## length of longest subsequence (initially: just first element)
    M = [0]   ## M[j] = index in X of the final member of the lowest subsequence of length 'j' yet found
    P = [-1]
    for i in range(1,X.__len__()):
        ## Find largest j <= L such that: X[M[j]] < X[i].
        ## X[M[j]] is increasing, so use binary search over j.
        j = -1
        start = 0
        end = L - 1
        going = True
        while going:
            if (start == end):
                if (X[M[start]] < X[i]):
                    j = start
                going = False
            else:
                partition = 1 + ((end - start - 1) / 2)
                if (X[M[start + partition]] < X[i]):
                    start += partition
                    j = start
                else:
                    end = start + partition - 1

        if (j >= 0):
            P.append(M[j])
        else:
            P.append(-1)

        j += 1
        if (j == L):
            M.append(i)
            L += 1
        if (X[i] < X[M[j]]):
            M[j] = i

    ## trace subsequence back to output
    result = []
    trace_idx = M[L-1]
    while (trace_idx >= 0):
        result.append(X[trace_idx])
        trace_idx = P[trace_idx]

    return list(result.__reversed__())

l1 = randomList(15,100)

See the revised version below, in this answer.


texts: Lazy-loading images using an IntersectionObserver

texts:
As part of a progressive enhancement revision, I created a module, which should handle loading images lazily.

You can find a working example on Codepen.

To each chuck of code below applies the following question: Am I accustomed to any bad coding habits? Would you do something different?

The image gets loaded, when the loadImage function is called, which can be passed an Image Element with a data-lazy attribute, or an URL and ultimately returns an Image element.

function loadImage(image) {

  return new Promise((resolve, reject) => {

    const isImage = image instanceof Image || image instanceof HTMLImageElement;

    /*
     * Would this be a better case for writing the if statement out?
     */
    const url = isString(image)
      ? image
      : (isImage && 'lazy' in image.dataset ? image.dataset.lazy : null);

    if (!url) {
      throw new Error('An URL has to be provided.' + isImage ? 'The [data-lazy] attribute is not set.' : '');
    }

    image = isImage ? image : new Image();

    image.addEventListener('load', () => {
      resolve(image);
    });

    image.addEventListener('error', () => {
      reject(new Error('An error occurred while loading the image.'));
    });

    image.src = url;

  });
}

Then I added a make function, which returns a function which becomes handy, when I create the IntersectionObserver.

function makeLoadImage(doAfterLoad) {
  return (image) => loadImage(image).then((image) => doAfterLoad(image) || image);
}

The factory function which returns the IntersectionObserver. You can decide, whether the images on screen should be loaded simultaneously or in order, and you can define a duration before the image gets loaded, which essentially prevents someone triggering the images to get loaded, when scrolling/swiping quickly through the page.

function createIntersectionObserver(loadImage, options = {}) {

  if (!('IntersectionObserver' in window)) {
    throw new Error('The IntersectionObserver is not supported by this browser.');
  }

  options = {
    loadInOrder: false,
    wait: 100,
    ...options
  };

  const queue = Promise.resolve();
  const timeouts = new Map();

  const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach((entry) => {
      const { intersectionRatio, target: image } = entry,
        /* entry.isIntersecting is not supported on Android, Chrome 51.0.2704.81 */
        isIntersecting = intersectionRatio >= options.threshold;

      if (isIntersecting) {
        timeouts.set(image, setTimeout(() => {
          options.loadInOrder ? queue.then(() => loadImage(image)) : loadImage(image);
          observer.unobserve(image);
          timeouts.delete(image);
        }, options.wait));
      } else if (!isIntersecting && timeouts.has(image)) {
        clearTimeout(timeouts.get(image));
      }

    });
  }, { ...options, threshold: [0, options.threshold] });

  return observer;

}

Finally, it is combined in setup function.

/**
 * Should I come up with a different name for this function,
 * if it is part of a module? It could be renamed, when it gets
 * imported by another module, but giving it a different name
 * in the first place would make it redudant to do after all.
 * So, I am guessing, "setup" as a name is too general, is it not?
 */
function setup(loadImage, images, options) {
  try {
    /* Progressive enhancement */
    const observer = createIntersectionObserver(loadImage, options);
    images.forEach((image) => observer.observe(image));
  } catch (error) {
    /* Fallback */
    images.forEach((image) => loadImage(image));
  }
}

You can see the module in action on Codepen.

What are your suggestions to improve my code?


texts: Loop through different controls and enabled the state of the whole group VBA

texts:
I got the below code that is looping through all controls and changing the state in a after update event and enables new row for user to use. Everything works fine but i'm just wondering whether there is a better way to achieve the same result as what i have done is long winded. This will only enable the controls if the combobox has data if blank skip enable.

Private Sub Item1_AfterUpdate()
    Call UpdateItemsToClean
End Sub

Private Sub UpdateItemsToClean()
    Dim ctl As MSForms.Control
    Dim lbl As MSForms.Label
    Dim cmb As MSForms.ComboBox
    Dim txtbox As MSForms.TextBox
    Dim optbtn As MSForms.OptionButton
    Dim i As Integer

    For i = 2 To ItemsListFrame.Controls.Count
        For Each ctl In ItemsListFrame.Controls
            If TypeName(ctl) = "Label" Then
                If ctl.Tag = "GroupItem" & i - 1 Then
                    Set lbl = ctl
                    If Controls("Item" & i - 1).Value <> vbNullString Then
                        Controls("OrderLbl" & i).Enabled = True
                    End If
                End If

            ElseIf TypeName(ctl) = "ComboBox" Then
                If ctl.Tag = "GroupItem" & i - 1 Then
                    Set cmb = ctl
                    If Controls("Item" & i - 1).Value <> vbNullString Then
                        Controls("Item" & i).Enabled = True
                    End If
                End If

            ElseIf TypeName(ctl) = "TextBox" Then
                If ctl.Tag = "GroupItem" & i - 1 Then
                    Set txtbox = ctl
                    If Controls("Item" & i - 1).Value <> vbNullString Then
                        Controls("Qty" & i).Enabled = True
                        Controls("UnitPrice" & i).Enabled = True
                        Controls("SubTotal" & i).Enabled = True
                        Controls("Comments" & i).Enabled = True
                    End If
                End If
            ElseIf TypeName(ctl) = "OptionButton" Then
                If ctl.Tag = "GroupItem" & i - 1 Or ctl.Tag = "InOut" & i - 1 Then
                    Set optbtn = ctl
                    If Controls("Item" & i - 1).Value <> vbNullString Then
                        Controls("OptionIn" & i).Enabled = True
                        Controls("OptionOut" & i).Enabled = True
                    End If
                End If
            End If
        Next ctl
      Next i
End Sub


texts: Function simulating single elevator movement

texts:
I am trying to write code for simulating movement of single elevator. This was a question to me and was pretty straightforward as the use-case was explained properly. So the problem contains following data:

  inputFloors : all floors elevator should go to. e.g. {5, 2, 9, 3, 8, 1}

  currentFloor : current floor where elevator is standing/user is entering the elevator. e.g. 6

  direction : direction of elevator movement like UP or DOWN.

Now since the user is entering at floor 6 and wants to go down then the route of the elevator should be 5, 3, 2, 1, 8, 9. That means the elevator should first go down the lesser floors in descending order and then go up the higher floors in ascending order. Similarly if the user wants to go up then the route should be 8, 9, 5, 3, 2, 1.

I wrote the code and it looked like a pretty simple use-case to me. But I wanted to see if there is any better way to do this. I am brushing up my c++ basics so this is the best solution i could think of.

My Code :

std::vector<int> singleElevatorSystem (int inputFloors[], int size, int currentFloor, string direction) {
  std::vector<int> High, Low;

  for (int i = 0; i < size; i++) {
    if (currentFloor < inputFloors[i]) {
      High.push_back (inputFloors[i]);
    } else if (currentFloor > inputFloors[i]) {
      Low.push_back (inputFloors[i]);
    }
  }

  std::sort (High.begin(), High.end());
  std::sort (Low.begin(), Low.end());

  if (direction.compare("UP") == 0) {
    High.insert(High.end(), Low.rbegin(), Low.rend());
    return High;
  } else if (direction.compare("DOWN") == 0) {
    std::reverse (Low.begin(), Low.end());
    Low.insert (Low.end(), High.begin(), High.end());
    return Low;
  }
}

int main () {
  int inputFloors[] = {5, 2, 9, 3, 8, 1};
  int currentFloor = 6;
  //string direction("UP");
  string direction("DOWN");

  std::vector<int> outputFloors = singleElevatorSystem (inputFloors, 6, currentFloor, direction);
  std::cout << "Elevator will stop at requested floors in sequence : ";
  for (int i = 0; i < 6; i++) {
    std::cout << outputFloors.at(i) << "  ";
  }

  std::cin.get();
  return 0;
}

I hardcoded the size of array and current floor value.

Any comments or updates please??


texts:
I recently learned about the difference between a copy and a deep copy. Some people where writing some rather lengthy functions to in order to create a deep copy.

Then I was just playing around and wondering if there is anything wrong with the following method:

var newDeepCopy = originalArray.concat();

Right, so... just concat the original array with... nothing? Am I missing anything?


texts:
I've been learning more programming in the past few years (C, Java, Arduino) for my hobbies. I read the "C for Dummies" book and found that it was good, but did not cover much - especially pointers... One of my friends from college (CS major) suggested a simple program exercise to see if I could figure out how to use pointers.  Well, I had to refer to a pdf of Ritchie's text "The C Programming Language" to learn about pointers. He asked me to make a program that returns the Fibonacci sequence. A month or so ago, I sent him my program, but he hasn't had time to review it since he is very busy with work these days. Basically what I am wondering about my program is if it is redundant or "too verbose" - basically is it written efficiently?  IMO, as a hobbyist programmer, it works just fine.

Below is the source code file he initially sent to me:

/**

* @file  fibonacci.cpp
*
* @brief Prints out a partial Fibonacci sequence.

*/

#include <stdio.h>

// Function prototype for fibonacci()
unsigned int Fibonacci(unsigned int);

int main(int argc, char** argv)
{
    printf("Fibonacci Sequence:\n");

    for (unsigned int n = 0; n < 10; ++n)
    {
        unsigned int fib = Fibonacci(n);
        printf("%d ", fib);
    }

    return 0;
}

// Computes the Nth Fibonacci number.
unsigned int Fibonacci(unsigned int N)
{
    // Actual implementation goes here!!
}

Below is my version of the program that I sent to him for review:

/**

* @file  fibonacci.cpp
*
* @brief Prints out a partial Fibonacci sequence.

*/

#include <stdio.h>
unsigned int n;
char nMax[3];  //user input for sequence up to and including value @ this index
int Nmax;

// Function prototype for fibonacci()
unsigned int Fibonacci(unsigned int);

int main(int argc, char** argv)
{
    printf("Please input the Nth index of the last sequence value.\n");
    printf("Program will return entire Fibonacci Sequence up to and including Nth value.\n");

    gets(nMax);
    Nmax =atoi(nMax);

    for (n = 0; n < Nmax; ++n)
    {
        unsigned int fib = Fibonacci(n);
        printf("%d ", fib);
    }

    return 0;
}

// Computes the Nth Fibonacci number.
unsigned int Fibonacci(unsigned int n)
{
    // Actual implementation goes here!!

    unsigned int N;  //function output value

    //declare a temp array of sequence values
    unsigned int tempseq[100];

    // declare two ptrs
    unsigned int *prev;  //pointer to previous or (n-1) value in sequence
    unsigned int *prevprev;  //pointer to previous previous or (n-2) value in sequence

    if (n==0)
    {   N = 1;  //1st seed value
        tempseq[n] = N;
    }
    else if(n==1)
    {
        N = 1;  //2nd seed value
        tempseq[n] = N;
    }
    else
    {
        prev = &tempseq[n-1];        //prev ptr points to n-1 array element
        prevprev = &tempseq[n-2];    //prevprev ptr points to n-2 array element

        N = *prev + *prevprev;       //fibonacci recurrence relation
        tempseq[n] = N;              //add current value of N to the temp array

    }

    return N;

}

EDIT:  Not to step on the toes of JS1 who recently replied, but I wanted to add an image here of my cmd line execution of my fibonacci.exe program to show that at least on my pc, it seems to work....


texts:
I worked on cmms project .
I have some scheduling , esch of schedule have some triggers (e.g,. Bymeter , byActivity ,ByPeriod).

I wrote some methods to generate workOrder for each Schedule if schedule is ok.

public async Task<IEnumerable<TodayScheduleTaskViewModel>> GetTodayTasks(int page, int recordsPerPage = 50)
    {
        int resultForSkip = page * recordsPerPage;
        var _result = new List<Schedule>();

        bool repeat = true;
        do
        {
            var data = await GetExpression(page, recordsPerPage).Cacheable().ToListAsync();
            if (data.Count == 0) { repeat = false; break; };
            _result.AddRange(Calculate(data).ToList());
            page++;
        } while ((_result.Count < recordsPerPage && repeat));

        return _result.Select(row => new TodayScheduleTaskViewModel
        {
            //map fields

        }).ToList();
    }

and :

 private IQueryable<Schedule> GetExpression(int page, int recordsPerPage = 50)
    {
        int resultForSkip = page * recordsPerPage;

        return _schedules.OrderBy(row => row.Code).Skip(() => resultForSkip).Take(() => recordsPerPage);
    }

and Calculate method :

 private IEnumerable<Schedule> Calculate(List<Schedule> schedules)
    {
        List<Schedule> result = new List<Schedule>();
        foreach (var schedule in schedules)
        {

            bool IsAllTriggersRequired = schedule.WhenFire == GenerateWorkOrderWhen.AllOfTheTriggersFire ? true : false;
            bool dontContinue = false;

            bool timeFalg = false, meterFlag = false, workFlag = false;
            int countersuccessTriggers = 0;

            foreach (var item in schedule.Triggers)
            {

                switch (item.TypeId)
                {

                    case TriggerType.ByWork:

                        if (dontContinue && !IsAllTriggersRequired) break;
                        int workValue = _equipmentFunctionService.GetAssetWorkValue(schedule.AssetId.Value,schedule.CalculatingType);
                        if ((workValue >= item.WorkValue) && !dontContinue)
                        {
                            workFlag = true;
                            dontContinue = true;
                            countersuccessTriggers++;
                        };
                        break;
                }

            }
            var AllTriggersAvailabe = countersuccessTriggers == schedule.Triggers.Count && IsAllTriggersRequired;
            var AnyTriggersAvailabe = timeFalg || meterFlag || workFlag;

            if (AllTriggersAvailabe || (!IsAllTriggersRequired && AnyTriggersAvailabe))
                result.Add(schedule);
        }
        return result;
    }

let's describe method and my goal:

I want to speed up my query.

1- Why use do...While in GetTodayTask :
my GridView Page size is const and I want Just return same records, First I get some Records and pass them to Calculate() Method to check some condition and maybe in Calculate() Method some records removed  (result count changed in calculate())


texts: Incremental Sieve of Eratosthenes Generator

texts:
So I was fiddling around with the Euler challenges. One of the things they mentioned in their discussions of the solutions is the Sieve of Eratosthenes and that you can only use it when you know an upper bound of the primes you want to generate.

I wondered whether the algorithm can be adapted to work without that upper bound. This works be replacing the bool[] for a Dictionary<int, int>. Where the original algorithm would fill all multiples immediately after finding a prime, I will fill them one at a time, keeping a dictionary to keep track of which prime has filled that value in the sieve. This way the sieve can be filled incrementally as enumeration continues.

In my version of C#, this method runs out of steam before we reach int.MaxValue, due to the increasing size of the dictionary. If I am correct, this algorithm runs in \$O(n)\$ space, and \$O(n)\$ time.

/// <summary>
/// Produce an "infinite" generator for primes.
/// </summary>
/// <remarks>Runs out of memory at prime 1_003_875_373.</remarks>
public static IEnumerable<int> Primes() {
  var sieve = new Dictionary<int, int>();
  var primeCandidate = 2;
  while (true) {
    // If sieve contains primeCandidate, it's not a prime. We retrieve its factor from the dictionary.
    if (sieve.TryGetValue(primeCandidate, out var smallestFactor)) {
      // Not needed anymore
      sieve.Remove(primeCandidate);

      // Look for the next multiple that isn't already in the sieve.
      // Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.
      unchecked {
        var nextMultiple = primeCandidate + smallestFactor;
        while (sieve.ContainsKey(nextMultiple)) {
          nextMultiple += smallestFactor;
        }
        sieve[nextMultiple] = smallestFactor;
      }
    }
    else {
      // In this case, we have found a prime. Add its square to the sieve:
      yield return primeCandidate;
      // Unchecked because if it overflows, we don't really care, since primeCandidate would have overflowed earlier.
      unchecked { sieve[primeCandidate * primeCandidate] = primeCandidate; }
    }
    // This cannot overflow!
    checked { primeCandidate++; }
  }
}

[TestMethod]
public void TestFirst20Primes() {
  var actual = Primes().Take(20).ToList();
  var expected = new[] { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71 };
  CollectionAssert.AreEqual(expected, actual);
}

My main concern is efficiency, both in memory and time.


texts: Creating an object in Python with lots of long arguments

texts:
See the proposed changes in this Pull Request under def add_talk.

date = self.talkDetailsWidget.dateEdit.date()
time = self.talkDetailsWidget.timeEdit.time()
presentation = Presentation(
    unicode(self.talkDetailsWidget.titleLineEdit.text()).strip(),
    unicode(self.talkDetailsWidget.presenterLineEdit.text()).strip(),
    unicode(self.talkDetailsWidget.descriptionTextEdit.toPlainText()).strip(),
    unicode(self.talkDetailsWidget.categoryLineEdit.text()).strip(),
    unicode(self.talkDetailsWidget.eventLineEdit.text()).strip(),
    unicode(self.talkDetailsWidget.roomLineEdit.text()).strip(),
    unicode(date.toString(Qt.ISODate)),
    unicode(time.toString(Qt.ISODate)))

There's a lot of boilerplate code (e.g. unicode(), seld.talkDetailsWidget, text(), strip(), etc.) How could you reduce that and still have the code be easy to understand?

My thinking is if something along the lines of this were possible:

map(str.strip,
    map(unicode,
        map(QLineEdit.text,
            map(self.talkDetailsWidget, fields))))


texts: Interleaving values from several iterables

texts:
I am new to Python and am trying to see if there is a cleaner way to write my code. The following code take iterables as parameter it produces the first value from the first parameter, then the first value from the the second parameter, ..., then the first value from the last parameter; then the second value from the first parameter and so on.If any iteratable produces no more values, this generator produces no more values.

If I do:

for i in skip('abcde','fg','hijk'):
  print(i,end='')

produces the values 'a', 'f', 'h', 'b', 'g', 'i', and 'c'. The code I've written is as under(which works):

def skip(*args):
  itrs = [iter(arg) for arg in args]
  while itrs != []:
     temp = []
     for i in range(len(itrs)):
        try:
          yield next(itrs[i])
          temp.append(itrs[i])
        except StopIteration:
          pass
      itrs = temp

Is there a cleaner/ concise way to write the code(without using any external libraries)?


texts:
So, I have my code here:

import turtle

class fractal:

    """A class containing methods that will replicate
    various fractals.

    Attributes:
        num: An integer representing the number of iterations
        t: A turtle graphics object imported from Turtle.py
    """

    def __init__(self, num, t=turtle.Turtle()):
        self.num = num
        self.t = t

    def kochCurve(self):
        axiom = 'F'
        for _ in range(self.num):
            linSys = 'F+F--F+F'
            axiom = axiom.replace('F',linSys)
        for i in axiom:
            if i == 'F':
                self.t.forward(10)
            elif i == '+':
                self.t.left(60)
            elif i == '-':
                self.t.right(60)

    def kochIsland(self):
        axiom = 'F-F-F-F'
        for _ in range(self.num):
            linSys = 'F+FF-FF-F-F+F+F'
            axiom = axiom.replace('F',linSys)
        for i in axiom:
            if i == 'F':
                self.t.forward(10)
            elif i == '+':
                self.t.left(90)
            elif i == '-':
                self.t.right(90)

    def tree(self):
        axiom = '[X]'
        for _ in range(self.num):
            linSys = 'F-[[X]+X]+F[+FX]-X'
            axiom = axiom.replace('X',linSys)
            axiom = axiom.replace('F','FF')

        self.t.setheading(90)
        self.t.setposition(0,-300)
        stack = []
        for i in axiom:
            if i == 'F':
                self.t.forward(10)
            elif i == '+':
                self.t.right(25)
            elif i == '-':
                self.t.left(25)
            elif i == '[':
                pos = self.t.position()
                head = self.t.heading()
                stack.append((pos,head))
            elif i == ']':
                (pos,head) = stack.pop()
                self.t.penup()
                self.t.setposition(pos)
                self.t.setheading(head)
                self.t.pendown()

fractal(3).kochCurve()

Overall, the code just seems a bit redundant and LONG. I'm creating this class to share on a repository for some others to view. However, I don't particularly enjoy the way it looks.

Essentially, this class makes a turtle from Turtle Graphics and draws fractals with it. So far, I have the three different fractals. All that's needed to call into the object is an integer that will be the number of iterations.

What improvements can I make here?


texts: Check if an array value exists as part of the url

texts:
I have the following bit of code in a service worker that checks to see it the url contains any of the values in an array and if so it breaks out of the function.  As it is run for every asset on a webpage, it can be run a lot of times so I was wondering if it could be optimised in any way:

const urlsToIgnore = [
  'boldchat.com',
  'pinimg.com',
  'responsetap.com',
  'facebook.net',
  'dwin1.com',
  'bing.com',
  'google-analytics.com',
  'googletagmanager.com',
  'hotjar.com',
  'pinterest.com',
];

self.addEventListener('fetch', event => {
  // don't load assets from these urls
  for (let i = 0; i < urlsToIgnore.length; i++) {
    if (event.request.url.indexOf(urlsToIgnore[i]) > -1) {
      return;
    }
  }

  // .... rest of code to cache the assets and page
});


texts: Circular buffer implementation for buffering TCP socket messages

texts:
I have written my own for practice and also some tweaks for my specific requirement.  There is an insert which can copy a range (well array copy really) which I am hoping is more efficient than individual element insert.

Can anyone make any comments specifically as regards efficiency and code elegance.  I need to use this with Java 1.6 and am getting a warning on the array = newArray(size); line in the constructor.  But that is the only issue I am currently aware of.

import java.util.Arrays;  //copyOf

public class CircularBuffer<T> {
    private T[] array;  //storage
    private int put_idx, get_idx, count; //get/put & internal num elements counter
    private final int size;   //size of internal array storage

    public CircularBuffer(int size) {
        get_idx = 0;
        put_idx = 0;
        count   = 0;
        this.size = size;

        //Type safety: A generic array of T is created for a varargs parameter - investigate how to remove warning
        array = newArray(size);
    }

    //@SafeVarargs - ok in java 1.7
    static <T> T[] newArray(int length, T... array)
    {
        return Arrays.copyOf(array, length);
    }

    void reset(){
        get_idx=put_idx=count=0;
    }

    public boolean empty() { return count == 0; }

    public boolean full() { return count == size; }

    int get_count() { return count; }

    //inserts a single new element
    public void insert(T element)
    {
        if(full())
            throw new ArrayIndexOutOfBoundsException("buffer full");

        array[put_idx++] = element;
        put_idx %= size;
        ++count;
    }

    //insert array of specified length
    public void insert(T[] thearray) {
        if(thearray.length + count > size)
            throw new ArrayIndexOutOfBoundsException("insufficient space to insert array");

        //first copy to end - contiguous array copy
        int remaining = size - put_idx;
        if(remaining >= thearray.length) {
            System.arraycopy(thearray, 0, array, put_idx, thearray.length);
            put_idx += thearray.length;
            put_idx %= size;
        } else {
            System.arraycopy(thearray, 0, array, put_idx, remaining);
            int rest = thearray.length - remaining;
            System.arraycopy(thearray, remaining, array, 0, rest);
            put_idx = rest;
        }
        count += thearray.length;
    }

    //get the oldest element, move read pointer
    public T get()
    {
        if(empty())
            throw new ArrayIndexOutOfBoundsException("buffer empty");

        final T ret = array[get_idx++];
        get_idx %= size;
        --count;
        return ret;
    }
}

Code to exercise class:

public class TestCircularBuffer {
    static public void main(String args[]) {
        new TestCircularBuffer().go();
    }

    void go() {
        int SIZE = 1000;
        int arr[] = new int[SIZE];

        for(int i = 0; i < SIZE; ++i) {
            arr[i] = i;
        }

        CircularBuffer<Integer> cb = new CircularBuffer<Integer>(10);

        //exercise circ buffer
        int i = 0;
        while(i < SIZE) {
            while(!cb.full())
                cb.insert(arr[i++]);

            while(!cb.empty())
                System.out.print(cb.get() + " ");
        }

        //now exercise array insert
        System.out.println("\nrange insert test");
        Integer marr[] = {1,2,3,4};

        i = 0;
        while(i < 20) {
            //will only be able to fit 2 lots
            cb.insert(marr);
            cb.insert(marr);

            while(!cb.empty())
                System.out.print(cb.get() + " ");

            ++i;
        }
    }
}


texts: Custom implementation of python queue to use dict instead of dqueue

texts:
A bit of context:
I have 100 addresses that can send transactions to a blockchain, and I have a web app that works like this:

Get request and handle it in a thread
Get a free address from the queue
Send a transaction
Return address to the queue

It's important to know that one address cannot send two transactions at once.

My approach was to make a custom python queue that uses a dict of "address: free/taken" instead of the normal queue.

Its good for two reasons:

I need to be able to get a random address for the dict
The base queue get and put method already handle thread-locking and timeout.

This seems to work, but I would like some feedback on it.

from queue import Queue
from enum import Enum
import random

class ChannelStatuses(Enum):
    FREE = 0
    TAKEN = 1
    UNDERFUNDED = 2

class ChannelDict(Queue):
    def __init__(self, channels_seeds):
        # Init base queue
        super(ChannelDict, self).__init__(len(channels_seeds))
        # Change queue from a 'dqueue' object to a dict full of free channels
        self.queue = {channel: ChannelStatuses.FREE for channel in channels_seeds}

    def _get(self):
        # Get a list of all free channels
        free_channels = self.get_free_channels()
        # Select a random free channel
        selected_channel = random.choice(free_channels)[0]
        # Change channel state to taken
        self.queue[selected_channel] = ChannelStatuses.TAKEN
        return selected_channel

    def _put(self, channel):
        # Change channel state to free
        self.queue[channel] = ChannelStatuses.FREE

    def _qsize(self):
        # Base queue checks if the queue is not empty by checking the length of the queue (_qsize() != 0)
        # We need to check it by checking how many channels are free
        return len(self.get_free_channels())

    def get_free_channels(self):
        # Get a list of channels with "FREE" status
        return list(filter(lambda item: item[1] == ChannelStatuses.FREE, self.queue.items()))

"channel" is another word for "address"

Used this answer as inspiration: https://stackoverflow.com/a/16506527/2126254

More context on how get/put are used,these methods are exposed:

@contextmanager
def get_channel(self, timeout=CHANNEL_QUEUE_TIMEOUT):
    """
    Get the next available channel
    :param float timeout: (Optional) How long to wait before raising an exception
    :return next avilable channel
    :rtype str

    :raises KinErrors.ChannelBusyError
    """
    try:
        channel = self.channels.get(True, timeout=timeout)
    except queue.Empty:
        raise ChannelsBusyError()

    try:
        yield channel
    finally:
        self.put_channel(channel)

def put_channel(self, timeout=CHANNEL_PUT_TIMEOUT):
    """
    Return a channel to the queue
    :param float timeout: (Optional) How long to wait before raising an exception

    :raises KinErrors.ChannelsFullError
    """
    try:
        self.channels.put(True, timeout=timeout)
    except queue.Full:
        raise ChannelsFullError()

And the user will use:

with get_channel() as channel:
    #send transaction


texts:
I have the following situation:
I have...

Models like ServerRoom and ServerCabinet
Repositories of the Model instances (in-memory collection)
PersistenceServices which are interfacing the persistence-method I chose (mssql db)

The problem I am facing is repetition.
Basically, the implementation of a PersistenceService is not really bound to a specific Model, only to it's instantiation (from a DataRow) and conversion (from Business Object to DataRow), so I thought the following would be good:

From

/// <summary>
/// Implements generic database-crud operations to prevent repetition
/// Most of the CRUD-operations are the exactly the same, and those are implemented
/// </summary>
/// <typeparam name="T"></typeparam>
public abstract class DbPersistenceService<T> : IPersistenceService<T>
    where T : class
{
    protected DataTable _dataTable;

    // Update, Delete, GetAll, Save, Delete, Contains and FindRow excluded

    /// <summary>
    /// Add an instance to the repository
    /// </summary>
    /// <param name="instance"></param>
    public void Add(T instance)
    {
        _dataTable.Rows.Add(ObjectToRow(instance));
    }

    /// <summary>
    /// Get the instance with the specified id
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public T GetById(long id)
    {
        var row = FindRow(id);
        if (row == null)
            return null;
        return RowToObject(FindRow(id));
    }

    /// <summary>
    /// Converts a datarow to the domain object
    /// </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    protected abstract T RowToObject(DataRow row);

    /// <summary>
    /// Converts a domain object to a datarow
    /// </summary>
    /// <param name="instance"></param>
    /// <returns></returns>
    protected abstract DataRow ObjectToRow(T instance);

}

So, the CRUD operations are the same for each model, only the conversion between domain and persistence layer is different (constructor of ServerCabinet needs other information from a DataRow than a ServerRoom) and this conversion is must be implemented by overriding RowToObject and ObjectToRow.
I am not satisfied with this design, as I still have to maintain one PersistenceService-class for each Model (e.g. ServerCabinetDbPersistenceService). I tried things like an interface IBusinessDataConverter, but it doesnt work, because that would be instance-methods whereas methods like GetById (above) cannot access an instance, only static, class-level methods.

How would you design it, do you have other general info about bad-practices I used?

          /* Using an ORM like EntityFramework is not an option */


texts:
I've finally gotten around to learning Lisp/functional programming. However, what I've noticed is that I'm trying to bring ideas back into JavaScript.

Example

Before

var myPlacemark,
    myLineString;

myLineString = ge.createLineString('');
myLineString.setLatitude(100);
myLineString.setLongitude(-100);
myPlacemark = ge.createPlacemark('');
myPlacemark.setGeometry(placemark);

After

var myPlacemark;

myPlacemark = (function(point, placemark){
  point.setLatitude(100);
  point.setLongitude(-100);
  placemark.setGeometry(point);
  return placemark;
})(ge.createPoint(''), ge.createPlacemark(''));

Is there any reason I shoudn't be doing it the 2nd way?


texts:
I have implemented a Javascript TypeWriter effect for my website. It types out code using the TypeWriter variable by adding each character on and setting a timeout. It then 'deletes' code using text slice and 're types.

I had big problems in setting a timeout for the individual functions because each time I did the speed would double.

I just tried to get the code working before making it more practical. At the moment my code is very linear and not very dynamic. Can anyone suggest some edits to make to make it more fluid? I'm not advanced, please go easy on me!

 /*
 typewriter.js
 Displays a typing effect on the home page.
 Tried to implement recursion instead of calling different functions but had trouble.
 **/
 var text1 = 'Hi, I\'m Ainsley I like';
 var text2 = ' love to code...';
 var id = 'typing-text1';
 var deleteUpTo = 17;
 var linebreak = 15;
 var speed = 150;
 var char = 0;
 var reType = 0;
 var textLength = text1.length;

 var typewrite = ' ';

 function typeWriter() {
    if (char < linebreak) {
       typewrite += text1[char];
       char++;
       setTimeout(typeWriter, speed);
       document.getElementById(id).innerHTML = typewrite;
    } else {
       typewrite += '<br />'
       printNewLine();
    }
 }

 function printNewLine() {
    if (char < text1.length) {
       typewrite += text1[char];
       char++;
       setTimeout(printNewLine, speed);
       document.getElementById(id).innerHTML = typewrite;
    } else {
       char = document.getElementById(id).innerHTML.length;
       deleteText();
    }
 }

 function deleteText() {
    if (char > 24) {
       typewrite = typewrite.slice(0, char);
       char--;
       document.getElementById(id).innerHTML = typewrite;
       setTimeout(deleteText, speed);
    } else {
       rePrintText();
    }
 }

 function rePrintText() {
    if (reType < text2.length) {
       typewrite += text2[reType];
       reType++;
       document.getElementById(id).innerHTML = typewrite;
       setTimeout(rePrintText, speed);
    }
 }


texts:
You're given an array containing integer values. You need to print the
  fraction of count of positive numbers, negative numbers and zeroes to
  the total numbers. Print the value of the fractions correct to 3
  decimal places.

  Input Format

  First line contains \$N\$, which is the size of the array.  Next line
  contains \$N\$ integers \$A_1, A_2, A_3, ⋯, A_N\$, separated by spaces.

  Constraints

  \$1 \le N \le 100\$
  \$−100 \le A_{i} \le 100\$

Solution

from __future__ import division

N = int(raw_input())
ary = map(int, raw_input().split())

count_negatives = len(filter(lambda x: x < 0, ary))
count_positives = len(filter(lambda x: x >0, ary))
count_zeros = len(filter(lambda x: x == 0, ary))

print count_positives / N
print count_negatives / N
print count_zeros / N

It seems that this problem has a very straightforward solution but I am more interested if there is a better functional approach.


texts: Python web-scraper to download table of transistor counts from Wikipedia

texts:
I have been looking for answers for how to easily scrape data from Wikipedia into a CSV file with Beautiful Soup. This is the code so far. Is there an easier way to do it?

import urllib.request
from bs4 import BeautifulSoup
import csv

#the websites
urls = ['https://en.wikipedia.org/wiki/Transistor_count']
data =[]

#getting the websites and the data
for url in urls:
##    my_url = requests.get(url)
    my_url = urllib.request.urlopen(url)

    html = my_url.read()
    soup = BeautifulSoup(html,'html.parser')

    My_table = soup.find('table',{'class':'wikitable sortable'})
    My_second_table = My_table.find_next_sibling('table')

    with open('data.csv', 'w',encoding='UTF-8', newline='') as f:
        fields = ['Title', 'Year']
        writer = csv.writer(f, delimiter=',')
        writer.writerow(fields)

    with open('data.csv', "a", encoding='UTF-8') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for tr in My_table.find_all('tr')[2:]: # [2:] is to skip empty and header
            tds = tr.find_all('td')
            try:
                title = tds[0].text.replace('\n','')
            except:
                title = ""
            try:
                year = tds[2].text.replace('\n','')
            except:
                year = ""

            writer.writerow([title, year])

    with open('data.csv', "a", encoding='UTF-8') as csv_file:
        writer = csv.writer(csv_file, delimiter=',')
        for tr in My_second_table.find_all('tr')[2:]: # [2:] is to skip empty and header
            tds = tr.find_all('td')
            row = "{}, {}".format(tds[0].text.replace('\n',''), tds[2].text.replace('\n',''))
            writer.writerow(row.split(','))


texts:
Is this implementation correct? Do you find any threading problem? Also, what parts of the code can be changed to be more C++11-ish?

#include <iostream>
#include <vector>
#include <thread>
#include <random>
#include <condition_variable>

namespace {
    int sleep_for_random_time() {
        std::random_device rd;
        std::mt19937 mt(rd());
        std::uniform_real_distribution<double> dist(1000, 4000);

        return dist(mt);
    }
}

class DiningPhilosopher {
public:
    DiningPhilosopher(int numOfPhilosophers_ = 5, int numOfForks_ = 5, int numOfEating_ = 3) : numOfPhilosophers(numOfPhilosophers_), numOfForks(numOfForks_), numOfEating(numOfEating_) {
        forks.push_back(new Fork);
        forks.push_back(new Fork);
        forks.push_back(new Fork);
        forks.push_back(new Fork);
        forks.push_back(new Fork);

        numAllowed = numOfForks - 1;
    }

    ~DiningPhilosopher() {
        for(const auto& fork : forks) {
            delete fork;
        }
    }

    DiningPhilosopher(const DiningPhilosopher&) = delete;
    DiningPhilosopher& operator = (const DiningPhilosopher&) = delete;

    void StartDining() {
        for(int i = 0; i < numOfPhilosophers; ++i) {
            threads.push_back(std::thread(&DiningPhilosopher::Philosopher, this, i));
        }

        std::for_each(threads.begin(),threads.end(), std::mem_fn(&std::thread::join));
    }
private:
    void WaitForPermission() {
        std::lock_guard<std::mutex> lock(permission);
        cv.wait(permission, [this] { return numAllowed > 0; });
        --numAllowed;
    }

    void GrantPermission() {
        std::lock_guard<std::mutex> lock(permission);
        ++numAllowed;

        if(numAllowed == 1) {
            cv.notify_all();
        }
    }

    void Think(int id) {
        std::chrono::milliseconds duration(sleep_for_random_time());
        std::this_thread::sleep_for(duration);
    }

    void Eat(int id) {
        this->WaitForPermission();
        forks[id]->mux.lock();
        forks[(id + 1) % numOfForks]->mux.lock();

        std::cout << "Philosopher "<< id << " is eating" << std::endl;
        this->Think(id);
        std::cout << "Philosopher "<< id << " has finished eating" << std::endl;

        forks[id]->mux.unlock();
        forks[(id + 1) % numOfForks]->mux.unlock();

        this->GrantPermission();
    }

    void Philosopher(int id) {
        for(int i = 0; i < numOfEating; ++i) {
            this->Think(id);
            this->Eat(id);
        }

        std::cout << "Philosopher " << id << " DONE" << std::endl;
    }

    struct Fork {
        std::mutex mux;
    };

    int numOfEating;
    int numOfPhilosophers;
    int numAllowed;
    int numOfForks;
    std::vector<std::thread> threads;
    std::vector<Fork*> forks;
    std::mutex permission;
    std::condition_variable_any cv;
};

int main()
{
    DiningPhilosopher dp;
    dp.StartDining();

    return 0;
}


texts: Simple multithreaded chat server in Rust

texts:
I'm trying to develop a simple Rust chat server. I'm not a Rust expert and come from Java and Kotlin.

This same server in Kotlin is:

import java.io.*
import java.net.*
import kotlin.concurrent.thread
import java.util.concurrent.ConcurrentHashMap

fun main(args: Array<String>) {
    val serv = ServerSocket(Integer.parseInt(args[0]))
    //val users = ConcurrentHashMap<String, PrintWriter>()
    val users = Collections.synchronizedMap(HashMap<String, PrintWriter>())

    while (true) {
        val s = serv.accept()
        thread {
            var sin = s.getInputStream().bufferedReader()
            val sout = PrintWriter(s.getOutputStream(), true)

            // read nick
            val nick = sin.readLine()
            users.put(nick, sout)

            sin.forEachLine {
                for (peer in users.values) {
                    if (peer == sout) continue
                    peer.println(it)
                }
            }
            users.remove(nick)
        }
    }
}

After many attempts I've come up with a working Rust implementation :

use std::env;
use std::io;
use std::io::Write;
use std::io::{LineWriter, BufReader, BufRead};
use std::net::{TcpListener, TcpStream};
use std::sync::{Arc, Mutex};
use std::collections::HashMap;
use std::thread;
use std::ops::DerefMut;

fn main() -> io::Result<()> {
    let args: Vec<String> = env::args().collect();
    let server_socket = TcpListener::bind(&*format!("localhost:{}", args[1]))?;
    let users: Arc<Mutex<HashMap<String, LineWriter<TcpStream>>>> = Arc::new(Mutex::new(HashMap::new()));

    for socket in server_socket.incoming() {
        let users = users.clone();
        thread::spawn(move || -> io::Result<()> {
            let socket = socket?;
            let socket_copy = socket.try_clone()?;
            let mut inp = BufReader::new(socket);
            let out = LineWriter::new(socket_copy);

            // read nick
            let mut nick = String::new();
            inp.read_line(&mut nick)?;
            nick.pop(); // discard '\n'
            let nick_copy = nick.clone();
            {
                let mut users = users.lock().unwrap();
                users.insert(nick, out);
            }

            for line in inp.lines() {
                {
                    let line = line?;
                    let mut users = users.lock().unwrap();
                    for (nick, peer) in users.deref_mut() {
                        if *nick == nick_copy { continue; }
                        writeln!(peer, "{}", line)?;
                    }
                }
            }

            // remove nick
            {
                let mut users = users.lock().unwrap();
                users.remove(&nick_copy);
            }
            Ok(())
        });
    }
    Ok(())
}

Too verbose for my taste.

I'm particularly dissatisfied with those clone ops. When to move? When to borrow?

I'd prefer to use for peer in users.values_mut() instead of for (nick, peer) in users.deref_mut() but then I've problems when comparing LineWriter references to discard sender.

I'd also prefer to use RwLock instead of Mutex.

Any pointers to simplify/enhance code will be greatly appreciated.


texts:
I was trying to give SUMIFS3D User-Defined-Function a nice review and ended up getting pretty side-tracked trying to figure out how to pass some parameters by array and whether or not I could send a 3D-range through the function (seems not).

It's a good one for review, I'm sure there are improvements - I wrote it in about 3 hours.

Function

SUMIF3D(ByVal sum_range As Range, ByVal list_Sheets As String, ByVal criteriaRange As Range, ByVal criteria As Variant, Optional ByVal isNumeric As Boolean = False)

Returns: Long

Input

Something like

=SUMIF3D(D1:D5,"sheet1,sheet2",H1:H5,I1)

To set it up just open a workbook and input:

Sheet1!D1:D5 = 1-5
Sheet2!D1:D5 = 10-50
Sheet1!H1:H5 = 1,5,10,15,20

And whatever arguments you want in Sheet1!I1=I5 e.g.

1   2   5   15  15
>0   >10 >=10    <10 20
>10

Or try your luck with matching strings.

It works on everything I've tried. It's a bad mama-jama

Option Explicit

Public Function SUMIF3D(ByVal sum_range As Range, ByVal list_Sheets As String, ByVal criteriaRange As Range, ByVal criteria As Variant, Optional ByVal isNumeric As Boolean = False) As Long
    Const OPERATORS As String = ">,<,<>,="
    Dim isPossible As Boolean
    Dim toSum() As Boolean
    Dim i As Long
    Dim j As Long

    Dim sumRangeCells() As Long
    ReDim sumRangeCells(1 To sum_range.Count, 1 To 2)
    Dim cell As Range
    i = 1
    For Each cell In sum_range
        sumRangeCells(i, 1) = cell.Row
        sumRangeCells(i, 2) = cell.Column
        i = i + 1
    Next

    Dim numberOfCells As Long
    Dim sheetsArray As Variant
    sheetsArray = Split(list_Sheets, ",")
    Dim sumRangeArray As Variant
    numberOfCells = (UBound(sheetsArray) + 1) * sum_range.Count
    ReDim sumRangeArray(1 To numberOfCells)

    Dim k As Long
    k = 1
    For i = LBound(sheetsArray) To UBound(sheetsArray)
        For j = 1 To sum_range.Count
            sumRangeArray(k) = Sheets(sheetsArray(i)).Cells(sumRangeCells(j, 1), sumRangeCells(j, 2))
            k = k + 1
        Next
    Next

    Dim critRangeArray As Variant
    critRangeArray = criteriaRange.Value2
    Dim criteriaArray As Variant
    criteriaArray = criteria.Value2

    ReDim toSum(1 To UBound(critRangeArray, 1))
    If Not IsArray(criteriaArray) Then
        If IsEmpty(criteriaArray) Then
            isPossible = False
        Else: isPossible = True
        End If
    Else
        If Not UBound(criteriaArray, 1) = UBound(critRangeArray, 1) Then
            isPossible = False
        Else: isPossible = True
        End If
    End If

    If Not isPossible Then Exit Function

    Select Case isNumeric
        Case 1
            If IsArray(criteriaArray) Then
                For i = 1 To UBound(critRangeArray)
                    If InStr(1, OPERATORS, Left$(criteriaArray(i, 1), 1)) > 0 Then
                        toSum(i) = Application.Evaluate(critRangeArray(i, 1) & criteriaArray(i, 1))
                    Else: toSum(i) = critRangeArray(i, 1) = criteriaArray(i, 1)
                    End If
                Next
            Else
                For i = 1 To UBound(critRangeArray)
                        If InStr(1, OPERATORS, Left$(criteriaArray, 1)) > 0 Then
                            toSum(i) = Application.Evaluate(critRangeArray & criteriaArray)
                        Else: toSum(i) = critRangeArray(i, 1) = criteriaArray
                        End If
                Next
            End If
        Case 0
            If IsArray(criteriaArray) Then
                For i = 1 To UBound(critRangeArray)
                    toSum(i) = critRangeArray(i, 1) = criteriaArray(i, 1)
                Next
            Else
                For i = 1 To UBound(critRangeArray)
                    toSum(i) = critRangeArray(i, 1) = criteriaArray
                Next
            End If
    End Select

    For j = LBound(sheetsArray) To UBound(sheetsArray)
        For i = 1 To UBound(toSum)
            If toSum(i) Then SUMIF3D = SUMIF3D + sumRangeArray(i + j * UBound(toSum))
        Next
    Next
End Function


texts: Numeric selfmade CAPTCHA in Windows application

texts:
Nowadays many sites introduce CAPTCHAs (Completely Automated Public Turing test to tell Computers and Humans Apart) for securing their sites. I wish to introduce the technique  in windows forms, as expression evaluation CAPTCHA.

Approach:

Two randomly generated integers are loaded into two different labels
Place a random operator (+,-,*) in between them
Users are requested to provide the calculated result in a text box
Compare the user input and expression evaluation result for confirmation.

Private Sub Generate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Generate.Click
    ' This function will generate the Numeric Captcha
    ' with two random number and one operator
    Dim Rand As New System.Random
    op = Rand.Next(0, 3)
    lblfirst.Text = Rand.Next(0, 10) 'first random number
    lblsecond.Text = Rand.Next(0, 10) 'second random number
    If op = 0 Then ' Operator selection
        lblop.Text = "+"
    ElseIf op = 1 Then
        lblop.Text = "-"
    ElseIf op = 2 Then
        lblop.Text = "*"
    End If
End Sub

Private Sub check_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles check.Click
    'Validating the user input with Random CAPTCHA
    Dim output As Integer
    If op = 0 Then ' choosing operator based on op
        output = CInt(lblfirst.Text) + CInt(lblsecond.Text)
    ElseIf op = 1 Then
        output = CInt(lblfirst.Text) - CInt(lblsecond.Text)
    ElseIf op = 2 Then
        output = CInt(lblfirst.Text) * CInt(lblsecond.Text)
    End If
    If output = CInt(txtResult.Text) Then
        MsgBox("Successfully varified")
    Else
        MsgBox("Varification Faild")
    End If
End Sub

Are there any suggestions on improving the technique?


texts:
I've implemented a simple thread-safe circular queue. I'm looking for code review, optimizations and best practices.

public class CircularQueue {
    int[] queue;
    int front;
    int rear;
    int currentSize;
    int size;

    public CircularQueue(int size) {
        this.queue = new int[size];
        this.front = 0;
        this.rear = 0;
        this.size = size;
        this.currentSize = 0;
    }

    public synchronized boolean add(int x) {

        if (currentSize == size) {
            throw new IllegalStateException("The queue is full: front size: " + rear);
        }

        queue[rear++] = x;
        rear = (rear + 1) % size;
        currentSize++;

        return true;
    }

    public synchronized int peek() {
        if (front == rear) {
            throw new IllegalStateException("The queue is empty");
        }
        return queue[front];
    }

    public synchronized int poll() {
        if (front > rear) {
            throw new IllegalStateException("The queue is empty");
        }
        currentSize--;
        return queue[front++];
    }
}


texts: Find the majority element, which appears more than half the time

texts:
The task:

  Given a list of elements, find the majority element, which appears
  more than half the time (> floor(len(lst) / 2.0)).

  You can assume that such element exists.

  For example, given [1, 2, 1, 1, 3, 4, 0], return 1.

My solution:

const lst = [1, 2, 1, 1, 3, 4, 0];
const findMajorityElem = lst => lst.reduce((acc, x) => {
  acc[x] = acc[x] ? acc[x] + 1 : 1;
// If I can assume that such an element exists, then it's sufficient to check which element occurs the most.
  if (!acc.major || acc.major[1] < acc[x]) { acc.major = [x, acc[x]]; }
  return acc;
}, {major: null}).major[0];

console.log(findMajorityElem(lst));


texts:
You are given an array of characters arr that consists of sequences of characters separated by space characters. Each space-delimited sequence of characters defines a word.

Implement a function reverseWords that reverses the order of the words in the array in the most efficient manner.

Explain your solution and analyze its time and space complexities.

Example:

input:  arr = [ 'p', 'e', 'r', 'f', 'e', 'c', 't', '  ',
                'm', 'a', 'k', 'e', 's', '  ',
                'p', 'r', 'a', 'c', 't', 'i', 'c', 'e' ]

output: [ 'p', 'r', 'a', 'c', 't', 'i', 'c', 'e', '  ',
          'm', 'a', 'k', 'e', 's', '  ',
          'p', 'e', 'r', 'f', 'e', 'c', 't' ]

Constraints:

[time limit] 5000ms

[input] array.character arr

0 ≤ arr.length ≤ 100
[output] array.character

My approach:

import java.io.*;

import java.util.*;

class Solution {

  static void reverseAword(char [] arr, int start, int end)
  {
    int len = end - start + 1;
    for( int i = start, j = end; i < len/2; i++,j-- )
    {
        char temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
  }

  static char[] reverseWords(char[] arr) {
    // your code goes here
    int len = arr.length;

    //Reverse the complete sentence
    reverseAword(arr,0,len - 1);

    int start = 0;
    for( int i = 0; i < len; i++)
    {
      //If there is a space, reverse the word from start till index - 1( before ' ')
      if( arr[i] == ' ' )
      {
        if( start == 0 )
          {
            reverseAword(arr,start,i - 1);
            start = 0;
          }
      }
        else if( i == len - 1)
        {
          if( start != 0)
              reverseAword(arr, start,i);
        }
        else
        {
          if( start == 0)
              start = i;
        }

    }

    return arr;
  }

  public static void main(String[] args) {

  char[] c1 = {' ', ' '};
    c1 = reverseWords(c1);

    System.out.println(Arrays.toString(c1));
  }

}

I have the following questions with respect to the above code:

1) How can I further improve the time and space complexity?

2) Can this problem be solved using a smarter way?

3) Are there too many redundant variables that we are better off with?

Reference


texts:
I have a function add that adds two lists of integers:

add [1, 2] [4, 5, 8] == [4, 7, 0]
add [9, 8, 9] [1, 3] == [1, 0, 0, 2]

I know that Integer from Prelude is already arbitrary large, I'm reinventing the wheel for exercise.

Here's the code:

import Data.Int(Int8)

-- Adds two integer lists.
-- Examples:
-- add [1, 2] [4, 5, 8] == [4, 7, 0]
-- add [9, 8, 9] [1, 3] == [1, 0, 0, 2]
add :: [Int8] -> [Int8] -> [Int8]
add xs ys = toIntList $ foldr addCarry [] sumWithCarry
  where (paddedXs, paddedYs) = padToSameLength xs ys
        sumWithCarry = foldr getSumAndCarry [] $ zip paddedXs paddedYs
        -- Turn the list of sums with carry into a list of sums
        toIntList [] = []
        -- If the first pair has a carry of one, add that to the list.
        -- This ensures that the resulting list can grow one digit
        toIntList xs@((_,carry):_) | carry >0  = carry : map fst xs
                                   | otherwise = map fst xs

-- Pads two lists of ints to the same length
-- by prepending zeros to the shorter one
padToSameLength xs ys =
  if lenDiff < 0
  then (padWithLeadingZeros xs (lenDiff * (-1)), ys)
  else (xs, padWithLeadingZeros ys lenDiff)
  where lenDiff = length xs - length ys
        padWithLeadingZeros list nr = take nr (repeat 0) ++ list

-- Given two same-sized list of ints, returns them
-- zipped as pairs of their sum and carry.
-- Example: getSumAndCarry [1, 2] [4, 8] == [(5, 0), (0, 1)]
getSumAndCarry :: (Int8, Int8) -> [(Int8, Int8)] -> [(Int8, Int8)]
getSumAndCarry (x, y) pairs = sumWithCarry x y : pairs
  where sumWithCarry x y | x + y >= 10 = ((x + y) - 10, 1)
                         | otherwise   = (x + y, 0)

-- Once we have added two lists like [7, 9, 8] and [2, 1, 4] to a list
-- of sums and carries, [(9, 0), (0, 1), (2, 1)],
-- we want to add the carry: [(9, 1), (1, 0), (2, 0)]
addCarry :: (Int8, Int8) -> [(Int8, Int8)] -> [(Int8, Int8)]
-- The rightmost pair. We don't do much since only the pair's left
-- neighbor will use its carry
addCarry pair [] = [pair]
addCarry (sum, carry) pairs@((_, prevCarry):_) =
  sumWithCarry sum carry prevCarry : pairs
  where sumWithCarry sum carry prevCarry | sum + carry + prevCarry >= 10 = ((sum + carry + prevCarry) - 10, 1)
                                         | otherwise = (sum + carry + prevCarry, 0)

It seems to work correctly but I'd really like to improve the code:

Generally, make it shorter wherever possible
Specifically, combine the functions getSumAndCarry and addCarry if possible since both  traverse the list, and I'd prefer add to be O(n).

Thanks a lot for your feedback!

For anyone interested, here's a version incorporating Zeta's feedback. It's tested with QuickCheck and does not suffer from the carry bug of the original code.


texts: Space and time efficient Algorithm for generating prime numbers

texts:
I have developed an algorithm for generating prime numbers (which turns out to be an optimized version of the Sieve of Eratosthenes) by reducing the space by a factor of 64.

/*
 * Explanation of algorithm

 * 1. Avoid storing all the even numbers as they cnt b prime numbers - so divide the size by 2

 * 2. Represent each bit of int as a odd number 1,3,5,7 and so on. Each int has 32 bits and will store prime numbers between 0 to 63.

 * 3. Again divide the counter by 32, so now the final size of the array would be 32*2=64 (because we are also avoiding even numbers)

 * 4. 1st Loop (i)-  Loop from i=3 upto squareroot of the given range and increment by 2(because we don't care about the even numbers)

 * 5. 2nd Loop (j)- Loop from square of the current number(i) till its less than the counter and increment j by 2*i (Again avoid the even number multiples)

 * 6. Mark all the multiples of the j to 1/true.(In our code we set the corresponding bit to 1)
 for e:g for setting 9 to be non-prime we simply divide it by 2 and set that bit to 1.

 * 7. While printing we check if the bit is set to 0. if yes, then print the number by multiplying (32*[currentIndexInArray]+bit-position)*2 +1.

 * Note: it will correctly print all numbers from 3 to given range(should be multiples of 64)

 *  Even if its not multiple of 64, it still works but wont consider the last 32 numbers in the range.

 *  Also, it prints 1 in the output and not 2, which probably can be handle by extra conditions.
 *  its more focused on generating primes above number 3.
 */

public class PrimeNumberOptimized {
    static int range = 256;

    public static void main(String[] args) {

        long startTime = System.currentTimeMillis();

        int[] NonPrimeNumbers = new int[(range>>6)+1];

        int k=0;
        for(int i=3;i*i <= range;i+=2){
            //Increment k, everytime i goes beyond int size
            if((i>>1)%32==0)
                k++;

            //Check if it is a prime number, if yes, mark all the bits which are multiples of this number.
            if((NonPrimeNumbers[k]&(1<<(i>>1)))==0)
            {
                for(int j=i*i;j <= range;j+=2*i){// increment j by 2*i, for :eg if i=5, then mark directly 15 skipping 10 as every alternate multiple will be an even number
                    //set the bit to 1. if i=3 and j=9, then we go to the 1st index in array and set the 9/2th bit in array value.
                    NonPrimeNumbers[j>>6]|=1<<(j>>1);
                }
            }
        }

        int primeCnt = 0;
        range >>= 6; // Divide the range by 64 as we need to iterate through the array which is reduced by factor of 64.

        for(int arrayIndex=0;arrayIndex < range;arrayIndex++){
            for(int bitPosition=0;bitPosition<32;bitPosition++) // Go through each bit of the array value
            {
                if((NonPrimeNumbers[arrayIndex]&(1<<bitPosition))==0) // check if the current bit is set to 0, if yes, then it represent prime number.
                {
                    System.out.println(((32*arrayIndex+bitPosition)*2)+1); // multiply by 32 to get the correct index in array, add the bitPosition to it and multiply by 2(again we are avoiding even numbers)
                    primeCnt++;
                }
            }
        }

        System.out.println("-Total no of Primes generated->"+(primeCnt));
        System.out.println("Total time ="+(System.currentTimeMillis()-startTime));
    }

}

Please have a look into this and let me know if it can be optimized any further. Compared with most of the algorithms found online and so far it's quite fast compare to other algorithms.


texts:
Is there a better way to code this specific algorithm using successively division through 2 which converts decimal numbers into binary numbers without calling a built-in function?

print "Please enter a decimal number."
prompt = '>> '
dec_number = input(prompt)
dec_new = dec_number
binstr = ''

'''dec2bin'''
while dec_new != 0:
  binstr += str(dec_new % 2)
  dec_new = dec_new // 2

print binstr[::-1]


texts:
I've written this function to give the neighbours of a vertex in a graph:

import Data.Matrix (Matrix, getRow, ncols)
import Data.Vector ((!))

type AdjacencyMatrix = Matrix Bool

-- Input: the graph's adjacency matrix and a vertex.
-- Output: the list of neighbours of that vertex.
neighbours :: AdjacencyMatrix -> Int -> [Int]
neighbours mat n = filter (\m -> row ! m) [0..(ncols mat)-1]
        where row = getRow n mat

Someone suggested here to replace my partial calls to getRow and (!) with calls to zip and/or fold. I can't really see how this would be done. Does anyone have suggestions of how to improve this?


texts: Drawing a castle and towers with acm.graphics

texts:
The following code is my solution of exercise 10 of chapter 5 of The Art and Science of Java. So here, using acm program and graphics, I need to draw a castle with two side towers and other three consecutive towers some distance away from the main building(castle and its two side towers). Is there any way to do this faster than that?

(The drawing is perfect as I spent plenty of time searching for the perfect location for every object on the canvas.)

import acm.program.*;
import acm.graphics.*;

public class Hw1 extends GraphicsProgram {

final double tower_width = 150;
final double tower_height = 600;
final double main_house_width = 400;
final double main_house_height = 500;
final double s_tower_width = 75;
final double s_tower_height = 300;
final double door_width = 50;
final double door_height = 100;
final double window_width = 100;
final double window_height = 100;

GRect create_tower(double x, double y) {
    GRect rect = new GRect(tower_width, tower_height);
    rect.move(x, y);
    return rect;
}

GRect create_main_home(double x, double y) {
    GRect rect = new GRect(main_house_width, main_house_height);
    rect.move(x, y);
    return rect;
}

GRect create_s_tower(double x, double y) {
    GRect rect = new GRect(s_tower_width, s_tower_height);
    rect.move(x, y);
    return rect;
}

GRect create_door(double x, double y) {
    GRect rect = new GRect(door_width, door_height);
    rect.move(x, y);
    return rect;
}

GOval create_window(double x, double y) {
    GOval circle = new GOval(window_width, window_height);
    circle.move(x, y);
    return circle;
}

GPolygon create_arch(double x, double y) {
    GPolygon arch = new GPolygon();
    arch.addVertex(x, y);
    arch.addVertex(x+150, y);
    arch.addVertex(x+75, y-150);
    return arch;
}

GPolygon create_s_arch(double x, double y) {
    GPolygon arch = new GPolygon();
    arch.addVertex(x, y);
    arch.addVertex(x+75, y);
    arch.addVertex(x+37.5, y-100);
    return arch;
}

GPolygon create_arch_door(double x, double y) {
    GPolygon arch = new GPolygon();
    arch.addVertex(x, y);
    arch.addVertex(x+50, y);
    arch.addVertex(x+25, y-50);
    return arch;
}

GPolygon create_house_arch(double x, double y) {
    GPolygon arch = new GPolygon();
    arch.addVertex(x, y);
    arch.addVertex(x+400, y);
    arch.addVertex(x+200, y-200);
    return arch;
}

public void run() {

    add(create_tower(700, 250));
    add(create_tower(150, 250));
    add(create_main_home(300, 350));
    add(create_s_tower(1000, 550));
    add(create_s_tower(1200, 550));
    add(create_s_tower(1400, 550));
    add(create_door(475, 750));
    add(create_window(350, 450));
    add(create_window(550, 450));
    add(create_arch(150, 250));
    add(create_arch(700, 250));
    add(create_s_arch(1000, 550));
    add(create_s_arch(1200, 550));
    add(create_s_arch(1400, 550));
    add(create_arch_door(475, 750));
    add(create_house_arch(300, 350));
}

}


texts: Avoiding Duplicates in a Ruby on Rails Factory Girl Factory with Fake

texts:
I have a Factory Girl factory that needs to generate a unique name using Faker. Unfortunately, Factory Girl generates duplicates relatively frequently, which causes intermittent test errors. I previously added a random integer after the Faker name, but I am now checking the database to make sure that a potential name from Faker doesn't already exist.

FactoryGirl.define do
  factory :company do
    name do
      name = Faker::Company.name
      name = Faker::Company.name while Company.exists?(name: name)
      name
    end
  end
end

The above code works but seems inelegant. I'm assigning name in the first row of the block so that only one DB lookup (instead of two) will be necessary in the most common case where a Fake name is unique.

I end the block with name as otherwise the while statement returns nil when the loop ends.


texts: Product of 2 numbers equals sum of numbers between them

texts:
Problem:

  Find all the pairs (a, b) whose product is equal to the sum of all numbers in the sequence [1..n] excluding both a and b.

I have made code for one program and need refactoring for code to get execution in less time. I am currently getting 13 sec for 500 number range.

def get_correct_array(n)
 beginning_time = Time.now
 puts " Begin with #{Time.now}"
 mul = 0
 arr = []
 last_arr = []

(1..n).each do |x|

 (x+1..n).each do |y|

    mul = x * y
    result = (1..n).reject {|n| n == x || n == y}.inject(&:+)
    if result == mul
        arr.concat([x,y])
        @x = x
        @y = y
    end
 end
end

last_arr << arr

if arr != []
 last_arr << (@x,@y = @y,@x)
end
if arr == []
 []
end

end_time = Time.now
puts " Ended with #{Time.now}"
puts "Time Elapsed -> #{(end_time - beginning_time)}"
p last_arr
end


texts:
I have modelled the task of super market pricing as per the below task.
http://codekata.com/kata/kata01-supermarket-pricing/

Please review my code and suggest any improvements.

class Product
{
    String Name; //Name of the product
    int unit_price;
    UnitType unit_type;
    boolean groupOffer; //Is this product eligible for a group offer?
    int buy,get; //If so..what are the values of buy and get..

    public Product(String name, int unit_price, UnitType unit_type, boolean groupOffer) {
        // TODO Auto-generated method stub
        Name = name;
        this.unit_price = unit_price;
        this.unit_type = unit_type;
        this.groupOffer = groupOffer;
    }

    public Product(String name, int unit_price, UnitType unit_type,boolean groupOffer, int buy, int get) {
        this(name,unit_price,unit_type,groupOffer);
        this.buy = buy;
        this.get = get;
    }

}

enum UnitType
{
    NUMERIC, //to represent non-breakable units.
    POUND,
    KG,
    GRAM;
}

public class SuperMarket {
    public static void main(String args[])
    {
        //Configuring the price of products.
        Product pen = new Product("Pen",5,UnitType.NUMERIC,Boolean.FALSE);
        Product potato = new Product("Potato",2,UnitType.POUND,Boolean.FALSE);
        Product soda = new Product("Soda",1,UnitType.NUMERIC,Boolean.TRUE,4,1);
        //Calculating the prices
        System.out.println(getPrice(pen,4));
        System.out.println(getPrice(pen,4.1f)); //Pen cannot be a fraction
        System.out.println(getPrice(potato,3));
        System.out.println(getPrice(potato,3.1f));//Potato can be a fraction
        System.out.println(getPrice(soda,10)); // Eligible for group offer
    }

    //Get the price of products
    public static float getPrice(Product product,float quantity)
    {
        if(product.unit_type == UnitType.NUMERIC)
        {
           if(quantity != Math.round(quantity))
               return -1000;
        }
        float price = product.unit_price * quantity;
        //To decrease the price of free items.
        if(product.groupOffer)
        {
             price = (quantity/(product.buy+product.get)) * product.buy * product.unit_price;
        }
        return price;
    }
}


texts:
I've been writing Python for years, but I've only just started using it in bigger programs than just simple server scripts. This means I now also want to use a more advanced logging system. To make things simple I created the following logger:

import logging
from inspect import getframeinfo, stack

logger = logging.getLogger()
formatter = logging.Formatter('%(asctime)s %(name)-7s %(levelname)-8s %(message)s')
file_handler = logging.FileHandler('mm.log')
file_handler.setFormatter(formatter)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.addHandler(stream_handler)
logger.setLevel(logging.INFO)

def l(*args, **kwargs):
    level = kwargs.get('level', 'info').lower()
    assert level in ('debug', 'info', 'warning', 'error', 'critical')
    caller = getframeinfo(stack()[1][0])
    file_line = "%s:%d - " % (caller.filename, caller.lineno)
    logger_input = file_line + ' '.join([str(a) for a in args])
    getattr(logger, level)(logger_input)

This logs to stdout and to a logfile and also logs the filename and the line number from which the log is made. It can be used as follows:

from tools import l

l('Log message')  # logs in INFO by default
l('Log message one', 'log message two')  # log multiple messages
l('Log message', level='critical')  # log in critical level

which creates something like this:

2017-10-10 20:47:16,170 root    INFO     test.py:5 - Log message
2017-10-10 20:47:16,171 root    INFO     test.py:14 - Log message one log message two
2017-10-10 20:47:16,171 root    CRITICAL test.py:116 - Log message

I import this in all the other files of my program and it seems to work quite ok. It enables to me to run the program from the command line and see the output, as well as running it as a daemon and seeing the output in the log files later. Furthermore, it's easy for debugging because it also logs the filename and line number, and I can easily change the default logging level with one line. Lastly, the use of a single l shortens the way of logging things. All in all, I'm quite happy with it.

I'm unsure if this is for some reason stupid though. Maybe there are situations which I can't oversee right now which would make this mess up things. Maybe the default conversion to strings is not smart for some reason?

Could anybody enlighten me as to what could be wrong with this or how it could be made better/more robust? All tips are welcome!


texts:
Just used DI containers in MVC projects, via constructor injection, and I'd need to now inject a service into a console app. I'm using Autofac so I followed what I found here.

The code would be something like this:

The service the console app depends on:

public interface IBatchService
{
    void WriteInformation(string input);
}
public class BatchService : IBatchService
{
    public void WriteInformation(string input)
    {
        Console.WriteLine(input);
        Console.ReadKey();
    }
}

The console app main method

public class Program
{
    private static IContainer Container { get; set; }
    static void Main(string[] args)
    {
        var builder = new ContainerBuilder();

        builder.RegisterType<BatchService.BatchService>().As<IBatchService>();
        Container = builder.Build();

        using (var scope = Container.BeginLifetimeScope())
        {
            var batchService = scope.Resolve<IBatchService>();

            batchService.WriteInformation("Injected!");
        }
    }

It's using the Service Locator if I'm not wrong (I'm trying to get my head around all of this), which I would be likely to avoid in case I could as it's thoroughly discussed in the web. But can I actually avoid it in a console app? Can any see any big flaw with this implementation?

The main method is almost as simple as this one, only one call to one service (although the service doesn't write a console). And that's the only code in the project in fact.


texts:
So I have recently tried to load an image and save it, but remove all of a certain color. I'm running the program and it is running really slow, is there a more efficient way to edit an image? My code is pasted below, or at least all that is relevant.

for x in range(50):
    im = pygame.image.load("horse%s.bmp") % (x)
    im.set_colorkey(im.get_at((0, 0)))
    surf = pygame.Surface((im.get_size(), pygame.SRCALPHA)
    surf.blit(im, (0, 0))
    pygame.image.save(surf, "horse%s.png") % (x)


texts:
I want a 4-bit resource to share status between processes and to retain status after shutdown and reboot. If the system were a microprocessor, I'd use a 4-bit register in non-volatile memory.

Process interaction with the shared resource is typically minutes to hours between interactions, however processes may attempt to access it at exactly the same moment. So there is a simple file locking mechanism. A process that finds the resource locked, will back off for a short while and then try again.

There are only 4 or 5 processes that deal with the resource. The short while (timeout) is 15 milliseconds plus random between 0 to 9 milliseconds. This is to prevent race conditions, processes locking each other, etc.

Processes will be daemonised, and they will use the functions below to access the pickle.

To simulate different processes, I'm using a few command prompt windows, started at about the same time. See the code.

All of Python's multitasking libraries, threading, Queue and DMTCP seem way too elaborate for my tiny 4-bit register. Hence this solution. Please comment.

import cPickle as pickle
import math
from time import sleep
import sys

'''
    There are 4 switches, A to D. Each can be On or Off.
    Switches must retain state on shutdown and/or reboot.

    Switch state is stored in a pickle in switch_state.p
    Switch state is a 4-bit number, ie max 15 decimal (all On)
    Switch A is bit 0, switch B is bit 1, and so on.

    Several processes may interact with switches.
    So, also in the pickle is a boolean 'locked'.
    All processes, when switching, must load the pickle, and first check if it's locked.
    If it is, it should wait until it becomes unlocked.
    If it's not, it should lock it, do its thing, and then unlock it.
'''

def new_state(statefile='switch_state.p'):
    try:
        switch = pickle.load(open(statefile, 'rb'))
    except:
        switch = {'state':0, 'locked': False}
        pickle.dump(switch, open(statefile, 'wb'))

# functions to turn state on and off
#
# using bitwise operations, so no need to check current state
# i.e. if you turn on a switch that's already on, nothing will change

def turn_on(cur_state, switchID):
    ON_bits = pow(2, ord(switchID) - ord('A'))
    return cur_state | ON_bits

def turn_off(cur_state, switchID):
    OFF_bits = ~pow(2, ord(switchID) - ord('A'))
    return cur_state & OFF_bits

def update_state(switchID, state, statefile='switch_state.p'):
    switch = pickle.load(open(statefile, 'rb'))

    while switch['locked']:
        # some other process is switching, wait till it finishes
        sleep(0.015 + random.random()/100)
        switch = pickle.load(open(statefile, 'rb'))

    if not switch['locked']:
        new_switch = {'state': switch['state'], 'locked': True}
        pickle.dump(new_switch, open(statefile, 'wb'))
        if state == 'On':
            newstate = turn_on(switch['state'], switchID)
        elif state == 'Off':
            newstate = turn_off(switch['state'], switchID)
        else:
            #shouldn't ever get here
            print 'unknown state'
            exit()

        new_switch = {'state': newstate, 'locked': False}
        pickle.dump(new_switch, open(statefile, 'wb'))
        report = 'switch {} is now {}, switchstate {}'
        print report.format(switchID, state, newstate)

new_state()

# test the above in three or four command shells
# python switchreg.py [switchID] [delaytime]
# switchID may be A to D
# shorter delaytimes simulate race-conditions better

switchID = sys.argv[1]
delaytime = float(sys.argv[2])
endrange = int(30/delaytime) # so time taken up by iterations is about the same

for i in range(0, endrange):
    update_state(switchID, 'On')
    sleep(delaytime)
    update_state(switchID, 'Off')


texts:
I have created a Simple Dictionary Chrome Extension. It is using JavaScript/ some HTML/ some CSS. The Manifest.jso file talks about the extension. The HTML is for a small/simple pop up and the JS is for the popup and user interactions.

MANIFEST.JSON

{
"manifest_version": 2,
"name": "My Simple Dictionary Extension",
"description": "A simple dictionary extension where users can look up a word in the extension and find its definition.",
"author": "Tristan Sun",
"version": "0.1",
"content_scripts":[
    {
        "matches": ["<all_urls>"],
        "js":["jquery-3.1.1.js"]
    }
],
"browser_action": {
    "default_title": "Dictionary Popup",
    "default_popup": "popup/popup.html",
    "default_icon": "dic.png"
},
"background": {
    "scripts": ["jquery-3.1.1.js","background.js"],
    "persistent": false
},
"permissions": ["tabs"]
}

POPUP.JS

(function () {
'use strict';

// add enter key functionality to click 'define' button.
document.getElementById('term').addEventListener("keyup", function (event) {
    event.preventDefault();
    //keycode is 13 when the key released is 'enter' key.
    if (event.keyCode === 13) {
        document.getElementById('define').click();
    }
});

//when define button is clicked, then handleButton in backgroundpage.
document.querySelector('button').addEventListener("click", function () {
    var backgroundpage = chrome.extension.getBackgroundPage();
    var term = document.querySelector('input').value;
    if (backgroundpage !== null) {
        backgroundpage.handleButtonClick(term);
    }

});
}());

//retrieve message from background.js getting the response from the dictionary api and adding it to the popup.
chrome.runtime.onMessage.addListener(function (response) {
'use strict';

var b = document.getElementById('seemore');
//    document.getElementById('label').innerHTML =
//set text as definition to be shown
var definition = document.getElementById('definition');
definition.innerText = response.results[0].lexicalEntries[0].entries[0].senses[0].definitions[0];

//set see more text
b.innerText = "Click for more info on this word.";
//link see more text
b.href = "";
//when href is clicked, create a new tab with the actual dictionary entry for the word at oxford dictionary.
b.addEventListener("click", function () {
    chrome.tabs.create({url: "http://en.oxforddictionaries.com/definition/" + response.results[0].id.toLowerCase()});
});
});

POPUP.HTML

<!DOCTYPE html>

    <title></title>
    <link rel="stylesheet" href="popup.css" />

    Insert a word:
    <input id="term" type="text">
    <button id="define">Define</button>

POPUP.CSS

body {
min-width: 295px;
}

label{
font-family: fantasy;
font-size: 1.5em;
}

#define{
background-color: crimson;
border: none;
color: white;
padding 10px 20px;
text-align: center;
font-size: 1em;
}


texts: Safely getting the next element of a list

texts:
I'm looking for general review and improvements on this code that safely gets the next element of a list (and wraps to the first element if you exceed the list). It just seems a little excessive for how simple of a task it is.
It should also be noted that this function will only work for lists that do not contain duplicate elements. Unless I modify it to take index numbers instead, I can't see that restriction changing. If length list < 2, it will return Nothing.

nextElem :: Eq e => e -> [e] -> Maybe e
nextElem e xs = nextElem' e (shiftList e xs)
    where
        shiftList e xs = let (ya, yb) = break (== e) xs in yb ++ ya
        nextElem' _ []      = Nothing
        nextElem' _ (x : [])= Nothing
        nextElem' e (x : xs)
            | x == e    = Just (head xs)
            | otherwise = nextElem' e xs


texts:
For the Join List algebraic data type:

data JoinList m a = Empty
                  | Single m a
                  | Append m (JoinList m a) (JoinList m a)
    deriving (Eq, Show)

This homework's problem states to implement indexJ:

  Exercise 2 The first annotation to try out is one for fast indexing
  into a JoinList . The idea is to cache the size (number of data ele-
  ments) of each subtree.

  This can then be used at each step to deter-
  mine if the desired index is in the left or the right branch. We have
  provided the Sized module that defines the Size type, which is simply
  a newtype wrapper around an Int .

  In order to make Size s more
  accessible, we have also defined the Sized type class which provides a
  method for obtaining a Size from a value.

  indexJ finds the JoinList element at the specified index. If the index
  is out of bounds, the function returns Nothing. By an index in a
  JoinList we mean the index in the list that it represents. That is,
  consider a safe list indexing function

I implemented indexJ, which searches for a matching index within a JList.

indexJ :: (Sized b, Monoid b) => Int -> JoinList b a -> Maybe a
indexJ _ Empty = Nothing
indexJ i (Single s x)
  | (getSize . size) s == i = Just x
  | otherwise               = Nothing
indexJ i (Append _ left right)
  | (getSize . size . tag) left >= i = indexJ i left
  | otherwise                        = indexJ i right

with the following background:

tag's definition

newtype Size = Size Int
  deriving (Eq, Ord, Show, Num)

getSize :: Size -> Int
getSize (Size i) = i

class Sized a where
  size :: a -> Size

...

tag :: Monoid m => JoinList m a -> m

Testing

jlIndex1 :: JoinList Size String
jlIndex1 = Append (Size 1) (Single (Size 0) "foo") (Single (Size 1) "bar")

*JoinList> indexJ 1 jlIndex1
Just "bar"
*JoinList> indexJ 33 jlIndex1
Nothing

Please critique my implementation.


texts:
I am trying to resolve following problem to improve my DS knowledge. Please advice which part of the code can be improved.

You run an e-commerce website and want to record the last N order ids
in a log. Implement a data structure to accomplish this, with the
following API:
record(order_id): adds the order_id to the log get_last(i): gets the
ith last element from the log. i is guaranteed to be smaller than or
equal to N. You should be as efficient with time and space as
possible.

Code explanation:
I choose linked list with single pointer (prev) to keep transaction logs. I suppose it would be called Stack Linked List.
stProduct -> linked list node
stProdStack -> struct to keep database information, namely ll tail and size (N)
record() examines db information struct tail pointer and order_id within range, then calls actual method to add node to the list: add_product().
I did not implement unit testing due to limited time to seat on.
PARDON MY ENGLISH xD
Code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>

//backward/stack linked list for storing transaction action log
typedef struct stProduct
{
    struct stProduct * prev;
    unsigned int order_id;
}
stProduct;

typedef struct stProdStack
{
    struct stProduct * tail;
    unsigned int size;
}
stProdStack;

stProduct* add_product(stProduct *tail, unsigned int order_id)
{
    stProduct *product = malloc(sizeof *product);
    if (!product) return NULL;
    product->order_id = order_id;
    product->prev = tail;
    return product;
}

bool record(stProdStack *stListInfo, unsigned int order_id)
{
    if (!stListInfo)
        return false;
    stProduct *tail = add_product(stListInfo->tail, order_id);
    if (tail)
    {
        stListInfo->tail = tail;
        return true;
    }
    else
    {
        return false;
    }
}

unsigned int get_last(const stProdStack *stListInfo, unsigned int i)
{
    if (!stListInfo) return 0;
    if (i > stListInfo->size) return 0;

    stProduct *current = stListInfo->tail;
    for (int j = 0; j < i - 1; j++)
    {
        current = current->prev;
    }

    return current->order_id;
}

int main(void)
{
    unsigned int N = 100;
    stProdStack product_stack = { NULL, N  };

    for (unsigned int i = 0; i < 300; i++)
    {
        if (!record(&product_stack, 1000 + i))
        {
            printf("transaction log record failed\n");
            break;
        }
    }

    printf("10th last product ID: %u\n", get_last(&product_stack, 10));

}

Result:
10th last product ID: 1290


texts: Is this quicksort efficient and acceptable?

texts:
In order to complete one of my assignment I needed to include a quicksort so I was wondering if this is correct and acceptable.

The code:

    private ArrayList<String> sort(ArrayList<String> ar, int lo, int hi){
        if (lo < hi){
            int splitPoint = partition(ar, lo, hi);
            sort(ar, lo, splitPoint);
            sort(ar, splitPoint +1, hi);
        }
        return ar;
    }

    private int partition(ArrayList<String> ar, int lo, int hi){
        String pivot = ar.get(lo);
        lo--;
        hi++;
        while (true){
            lo++;
            while (lo<hi && ar.get(lo).compareTo(pivot) < 0){
                lo++;
            }
            hi--;
            while (hi>lo && ar.get(hi).compareTo(pivot) >= 0){
                hi--;
            }
            if (lo<hi){
                swap(ar, lo, hi);
            }else {
                return hi;
            }
        }
    }

The additional swap method:

    private ArrayList<String> swap(ArrayList<String> ar, int a, int b){
        String temp = ar.get(a);
        ar.set(a, ar.get(b));
        ar.set(b, temp);
        return ar;
    }

If this is incorrectly done can you please give me some pointers and tell me why. Otherwise I would gladly accept any suggestions you have.


texts:
I'm given N integers. I need to find the maximum number of unique integers among all the possible contiguous subarrays of size M.

Scanner in = new Scanner(System.in);
Deque deque = new ArrayDeque<Integer>();
int n = in.nextInt();
int m = in.nextInt();
in.nextLine();
String s = in.nextLine();
in.close();

int maxUnique = 0;
List<Integer> numbers = Stream.of(s.split(" "))
    .map(Integer::parseInt)
    .collect(Collectors.toList());
for (int i = 0; i <= n-m; i++) {
    HashSet<Integer> unique = new HashSet<>(numbers.subList(i, i+m));
    if (maxUnique < unique.size())
        maxUnique = unique.size();
    if (maxUnique == m) {
        System.out.println(maxUnique);
        return;
    }
}
System.out.println(maxUnique);

It works fine, but fails on big arrays due to timeout. For example N=100000, M=98777 times out.

How can I improve it?


texts: Test for an array being subset of another master array

texts:
I was trying to build a small utility function to check if an array is part of other array. It's testing if an array is a subset of another master array.

const masterArray = [1,2,3,4,5,6];
const candidateArray = [2,5,6];

//Test for subset.

//create a set from the two.
const s1 = new Set(masterArray.concat(candidateArray));

//Compare the sizes of the master array and the created set
//If the sizes are same, no new elements are added that means
//the candidate is complete subset.
s1.size === masterArray.length;

Can this be handled in a better way?


texts: Calculating the number 8 chars long which contains all possible numbers containing the numbers from 0 to n

texts:
I have the following code:

    Integer cr = 3;
    String y = "\"\r\n\"";

    for (Integer i = 0; i < cr; i++)
    {
        for (Integer j = 0; j < cr; j++)
        {
            for (Integer k = 0; k < cr; k++)
            {
                for (Integer l = 0; l < cr; l++)
                {
                    for (Integer m = 0; m < cr; m++)
                    {
                        for (Integer n = 0; n < cr; n++)
                        {
                            for (Integer o = 0; o < cr; o++)
                            {
                                for (Integer p = 0; p < cr; p++)
                                {
                                    consolus.append(i.toString()+j.toString()+k.toString()+l.toString()+m.toString()+n.toString()+o.toString()+p.toString() + y);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

Is there some way I can write this more efficiently? Essentially, the output is a number 8 chars long which contains all possible numbers containing the numbers from 0 to cr. This method currently works, however it doesn't seem efficient, and then writing to the TextView consolus, only occurs after all the for statements complete.


texts: Insert node in sorted doubly linked list

texts:
Description:

  Given a reference to the head of a doubly-linked list and an integer,
  create a new Node object having data value  and insert it into a
  sorted linked list.

Code:

Node SortedInsert(Node head, int data) {

    Node current  = head;
    Node previous = null;
    while (current != null && current.data < data) {
        previous = current;
        current  = current.next;
    }

    Node node = new Node();
    node.data = data;
    node.next = current;
    node.prev = previous;

    if (previous == null) {
        head = node;
    } else {
        previous.next = node;
    }

    if (current != null) {
        current.prev = node;
    }

    return head;
}

This solution required me to do a lot of head scratching which I fear would be difficult to do in front of an interviewer. Any other approach with fewer chances of mistakes?


texts: Printing out Pascal's Triangle in row-major format

texts:
Here's the problem statement:

  Given an integer value, print out Pascal's Triangle to the
  corresponding depth in row-major format:

  Input Sample:

6

  Output Sample:

1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 1 5 10 10 5 1

I need some practice with recursion, so I tried that approach:

var pascalDepth = parseInt(line, 10); //The input integer is provided on a single line as a text value, so this handles it.
var testTriangle = pascalTriangle(pascalDepth);
var output = [];

for(var i = 0; i < testTriangle.length; i++){
    for(var j = 0; j < testTriangle[i].length; j++){
        output.push(testTriangle[i][j]);
    }
}

console.log(output.join(" "));

function pascalTriangle(totalLines, triangle) {
    if (typeof triangle === 'undefined') {
        triangle = [];
    }

    if (triangle.length === totalLines) {
        return triangle;
    }

    if (triangle.length > 0) {
        var triangleLine = [];
        for (var i = 0; i < triangle.length; i++) {
            if (typeof triangle[triangle.length - 1][i - 1] === 'undefined') {
                triangleLine.push(1);
            } else {
                triangleLine.push((triangle[triangle.length - 1][i - 1] + triangle[triangle.length - 1][i]));
            }
        }
        triangleLine.push(1);
        triangle.push(triangleLine);
    } else {
        triangle.push([1]);
    }
    return pascalTriangle(totalLines, triangle);
}


texts:
I have this JSON code that I got from a get request with Azure API. Everything works how I want it but it doesn't look good. There must be an easier way to parse the data.
import json
#GET REQUEST code here, it works now the code below is grabbing the result and loading it.
formatted_response = {'cost': 0, 'timespan': '2020-07-07T03:00:00Z/2020-07-07T03:15:00Z', 'interval': 'TM', 'value': [{'id': '/subscriptions/hjhkjhjljkjknlkjjlkj/Groups/jhkjhjkhjs/providers/Micro/virtualMachines/jhjkhkjhjkhkhljkl/providers/MicInsights/metrics/Percentage CPU', 'type': 'Microsoft.Insights/metrics', 'name': {'value': 'Percentage CPU', 'localizedValue': 'Percentage CPU'}, 'displayDescription': 'The percentage of allocated compute units that are currently in use by the Virtual Machine(s)', 'unit': 'Percent', 'timeseries': [{'metadatavalues': [], 'data': [{'timeStamp': '2020-07-07T03:00:00Z', 'average': 2.4659375}, {'timeStamp': '2020-07-07T03:01:00Z', 'average': 2.974375}, {'timeStamp': '2020-07-07T03:02:00Z', 'average': 2.90265625}, {'timeStamp': '2020-07-07T03:03:00Z', 'average': 1.72484375}, {'timeStamp': '2020-07-07T03:04:00Z', 'average': 1.1275}, {'timeStamp': '2020-07-07T03:05:00Z', 'average': 0.05640625}, {'timeStamp': '2020-07-07T03:06:00Z', 'average': 0.05515625}, {'timeStamp': '2020-07-07T03:07:00Z', 'average': 0.055}, {'timeStamp': '2020-07-07T03:08:00Z', 'average': 0.28765625}, {'timeStamp': '2020-07-07T03:09:00Z', 'average': 0.0546875}, {'timeStamp': '2020-07-07T03:10:00Z', 'average': 0.054375}, {'timeStamp': '2020-07-07T03:11:00Z', 'average': 0.05734375}, {'timeStamp': '2020-07-07T03:12:00Z', 'average': 0.0553125}, {'timeStamp': '2020-07-07T03:13:00Z', 'average': 0.05609375}, {'timeStamp': '2020-07-07T03:14:00Z', 'average': 0.0528125}]}], 'errorCode': 'Success'}], 'namespace': 'Microsoft/virtualMachines', 'resourceregion': 'eastus8'}

p = formatted_response['value']

for i in p:
    for j in i:
        if j == 'timeseries':
            q = i[j]
for l in q:
    for u in l:
        if u =="data":
            g=l['data']

for r in g:
    for s in r:
        if s == "average":
            print(r[s])

$ python testapi.py
2.4659375
2.974375
2.90265625
1.72484375
1.1275
0.05640625
0.05515625
0.055
0.28765625
0.0546875
0.054375
0.05734375
0.0553125
0.05609375
0.0528125