texts: How to break this curse by a pure functional recursive function?

texts:
I have written two programs to find out a loopy path in a directed graphs.

The first version is a pure functional recursive solution, but its complexity is exponential. The second version following it achieves a linear complexity, but it doesn't look perfect either.

 def GetACycle(start: String, maps: Map[String, List[String]]): List[String] = {

    def explore(node: String, visits: List[String], steps: Int): List[String] = {
      println(List.fill(steps)("\t").mkString + node)
      if (visits.contains(node)) (visits.+:(node)).reverse
      else {
        if (maps(node).isEmpty) Nil
        else {
          val id = maps(node).indexWhere(x => !explore(x, visits.+:(node), steps + 1).isEmpty)
          if (id.!=(-1))
            explore(maps(node)(id), visits.+:(node), steps + 1)
          else
            Nil
        }
      }
    }

    explore(start, List(), 0)
  }

The second version uses mutable variables, the "visits" and "path", though it achieves a linear complexity in terms of number of visited nodes.

Would it be possible to achieve such a linear complexity in this situation while using a pure functional recursion without any mutable variables?

  def GetACycle2(start: String, maps: Map[String, List[String]]): List[String] = {
val nodes = maps.:\(Set[String]())((item, set) =>
  item._2.:\(set)(((i, set) => set.+(i))).+(item._1))
val pairs = nodes.toList.zip(List.fill(nodes.size)(false))

var visits = pairs.toMap
var path = List[String]()

def explore(node: String, steps: Int): Boolean = {
   println(List.fill(steps)("\t").mkString + node)
  path = path.+:(node)
  if (visits(node)) { visits = visits.updated(node, true); true }
  else {
    visits = visits.updated(node, true)
    if (maps(node).isEmpty) false
    else {
      maps(node).exists( x => explore(x, steps+1))
    }
  }
}

explore(start, 0)
path

}


texts: Linked List Interview Code methods, runtime, and edge cases refactored

texts:
In my previous post I had a number of steps given to me from the accepted answer on how I can write more production ready code. In this post I want this code to be reviewed as near production code I'd write in an interview. I'd like to know how well optimized my code is now from this improvements I've made to it. If there are other optimizations or c++11 features I could be using here please share that as well.

I also included comments on worst case run time complexity for my member functions, I'd like some feedback on this and my space complexity too.

#include <iostream>
#include <string>

class LinkedList
{
    private:
        struct Node
        {
            int data;
            Node* next;
            Node(int data_) : data(data_), next(nullptr) { }
        };
        Node* _head;
        Node* _tail;
    public:
        LinkedList() : _head(nullptr) { }
        LinkedList(int data) { // O(1)
            Node* n = new Node(data);
            _head = n;
            _tail = n;
        }
        ~LinkedList() { // O(n)
            Node* current = _head;
            Node* n;
            while(current) {
                n = current;
                current = current->next;
                delete n;
            }
            _head = nullptr;
        }
        void append(int new_data) { // O(1)
            auto n = new Node(new_data);
            if(!_head) {
               _head = n;
               _tail = n;
            }
            else {
                _tail->next = new Node(new_data);
                _tail = _tail->next;
            }
        }
        void remove(int target_data) { // O(n)
            if(!_head) { return; }
            Node* previous = nullptr;
            auto current = _head;
            for(; current->data != target_data; current = current->next) {
                if(!current->next) {
                    return;
                }
                previous = current;
            }
            if(!current->next) {
                if(previous) {
                    delete current;
                    previous->next = nullptr;
                }
                else {
                     delete current;
                    _head = nullptr;
                }
            }
            else {
                auto dangling_ptr = current->next;
                current->data = current->next->data;
                current->next = current->next->next;
                delete dangling_ptr;
            }
        }
        friend std::ostream& operator<<(std::ostream& os, const LinkedList& linked_list) { // O(n)
            Node* current = linked_list._head;
            if(!current) {
                os << "Linked List is empty" << std::endl;
                return os;
            }
            else {
                for(; current; current = current->next) {
                    os << '(' << std::to_string(current->data) << ")->";
                }
                os << "nullptr";
                return os;
            }
        }
};

int main()
{
    LinkedList linked_List(0);
    linked_List.append(1);
    linked_List.append(2);
    linked_List.append(3);
    linked_List.append(4);

    std::cout << linked_List << std::endl;

    linked_List.remove(0);
    linked_List.remove(4);
    linked_List.remove(2);
    std::cout << linked_List << std::endl;

    linked_List.remove(3);
    linked_List.remove(1);
    std::cout << linked_List << std::endl;

    LinkedList linked_List_two;
    linked_List_two.append(1);
    linked_List_two.append(2);
    linked_List_two.append(3);
    linked_List_two.append(4);

    std::cout << linked_List_two << std::endl;

    linked_List_two.remove(0);
    linked_List_two.remove(4);
    linked_List_two.remove(2);
    std::cout << linked_List_two << std::endl;

    linked_List_two.remove(3);
    linked_List_two.remove(1);
    std::cout << linked_List_two << std::endl;
}


texts:
Basically, this is a recursive function to generate all of the permutations of an array.

The idea is this:

recursive case: start at the specified array index, and make a case for starting the next index (incremented one) for each of the indexes that come after the specified index by swapping the index with the next if not the same.

base case: the array has has no indexes greater than the current index. store the array, and increment the number of permutations found.

Here's what I thought would work:

public static void <T> permute (T[][] permutations, T[] array)
{
    if (permutations.length != factorial(array.length))
        throw new IllegalArgumentException();
    permute(permutations, array, 0, 0);
}
private static int <T> permute(
        T[][] permutations,
        T[] array,
        int midStart,
        int count)
{
    if (midStart == array.length)
    {
        permutations[count] = Arrays.copyOf(array, array.length);
        return count + 1;
    }
    else
    {
        for (int i = midStart; i < array.length; i++)
        {
            T temp = array[i];
            array[i] = array[midStart];
            array[midStart] = temp;
            count = permute(permutations, array, midStart + 1, count);
        }
        return count;
    }
}

But this doesn't work because array being passed on the recursive call is being altered before the caller swaps the values again.

What's an efficient way to do this without needing to change it to something like so (without the extra space to store another array at each function call)?

private static <T> int permute(
        T[][] permutations,
        T[] array,
        int midStart,
        int count)
{
    if (midStart == array.length)
    {
        permutations[count] = Arrays.copyOf(array, array.length);
        return count + 1;
    }
    else
    {
        for (int i = midStart; i < array.length; i++)
        {
            T temp = array[i];
            array[i] = array[midStart];
            array[midStart] = temp;
            count = permute(
                        permutations,
                        Arrays.copyOf(array, array.length),
                        midStart + 1,
                        count);
        }
        return count;
    }
}


texts: Computing sum of elements with mutlithreads

texts:
I'm reading about multithreads with C++. My code is to compute the sum of elements using multithread approach. The code is

#include <iostream>
#include <thread>
#include <vector>
#include <atomic>

void func(std::atomic<long long>& sum, const std::vector<long long>& vec)
{
    long long result(0);
    for(int i(0); i < vec.size(); ++i){
        result += vec[i];
    }
    sum += result;
}

int main()
{
    // create a variable to hold the result.
    std::atomic<long long> sum(0);

    // create vector of threads
    std::vector<std::thread> threads;

    // generate numbers
    std::vector<long long> num;
    for(long long i(1); i<=10000000; ++i)
        num.push_back(i);

    // each thread should compute the sum of some numbers
    long long k(0);
    //create 1,000 threads
    for(int i(0); i<1000; ++i){
        // extract elements from the big elements vector (i.e. in this example, each thread handles 10,000)
        std::vector<long long> temp(&num[k],&num[k+10000]);
        k+=10000;
        threads.push_back(std::thread{ func, std::ref(sum), temp });
    }
    for(auto& t : threads){
        t.join();
    }
    std::cout << "Sum = " << sum << std::endl;

    return 0;
}

I would like to know if my code can be enhanced more. The comments should be enough to explain the code. Thank you.


texts: Binary values in hexidecimal notation written directly to video memory

texts:
In X86 Legacy boot loader prologue the first seven instructions preserve the state of the 8 general purpose and 6 segment registers. This is where they are displayed, right justified without leading zeros. Most often you'll see this kind of thing formulated as an ASCII string, then displayed with printf or maybe if INT 80 or SYSCALL under Linux.

The addresses are absolute and for those that may be interested in executing the code, you can PM me and I'll send the current version that can be assembled with NASM. Then breakpoints can be set and in my case I use BOCH's.

Here is the result;

SI is already pointing to the beginning of this string

  'AXCXDXBXSPBPSIDIESDSCSSSFSGS'

 700  83C61B            add     si, 27     Point to last character
 703  FD                std                Do things in reverse
 704  6800B8            push    VIDEO_SEG
 707  07                pop     es
 708  BF9C09            mov     di, 0x99c  Row 15 Column 30 (zero indexed)
 70B  B90E00            mov     cx, 14     Values to be displayed
 70E  B407              mov     ah, 0x7    in low intensity white

At this point SP is pointing to the values preserved in proglogue.

that is why this instruction without the corresponding push works. After all, is said and done, SS:SP will be pointing to the far pointer back into the BIOS.

 710  5A                pop     dx      Retrieve registers value

Retain pointer to end of hex value (DI) and in case we change attribute which is in AH, preserve it too.

 711  57                push    di
 712  50                push    ax            AH = White
 713  09D2              or      dx, dx        Is value zero
 715  7502              jnz     719
 717  FEC4              inc     ah            AH = Grey
 719  E8BFFF            call    6db

Now registers mnemonic can be displayed in bright yellow

 71C  B40E              mov     ah, 14        Attribute bright yellow
 71E  AC                lodsb
 71F  AB                stosw
 720  AC                lodsb
 721  AB                stosw

 722  58                pop     ax            AH = White again
 723  5F                pop     di
 724  81EFA000          sub     di, 160       Bump pointer up one line
 728  FEC9              dec     cl
 72A  740A              jz      736           Bail if done ZF=1

As soon as CL = 8, that means all the segment registers have been displayed and we can move over to the next column

 72C  80F908            cmp     cl, 8
 72F  75DF              jnz     710
 731  BF200A            mov     di,0xa20      DI = 5DC
 734  EBDA              jmp     710

One thing I had considered here is adding 444H to DI instead, which in effect does exactly the same and then the left column would stay relative if the word at 709H was changed.

Finally, restore DF

 736  FC                cld

This is where DX will be right justified without leading spaces

 6DB  51                push    cx
 6DC  B105              mov     cl, 0x5

 Converts low nibble in AL to corresponding 0-1 or A-F
 6DE  88D0              mov     al, dl
 6E0  240F              and     al, 0xf
 6E2  3C0A              cmp     al, 0xa
 6E4  7202              jc      6e8
 6E6  0407              add     al, 0x7
 6E8  0430              add     al, 0x30
 6EA  AB                stosw
 6EB  FEC9              dec     cl

 Asserting DX here assures only one zero will be displayed for zero
 values in DX
 6ED  C1EA04            shr     dx, 4
 6F0  75EC              jnz     6de
 6F2  D1E1              shl     cx, 1
 6F4  29CF              sub     di, cx
 6F6  B82D0F            mov     ax, 0xf2d
 6F9  66AB              stosd                  Write bright white hyphen
 6FB  59                pop     cx
 6FC  C3                ret


texts: Config based Hide Show Rules Processor in JavaScript

texts:
I am working on a library which does DOM hide and show based on other DOM elements.

I have written a basic structure for the library.

The below is the code to handle DOM elements hiding when a checkbox is checked and unchecked.

My overall goal is to make this library extensible and maintainable.

Am I following SOLID principles?
Is there any better way to do it?
Are there any design patterns to follow?

// basic data structure of config object
var rules = [
  {
    sourceId: 'mainCheckbox',
    targetId: 'exampleDiv1',
    ruleType: 'onlyOnChecked',
    targetVisibilityOnChecked: 'hide', // show / hide
    targetVisibilityOnUnchecked: 'show',
    doNotReset: false
  }
]

var ruleToProcessorMap = {
  onlyOnChecked: OnlyOnCheckedRuleProcessor
}

var RuleEngine = {}

RuleEngine.run = function(rules) {
  var ruleIndex
  for (ruleIndex = 0; ruleIndex < rules.length; rules++) {
    this.processRule(rules[ruleIndex])
  }
}

RuleEngine.processRule = function(ruleObj) {
  var ruleProcessor = new ruleToProcessorMap[ruleObj.ruleType](ruleObj)
  ruleProcessor.process()
}

function OnlyOnCheckedRuleProcessor(options) {
  this.options = options || {}
}

OnlyOnCheckedRuleProcessor.prototype.process = function() {
  var $sourceId = $id(this.options.sourceId),
    ctx = this

  $sourceId.on('click', onSourceClick)

  function onSourceClick() {
    var elementVisibilityHandler = new ElementVisibilityHandler({
        elementId: ctx.options.targetId,
        doNotReset: ctx.options.doNotReset
      }),
      show = elementVisibilityHandler.show,
      hide = elementVisibilityHandler.hide

    var visibilityMap = {
      show: show,
      hide: hide
    }

    var onCheckedFunc = visibilityMap[ctx.options.targetVisibilityOnChecked]
    var onUncheckedFunc = visibilityMap[ctx.options.targetVisibilityOnUnchecked]

    if ($sourceId.is(':checked')) {
      onCheckedFunc.call(elementVisibilityHandler)
    } else {
      onUncheckedFunc.call(elementVisibilityHandler)
    }
  }
}

function ElementVisibilityHandler(options) {
  this.options = options || {}

  this.$element = $id(options.elementId)
}

ElementVisibilityHandler.prototype.show = function() {
  if (isContainerElement(this.$element)) {
    if (this.options.doNotReset) {
      simpleShow(this.$element)
    } else {
      showWithChildren(this.$element)
    }
  }
}

ElementVisibilityHandler.prototype.hide = function() {
  if (isContainerElement(this.$element)) {
    if (this.options.doNotReset) {
      simpleHide(this.$element)
    } else {
      hideAndResetChildren(this.$element)
    }
  }
}

function simpleHide($element) {
  return $element.hide()
}

function hideAndResetChildren($element) {
  var $children = simpleHide($element)
    .children()
    .hide()

  $children.find('input:checkbox').prop('checked', false)

  $children.find('textarea, input').val('')
}

function simpleShow($element) {
  return $element.show()
}

function showWithChildren($element) {
  simpleShow($element)
    .children()
    .show()
}

function $id(elementId) {
  return $('#' + elementId)
}

function isContainerElement($element) {
  if (typeof $element === 'string') {
    $element = $id($element)
  }

  return $element.prop('tagName').toLowerCase()
}

// execution starts here
RuleEngine.run(rules)

```


texts: Creating a concurrent/parallel ForEachAsync that can fail immediately or wait until enumeration is complete

texts:
I needed an asynchronous parallel ForEach mechanism so I could enumerate an enumerable by N degrees of concurrency and process an action for each item.  Searching around, my code was modeled/merged from a few posts I found.

The tests I have been running are:

Run body() to completion
Inside the body(), do a CancellationTokenSource.Cancel()
Inside the body(), throw a OperationCancelledException()
Inside the body(), throw a NotSupportedException()

First, this points to a Stephen Toub post here.  I came up with combination of Toub's methods to have maxDegreeOfConcurrency and exception options (following bits from here)..

public static async Task ForEachAsync<T>( this IEnumerable<T> source, Func<T, Task> body, AsyncParallelOptions parallelOptions )
{
    ConcurrentBag<Exception> exceptions = null;

    var maxDegreeOfConcurrency = parallelOptions.MaxDegreeOfParallelism;

    // If they pass in a CancellationToken from caller of ForEachAsync need to create linked token source in case caller cancels, I want
    // ForEachAsync to cancel as well.  If they want to failImmediately, make a new CancellationTokenSource so I can stop processing partitions
    var cts = parallelOptions.CancellationToken != null ? CancellationTokenSource.CreateLinkedTokenSource( parallelOptions.CancellationToken ) :
              parallelOptions.FailImmediately ? new CancellationTokenSource() : null;

    var allDone = Task.WhenAll(
        from partition in Partitioner.Create( source ).GetPartitions( maxDegreeOfConcurrency )
        select Task.Run( async delegate
        {
            using ( partition )
            {
                while ( ( cts == null || !cts.IsCancellationRequested /* either from caller or failImmediately */ ) && partition.MoveNext() )
                {
                    await body( partition.Current )
                    .ContinueWith( t =>
                        {
                            // If body() threw an error, cancel if a CancellationTokenSource is present.
                            if ( t.IsFaulted )
                            {
                                if ( parallelOptions.FailImmediately )
                                {
                                    cts.Cancel();
                                }

                                // Always gather the exception to throw at the end
                                if ( exceptions == null ) exceptions = new ConcurrentBag<Exception>();

                                foreach ( var ex in t.Exception.InnerExceptions )
                                {
                                    exceptions.Add( ex );
                                }
                            }
                        }
                );
                }
            }
        }, cts.Token ) );

    // Wait until all finished (or errored out) and then return exceptions
    await allDone;

    // Question: allDone is never going to have IsCanceled or IsFaulted correct?  because await body() will swallow all exceptions?
    Console.WriteLine($"ForEachAsync Extension: Check Exceptions, {exceptions?.Count ?? 0} total, allDone.IsCanceled: {allDone.IsCanceled}, allDone.IsFaulted: {allDone.IsFaulted}, cts.IsCancellationRequested: {cts.IsCancellationRequested}" );

    if ( exceptions != null )
    {
        throw new AggregateException( exceptions );
    }
    else if ( cts.IsCancellationRequested )
    {
        throw new OperationCanceledException();
    }
}


texts: Convert JSON to a different format (nested json)

texts:
This is really not a question. I was looking up this solution but couldn't find it anywhere. Thought of posting it here so it may save someone's time.

Here was my issue: I had a JSON coming from server which was not nested. Lets take example of Movies:

var movies = [
  {"name":"Ice Age 3", "language":"English", "year":"2012"},
  {"name":"Ice Age 3", "language":"French", "year":"2011"},
  {"name":"Ice Age 3", "language":"German", "year":"2013"}
];

Now effectively speaking, there is no need for server to return it like this, however this was my case and since I was using jquery-template I wanted to have it as a nested JSON object. Something like this:

var movies = [{
    "name": "Ice Age 3",
    "details": [
        {"language": "English", "year": "2012"},
        {"language": "French", "year": "2011"},
        {"language": "German", "year": "2013"}
    ]
}];

Here is the code which I wrote to convert it:

function convert(arr) {
    var convertedArray = [];

    $(arr).each(function () {
        var found = false;
        for (var i = 0; i < convertedArray.length; i++) {
            if (convertedArray[i].name === this.name) {
                found = true;
                convertedArray[i].details.push({
                    "language": this.language,
                    "year": this.year
                });
                break;
            }
        }
        if (!found) {
            convertedArray.push({
                "name": this.name,
                "details": [{
                    "language": this.language,
                    "year": this.year
                }]
            });
        }
    });

    return convertedArray;
}

I am sure there would be a better approach for this. But for me it worked.


texts: Inverse mapping with bilinear interpolation on an image

texts:
The following is my solution for an inverse mapping with bilinear interpolation on an image. The original image is img and newmatrix is the transformed image. invRot is the inverse transformation matrix.

How can I optimize the nested for loops (or remove them altogether) to give me a better time complexity for large values of row and col?

newmatrix = np.zeros((row, col, 3), np.uint8)
for r in range(row):
    for c in range(col):
        if offset > 0:
            offset = -1 * offset
        pt = np.array([r+offset,c,1]) #Adjust the offset.
        newpt = np.matmul(invRot, pt) #Reverse map by reverse rotation and pick up color.

        #Check the bounds of the inverse pts we got and if they lie in the original image,
        #then copy the color from that original pt to the new matrix/image.
        if (newpt[0] >= 0 and newpt[0] < (yLen - 1) and newpt[1] >= 0 and newpt[1] < (xLen - 1)):
            x = np.asarray(newpt[1])
            y = np.asarray(newpt[0])

            x0 = np.floor(x).astype(int)
            x1 = x0 + 1
            y0 = np.floor(y).astype(int)
            y1 = y0 + 1

            Ia = img[y0, x0]
            Ib = img[y1, x0]
            Ic = img[y0, x1]
            Id = img[y1, x1]

            color1 = (x1-x) * (y1-y) * Ia
            color2 = (x1-x) * (y-y0) * Ib
            color3 = (x-x0) * (y1-y) * Ic
            color4 = (x-x0) * (y-y0) * Id

            weightedAvgColor = color1 + color2 + color3 + color4
            newmatrix[r][c] = weightedAvgColor


texts:
In my ASP.NET MVC code, I like to use controller service classes for my controllers. These service classes contain methods for retrieving viewmodel objects.

Here is an example controller snippet:

public SubscriptionsController(ISubscriptionsControllerService service)
{
    _service = service;
}

public ActionResult Index(Guid id)
{
    return View("Subscriptions", _service.GetSubscriptionsViewModelOnGet(id));
}

[HttpPost]
public ActionResult Index(SubscriptionsViewModel viewModel)
{
    _service.SaveSubscriptions(viewModel);

    return View("Subscriptions", _service.GetSubscriptionsViewModelOnPost(viewModel));
}

As you can see, I have a method for retrieving the subscriptions viewmodel on a GET request, as well as the equivalent for a POST request.

The POST method takes in an existing viewmodel object and updates any relevant data e.g. a list of subscription items, that need to be refreshed before passing back to the view.

My question is whether the naming of the methods (GetSubscriptionsViewModelOnGet() and GetSubscriptionsViewModelOnPost()) makes sense. They seem OK to me, but I'm interested in other people's views.


texts: Sum even fibonacci numbers up to a limit

texts:
After I have tackled the first problem I come to Project Euler Problem 2 which states

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

If we take into account that

adding 2 odd numbers will result in an even number
adding an odd to an even number will result in an odd number

we only need to take every third term.
But before we can get there we need to get all the fibonacci numbers like so
private static IEnumerable<int> GetFibonacciNumbers()
{
    var first = 0;
    var second = 1;
    while (true)
    {
        var nextFibonacciNumber = first + second;
        yield return nextFibonacciNumber;

        first = second;
        second = nextFibonacciNumber;
    }
}

which will generate infinite terms of the fibonacci numbers. We will then restrict this by using the TakeWhile() extension method.
Getting only the even terms up to a specific limit can be achieved by
private static IEnumerable<int> GetEvenFibonacciNumbersTill(int upperLimit)
{
    var counter = 0;
    foreach (var currentTerm in GetFibonacciNumbers().TakeWhile(i => i < upperLimit))
    {
        counter++;
        if (counter == 3) // every third term is even
        {
            yield return currentTerm;
            counter = 0;
        }
    }
}

which is called by the int Solve() method like so
private static readonly int fourMillions = 4000000;
public static int Solve()
{
    return GetEvenFibonacciNumbersTill(fourMillions).Sum();
}

As usual any improvements in style, performance, naming or memory usage are welcome.


texts:
Is there a better way to do this?

This function takes, as an argument, a natural number, n, which is between 1 and 52 inclusive and returns a list containing the point value associated with that number as an integer. The aces are the numbers 1,14,27,40 in the respective suits and they worth either 1 or 11 points. The regular cards with the numbers 2-10,15-23,28-36,41-49 in their respective suits are worth their face values. The face cards
are represented by the numbers 11-13,24-26,37-39,50-52 in their respective suits and they are each worth 10 points.

def getPoints(n):
    #the ace values
    if n == 1 or n == 14 or n == 27 or n == 40:
        return [1,11]
    #the regular card values
    if 2<=n<=10:
        return [n]
    if n == 15 or n == 28 or n == 41:
        return [2]
    if n == 16 or n == 29 or n == 42:
        return [3]
    if n == 17 or n == 30 or n == 43:
        return [4]
    if n == 18 or n == 31 or n == 44:
        return [5]
    if n == 19 or n == 32 or n == 45:
        return [6]
    if n == 20 or n == 33 or n == 46:
        return [7]
    if n == 21 or n == 34 or n == 47:
        return [8]
    if n == 22 or n == 35 or n == 48:
        return [9]
    if n == 23 or n == 36 or n == 49:
        return [10]
    if 11<=n<=13 or 24<=n<=26 or 37<=n<=39 or 50<=n<=52:
        return [10]


texts: Is there a way for Rcpp's dpois function where I can send a vector `theta` as param?

texts:
In R, the function dpois (the poison distribution) can be used as dpois(x,theta) with both x and theta being vectors. However, in Rcpp, it can't be used like that. Can anyone suggest some function to replace the loop in the following dtpoi0 function.
#include <algorithm>
#include <RcppArmadillo.h>

using namespace Rcpp;
using namespace arma;

// [[Rcpp::depends("RcppArmadillo")]]
// [[Rcpp::export]]
imat misy(const ivec& x) {
  const int s1 = std::min(x(0), x(1));
  const int s2 = std::min(x(0), x(2));
  const int s3 = std::min(x(1), x(2));
  imat missy(3, 1, fill::zeros);

  for (int i = 0; i <= s1; ++i) {
    for (int j = 0; j <= s2 and i + j <= x(0); ++j) {
      for (int k = 0; k <= s3 and i + k <= x(1) and j + k <= x(2); ++k) {
        missy = join_rows(missy, ivec{i, j, k});
      }
    }
  }
  missy.shed_col(0);
  return (missy);
}

// [[Rcpp::export]]
double dtpoi0(const ivec& x, const vec& theta) {
  imat missy = misy(x);
  double fvalue = 0.0;
  missy.each_col([&](ivec& v) {
    ivec u=join_cols(x - v(uvec{0, 0, 1}) - v(uvec{1, 2, 2}), v);
    double prod = 1;
    for (int i = 0; i < (int (u.n_elem)); ++i) {
      prod *= R::dpois(u(i), theta(i), 0);
    }
    fvalue += prod;
  });
  return fvalue;
}


texts: API method to validate Facebook OAuth token

texts:
I am new to Java / OOP and I'm concerned that I have a method which is doing far too much "stuff" - but I don't easily see how it can be shortened in a way which is not contrived / arbitrary.

This is a server-side API method built using Google App Engine.

Currently, the method (which is really just a template at this stage):

Validates a user's Facebook OAuth token against Facebook's own
servers - this is all done behind the scenes in a FacebookHelper
class I have written.
Catches any exceptions (most likely an
    IOException) thrown during this validation process.
Asks the user to
    log in again if their token is invalid (if (authToken == null)).
Else if authentication has been successful, tries to get the user
    record from my database.
If it doesn't exist, adds the user to the
    database. (registerUserInDatabase).
Responds with a personalised
    welcome to the user - after having registered the user if they were
    not already registered.

Code:

@ApiMethod(name = "getUserData", path = "get_user_data")
public Bean getUserData(@Named("token") String token) {

    Bean response = new Bean();
    FacebookAuthToken authToken;
    User user;
    String userPersonalisedWelcome;

    try {
        authToken = ServerFacebookHelper.getAuthToken(token);
    } catch (Exception e) {
        response.setData("Exception occurred");
        return response;
    }

    if (authToken == null) {
        response.setData("Token invalid, please log in");
        return response;
    } else {
        user = getUserFromDatabase(authToken);
        if (user == null) {
            user = registerUserInDatabase(authToken);
            userPersonalisedWelcome = user.getPersonalisedWelcome;
            response.setData(userPersonalisedWelcome);
        } else {
            response.setData(user.getPersonalisedWelcome);
        }
        return response;
    }
}

Obviously there is already a huge amount of work being done outside this method, such as API calls and database reads/writes, but it still feels far too procedural and frankly "dumb". At the same time, everything it encapsulates is required in order to service this "getUserData" API request - so perhaps I am overthinking here.


texts:
I'm reviewing some code and I came across this:

// Select the last parameter in the list
if (parametersListBox.SelectedIndex > -1)
{
    parametersListBox.SetSelected(parametersListBox.SelectedIndex, true);
}

ParametersListBox being a C# ListBox. Despite the fact that the comment is wrong, does this actually do something or is this just useless code?


texts: Counting significant figures in a number

texts:
I decided to make something to count the significant figures in a number to see how easily it could be done, but I think there may have been a better or simpler way. Any advice even just for conventional purposes is appreciated!

def count_sig_figs(answer):
    '''This fucntion will count the sigfigs used in the answer of a user'''
    sig_fig_count = 0
    num_list = list(answer)

    for index in range(len(num_list)):
        try:
            fig = int(num_list[index])
            if fig != 0:
                sig_fig_count +=1
            elif check_zero_sig(index, num_list, sig_fig_count):
                sig_fig_count += 1
        except:
            continue
    return sig_fig_count

def check_zero_sig(index, num_list, sig_fig_count):
    '''Checks for significance in a zero from a list'''
    try:
        decimal = num_list.index('.')
        if index > decimal and sig_fig_count > 0:
            return True
    except:
        if index == 0:
            return False
        elif index == len(num_list):
            return False
        new_index = index+1

        if num_list[new_index] == '.' and sig_fig_count > 0:
            return True
        elif num_list[new_index] == '.' and sig_fig_count == 0:
            return False
        elif num_list[new_index] != '.' and sig_fig_count > 0:
            fig = int(num_list[new_index])
            if fig != 0:
                return True
            else:
                return check_zero_sig(new_index, num_list, sig_fig_count)
        elif num_list[new_index] != '.' and sig_fig_count == 0:
            fig = int(num_list[new_index])
            if fig != 0:
                return True
            else:
                return check_zero_sig(new_index, num_list, sig_fig_count)
        else:
            return False

def test():
    print(count_sig_figs('1')) # 1 sig fig
    print(count_sig_figs('10')) # 1 sig fig
    print(count_sig_figs('100')) # 1 sig fig
    print(count_sig_figs('1004')) # 4 sig figs
    print(count_sig_figs('10004')) # 5 sig figs
    print(count_sig_figs('105')) # 3 sig figs
    print(count_sig_figs('01')) # 1 sig fig
    print(count_sig_figs('1.2035')) # 5 sig figs
    print(count_sig_figs('001.09508')) # 6 sig figs
    print(count_sig_figs('0.00110')) # 3 sig figs

if __name__ == "__main__":
    test()


texts:
I'd like to know if there is a standard way of creating a matrix like the one shown below using the R programming language.

$$
        \begin{bmatrix}
        1 & \rho & \rho^2 & \cdots & \rho^{T-1}\\
        \rho & 1 & \rho & \cdots & \rho^{T-2}\\
        \rho^2 & \rho & 1  & \cdots & \rho^{T-3}\\
        \vdots &\vdots &\vdots & \ddots & \vdots\\
        \rho^{T-1} & \rho^{T-2} & \rho^{T-3} & \cdots & 1
        \end{bmatrix}
$$

The code I've been using to create matrices like this one is shown below.

For illustrative purposes, let rho = 0.8 and T = 20.

rho <- 0.8
t   <- 20
toeplitz(c(1, poly(rho, t-1, raw=TRUE)))

Although the output of this code does, indeed, produce the matrix of interest, I get the feeling that there's probably a better way of doing it.

Can this code snippet be improved - in the sense that there is a more elegant, more standard, more correct, or more efficient way of creating the matrix?


texts: Determining primality by removing select composits

texts:
Calculating many remainders for each prime and composite consumes more time.

I use a factoring function to find factors of single values.

When I use a factoring function to find lists of primes, I use a wheel.

A wheel exploits composite values punctuating an otherwise prime sequence.

The primary advantage of a wheel is reducing significantly, the candidate list and so processing.

My wheel eliminates 2, 3, 5 and 7 multiples from the a list. For the longest time, I used only elimination of 2s, 3s and 5s because the wheel list is only 8 values and simple to construct but there are just to many 7s.

Take the list of primes 11,13,17,19,23,29,31,39 and add 30 to each of the previous 8 values for subsequent values.

Take the first 55 from the list and remove the 7 multiples. The deltas will be this wheel.

What should be faster is subtraction of one list from another where the calc is compare and once only for each.

wl = [2,4,2,4,6,2,6,4,2,4,6,6,2,6,4,2,6,4,6,8,4,2,4,2,4,8,6,4,6,2,4,6,2,6,6,4,2,4,6,2,6,4,2,4,2,10,2,10]
-- the so-called wheel: the recurring pattern in a composite punctuated list
n7sl = scanl (+) 11 $ cycle wl -- infinite

-- short list of composits with no 2's, 3's 5's or 7's; 77%+ reduced
n7s = take 150 $ n7sl

-- diagonalize and limit the factor's composite list
lls i y = drop i.take y $ n7sl

-- substract the 1st list from the 2nd, infinite list
rms [] _ = [] -- stop when first list is exhausted
rms n@(x:xs) p@(y:ys)
    | x==y = rms xs ys
    | x>y  = y:rms n ys
    | y>x  = rms xs p

-- generate the composite list
comps [] _ _ _ _  =[]
comps (n:ns) [] y i b = comps ns (lls (i+1) y) y (i+1) b
comps k@(n:ns) (r:rs) y i b
      | m>b  =comps ns (lls (i+1) y) y (i+1) b
      | m<=b =m:comps k rs y i b
   where m = n*r

-- the result of `comps` is not just a diagonalization but 2, top & irregular bottom
-- `comps` is maybe necessary to stop when the limit of a list is reached
-- otherwise, I was using a list comprehension which is way less complicated

-- `comps` has to many parameters so this to reduce it to 1
-- it will be subtracted the fixed length wheel numbers and the lazy wheel
comp1 n =sort $ comps n7s (lls 0 n) n 0 (11*(last.take n $ n7sl))
-- put everything together to generate primes

last $ rms (comp1 5000) n7sl

240641

(0.12 secs, 65,219,592 bytes)

last $ rms (comp1 10000) n7sl

481249

(0.24 secs, 143,743,944 bytes)

last $ rms (comp1 15000) n7sl

721891

(0.37 secs, 220,099,904 bytes)

Question is this better that factoring? Is there a better way to generate multiples without multiplying in comps or list comprehensions?

Any prime list I generate excludes 2,3,5 & 7 because they are misbehaved, irregular and to well known.


texts:
The following PHP code does exactly what I need it to do but, as a complete PHP novice, I am wondering: what can be improved here?

$theurl='./section-1.html';
function getbody1($filename) {
  $file = file_get_contents($filename);
  $bodypattern = ".*";
  $bodyendpattern = ".*";
  $thecontainer = "id=\"container\"";
  $thecleanup = "";
  $noheader = preg_replace("/".$bodypattern."/", "", $file);
  $noheader = preg_replace("~".$bodyendpattern."~", "", $noheader);
  $noheader = preg_replace("|".$thecontainer."|", "", $noheader);
  $noheader = preg_replace("#".$thecleanup."#", "", $noheader);
  return $noheader;
}
echo getbody1("$theurl");


texts: Is my implementation of FizzBuzz overkill?

texts:
I am doing FizzBuzz on a take home test (in Unity).  I am sure this is just a competency check, but I went ahead and followed some coding conventions such as using constant fields, dependency injection, comments, etc.  Is this overkill?  If I should "dumb it down", how should I do so?  Also, as seen in the directions, it implies that for multiples of 3 and 5, I should print out "Fizz", "Buzz", and "FizzBuzz"...but I am reading too much into it, right?

I am trying to have an optimal program here in terms of production code.  I hope I am not being too picky and misusing Code Review.

///******************************************
// * FizzBuzz.cs
// *
// * INSTRUCTIONS:
// * Write a program that prints the numbers 1 to 100.
// * For multiples of 3, output the string "Fizz" instead of the number.
// * For multiples of 5, output the string "Buzz" instead of the number.
// * For multiples of 3 & 5, output "FizzBuzz" instead of the number.
// ******************************************/

using UnityEngine;
using System.Collections;

public class FizzBuzz : MonoBehaviour
{
    private const string FIZZ = "Fizz";
    private const string BUZZ = "Buzz";
    private const string FIZZ_BUZZ = "FizzBuzz";

    void Start()
    {
        PrintFizzBuzz(100);
    }

    /// <summary>
    /// Prints the numbers [1, n], unless it is a multiple of 3 or 5.
    /// If a multiple of 3, prints FIZZ.
    /// if a multiple of 5, prints BUZZ.
    /// if a multiple of 3 and 5, prints FIZZ_BUZZ.
    /// </summary>
    /// <param name="n">The maximum number [1, infinity] to print to</param>
    private void PrintFizzBuzz(int n)
    {
        if (n < 1)
        {
            Debug.Log("int n in fizzBuzz.PrintFizzBuzz(int) must be >= 1");
            return;
        }
        for (int i = 1; i <= n; i++)
        {
            if (i % (3 * 5) == 0)
            {
                Debug.Log(FIZZ_BUZZ);
            }
            else if (i % 3 == 0)
            {
                Debug.Log(FIZZ);
            }
            else if (i % 5 == 0)
            {
                Debug.Log(BUZZ);
            }
            else
            {
                Debug.Log(i);
            }
        }
    }
}


texts:
After some 'digging' into the dark corners of legacy code I've found class, which handles INI files. It does reading and writing to the file, but I haven't found any exception handling logic. What kind of potential problems, if any, can you detect and what is your suggestion/advise for improving the code, based on these three C++ code snippets:

Constructor

IniValue::IniValue(const char* FileName, const char* Section, const char* Entry, int sz, PersistMediumEnum medium_, int iniprofileId_)
:filename(NULL)
,section(new char[strlen(Section)+1])
,entry(new char[strlen(Entry)+1])
,buffer(new char[sz])
,bufsiz(sz)
{
  if (FileName == NULL) {
    FileName = "somefile.ini";
  }

  // 'GetFullInifileName' calls windows functions 'GetEnvironmentVariable', 'CreateDirectory', 'CopyFile', 'DeleteFile'
  std::string fullname = GetFullInifileName(FileName);

  filename = new char[fullname.length()+1]; strcpy(filename, fullname.c_str());

    strcpy(section, Section);
    strcpy(entry, Entry);
    buffer[0] = 0;
}

Some function, which reads values from the file:

void IniValue::TheGetProfileString() {
    char* defstr = new char[bufsiz];
    strncpy(defstr, buffer, bufsiz);

  IniPersistIF* inf = IniPersistIF::get(medium);

  //calls windows 'GetPrivateProfileString'
  inf->Read(section, entry, defstr, buffer, bufsiz, filename, iniprofileId);
  delete [] defstr;
}

Destructor

IniValue::~IniValue() {
  IniValue* thys = this;

  assert(section[0] != '\0');
  assert(filename[0] != '\0');

  IniPersistIF* inf = IniPersistIF::get(medium);
  assert(inf != NULL);

  assert(section[0] != '\0');
  assert(filename[0] != '\0');

  // Calls Windows 'WritePrivateProfileString' function
  inf->Write(section, entry, buffer, filename, iniprofileId, defaultval, bModified);

  delete [] buffer;
  delete [] entry;
  delete [] section;
  delete [] filename;
}


texts: Instance of one class to contain arbitrary number of instances of another class in Python

texts:
I'm trying to see if there is a better way to design this. I have a class Animal that is inherited by Male and Female classes (Female class has an additional attribute). I also have a class called Habitat, an instance of each would contain any number of Animals including 0.

class Animal:

    def __init__(self, life_span=20, age=0):
        self.__life_span = life_span
        self.__age = age

    def get_life_span(self):
        return self.__life_span

    def get_age(self):
        return self.__age

    def age(self):
        self.__age += 1

class Female(Animal):

    __gender = 'female'

    def __init__(self, pregnant=False):
        self.__pregnant = pregnant

    def impregnate(self):
        self.__pregnant = True

class Male(Animal):

    __gender = 'male'

class Habitat:

    def __init__(self, list_of_animals=[Male(), Female()]):
        self.__list_of_animals = list_of_animals

    def __add_male(self):
        self.__list_of_animals.append(Male())

    def __add_female(self):
        self.__list_of_animals.append(Female())

    def add_animal(self):
        if random.choice('mf') == 'm':
            self.__add_male()
        else:
            self.__add_female()

    def get_population(self):
        return self.__list_of_animals.__len__()

Before I add any more functionality, I would like to find out if that's a proper way to design these classes. Maybe there is a design pattern I can use? I'm new to OOP, any other comments/suggestions are appreciated.


texts:
The problem is adding two lists as numbers L1 = [1,9,9] and  L2 = [0,9,9]:

?- sum([1,9,9],[0,9,9], Lo).
Lo = [2,9,8]

But I also wanted to add this:

?- sum([8,1,9],[1,8,2],Lo).
Lo = [1, 0, 0, 1].

I used the backtracking method I've learned:

link([],L,L).
link([Head|Tale],L2,L3):- link(Tale,L2,L), L3=[Head|L].

inve([],[]):-!.
inve([X|Xs],L):- inve(Xs,L2), link(L2,[X],L).

sum(L1,L2,L3):- inve(L1,LI1),inve(L2,LI2), sumID(LI1,LI2,L), inve(L,[Li|LIs]),
                     Li > 9, Li2 is Li-10 , L3 = [1,Li2|LIs] ,!.
sum(L1,L2,L3):- inve(L1,LI1),inve(L2,LI2), sumID(LI1,LI2,L), inve(L,L3),!.

sumID([],[],[]):- !.
sumID([X|[Xs|Xss]],[Y|Ys],[L|Ls] ):- XY is X+Y , XY > 9 , Head is XY - 10,
                                  L = Head, Xs1 is Xs + 1,
                              sumID([Xs1|Xss], Ys, LTail) ,Ls = LTail,!.

sumID([X|Xs],[Y|Ys],[L|Ls]):- L is X+Y, sumID(Xs,Ys,LTail),
                           Ls = LTail.

A friend told me to invest list and add from *Left to Right*, and later invest the final list. How can I improve this solution in order not to be so long? I'd appreciate a better idea to solve this problem, too. I made it in more than 2 hours and in the exam this is supposed to be in 20min.


texts: Generate consecutive sentence of int values accessed from different threads

texts:
I need to generate a sequence of int values: { 0, 1, 2, ... }, but there's a twist: I need to access them from different threads.

So I wrote this code:

class Counter
{
    private static Counter instance = new Counter();
    private static int i = 0;

    public static Counter Instance
    {
        get
        {
            return instance;
        }
    }

    public int Next()
    {
        lock (this)
        {
            return i++;
        }
    }

    public void Reset()
    {
        lock (this)
        {
            i = 0;
        }
    }

}

May this be implemented in a simpler way?


texts:
I created event delegation like concept which is present in jQuery. AFAIK, event delegation is used to register an event for an element which is supposed to be added dynamically. So, in jQuery we do the following:

$(document.body)
    .on('click', '.main', function(){ /* code here */ });
    .on('click', 'div.main', function(){ /* code here */ });
    .on('click', 'div#main.main', function(){ /* code here */ });
    .on('click', 'div#main.main[attr="1"]', function(){ /* code here */ });

So, instead of doing this event delegation in jQuery, I am doing using pure JavaScript. Here is my code:

var sb = (function () {
    var eventObject = {};
    document.body.addEventListener('click', function(e){
        console.dir(e.currentTarget);
        var el = e.target;
        var parent = el.parentElement;
        while(parent !== document.body){
            for(var item in eventObject){
                var elements = document.querySelectorAll(item);
                for(var i = 0, ilen = elements.length; i < ilen; i++){
                    if(el === elements[i]){
                        eventObject[item].call(el, e);
                        return;
                    }
                }
            }
            el = parent;
            parent = el.parentElement;
        }
    }, false);

    return {
        on: function(event, selector, callback){
            eventObject[selector] = callback;
            return sb;
        }
    }
})();

As you can see, in the above code, I have hard coded the click event (which is fine for now)

Now, I will use the above code like this:

sb
    .on('click', '.main', function(){ /* code here */ });
    .on('click', 'div.main', function(){ /* code here */ });
    .on('click', 'div#main.main', function(){ /* code here */ });
    .on('click', 'div#main.main[attr="1"]', function(){ /* code here */ });

This is working fine but I feel like I am overdoing things here in the above created plugin.


texts: Python Bingo game that stores card in a dictionary

texts:
I am super proud of this python bingo game I wrote. I am posting it here to make get some help reviewing it to make sure I'm using the best practices. This is for a class, and my professor is a stickler for using best practices. I went above and beyond what the assignment called for so I need a little more helping making sure the code is okay. Any help is appreciated!

Here is the code:

# Author: Helana Brock
# Homework 2, problem 3

import random

random_draw_list = random.sample(range(1, 76), 75)

def generate_card():
    """
    Generates a bingo card and stores the numbers in a dictionary.
    """
    card = {
        "B": [],
        "I": [],
        "N": [],
        "G": [],
        "O": [],
    }
    min = 1
    max = 15
    for letter in card:
        card[letter] = random.sample(range(min, max), 5)
        min += 15
        max += 15
        if letter == "N":
            card[letter][2] = "X" # free space!
    return card

def print_card(card):
    """
    Prints the bingo card.

    Arguments:
        card (dictionary): The card to be printed out.
    """
    for letter in card:
        print(letter, end="\t")
        for number in card[letter]:
            print(number, end="\t")
        print("\n")
    print("\n")

def draw(card, list):
    """
    Pops a number off a list of random numbers. Using the pop method ensures no duplicate
    numbers will be drawn.

    Arguments:
        card (dictionary): The card to to check for the number that was drawn.
        list (list): The list of random numbers to be drawn from.
    """
    number_drawn = random_draw_list.pop()
    for letter in card:
        i = 0
        for number in card[letter]:
            if number == number_drawn:
                card[letter][i] = "X"
            i += 1
    return number_drawn

def check_win(card):
    """
    First checks for diagonal wins, then four-corner, then horizontal, and finally, vertical.

    Arguments:
        card (dictionary): The card to check for a win.
    """
    win = False
    if card["B"][0] == "X" and card["I"][1] == "X" and card["N"][2] == "X" and card["G"][3] == "X" and card["O"][4] == "X":
        win = True
    elif card["O"][0] == "X" and card["G"][1] == "X" and card["N"][2] == "X" and card["I"][3] == "X" and card["B"][4] == "X":
        win = True
    elif card["B"][0] == "X" and card["O"][4] == "X" and card["B"][4] == "X" and card["O"][0] == "X":
        win = True
    for letter in card:
        if(len(set(card[letter]))==1):
            win = True
    for i in range(5):
        cnt = 0
        for letter in card:
            if card[letter][i] == "X":
                cnt += 1
        print(cnt)
        if cnt == 5:
            win = True
            break
    return win

def main():
    """
    Main method for the program. Generates a card, prints it, and loops through drawing
    and printing until the check_win method returns True or the user enters "quit".
    """
    print("Let's play bingo!")
    card = generate_card()

    print("\nHere is your card:\n")
    print_card(card)

    print("\nKeep pressing enter to continue or type quit to exit.\n")
    user_input = input()
    win = check_win(card)
    balls_till_win = 0

    while win == False and user_input != "quit":
        number_drawn = draw(card, random_draw_list)
        balls_till_win += 1

        print(f"\nNumber drawn: {number_drawn}.")
        print(f"Total balls drawn: {balls_till_win}.\n")
        print_card(card)

        win = check_win(card)

        user_input = input()
    if win == True:
        print(f"\nBingo! Total balls to win: {balls_till_win}.")
    else:
        print("Goodbye! Thanks for playing!")

main()


texts: Excel VBA script – concatenates multiple values using Loop

texts:
I have an Excel VBA script that concatenates five values: three static text strings, and values contained in two dynamic user-input ranges.  One of the ranges contains values that need to be concatenated repeatedly in the output, top to bottom, over and over, until the end of the data in the other range is reached.

So, given sample values:

  TextA: Alpha
  TextB: Gamma
  TextC: Delta

  LoopRange:

  AAA
  BBB
  CCC

  UserRange:

  111
  222
  333
  444
  555
  666
  777
  888

The output should be:

AlphaAAAGamma111Delta
AlphaBBBGamma222Delta
AlphaCCCGamma333Delta
AlphaAAAGamma444Delta
AlphaBBBGamma555Delta
AlphaCCCGamma666Delta
AlphaAAAGamma777Delta
AlphaBBBGamma888Delta

The script I've written works, but in a rather janky way.  It builds the output in stages — creating a new column of data, combining it with existing values, combining those results with remaining values until the output is achieved, then deleting the leftovers.

The enhancement I'm looking for is how to avoid the piecemeal process currently in place.  I'm thinking there's a way to nest the Loop inside a For statement but I haven't been able to figure it out.

Sample of the worksheet

Sub LoopAndConcat()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim TextA As String
Dim TextB As String
Dim TextC As String
Dim LoopRange As Range
Dim CellA As Long
Dim CopyRange As Range
Dim CellB As Range
Dim LastRow As Long
Dim CellC As Long

TextA = ActiveSheet.Cells(3, "A").Value
TextB = ActiveSheet.Cells(6, "A").Value
TextC = ActiveSheet.Cells(9, "A").Value

Set LoopRange = Range(ActiveSheet.Cells(12, "A"), ActiveSheet.Cells(Rows.Count, "A").End(xlUp))

Do
CellA = CellA + 1
LoopRange.Copy Range("E" & Rows.Count).End(xlUp)(2)
Loop Until CellA = 10

Set CopyRange = Range(ActiveSheet.Cells(2, "E"), ActiveSheet.Cells(Rows.Count, "E").End(xlUp))

For Each CellB In CopyRange
  If Not CellB.Offset(0, -3).Value = "" Then
    CellB.Offset(0, -2).Value = TextA & CellB.Value & TextB
  End If
Next CellB

LastRow = Range("B" & Rows.Count).End(xlUp).Row

For CellC = 2 To LastRow
ActiveSheet.Cells(CellC, "C").Value = ActiveSheet.Cells(CellC, "C").Value & _
                                      ActiveSheet.Cells(CellC, "B").Value & _
                                      TextC
Next CellC

CopyRange.ClearContents

Application.ScreenUpdating = True
Application.DisplayAlerts = True

If Not LoopRange Is Nothing Then Set LoopRange = Nothing
If Not CopyRange Is Nothing Then Set CopyRange = Nothing

End Sub


texts:
I am using this code in my controller and would like to know if this is good code to use or if I can write it better, or more compact, and so on. I am just trying to learn from this. It does work, so that is not my question.

public function search()
{
    $search     = Input::get('search');
    $result     = Categories::where('name', 'LIKE', '%'. $search .'%')->get();

    if ($result->first()) {

        $categories     = Categories::where('name', 'LIKE', '%'. $search .'%')->Paginate(Auth::user()->categories);

        Session::flash('alertMessage', 'The below results are filtered due to a search action!');

        return View::make('categories.index', compact('categories'));
    }
    else {

        $categories = Categories::orderBy('name', 'asc')->Paginate(Auth::user()->categories);

        Session::flash('alertMessage', 'Your search has returned 0 results from the database.');

        return View::make('categories.index', compact('categories'));
    }
}


texts:
Summary: Given a string find the number of anagramic pairs of substrings of it. e.g 'abba' pairs are [a,a],[b,b],[ab,ba],[abb,bba] so we have 4 pairs.

I'm wondering if anyone can help me improve my code so that it runs faster. My code passes all test cases when running locally, but times out on hackerrank. Any ideas ?

module.exports = (s = '') => {
    let count = 0
    let pairs = []
    for (let wordSize = 1; wordSize < s.length; wordSize++) {
        for (let wordPosition = 0; wordPosition < s.length; wordPosition++) {
            const letters = s.substr(wordPosition, wordSize)
            const wordKeys = letters.split('');
            pairs.push({ letters, keys: wordKeys, wordPosition })
        }
    }
    let pairIndexes = {}
    for (let i = 0; i < pairs.length; i++) {
        const word = pairs[i]
        pairs.forEach((value, index) => {
            if (word.wordPosition !== value.wordPosition && index !== i && value.keys.length === word.keys.length) {
                const wordSorted = word.keys.sort().join('')
                const valueSorted = value.keys.sort().join('')

                if (wordSorted !== valueSorted) return
                if (pairIndexes[wordSorted] === undefined) pairIndexes[wordSorted] = {}
                const pairKeyWord = `${word.wordPosition}-${value.wordPosition}`
                const pairValueWord = `${value.wordPosition}-${word.wordPosition}`
                if (pairIndexes[wordSorted][pairValueWord] === pairKeyWord) return
                pairIndexes[wordSorted][pairKeyWord] = pairValueWord
            }
        })
    }
    //console.log(pairs)
    //console.log(pairIndexes)
    for (const key in pairIndexes) {
        if (pairIndexes.hasOwnProperty(key)) {
            const pairs = pairIndexes[key];
            count += Object.keys(pairs).length
        }
    }
    return count
}

Test cases:

test('A - Given a string return pairs of anagrams', () => {
  const s = 'mom'
  const expected = 2
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('B - Given a string return pairs of anagrams', () => {
  const s = 'abba'
  const expected = 4
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('C - Given a string return pairs of anagrams', () => {
  const s = 'abcd'
  const expected = 0
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('D - Given a string return pairs of anagrams', () => {
  const s = 'ifailuhkqq'
  const expected = 3
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('E - Given a string return pairs of anagrams', () => {
  const s = 'kkkk'
  const expected = 10
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('F - Given a string return pairs of anagrams', () => {
  const s = 'cdcd' // c,c d,d cd,cd, cd,dc dc,cd
  const expected = 5
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('G - Given a string return pairs of anagrams', () => {
  const s = 'ifailuhkqqhucpoltgtyovarjsnrbfpvmupwjjjfiwwhrlkpekxxnebfrwibylcvkfealgonjkzwlyfhhkefuvgndgdnbelgruel'
  const expected = 399
  const result = anagrams(s)
  expect(result).toBe(expected)
})

test('H - Given a string return pairs of anagrams', () => {
  const s = 'gffryqktmwocejbxfidpjfgrrkpowoxwggxaknmltjcpazgtnakcfcogzatyskqjyorcftwxjrtgayvllutrjxpbzggjxbmxpnde'
  const expected = 471
  const result = anagrams(s)
  expect(result).toBe(expected)
})


texts: Python: count number of pairs in array(list)

texts:
A solution for a small algorithmic problem. I believe tests are pretty descriptive:

def pairs(n):
    return n * (n - 1) / 2

def solution(lst):
    res = 0
    stack = lst[0:1]
    lst = sorted(lst[1:])
    while(len(lst)):
        nxt = lst.pop()
        if len(stack) and stack[0] == nxt:
            stack.append(nxt)
        else:
            res += pairs(len(stack))
            stack = [nxt]
    else:
        res += pairs(len(stack))
    return res

assert(pairs(3) == 3)
assert(pairs(2) == 1)
assert(pairs(0) == 0)
assert(solution([5, 3, 1, 5, 5, 3]) == 4)
assert(solution([5, 5]) == 1)
assert(solution([5]) == 0)
assert(solution([]) == 0)

UPDATE: there is a bug. I shouldn't take a first element before sorting an array


texts:
I wrote a script to calculate document distance. It seems working but I couldn't be sure. (I tried for the small strings and it seems working) Also I am not sure that its fast enough for large texts.

Here is the Document Distance formula:

The frequency is the number of occurrences for each object. Such as for
"D1: be or not to be" the frequency will be freq$$(D_1) = {be=2, not=1, or=1, to=2}$$ and $$||D_1|| = \sqrt{2^2 + 1^2 + 1^2 + 2^2}$$

from math import sqrt
from string import ascii_lowercase

alphanumerics = ascii_lowercase + "0123456789"

file1 = open("document1.txt", "r")
file2 = open("document2.txt", "r")
print(file1)

document1 = ""
for line in file1:
    document1 += line + ""

document2 = ""
for line in file2:
    document2 += line + ""

if document1 == "":
    print("---  The document1.txt file is empty! ---")
    raise ValueError
elif document2 == "":
    print("---  The document2.txt file is empty!! ---")
    raise ValueError

print(document1, document2)

def word_processor(document):
    '''returns an array that only contains the words in the text'''
    doc_word = []
    word = ""
    count_space = 0
    for char in document.lower():
        if char in alphanumerics:
            word += char
            count_space = 0
        elif char == " " and count_space == 0:
            doc_word.append(word)
            word = ""
            count_space += 1
    doc_word.append(word)
    return doc_word

doc1_words = word_processor(document1)
doc2_words = word_processor(document2)

dot_product = 0
doc1_word_freq = {i: doc1_words.count(i)
                for i in doc1_words}  # the doc1 vector
doc2_word_freq = {i: doc2_words.count(i)
                for i in doc2_words}  # the doc2 vector
for key, value in doc1_word_freq.items():
    if key in doc2_word_freq.keys():
        dot_product += doc2_word_freq[key] * value # the dot product of the two doc vectors

doc1_mag = sqrt(sum([value**2 for value in doc1_word_freq.values()])) # the magnitude of the each document
doc2_mag = sqrt(sum([value**2 for value in doc2_word_freq.values()]))

similarity = dot_product / (doc1_mag * doc2_mag) * 100
print("The similarity between 2 document is", similarity, "percent")

Any ideas ?

I did not use the acos function since I don't think I need it.


texts: Xorgens4096 PRNG with global seeder in C#

texts:
This is a basic implementation of the non-cryptographic Xorgens4096 pseudo random number generator with a global, thread safe seeder. The goal is to provide a high quality generator that can be instantiated in multiple threads while still guaranteeing that the seed for each generator is unique. To ensure uniqueness of each generator's state, SHA512 is used in feedback mode (if that's the right word).

Is this the right approach? Any criticism and tips are very much appreciated.

using System;
using System.Diagnostics;
using System.Text;
using System.Security.Cryptography;

// big state non-cryptographic PRNG with a global seeder

class Xorgens4096
{
    // seeder part

    static private SHA512 sha512;

    static public byte[] hash;

    // set master seed using some common data for uniqueness

    static Xorgens4096()
    {
        sha512 = SHA512.Create();

        SetMasterSeed(String.Format("{0}-{1}-{2}",
            DateTime.UtcNow.Ticks,
            Process.GetCurrentProcess().Id,
            Guid.NewGuid()));
    }

    // set master seed used to derive states of all generator instances

    static public void SetMasterSeed(string seed)
    {
        hash = Encoding.Unicode.GetBytes(seed);
    }

    // create generator state using a seed or master seed (thread safe)

    static private void Seed(string seed, ulong[] state)
    {
        lock (hash)
        {
            if (String.IsNullOrEmpty(seed) == false)
                hash = Encoding.Unicode.GetBytes(seed);

            for (int i = 0; i < 8; i++)
            {
                hash = sha512.ComputeHash(hash);
                Buffer.BlockCopy(hash, 0, state, i * 64, 64);
            }
        }
    }

    // generator part

    public ulong[] state = new ulong[64];
    public ulong index;
    public ulong weyl;

    public Xorgens4096(string seed = "")
    {
        Seed(seed);
    }

    public void Seed(string seed)
    {
        Seed(seed, state);
        index = 0;
        weyl = 0;
    }

    // actual xorgens4096 generator

    public ulong Gen()
    {
        ulong t = state[index = (index + 1) & 63];
        t ^= t << 33;
        t ^= t >> 26;

        ulong v = state[(index + 11) & 63];
        v ^= v << 27;
        v ^= v >> 29;

        state[index] = (v ^= t);

        weyl += 0x61c8864680b583eb;

        return v + (weyl ^ (weyl >> 27));
    }
}


texts: Spliting PDF and get thumbnail while adding it to a ListView

texts:
I'm doing a application to work with PDF and TIFF files.
To divide them, the user opens the file or folder (if it is a folder, it gets all the files inside) and the app splits the file, getting a tiny image (thumbnail) in JPG format. Then it creates a ListViewItem adding the thumbnail, the name and the size of the file.

But it takes too long (1:40min) with a PDF with 68 pages, so if a larger PDF is opened, it will take too long.

So I wish someone could say where can I improve my code so it doesn't take that long.

CODE

public void SplitPDF2(string input)
{
    try
    {
        iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(input);
        iTextSharp.text.pdf.PdfReader.unethicalreading = true;
        string name = Path.GetFileNameWithoutExtension(input);
        for (int i = 1; i <= reader.NumberOfPages; i++)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //get thumbnail from 1st page-----------------------------------------------------
                using (var document = PdfiumViewer.PdfDocument.Load(input))
                {
                    var image = document.Render(i - 1, 60, 84, 300, 300, true);
                    image.Save(ms, ImageFormat.Jpeg);
                    thumbnails.Images.Add(j.ToString(), image);
                    image.Dispose();
                }
                //split pdf-----------------------------------------------------------------------
                string p = AppDomain.CurrentDomain.BaseDirectory + "temporario\\" + name + " - Pagina " + i + ".PDF";
                using (Stream outputStream = new FileStream(p, FileMode.Create))
                {
                    Document doc = new Document();
                    PdfWriter pdfWriter = PdfWriter.GetInstance(doc, outputStream);
                    doc.Open();
                    PdfContentByte pdfContentByte = pdfWriter.DirectContent;
                    PdfImportedPage importedpage = pdfWriter.GetImportedPage(reader, i);
                    iTextSharp.text.Rectangle mediabox = reader.GetPageSize(i);

                    doc.SetPageSize(mediabox);
                    doc.NewPage();
                    pdfContentByte.AddTemplate(importedpage, 0, 0);

                    doc.Close();
                    doc.Dispose();
                    pdfWriter.Dispose();
                }
                //in the end it will add the thumbnail, the name and the size of the file to the ListView
                FileInfo f = new FileInfo(p);
                ListViewItem _item1 = new ListViewItem();
                _item1.ImageKey = j.ToString(); //image
                _item1.SubItems.Add(name + " - Pagina " + i + ".PDF"); //name
                _item1.SubItems.Add(f.Length.ToString()); //size

                lista2.Items.Add(_item1);
                j++;
            }
        }
        reader.Dispose();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString(), "Erro", MessageBoxButtons.OK);
    }
}


texts: First user login function: Security and efficency opinions

texts:
I am writing an application for work. This application will sit on a closed network but I still have to be concerned about security. There will be a maximum of three types of user for this application: User (read only), admin (data edits only) and super admin (access all areas). But at the moment I am trying to get a feel for security on a basic level.

Just so I am clear about the user options: I meant that only 3 people will be permitted to use the application. So, there will only ever be ONE basic "User" and not a number of basic users.

Would one of you kind people please look at the following code to review its efficiency and security with the possibility of offering some tips on improvement.

function loginUser($username, $password)
{

    include('assets/con.php');

    /* Set the salt. */
    $salt = 'JwethYGkuuygTYFIYTFrfkuyGUTf75kUY4uyk6';

    /* Apply SHA512 password and salt encryption. */
    $password = hash('SHA512', $password);
    $salt = hash('SHA512', $salt);

    $query = 'SELECT username FROM users WHERE username = ? AND password = ? AND pass_salt = ?';
    if( $statement = $con->prepare($query) )
    {
        $statement -> bind_param( 'sss', $username, $password, $salt );
        $statement -> execute();
        $statement -> store_result();
        $num_row = $statement -> num_rows;
        $statement -> bind_result($username);
        $statement -> fetch();
        $statement -> close();
    }

    else die( "Failed to prepare query." );

    if( $num_row === 1 )
    {
        $_SESSION['userName'] = $username;
        return true;
    }
    return false;
}


texts: Factory that chooses between factories based on XML element name

texts:
I have an implementation of a factory like so:

public class CommandActionFactory : IFactory<ICommandAction, XElement>
{
    private readonly IDictionary<string, IFactory<ICommandAction, XElement>> commandActionFactories;

    public IDictionary<string, IFactory<ICommandAction, XElement>> CommandActionFactories
    {
        get
        {
            return commandActionFactories;
        }
    }

    public CommandActionFactory(IDictionary<string, IFactory<ICommandAction, XElement>> factories)
    {
        if (factories == null)
        {
            throw new ArgumentNullException("factories");
        }

        this.commandActionFactories = factories;
    }

    public ICommandAction Create(XElement parameter)
    {
        if (parameter == null)
        {
            throw new ArgumentNullException("parameter");
        }

        return CommandActionFactories[parameter.Name.LocalName].Create(parameter);
    }
}

This factory picks between factories of the same type, based on the name of the root XML element passed to it. This means I can have bespoke factories for different XML structures, while still referring to only one top-level factory.

FXCop flags the constructor and public getter with the following warning:

  CA1006    Do not nest generic types in member signatures.

So I tried simplifying the generic type as follows:

public interface IXmlCommandActionFactory : IFactory<ICommandAction, XElement>
{
}

public class CommandActionFactory : IXmlCommandActionFactory
{
    private readonly IDictionary<string, IXmlCommandActionFactory> commandActionFactories;

    public IDictionary<string, IXmlCommandActionFactory> CommandActionFactories
    {
        get
        {
            return commandActionFactories;
        }
    }

    public CommandActionFactory(IDictionary<string, IXmlCommandActionFactory> factories)
    {
        if (factories == null)
        {
            throw new ArgumentNullException("factories");
        }

        this.commandActionFactories = factories;
    }

    public ICommandAction Create(XElement parameter)
    {
        if (parameter == null)
        {
            throw new ArgumentNullException("parameter");
        }

        return CommandActionFactories[parameter.Name.LocalName].Create(parameter);
    }
}

However I'm wondering whether, while it makes the issue go away, the new solution is actually hampering readability by hiding the expected type behind another interface.

Which do you think is more readable? This is intended to be a public API.


texts: Get top of request given the file exists in Node.js application

texts:
The user can specify which source to get the list, if the file is not found then Boom returns 404. After that, the found source will fetch the top list and append source, query and data in the response. It's simple as that. I'm just wondering if this code is clean enough to the industry standard.

This application is written in Hapi and using Boom. My code is really simple but I figure there must be something I can do to make it simpler.

  handleRequest: function handleRequest(request, reply) {
    var source = request.params.source;
    var handler;
    try {
      handler = require('../services/' + source);
    } catch (err) {
      err.message = 'Unknown Resource: ' + source;
      return reply(Boom.notFound('Source unknown', err));
    }

    handler.getTopList(request)
    .then(function thenFunc(obj) {
      var response = {};
      if (source) {
        response.source = source;
      }
      if (obj.query) {
        response.query = obj.query;
      }
      response.data = obj.list;
      reply(response);
    })
    .catch(function catchFunc(topErr) {
      return reply(Boom.create(500, 'Error', {message: topErr}));
    });
  },


texts:
I have an imperative programming background and I've decided to study functional programming by applying it to problems found on sites such as Project Euler and Rosalind. My language of choice is Scheme (I use CHICKEN). As can be seen, I'm only starting out.

This is about the 3rd problem found on Rosalind, that goes like this:

  In DNA strings, symbols 'A' and 'T' are complements of each other, as
  are 'C' and 'G'.

  The reverse complement of a DNA string s is the string sc formed by
  reversing the symbols of s, then taking the complement of each symbol
  (e.g., the reverse complement of "GTCA" is "TGAC").

  Given: A DNA string s of length at most 1000 bp.

  Return: The reverse complement sc of s.

Here's my code, which solves the problem:

(define (complement-of char)
  (cond
    ((eq? char #\A)
     #\T)
    ((eq? char #\T)
     #\A)
    ((eq? char #\C)
     #\G)
    ((eq? char #\G)
     #\C)
    (else
      char)))

(define (apply-complements dna-string)
  (reverse-list->string
    (map complement-of
     (string->list dna-string))))

(define (solve-problem infile-name outfile-name)
  (let ((outfile-port (open-output-file outfile-name))
        (infile-port (open-input-file infile-name)))
    (begin
      (write-line
         (apply-complements (read-line infile-port)) outfile-port)
      (close-output-port outfile-port))))

Is there a nicer way to write complement-of? Perhaps something like a dictionary, or would that be too much work in this particular case?

Is solve-problem there appropriate from a style POV, or is this more appropriate?

(define (solve-problem infile-name outfile-name)
  (let ((outfile-port (open-output-file outfile-name))
        (infile-port (open-input-file infile-name)))
    (begin
      (write-line
         (apply-complements
           (read-line infile-port))
         outfile-port)
      (close-output-port outfile-port))))

Also, is there a way to avoid using begin and still make things look readable? The only idea that comes to mind is extracting a function and through recursion decide whether or not it writes to the file, or closes it. But that feels hardly intuitive.

Finally, I'd like to hear of any other issues my code has.


texts: Conversion helper with support for enumerations and Nullable

texts:
I recently wrote this code as a more versatile stand-in for Convert.ChangeType. I have a nagging feeling that there's something I might be overlooking, or that there might be a more efficient algorithm for this.

    /// <summary>
    ///     Returns an object of type <typeparamref name="T"/> whose value is equivalent to that of the specified
    ///     object.
    /// </summary>
    /// <typeparam name="T">
    ///     The output type.
    /// </typeparam>
    /// <param name="value">
    ///     An object that implements <see cref="IConvertible"/> or is <see cref="Nullable{T}"/> where the underlying
    ///     type implements <see cref="IConvertible"/>.
    /// </param>
    /// <returns>
    ///     An object whose type is <typeparamref name="T"/> and whose value is equivalent to <paramref name="value"/>.
    /// </returns>
    /// <exception cref="System.ArgumentException">
    ///     The specified value is not defined by the enumeration (when <typeparamref name="T"/> is an enum, or Nullable{T}
    ///     where the underlying type is an enum).
    /// </exception>
    /// <exception cref="System.InvalidCastException"
    /// <remarks>
    ///     This method works similarly to <see cref="Convert.ChangeType(object, Type)"/> with the addition of support
    ///     for enumerations and <see cref="Nullable{T}"/> where the underlying type is <see cref="IConvertible"/>.
    /// </remarks>
    internal static T ChangeType<T>(object value) {

        Type type = typeof(T);
        Type underlyingNullableType = Nullable.GetUnderlyingType(type);

        if ((underlyingNullableType ?? type).IsEnum) {

            // The specified type is an enum or Nullable{T} where T is an enum.

            T convertedEnum = (T)Enum.ToObject(underlyingNullableType ?? type, value);

            if (!Enum.IsDefined(underlyingNullableType ?? type, convertedEnum)) {
                throw new ArgumentException("The specified value is not defined by the enumeration.", "value");
            }

            return convertedEnum;
        } else if (type.IsValueType && underlyingNullableType == null) {

            // The specified type is a non-nullable value type.

            if (value == null || DBNull.Value.Equals(value)) {
                throw new InvalidCastException("Cannot convert a null value to a non-nullable type.");
            }

            return (T)Convert.ChangeType(value, type);
        }

        // The specified type is a reference type or Nullable{T} where T is not an enum.
        return (value == null || DBNull.Value.Equals(value)) ? default(T) : (T)Convert.ChangeType(value, underlyingNullableType ?? type);
    }


texts: Making a selection in a dropdown based on several possible values

texts:
I'm making a Chrome extension that lets you choose a size of an item and check out quickly.

I have a value called "Large" in sizePref array in my chrome.storage. And when it calls that value, it will choose an option in a dropdown based on that. However, possible labels are "Large", "L", "M/L" or "L/XL" ("Large" being the most often) with the  value changing each time.

What is the most efficient way for me to ensure that it makes the correct selection (assuming the speed of doing so is the highest priority)?

This is my current code which just chooses "L" if "Large" doesn't exist. This code works without errors, but I want it to be improved.

chrome.storage.sync.get('sizePref', function(items) { // Get size preferences from storage
        var sizePref = items.sizePref.top1; // Set size to a var

        var sizeVal = $("#size option").filter(function() {
            return $(this).html() == sizePref;
        }).val();

        var sizeVal2 = $("#size option").filter(function() {
            return $(this).html() == "L";
        }).val();

        if (sizeVal !== undefined) {
            $("#size").val(sizeVal);
        } else {
            $("#size").val(sizeVal2);
        }

    });

The targeted dropdown code is as follows:

<select id="size" name="size"><option value="25243">Small</option>
<option value="25244">Medium</option>
<option value="25245">Large</option>
<option value="25246">XLarge</option></select>


texts: Read Data from a serial port and write to influxdb

texts:
I have a energy meter which sends the kWh count periodically every few seconds via a serial port.
To store this data I write the counter value and the calculated average power of the last 10s in a influxdb measurment.
To calculate the power i use a loop that compares the current counter value with the one 10s ago. To avoid that the loop is interrupted by reading the serial interface or sending the data via http i use serial_asyncio and aiohttp.
I am pretty new to Python and got my script running by doing serveral asyncio tutorials, so i am not sure if i mixed some old and new syntax.
The script is working, but I am not happy with a few things.

Is there a better way to pass the counter value from the serial data_received function to my calc_delta function without the use of global?

Am I using asyncio properly? I found different examples using asyncio.ensure_future() or loop.run_until_complete().

Is the overall structure okay, what could i have done better?

import aiohttp
import asyncio
from datetime import datetime
import serial_asyncio
import serial
import time

value = None
last_value = 0
token = "myInfluxdbToken"

class Input(asyncio.Protocol):
    data_buffer = ""

    def connection_made(self, transport):
        self.transport = transport
        print("port opened", transport)

    def data_received(self, data):
        global value

        self.data_buffer += data.decode("utf-8")
        # find counter value in received string
        if "eHZ" in self.data_buffer:
            data_tmp = self.data_buffer.replace("\r\n", "")
            value_str = data_tmp.partition("1.8.1*255(")[2][:11]

            if len(value_str) == 11:
                value = float(value_str)
                print(str(value))
                asyncio.ensure_future(send_data(value, "counter"))
            # Reset the data_buffer!
            self.data_buffer = ""

async def calc_delta():
    global value, last_value
    # calculate counter delta
    while True:
        delta = 0
        print(value)
        if value:
            delta = value - last_value
            last_value = value
        # 10s * 3600s/h * 1000W  Calculates Avg Power of last 10s from kWh delta
        deltaW = delta / 10 * 3600 * 1000
        if deltaW < 50000:
            await send_data(deltaW, "deltaW")
            print(time.perf_counter(), deltaW)
        else:
            print(time.perf_counter(), "data invalid")

        await asyncio.sleep(10)

async def send_data(data, tag):
    async with aiohttp.ClientSession() as session:
        async with session.post(
            "http://localhost:8086/api/v2/write?org=my_org&bucket=testdata&precision=s",
            data=f"ehzdata,type={tag} value={data}",
            headers={"Authorization": f"Token {token}"},
        ) as response:
            print("Status:", response.status)

loop = asyncio.get_event_loop()
serial_coro = serial_asyncio.create_serial_connection(
    loop, Input, "/dev/ttyUSB0", baudrate=9600, parity=serial.PARITY_EVEN, bytesize=7
)
counter_coro = calc_delta()
asyncio.ensure_future(serial_coro)
loop.run_until_complete(counter_coro)
loop.run_forever()
loop.close()


texts:
This seems to work, but for some reason I'm not entirely sure about it.

Can anyone point out any issues with this simple pub/sub library?
Thank you!

(function (undefined) {
    window.mylib = $.extend(window.mylib, (function () {

        var subscriptionsBag = function() {
            var self = this;
            self.count = -1;
            self.handlers = {};

            var cancel = function(index) {
                var self = this;
                delete self.handlers[index];
            };

            self.add = function (fn) {
                if (typeof(fn) !== "function") {
                    throw new Error("function expected.");
                }

                var index = ++self.count;
                self.handlers[self.count] = fn;

                return {
                    cancel: cancel.bind(self, index)
                };
            };

            self.fire = function(obj) {
                for (var handlerKey in self.handlers) {
                    if (!self.handlers.hasOwnProperty(handlerKey)) {
                        continue;
                    }
                    var handler = self.handlers[handlerKey];
                    if (!handler) continue;
                    handler(obj);
                }
            };
        };

        var subscriptions = {
            "": {}
        };

        var publish = function(e, obj) {
            var evt = "@" + e;
            var subs = subscriptions[evt];
            if (!subs) return;

            subs.fire(obj);
        };

        var subscribeTo = function (e, fn) {
            var evt = "@" + e;
            var subs = subscriptions[evt] = (subscriptions[evt] || new subscriptionsBag());
            return subs.add(fn);
        };

        var events = {
            publish: publish,
            subscribeTo: subscribeTo
        };

        return {
            events: events
        };
    })());
})();


texts: Dijkstra's shortest-path algorithm implemented via Priority Queues and an adjacency matrix represented graph

texts:
My adjacency matrix looks like this, where non-zero weights denote edges.
[0, 2, 0, 0, 3]
[2, 0, 2, 4, 0]
[0, 2, 0, 3, 0]
[0, 4, 3, 0, 1]
[3, 0, 0, 1, 0]
Here's my attempt, would appreciate a code review.

private static class Edge implements Comparable<Edge> {
    private int source;
    private int destination;
    private int weight;

    public Edge(int source, int destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;
    }

    public String toString() {
        return source + "---" + weight + "---" + destination;
    }

    @Override
    public int compareTo(Edge other) {
        return Integer.compare(this.weight, other.weight);
    }

    @Override
    public boolean equals(Object other) {
    if (other instanceof WeightedGraphMatrix.Edge) {
            return equals((WeightedGraphMatrix.Edge)other);
        }
        return false;
    }

    private boolean equals(Edge other) {
        return other.destination == this.destination;
    }

    @Override // Uses only the destination to calculate hash for the purposes of maintaining the visited hashset.
    public int hashCode() {
        int hash = 17;
        int hashMultiplikator = 79;
        return hash * hashMultiplikator * destination;
    }
}

public static void printDijkstras(int [][] graph, int source) {
    // Prints shortest distances to all nodes from the source.
    System.out.println(Arrays.toString(Dijkstras(graph, source)));
}

public static int[] Dijkstras(int [][] graph, int source) {
    // Ideally should check matrix's validity to be square and symmetric but haven't done here since its pretty straightforward.

    int [] nodesVisited = new int [graph.length];
    Queue<Edge> edgeQueue = new PriorityQueue<>();
    int [] shortestDistance = new int[graph.length];
    Arrays.fill(shortestDistance, Integer.MAX_VALUE);

    // Start with the source vertex.
    int currentNode = source;
    shortestDistance[0] = 0;
    nodesVisited[0] = 1;

    do {
        for (int col = 0; col<graph[currentNode].length; col++) {
            // Take all edges from this node. Skip self & 0-weight edges
            if (col == currentNode || graph[currentNode][col] == 0) {
                continue;
            }
            edgeQueue.add(new Edge(currentNode, col, graph[currentNode][col]));

            // Update distance for this destination if better than existing.
            if (shortestDistance[col] > shortestDistance[currentNode] + graph[currentNode][col])
            {
                shortestDistance[col] = shortestDistance[currentNode] + graph[currentNode][col];
            }
        }

        //find cheapest edge to a not already visited destination.
        Edge edge = edgeQueue.remove();
        while (nodesVisited[edge.destination] == 1) {
            if (edgeQueue.isEmpty()) {
                return shortestDistance;
            }
            edge = edgeQueue.remove();
        }

        // Now that you've reached this edge as a destination, record it.
        currentNode = edge.destination;
        nodesVisited[edge.destination] = 1;
    } while (!edgeQueue.isEmpty());

    return edgesVisited;
}

Would also appreciate some help figuring out the runtime for my implementation and if it can be improved. For a Graph with V vertices and E edges, my outer loop runs V times, and the inner loop which iterates over each vertex's edges runs V times as well, leading to a runtime of V^2. The PQ remove call takes O(logE) time, so I think it ends up being O(V^2 + logE) which doesn't sound very efficient.


texts: Quicksort using Lomuto partition scheme in C

texts:
This is my implementation of the divide-and-conquer Quicksort algorithm using the Lomuto partition scheme in C. This is part of a personal project and I'm following Linus Torvalds's coding style.
void swap(int *i, int *j)
{
    int tmp = *i;
    *i = *j;
    *j = tmp;
}

int partition(int *arr, int l, int r)
{
    int pivot = arr[r];
    int i = l;
    for (int j = l; j < r; ++j) {
        if (arr[j] < pivot) {
            swap(&arr[i], &arr[j]);
            ++i;
        }
    }
    swap(&arr[i], &arr[r]);
    return i;
}

void quicksort(int *arr, int l, int r)
{
    if (l >= r)
        return;

    int i = partition(arr, l, r);

    quicksort(arr, l, i - 1);
    quicksort(arr, i + 1, r);
}

The function void quicksort(int *arr, int l, int r) can be called like this:
int arr[] = {4, 1, 0, 2, 5, 3, 8, 9, 7, 6};
size_t arrlen = sizeof(arr) / sizeof(int);
quicksort(arr, 0, arrlen - 1);


texts: Using a custom comparison function for BTreeSet and a foreign type

texts:
As detailed in this SO question, I'm using custom logic in a BTreeSet to automatically sort a foreign data type as elements are added to the container.  Note that the Data type is used from another module in the actual implementation, so I can't just implement Ord for it, necessitating this approach.

I'm concerned that the iterator pipeline I'm using in main() is too complex and that the various impls are just boilerplate for something that really boils down to a single line of actual desired logic.

Here's a Rust Playground link.

use std::collections::BTreeSet;
use std::convert::{From, Into};
use std::cmp::Ordering;
use std::ops::Deref;

// Here's the original struct...
#[derive(PartialEq, Eq, Clone, Copy, Debug)]
struct Data(usize);

impl From<usize> for Data {
    fn from(i: usize) -> Self {
        Data(i)
    }
}

// And here's the wrapper type we'll use to sort it.
#[derive(PartialEq, Eq, Debug)]
struct SortableData(Data);

impl Deref for SortableData {
    type Target = Data;
    fn deref<'a>(&'a self) -> &'a Data {
        &self.0
    }
}

impl From<Data> for SortableData {
    fn from(data: Data) -> Self {
        SortableData(data)
    }
}

impl PartialOrd for SortableData {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for SortableData {
    fn cmp(&self, other: &Self) -> Ordering {
        (self.0).0.cmp(&(other.0).0)
    }
}

fn main() {
    let source: [Data; 3] = [Data(9), Data(4), Data(2)];
    let sorted: BTreeSet<SortableData> = source.iter().cloned().map(|i| i.into()).collect();
    for d in sorted.iter() {
        println!("{:?}", **d);
    }
}


texts:
I learned code about a week ago and I wanna hear some recommendations and stuff I could add to my code. This is a fight system I made for my text based game. Please tell me what I could do better.

import random
import time
import sys
def fight_snake():
    fdmg1 = int(random.randint(1,7))
    edmg1 = int(random.randint(1,6))
    print("You hit a", fdmg1)
    print("The Snake hits a", edmg1)
    time.sleep(1)
    if edmg1 > fdmg1:
        print("You died")
    elif edmg1 < fdmg1:
        print("You killed the Snake")
    else:
        print("You didnt kill the Snake but you managed to escape")

def fight_enemy_a():
    fdmg1 = int(random.randint(1,7))
    edmg_a = int(random.randint(4,10))
    print("You hit a", fdmg1)
    print("The Enemy hits a", edmg_a)
    time.sleep(1)
    if edmg_a > fdmg1:
        print("You died")
    elif edmg_a < fdmg1:
        print("You killed the Enemy")
    else:
        print("You didnt kill the Enemy but you managed to escape")

def fight_enemy_b():
    fdmg1 = int(random.randint(1,7))
    edmg_b = int(random.randint(4,9))
    print("You hit a", fdmg1)
    print("The Enemy hits a", edmg_b)
    time.sleep(1)
    if edmg_b > fdmg1:
        print("You died")
    elif edmg_b < fdmg1:
        print("You killed the Enemy")
    else:
        print("You didnt kill the Enemy but you managed to escape")

def fight_enemy_c():
    fdmg1 = int(random.randint(1,7))
    edmg_c = int(random.randint(1,7))
    print("You hit a", fdmg1)
    print("The Enemy hits a", edmg_c)
    time.sleep(1)
    if edmg_c > fdmg1:
        print("You died")
    elif edmg_c < fdmg1:
        print("You killed the Enemy")
    else:
        print("You didnt kill the Enemy but you managed to escape")


texts:
So I'm currently using python to unscramble words that are retrieved from an OCR program (pytesseract).

The current code I am using to unscramble words is this:

import numpy as nm
import pytesseract
import cv2
import ctypes
from PIL import ImageGrab

def imToString():

    # Path of tesseract executable
    pytesseract.pytesseract.tesseract_cmd =r'C:\Program Files (x86)\Tesseract-OCR\tesseract'
    while(True):

        # ImageGrab-To capture the screen image in a loop.
        # Bbox used to capture a specific area.
        cap = ImageGrab.grab(bbox =(687, 224, 1104, 240))

        # Converted the image to monochrome for it to be easily
        # read by the OCR and obtained the output String.
        tesstr = pytesseract.image_to_string(
                cv2.cvtColor(nm.array(cap), cv2.COLOR_BGR2GRAY),
                lang ='eng')
        checkWord(tesstr)

def checkWord(tesstr):

    dictionary =['orange', 'marshmellow']

    scrambled = tesstr
    for word in dictionary:
        if sorted(word) == sorted(scrambled):
            print(word)

imToString()

I wanna know if there is anyway to reduce the time it takes to:

Scan/Process the image.
Look through the 'dictionary', as there are many more words to go through. Or another more efficient alternative.

Thanks


texts:
Here is a class that I made to validate forms data.  I will really appreciate any criticism and hints.

  <?php

class formvalidator {

    public $filtered, $errors,$db,
    $fields_type = Array(), $error_msgs = Array();

    public function validate($form, $fields, $error_msgs) {

        $this->fields_type = $fields;
        $this->error_msgs = $error_msgs;

        foreach ($form as $field => $data) {

            if (isset($this->fields_type[$field])) {
                if (method_exists($this, $this->fields_type[$field])) {
                    $_POST[$field] = call_user_func_array(array($this, $this->fields_type[$field]), array($data));

                    if ($_POST[$field] === false) {
                        $this->errors[$field] = sprintf($this->error_msgs[$field], $data);
                     }
                }
            } else {//Else ? unset it Security ?
                unset($_POST[$field]);
            }
        }

        //Manual validation for password and password confirmation
        if($_POST['form'] == 'signup' or $_POST['form'] == 'login')
        if (!isset($_POST['password'])) {
            $this->errors[$field] = sprintf($this->error_msgs['password'], '');
        }
        if (isset($_POST['repassword']) and $_POST['password'] != $_POST['repassword']) {
            $this->errors[$field] = sprintf($this->error_msgs['repassword'], '');
        }
        //End of password confirmation and password check.

        //
        $_POST = $this->clean($_POST);

        if (is_null($this->errors)) {
            return true;
        } else {

            return false;
        }
    }

    public function value_calss($input) {
        if (isset($_POST[$input])) {
            if (isset($this->errors[$input])) {
                echo ' error ';
            } else {
                echo '" value = "' . $_POST[$input];
            }
        }
    }

    public function errors() {

        if (!is_null($this->errors)) {
            echo '

Please Fix these:

';
            foreach ($this->errors as $error)
                echo "
$error
";
            echo '

';
        }
    }

    public function setError($error) {
        $this->errors[] = $error;
    }

    //Validations

    public function IsEmail($email) {
        return filter_var($email, FILTER_VALIDATE_EMAIL);
    }

    public function IsAlphaNum($str) {
        if (ctype_alnum($str))
            return trim($str);
        else
            return false;
    }

    public function IsString($str) {
        if (preg_match("/^[A-Za-z0-9\s]+[^ ]$/", $str))
            return trim($str);
        else
            return false;
    }

//Explite will return false on empty values which will cause raise error flag.
    public function explite($input) {
        return trim($input);
    }

    public function text($input){
        return trim(htmlentities($input));
    }

    public function IsDate($is_date){
        if(strtotime($is_date))
            return date("Y-m-d",strtotime($is_date));
        else
            return false;
    }

    public function file($input)
    {
        return $input;
    }

    public function boolen($input)
    {
        if($input)
            return true;
        else false;
    }

    public function clean($input) {
        $clean = Array();
        foreach ($input as $field => $data) {
            $clean[$field] = mysql_real_escape_string($data);
        }
        return $clean;
    }

}

?>

Update: New Version on gist