texts: Abstracting device IO / glue logic in a CPU emulator

texts:
In my Motorola 6809 CPU emulator (written in C++14) I'm working on an abstraction to represent the wiring between emulated devices, such as the ports on a 6522 VIA, or the interrupt lines connecting a peripheral to the CPU.
The abstraction uses functional composition.  Each OutputPin encapsulates a developer-supplied function that returns the current state of that output.  InputPin objects belonging to a different device have a copy of the OutputPin to which they are attached.  Each InputPin may only be attached to a single OutputPin, but an OutputPin may be attached to multiple InputPins.
This abstraction is working, and allows for expressive and powerful constructions like this, which does a "wired-and" of three IRQ lines (where one of them is active-high) and attaches it to the CPU's IRQ input and each time the state of that line is tested the composed functions generate the correct result based on the current state of the three inputs:
cpu.IRQ << (!fdc.DIRQ & via.IRQ & acia.IRQ);

and this, which generates an output signal that is the parity of 8 other outputs.
OutputPin parity = out[0] ^ out[1] ^ out[2] ^ out[3] ^ out[4] ^ out[5] ^ out[6] ^ out[7];

My concern, though, is performance.  I had hoped that compilers might be able to elide many of the function calls and collapse them into simpler expressions but initial tests with clang 12.0 on macOS don't appear to show any sign of this.
Is there anything I could be doing to improve the run-time efficiency, or am I hoping for too much from the compiler's optimiser?
Here's the complete implementation as a header with inline functions:
static inline bool default_true() {
        return true;
}

class OutputPin {

public:
        using Function = std::function<bool()>;

protected:
        Function        f = default_true;

public:
                        OutputPin() { }

                        OutputPin(const Function& f) : f(f) { }

        void            bind(const Function& _f) {
                                f = _f;
                        }

                        operator bool() const {
                                return f();
                        }

        OutputPin       operator !() const {
                                return OutputPin([&]() {
                                        return !f();
                                });
                        }
};

class InputPin {

protected:
        OutputPin       input;

public:
        void            attach(const OutputPin& _input) {
                                input = _input;
                        }

        operator        bool() const {
                                return input;
                        }
};

inline void operator<<(InputPin& in, const OutputPin& out)
{
        in.attach(out);
}

inline OutputPin operator&(const OutputPin& a, const OutputPin& b)
{
        return OutputPin([=]() {
                return (bool)a && (bool)b;
        });
}

inline OutputPin operator|(const OutputPin& a, const OutputPin& b)
{
        return OutputPin([=]() {
                return (bool)a || (bool)b;
        });
}

inline OutputPin operator^(const OutputPin& a, const OutputPin& b)
{
        return OutputPin([=]() {
                return (bool)a ^ (bool)b;
        });
}

and here's a trivial test case for the above header (but which generates 60kB of assembler output!):
#include "device.h"

int main()
{
        OutputPin   a, b, c;
        InputPin    i;

        i << (!a & b & c);

        return i;
}


texts: Should jQuery DOM Ready code be in the page with the HTML or separate JavaScript file?

texts:
I have an application with HTML, external JavaScript and a bit of jQuery on the page which is initializing specific stuff to that page. I try to keep most of the JavaScript in other files. However I'm unsure if stuff in the DOM Ready function should be split into a separate file as well which is specific to that page. I'm wondering the best way to structure this.

The code for the calculator.html page might look like this:

<!doctype html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <link type="text/css" href="css/global.css" rel="stylesheet">
        <script type="text/javascript" src="js/jquery.js"></script>
        <script type="text/javascript" src="js/global.js"></script>
        <script type="text/javascript" src="js/calculator.js"></script>
        <script>
            $(function() {
                calc.initialize();
                calc.loadPreviousState();
            });
        </script>
    </head>
    <body>
        <!-- page HTML code here -->
    </body>
</html>

The global.js files would be common JavaScript functions used on most pages. The calc.js file is only used by the calculator.html page and might have 20 odd functions in it. Assume that the two function calls inside the DOM Ready event need to be done on DOM load.

My question is, should I move this DOM Ready code into the top of the calculator.js file for clean code and readability? That way all the JavaScript would be contained in it's own file. For example here's the revised calculator.js file:

$(function() {
    calc.initialize();
    calc.loadPreviousState();
});

var calc = {
    initialize: function() {
        // code here
        return true;
    },
    loadPreviousState: function() {
        // code here
        return true;
    }
};

What's best practice here?

Many thanks!


texts:
I wrote a NodeJS HTTP server specifically for serving static files. I didn't bother much about security since the server is going to be used locally in my Electron application.

function buildStaticServer() {
    const fs = require("fs");
    const urlModule = require("url");
    return require("http").createServer(function(req, res) {
        var parsedUrl = urlModule.parse(req.url, true);
        var completePath = __dirname + parsedUrl.pathname;
        console.log(completePath);
        fs.stat(completePath, function(err, statObj){
            //we first check if the pathName exists
            if(err){
                res.writeHead(404);
                return res.end("404 Directory not found");
            }
            if(statObj.isDirectory()){
                //if the pathname is a directory, we're gonna try to send the index.html in that directory
                fs.readFile(completePath + "/index.html", function(err, data){
                    if(err){
                        res.writeHead(404);
                        return res.end("404 File Corrupt or Not Found");
                    }
                    res.writeHead(200);
                    res.write(data);
                    return res.end();
                })
            }
            fs.readFile(completePath, function(err, data){
                if(err){
                    res.writeHead(404);
                    res.end("404 File Corrupt or Not Found");
                    return;
                }
                res.writeHead(200);
                res.write(data);
                return res.end();
            })
        });
    });
}
var staticServer = buildStaticServer().listen(9000);


texts:
This is a simple program to run a command-line program with given parameters and verify that it writes the expected output to stdout or stderr. The specification file is passed as the first argument. It's formatted like this:

echo foo -> foo
man -> What manual page do you want?

with program and arguments to the left of -> and output on the right.

I don't often work so low-level, so I'm most interested in whether I'm managing resources properly.

#define _GNU_SOURCE

#include <errno.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#define MAX_ARGS 10
#define MAX_LINE 256

const char* parse_args(char **args, const char *line)
{
    size_t index = 0;
    size_t delimiter_index = 0;
    while (args[index] != NULL && index < MAX_ARGS - 1)
    {
        ++index;
        args[index] = strtok(NULL, " ");
        if (args[index] && strncmp(args[index], "->", 2) == 0)
        {
            delimiter_index = index;
            args[index+1] = strtok(NULL, "\n");
            break;
        }
    }

    args[delimiter_index] = '\0';
    const char *expected_result = args[delimiter_index + 1];
    if (delimiter_index == 0 || expected_result == NULL)
    {
        fprintf(stderr, "Line <%s> is malformed\n", line);
        return NULL;
    }

    if (strlen(expected_result) > MAX_LINE)
    {
        fprintf(stderr,
                "Invalid specification. Only results less than %d chars supported",
                MAX_LINE);
        return NULL;
    }

    return expected_result;
}

bool run_test(char *line)
{
    char *args[MAX_ARGS] = {};
    args[0] = strtok(line, " ");
    if (!args[0]) return true;

    const char* expected_result = parse_args(args, line);
    if (!expected_result)
    {
        return false;
    }

    int stdout_pipe[2];
    if (pipe(stdout_pipe) != 0)
    {
        fprintf(stderr, "Unable to open pipe\n");
        return false;
    }

    pid_t pid = fork();
    if (pid == -1)
    {
        fprintf(stderr, "Unable to fork process\n");
        return false;
    }

    if (pid == 0)
    {
        // Redirect streams so caller can read stdout
        dup2(stdout_pipe[1], STDOUT_FILENO);
        dup2(stdout_pipe[1], STDERR_FILENO);
        close(stdout_pipe[0]);
        execvp(args[0], args);

        // exec* only ever returns if it fails
        fprintf(stderr, "Failed to execute test program: %s\n",
                strerror(errno));
        return false;
    }

    close(stdout_pipe[1]);

    char actual_result[MAX_LINE] = {};
    ssize_t bytes_read = read(stdout_pipe[0], actual_result, MAX_LINE);
    if (bytes_read == -1)
    {
        fprintf(stderr, "Unable to read program output\n");
        return false;
    }

    // Strip newline
    if (actual_result[bytes_read - 1] == '\n')
    {
        actual_result[bytes_read - 1] = '\0';
    }

    if (strcmp(actual_result, expected_result) != 0)
    {
        fprintf(stderr, "Test Failed: ");
        for (int arg = 0; arg < MAX_ARGS; ++ arg)
        {
            if (!args[arg]) break;
            fprintf(stderr, "%s ", args[arg]);
        }
        fprintf(stderr, "\n");
        fprintf(stderr, "Expected: %s\n", expected_result);
        fprintf(stderr, "Actual: %s\n", actual_result);
        return false;
    }

    return true;
}

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: %s <test_specification>\n", argv[0]);
        return 1;
    }

    const char *spec_pathname = argv[1];
    FILE* spec = fopen(spec_pathname, "r");
    if (!spec)
    {
        fprintf(stderr, "Cannot open <%s> for reading\n", spec_pathname);
        return 1;
    }

    int return_code = 0;

    char *line = NULL;
    size_t line_length = 0;
    while (getline(&line, &line_length, spec) != -1)
    {
        if (!run_test(line))
        {
            return_code = 1;
        }
    }

    free(line);
    return return_code;
}


texts:
The following code was inspired from a tutorial I found online:

#include <cstdio>
#include <cstdarg>

double average_function(const int num_elements, ...)
{
    va_list elements;
    double sum = 0.0;

    va_start(elements, num_elements);
    for(int i = 0; i < num_elements; ++i) {
        sum += va_arg(elements, double);
    }
    va_end(elements);
    return sum / num_elements;
}

int main( int argc, char ** argv ) {

    printf("Average: %lf", average_function(5, 25.0, 35.7, 50.1, 127.6, 75.0));
    return 0;

}

I believe that the same can be done in many different ways.

Is there a better way to do the same without having as first arguments of the function the number of elements we want to sum? For example having instead a function to compute the average that have in its input only the set of elements we want to take into account without a their length?


texts: Array based queue implementation with C++20

texts:
I implemented a queue that holds elements on an array as underlying data type:
#include <cstddef>
#include <cassert>
#include <concepts>
#include <stdexcept>
#include <type_traits>
#include <iostream>

namespace mine {
template <std::semiregular T, std::size_t N> class queue {
public:
  using value_type = std::remove_cv_t<T>;
  using const_value_type = std::add_const_t<value_type>;

  using reference_type = std::add_lvalue_reference_t<value_type>;
  using const_reference_type = std::add_const_t<reference_type>;

  using size_type = std::size_t;
  using const_size_type = std::add_const_t<size_type>;

  void enqueue(const value_type val) {
    if (current_size == N) {
      throw std::overflow_error("queue overflowed.");
    }

    if (current_size == 0) {
      m_head = m_tail = 0;
    }

    m_tail = current_size;
    m_data[current_size++] = val;
  }

  value_type dequeue() {
    if (current_size == 0) {
      m_head = m_tail = 0;
      throw std::underflow_error("queue underflowed.");
    }

    --current_size;

    auto ret = m_data[m_head];
    m_data[m_head] = T{};
    ++m_head;
    return ret;
  }

  [[nodiscard]] reference_type head() { return m_data[m_head]; }
  [[nodiscard]] const_reference_type head() const { return m_data[m_head]; }

  [[nodiscard]] reference_type tail() { return m_data[m_tail]; }
  [[nodiscard]] const_reference_type tail() const { return m_data[m_tail]; }

  [[nodiscard]] bool empty() noexcept { return current_size == 0; }
  [[nodiscard]] const bool empty() const noexcept { return current_size == 0; }

  [[nodiscard]] size_type size() noexcept { return current_size; }
  [[nodiscard]] const size_type size() const noexcept { return current_size; }

private:
  size_type m_head = 0;
  size_type m_tail = 0;
  int current_size = 0;
  value_type m_data[N]{};
};

}

And I wonder about the possible blunders, what is missing and how to make it better in general. Thanks a lot.


texts: Converting Kinect Methods from Beta 2, to Version 1

texts:
So I have convert the getDisplayPosition from the beta version of the Kinect SDK to the full version. Here's what I have right nowThe Original

 private Point getDisplayPosition(Joint joint)
    {
        float depthX, depthY;
        nui.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
        depthX = Math.Max(0, Math.Min(depthX * 320, 320));  //convert to 320, 240 space
        depthY = Math.Max(0, Math.Min(depthY * 240, 240));  //convert to 320, 240 space
        int colorX, colorY;
        ImageViewArea iv = new ImageViewArea();
        // only ImageResolution.Resolution640x480 is supported at this point
        nui.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);

        // map back to skeleton.Width & skeleton.Height
        return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
    }

My Version

private Point getDisplayPosition(Joint joint)
    {
        float depthX, depthY;
        KinectSensor sensor = kinectSensorChooser1.Kinect;
        DepthImageFormat depth = DepthImageFormat.Resolution320x240Fps30;
        depthX = 320;
        depthY = 240;
        sensor.MapSkeletonPointToDepth(joint.Position, depth);
        depthX = Math.Max(0, Math.Min(depthX * 320, 320));
        depthY = Math.Max(0, Math.Min(depthY * 240, 240));
        int colorX, colorY;
        colorX = 320;
        colorY = 240;

        return new Point((int)(skeleton.Width * colorX / 640.0), (int)(skeleton.Height * colorY / 480));
    }

Basically I want to know if my version will do the same thing as the origin


texts:
I'm developing a complex app with Spring Boot and MongoDB. I have a Video class like the following. Note: All getters setters are omitted.

class Video{
    ObjectId _id;
    private List<OReelOCategoryLGroup> listOfReelIdCategoryIdAndGroups;
    //some other fields
}

public class OReelOCategoryLGroup {
    ObjectId reelId;
    ObjectId categoryId;
    List<Group> groups;
}

public class Group {
    ObjectId _id;
    Boolean isMandatory=false;
    String dueDate;
}

I am receiving the following structure from the front-end.

{
    "reelId":"5eda6be5b31e96f58b3a7c65",
    "groupId":"5eda6bed217c01319701aea0",
    "category":[
        {
            "categoryId":"5eda6bf48ebcb19e031f2aa2",
            "videoId":["5eda6bff1230f45ae4b7e54a","5eda6c0464ba746e243a4d6d","5eda6c0eed64b31232bf1095"]

        },
        {
            "categoryId":"5eda6bf48ebcb19e031f2aa2",
            "videoId":["5eda6c14214ca295b6473c78"]

        }
    ]
}

The representation of the class is

public class OReelLCategoryOGroup {
    ObjectId reelId;
    ObjectId groupId;
    List<OIdOVideoId> category;

}

public class OIdOVideoId {

    ObjectId categoryId;
    List<ObjectId> videoId;

}

I want to update OReelLCategoryOGroup to each and every videoId what I receive from front-end. So I coded

public String addVideoToCurrentGroupFromAnotherReel(OReelLCategoryOGroup list) {

    Set<ObjectId> notFoundIds = new HashSet<>();

    for (OIdOVideoId cat : list.getCategory()) {

        for (ObjectId vId : cat.getVideoId()) {
            Optional<Video> video = videoRepository.findBy_id(vId);
            if (video.isPresent()) {
                Video v=video.get();

                OReelOCategoryLGroup flat = new OReelOCategoryLGroup();

                Group group = new Group();
                group.set_id(list.getGroupId());
                group.setIsMandatory(false);

                flat.setReelId(list.getReelId());
                flat.setCategoryId(cat.getCategoryId());
                flat.setGroups(Arrays.asList(group));

                v.getListOfReelIdCategoryIdAndGroups().add(flat);
                save(v);
            } else {
                notFoundIds.add(vId);
            }

        }
    }

    if (notFoundIds.size() > 0) {
        return "Few videos successfully added to group, but " + notFoundIds.toString() + " are not found in database";
    }
    return "Videos successfully added to group";
}

Here the complicity is \$O(n^2)\$. But if listOfReelIdCategoryIdAndGroups contains reelId == list.getReelId() && categoryId == cat.getCategoryId() then I have to add the group to that list of groups. If I'm going to check it, there will be another loop inside the nested loop. So complexity is \$O(n^3)\$.

for (OIdOVideoId cat : list.getCategory()) {
    for (ObjectId vId : cat.getVideoId()) {
        if (video.isPresent()) {

            for(OReelOCategoryLGroup g:v.getListOfReelIdCategoryIdAndGroups()){
                if(g.getReelId()==list.getReelId() && g.getCategoryId()==cat.getCategoryId()){
                    g.getGroups().add(group);
                }else{
                    // insert
                }
            }
        }
    }
}

I feel this is inefficient. Is there any way to overcome to this problem with Java 8, Stream API?


texts:
I wrote a simple class that substitutes all file inputs in an HTML for a more complex template and set some actions on it. The code is rather small, but I'm not used to write JavaScript.

I wonder if there is a design pattern or extensively used way to set the callbacks? Of course, overall improvements are welcome as well.

The full code is here:

$(document).ready ->
  $('input[type="file"]').each ->
    new PhotoInput(this)

class PhotoInput
  constructor: (originalInput) ->
    @renderTemplate(originalInput)
    @setClickActions()
    @setPreviewRender()

  renderTemplate: (originalInput) ->
    @template = ich.image_file_input_template # this is ICanHazJS call - it loads a mustache template there.
      fileInput: $(originalInput)[0].outerHTML
    @fileInput = @template.find('input[type=file]').first()
    @previewImage = @template.find('.file-input-preview img')
    $(originalInput).replaceWith(@template)

  setClickActions: ->
    @template.find('#select-file').click =>
      @fileInput.focus().click()
    @template.find('.file-input-preview').click =>
      @fileInput.focus().click()

  setPreviewRender: ->
    @fileInput.change =>
      @previewImage.attr('alt', @fileInput.val())
      if(@fileInput[0].files && @fileInput[0].files[0])
        reader = new FileReader()
        reader.onload = (e) =>
          @previewImage.attr('src', e.target.result)
        reader.readAsDataURL(@fileInput[0].files[0])


texts: Max Sum of Nodes in Each Path in Binary Tree

texts:
I wanted to get a review on an algorithm I wrote for a binary tree problem. The problem is the following.

  Return the maximum sum between all branches in a binary tree. A branch
  is defined as all paths from root to leaf.

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

#branch one
root = Node(10)

second = Node(5)
root.left = second

third = Node(1)
second.left = third

fourth = Node(3)
third.left = fourth

tenth = Node(5)
third.right = tenth

fifth = Node(20)
root.right = fifth

sixth = Node(60)
fifth.left = sixth

seventh = Node(3)
fifth.right = seventh

nineth = Node(40)
seventh.right = nineth

def find_max_sum_of_binary_tree_path(root):
    curr_list = []
    curr_max = [0]

    def binary_tree_recurse(node):
        if node:
            if not node.left and not node.right:
                curr_list.append(node.value)
                list_sum = sum(curr_list)
                if list_sum > curr_max[0]:
                    curr_max[0] = list_sum
                curr_list.pop()

            curr_list.append(node.value)
            binary_tree_recurse(node.left)
            binary_tree_recurse(node.right)
            curr_list.pop()

    binary_tree_recurse(root)
    return curr_max[0]

  #      10
  #      / \
  #     5   20
  #    /   / \
  #   1   60   3
  #  / \       \
  # 3   5       40

find_max_sum_of_binary_tree_path(root) #should return 90 based on my tree
>90

I'd like to stick to a recursive approach, but open to suggestions on anything else. I am mostly concerned about time complexity and improving the performance of this function. Does anyone know what the current time complexity is?


texts: Summing the digits of a number (subtracting the first digit if it is negative)

texts:
I'm working on some practice problems using higher- order functions and while I was able to solve this problem. I can't help but think this code is ugly and not the most eloquent it could be. Is there a way to combined map and reduce is a cleaner way than I have done ? Additionally, is there any other methods or improvements I could have used here ? I'm just looking to get better and any feedback would be appreciated.

Problem: Given a number, "sumDigits" returns the sum of all its digits. If the number is negative, the first digit should count as negative.

function sumDigits(num) {

  //create array of number char
  var string = num.toString().split('');

  //if first char is negative symbol let the first numeric element be negative
  if (string[0] === "-") {
    string[1] = '-' + string[1];
    string.shift();
  }

  //convert string to int
  var toInteger = string.map(function(x) {
    return Number(x);
  });

  //get sum
  return toInteger.reduce(function(sum, current) {
    sum += current;
    return sum;
  })
}

sumDigits(-316);


texts: Calling many web services asynchronously

texts:
I need to process a bunch of completed orders (thousands). To make it faster, I'm using a SemaphoreSlim to schedule a number of orders to be processed in parallel. Every order goes through multiple web service calls to various APIs (SOAP, REST). Then I need to take the returned data and process it into a PDF. Here is what I am doing currently (note that this is in an ASP.NET app):

private async Task ProcessOrders(List<Orders> orders)
{
    var allTasks = new List<Task>();
    var throttler = new SemaphoreSlim(initialCount: 5);

    foreach (var order in orders.Where(x => !x.HasError))
    {
        // do an async wait until we can schedule again
        await throttler.WaitAsync();

        // using Task.Run() to run the lambda in its own parallel
        // flow on the thread pool
        allTasks.Add(Task.Run(async () =>
        {
            try
            {
                // Call external web service here
                // Build order report PDF here
            }
            finally
            {
                throttler.Release();
            }
        }));
    }

    await Task.WhenAll(allTasks);
}

However, I'm new to TPL and I don't know if this is the right way to do something like this. If it's relevant, this app is hosted on Amazon's AWS cloud.


texts:
I must write updates in a database from a flat file (CSV).  I want to do that in the shell, with tools such as AWK.

#!/bin/bash

cat in.csv | sed -e '1d' | awk -F';' -v q=\' '{               # For each line.
    print "DECLARE @v_trmID varchar(16) = " q $1 q
    print "DECLARE @v_trmNom varchar(6) = " q $3 q
    print "DECLARE @v_trmNbrTrav smallint = " $4
    print "IF EXISTS (SELECT 1 FROM trimestre WHERE trmID = @v_trmID AND trmNom = @v_trmNom)"
    print "    BEGIN"
    print "        UPDATE trimestre"
    print "        SET trmNbrTrav = @v_trmNbrTrav"
    print "        WHERE trmID = @v_trmID AND trmNom = @v_trmNom"
    print "    END"
    print "ELSE"
    print "    BEGIN"
    print "        PRINT " q "The script execution FAILED for record " NR " (pfiID " q " + @v_trmID + " q ", trimestre " q " + @v_trmNom + " q ")." q
    print "    END"
    print "go"
    print ""
}'

Though, there a 2 things I don't like:

The way quotes are inserted; it becomes really difficult to follow, even if I choose for the simpler way I found to write quotes inside an AWK string (instead of multiple escape sequences).  Still, not that readable.
The fact that every SQL line is not readable as is.  Code is not highlighted as SQL.  I'd like to find a "here doc" solution, where I wouldn't have to prefix lines with printf.

Do you have any pieces of advice or better ideas on the way to write robust (because more readable / easily modifiable) code?


texts: Working with forms in Meteor, using selectors for every input

texts:
I'm trying to work with forms, and just getting a grasp on JavaScript. Basically I'm unsure if there is a more reusable way to handle forms with Meteor/jQuery.

// Creating a new prayer, including the preview
Template.newPrayer.events({
    'click input.save' : function() {
        var title = $("#prayer_title");
        var prayer = $("#prayer");
        var preview_container = $("#prayer_preview");
        var currentUser = Meteor.userId();

        if( currentUser !== null ) {
            Prayers.insert({
                title: title.val(),
                prayer: prayer.val(),
                user: currentUser });

            title.val('');
            prayer.val('');
            preview_container.fadeOut();
        }
    },
    // Auto-updating the preview
    'keyup #prayer' : function() {
        var preview_container = $("#prayer_preview");
        preview_container.fadeIn();
        var preview_formatted = prayer.value.replace(/\n/g,'
');
        $(".preview_text").html(preview_formatted);
    }
});

Is there a better way to do this, should my template be laid out in a different way?

<template name="newPrayer">

{{title}}

    <form id="new_prayer">
        Title
        <input id="prayer_title" class="item" type="text" tabindex="1"/>

        <textarea id="prayer" class="item" name="prayer" tabindex="2" required="true" wrap="soft" autofocus="true" cols="60" rows="10"></textarea>
        <input type="button" class="save item" value="Save Prayer" tabindex="3" />
    </form>

Preview

</template>

Is there a better way to handle form data and form display, without having selectors for every form element, and then having to clear each one?

It seems like I'm not utilizing the full potential of Meteor's reactivity and templating features. Also open to any other pointers/tips with my code. The code works as is.

P.S. This code is just me learning Meteor/JS and the beginning of a small project.


texts: Counting increasing subsequences with a "hacker's" Binary Index Tree

texts:
This is an \$O(n \sqrt n)\$ solution to the the following problem:

  Given a sequence, compute the number of non-empty increasing subsequences

The algorithm is to compute g(i) = # of increasing subsequences that end at index i using dynamic programming, and then sum over i. A full description of the algorithm used can be found here. However, naively using dynamic programming yields an \$O(n^2)\$ solution, which is too slow. It's possible to get \$O(n \log n)\$ using a BIT, but I opted for the \$O(n \sqrt n)\$ "hacker's" BIT, implemented below. As I am a novice (relatively), my question is: how could I have implemented it better? Specifically, I generally prefer to program in a more functional style, but this code is very imperative. How could I have made it more functional?

from math import sqrt
from bisect import bisect_left

def count_sequences(seq):
    # Normalize seq
    seq_sorted = sorted(seq)
    seq = list(map(lambda x: bisect_left(seq_sorted, x), seq))

    # Initialize the memoization arrays
    n = len(seq); f = [0]*n
    nn = int(sqrt(len(seq))); ff = [0]*(nn+2)

    # Compute g(i) = f(s[i])
    for s in seq:
        res = sum([
            1,
            sum(ff[: (s // nn)]),
            sum(f[(s // nn)*nn : s])
        ])

        f[s] += res
        ff[s // nn] += res

    # Sum all g(i)
    return sum(ff)


texts: Generating a bytearray by choosing an exclusive set of parameters

texts:
I am new to python so tips to any part of the code are welcome.

My main problem is how to "overload" the function properly. Is this how supposed to be done with parameters that gets passed exculsivly?
It is intended that only Bytes, Words or a DWord will get passed in the corresponding parameter. (If multiple are passed the longest one is prefered. Sidenote: The naming is based on an old 16bit processor thats why word is 16 bit and Dword is 32)

I also wanted to make the range check of the optional arguments in the beginning but as I default them to None,  I had to check for None in the first place before I can check the range and this would make the None check redundant.

I had something like max(Word1,Word2) >= 2**16 in mind, because I hoped in python the max would yield None and the larger would give false, but > is not implemented for None. So to get it to work I used the check for None first. But this seems not elegant.

Afterwards I assign the bigger datachunks to Bytes and raise Errors if the data didn't fit in the range of the type. If nothing is passed the Data is set to 0 to fill up the array in the end.

If no length  was given the length calculated by the checks is used.

In the end all the data gets packed into a bytearray (the Message to be sent later). Because bytearray() checks if the elements are in range, the Bytes are not checked seperatly.

Is there a more pythonic way to do it?

def packMessage(DeviceID, Offset, dataLength=None,
                Byte0=None, Byte1=None, Byte2=None, Byte3=None,
                Word0=None, Word1=None, DWord0=None):

    Bytes = [Byte0, Byte1, Byte2, Byte3]
    length = 0
    # check if the values to be used are in range
    if Offset >= 2**16:
        raise ValueError
    else:
        Offset_low = Offset & 0x00FF
        Offset_high = (Offset & 0xFF00) >> 8

    if dataLength is not None and not 1 <= dataLength <= 4:
        raise ValueError

    # split bigger data to bytes and check the data length
    if DWord0 is not None:
        if 0 <= DWord0 <= 2**32:
            Bytes[0] = DWord0 & 0xFF
            Bytes[1] = (DWord0 & 0xFF00) >> 8
            Bytes[2] = (DWord0 & 0xFF0000) >> 16
            Bytes[3] = (DWord0 & 0xFF000000) >> 24
            length = 4
        else:
            raise ValueError
    elif Word0 is not None:
        if 0 <= Word0 <= 2**16:
            Bytes[0] = Word0 & 0xFF
            Bytes[1] = (Word0 & 0xFF00) >> 8
        else:
            raise ValueError
        if Word1 is not None:
            if 0 <= Word1 <= 2**16:
                Bytes[2] = Word1 & 0xFF
                Bytes[3] = (Word1 & 0xFF00) >> 8
                length = 4
            else:
                raise ValueError
        else:
            Word1 = 0
            Bytes[2] = Bytes[3] = 0
            length = 2
    else:
        for i in range(len(Bytes)):
            if Bytes[i] is not None:
                length = i
            else:
                Bytes[i] = 0

    # if no length given take calculated length
    if dataLength is None:
        dataLength = length

    # return the Message
    return bytearray([DeviceID, dataLength, Offset_low,
                      Offset_high, Bytes[0], Bytes[1], Bytes[2], Bytes[3]])

Side note: I decided that the compare order of the Bytes doesn't matter that much so I ditched it for now and replaced it with a loop for now.

It looked like this before:

if Byte0 is not None:
    if Byte1 is not None:
        if Byte2 is not None:
            if Byte3 is not None:
                length = 4
            else:
                Byte3 = 0
        else:
            length = 3
            Byte2 = 0
            Byte3 = 0
    else:
        length = 2
        Byte1 = 0
        Byte2 = 0
        Byte3 = 0
else:
    length = 1
    Byte0 = 0
    Byte1 = 0
    Byte2 = 0
    Byte3 = 0

I don't see a nice way to wrap this up. So If there is a beautiful solution for this let me know, otherwise feel free to ignore it.


texts: KNN search by distinct category in postgis/postgres

texts:
I have a postgres table, etablissements with millions of rows, and a geom (st_point) column , spatially indexed (using gist). I'm using the PostGIS extension.
Those rows may have a different category, activite_principale.

I want to find from a given, fixed point (coordinates) the closest etablissements for 5 or 6 different categories called "activite_principale" (1 closest company per category).

Here's what I did right now and which is working :

      (WITH closest_candidates AS (
      SELECT
        ent.id,
        ent.name,
        ent.geom
      FROM
        geo_data.etablissements ent
      WHERE ent.activite_principale = '1071C'
      ORDER BY
        ent.geom <->
        'SRID=4326;POINT (5.4153978921979125 43.271437384501965)'::geometry
      LIMIT 10
    )
    SELECT id
    FROM closest_candidates
    ORDER BY
      ST_Distance(
        geom,
        'SRID=4326;POINT (5.4153978921979125 43.271437384501965)'::geometry
        )
    LIMIT 1)
    UNION ALL
    (WITH closest_candidates AS (
      SELECT
        ent.id,
        ent.name,
        ent.geom
      FROM
        geo_data.etablissements ent
      WHERE ent.activite_principale = '4711D'
      ORDER BY
        ent.geom <->
        'SRID=4326;POINT (5.4153978921979125 43.271437384501965)'::geometry
      LIMIT 10
    )
    SELECT id
    FROM closest_candidates
    ORDER BY
      ST_Distance(
        geom,
        'SRID=4326;POINT (5.4153978921979125 43.271437384501965)'::geometry
        )
    LIMIT 1)
  --  UNION ALL
-- [...]  And so on...

I clustered the etablissements table around the geom spatial index and ran VACUUM ANALYZE geo_data.etablissements;

Here's the result of EXPLAIN ANALYZE after clustering.

The query planning is shorte and the execution too but it's still slow (350-450ms).

I use postgres 10 & postgis 2.4.

I'm not convinced my cascading UNION ALL is the best solution, that's why I'm asking. My problem : how to find the X closest points of table Y with distinct Z categories, and you are guaranteed each row is the closest X for category Z in PostGIS.

I don't know how to improve based on those explanations from the query planner. Can I do better performance ?

Note : this is a cross-post from the GIS stackexchange


texts: Shortening System.out - which is better?

texts:
Oftentimes people will shorten System.out to just out and make an analog called in (e.g. Scanner in = new Scanner(System.in);). I've seen two methods of doing this
Method 1:
import static java.lang.System.out;
Method 2:
static final PrintStream out = System.out;
Is there a coding convention or best practices for this? If so, which one is it and why is it more readable?


texts: Find Todos by Line Number (or any other reference) in Python

texts:
I write a lot of TODO's but I never keep track of where they are.

This program will search through files (and recursively through folders if needed) and find any TODO comments and their line number.

The details will be printed to the screen and a file will be generated in the folder which is a csv of the files and TODO details.

You can choose different filetypes, comments and TODO phrases to suit , so it is not just for python.

GitHub

from os.path import exists
import sys
from glob import glob

class TodoLocater:
    def __init__(self, path, ext, td, comment, recursive=False):
        self.path = path
        self.ext = ext
        self.td = td
        self.comment = comment
        self.recursive = recursive
        self.todos = {}

    def get_files(self):
        try:
            g = glob(self.path + f"/**/*{self.ext}", recursive=self.recursive)
            if exists(self.path):
                for x in g:
                    print(f"Searching  ::  {x}")

                    result = self.find_todo(x)
                    if result:
                        self.todos[x] = result
            else:
                raise OSError("Path does not exist.")
        except Exception as e:
            print(e)

    def find_todo(self, f):
        temp_todos = []
        line_no = 0
        with open(f, "r") as input_:
            for line in input_:
                line_no += 1
                if self.comment in line and self.td in line:
                    temp_todos.append([f, f"Line - {line_no}  ::  {line.strip()}"])
        return temp_todos

    def show_todos(self):
        line = "-" * 100
        self.get_files()
        for k, v in self.todos.items():
            print(f"\n{line}\n\n{k}")
            for x in v:
                print(f">>>{x[1]}")
            self.save_csv(k, [v])

    def save_csv(self, fn, todos):
        import csv

        with open(fn + ".csv", "w", newline="") as csvfile:
            w = csv.writer(csvfile, delimiter=",", quoting=csv.QUOTE_MINIMAL)
            for row in todos:
                for r in row:
                    w.writerow(r)

if __name__ == "__main__":
    path = "."
    ext = "py"
    td = "TODO"
    comment = '#'

    find = TodoLocater(path, ext, td, comment, recursive=True)
    find.show_todos()


texts: Saving the values of all variabled declared in a block

texts:
Often when running exprimental code to empirically investigate an algorithm, you tweak a parameter, then rerun the code, and generate a bunch of saved models for various parameters.

To make sure I don't loose what the parameters were set to I defined a macro that saves there values.

module Util
using JLD

export @param_save #...

function names_candidates(blk::Expr)
    names_in_block = Vector{Symbol}()
    for a in blk.args
        typeof(a) <: Expr || continue
        if a.head == :(=)
            push!(names_in_block, a.args[1])
        else #Recurse, so we captured things in blocks or behind `const`
            append!(names_in_block, names_candidates(a))
        end
    end
    names_in_block
end

macro param_save(filename, blk::Expr)
    names_in_block =  names_candidates(blk)
    quote
        $(esc(blk))
        names_defined = Set($(names_in_block)) ∩ Set(names(current_module()))
        names_and_vals =[(string(name), eval(name)) for name in names_defined]
        println("Paramaters -- saving to $($filename)")
        println("----------")
        println(join(("$n = $v" for (n,v) in names_and_vals),"\n"))
        JLD.save($filename, Base.flatten(names_and_vals)...)
        println("----------")
    end
end
#...
end #module

Usage:

using Util

base_name = "paper_v1"
param_save_fn =  "../models/adagram/$(base_name).params.jld"
output_fn = "../models/adagram/$(base_name).adagram_model"#"file to save the model (in Julia format)"
@assert !isfile(output_fn)
@param_save param_save_fn begin
        nprocessors = nprocs()
        train_fn  =  "../data/corpora/WikiCorp/tokenised_lowercase_WestburyLab.wikicorp.201004.txt" #"training text data"
        output_fn = output_fn #file to save the model (in Julia format)"
        dict_fn = "../data/corpora/WikiCorp/tokenised_lowercase_WestburyLab.wikicorp.201004.1gram" #"dictionary file with word frequencies"

        window = 10 #"(max) window size" C in the paper
        min_freq  = 20 #"min. frequency of the word"
        remove_top_k = 0 #"remove top K most frequent words"
        dim  = 300 #"dimensionality of representations"
        prototypes = 5 #"number of word prototypes" T in the paper
        alpha = 0.15 #"prior probability of allocating a new prototype"
        d  = 0.0 #"parameter of Pitman-Yor process" D in paper
        subsample = 1e-5 #"subsampling treshold. useful value is 1e-5"
        context_cut  = true #"randomly reduce size of the context"
        epochs = 1 #"number of epochs to train"
        initcount = 1. #"initial weight (count) on first sense for each word"
        stopwords = Set{AbstractString}() #"list of stop words"
        sense_treshold = 1e-10 #"minimal probability of a meaning to contribute into gradients"
        save_treshold = 0.0 #"minimal probability of a meaning to save after training"
end

Output:

Paramaters -- saving to ../models/adagram/paper_v1btempexample.params.jld
----------
train_fn = ../data/corpora/WikiCorp/tokenised_lowercase_WestburyLab.wikicorp.201004.txt
alpha = 0.15
subsample = 1.0e-5
sense_treshold = 1.0e-10
initcount = 1.0
nprocessors = 1
epochs = 1
window = 10
output_fn = ../models/adagram/paper_v1btempexample.adagram_model
min_freq = 20
prototypes = 5
context_cut = true
stopwords = Set{AbstractString}()
remove_top_k = 0
save_treshold = 0.0
dict_fn = ../data/corpora/WikiCorp/tokenised_lowercase_WestburyLab.wikicorp.201004.1gram
dim = 300
d = 0.0
----------

Writing code with macros is hard.
It took me a few shots to get the escaping all right.

Is this reasonable code?
AFAICT julia doesn't have a method like pythons locals() that lists all variables in a given scope.
So I have to work around that by finding possible variables in the AST then cross referencing that against all variables in the module.


texts:
I am a beginner in programming. To rotate the array to left, I have written the below code. Please point out how to optimize the code and anything I am doing which is not good programming practice.

package arrays;

import java.util.Scanner;

public class ArrayLeftRotation {

    public static int[] LeftRotation(int numberOfLeftRotations, int[] a, int[] b) {

        int n1 = numberOfLeftRotations, n2 = numberOfLeftRotations;
        /*
         * First for loop Given array a0=1,a1=2,a3=4,a4=5,a5=6,a6=7; First we
         * are shifting the first 3 elements to last 3 slots and the array looks
         * like below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; The above step we are
         * performing through below logic
         * a[array.length-numberOfLeftRotations]=b[i]; GIVEN ARRAY LENGTH -
         * NUMBER OF LEFT ROTATIONS IS THE STARTING POINT TO MOVE THE FIRST
         * ELEMENTS OF THE ARRAY TO LAST
         */
        for (int i = 0; i < numberOfLeftRotations; i++) {
            a[a.length - n1] = b[i];
            n1--;
        }
        /*
         * Second for loop After executing the above loop the array look like
         * below a0=1,a1=2,a2=3,a3=,a4=1,a5=2,a6=3; now except the last three
         * slots every thing needs to be changed
         * a0=4,a1=5,a2=6,a3=7,a4=1,a5=2,a6=3; we achieved the above array
         * result through below logic a[i]=b[numberOfLeftRotations]; REPLACED
         * THE REMAINING SLOTS WITH THE VALUES STARTING FROM
         * NUMBEROFLEFTROTATIONS
         */
        for (int i = 0; i < a.length - numberOfLeftRotations; i++) {
            a[i] = b[n2];
            n2++;
        }
        return a;
    }

    public static int[] LeftRotation(int numberOfLeftRotations, int[] a) {

        return a;

    }

    public static int[] printArray(int[] a) {

        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
        return a;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of Left Rotations need to be done");
        int l = sc.nextInt();
        System.out.println("Enter number of elements in an array");
        int e = sc.nextInt();
        int[] a = new int[e];

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

        int[] b = a.clone();

        LeftRotation(l, a, b);
        printArray(a);

    }
}


texts: Ruby code to parse and analyze social media stats in json format

texts:
What do you think about this code I wrote.
It reads several json files ( I attached them as pastebins)
and the code outputs summary information calculated from the input.

# 1) calculate the
# engagement rate from the first JSON file (the user's Instagram media)
# - Calculate the average number of comments - Calculate the average
# number of likes - Calculate the engagement rate using (Average Likes +
# Average Comments)/# of Followers which is 435
#
# 2) Combine the 2 sets of JSON data (Instagram media objects with their
# Instagram insights), then output a single JSON file where the insights
# are paired with their media objects in a clean format.
#
# Question 1.json: https://pastebin.com/V3Ue87H4
# Question2A.json: https://pastebin.com/YifXzimZ
# Question2B.json: https://pastebin.com/6X0JYXtD

require 'json'
input = JSON.parse( File.read('Question 1.json') )["data"]
avg_likes    = input.map { |x| x["like_count"] }.    inject{ |sum, el| sum + el }.to_f / input.size
avg_comments = input.map { |x| x["comments_count"] }.inject{ |sum, el| sum + el }.to_f / input.size
puts "Answer for Question 1: #{avg_likes + avg_comments / 435}\n\n"

input_a = JSON.parse( File.read('Question2A.json') )["data"]
input_b = JSON.parse( File.read('Question2B.json') ).map { |x| x["data"] }.flatten
output = input_a.map do |post|
  {
    :permalink => post["permalink"],
    :impressions => input_b.find { |x| x["id"] == "#{post['id']}/insights/impressions/lifetime" }["values"][0]["value"],
    :engagement  => input_b.find { |x| x["id"] == "#{post['id']}/insights/engagement/lifetime"  }["values"][0]["value"],
    :reach       => input_b.find { |x| x["id"] == "#{post['id']}/insights/reach/lifetime"       }["values"][0]["value"],
    :saved       => input_b.find { |x| x["id"] == "#{post['id']}/insights/saved/lifetime"       }["values"][0]["value"]
  }
end
puts "Answer for Question 2: " + JSON.pretty_generate(output)

# EXAMPLE OUTPUT - generated by running ruby coding_test.rb
#
# Answer for Question 1: 22.704827586206896
#
# Answer for Question 2: [
#   {
#     "permalink": "https://www.instagram.com/p/B40LKjkAlDV/",
#     "impressions": 236,
#     "engagement": 33,
#     "reach": 187,
#     "saved": 2
#   },
#   {
#     "permalink": "https://www.instagram.com/p/B4z4Vq5Ag5g/",
#     "impressions": 212,
#     "engagement": 22,
#     "reach": 170,
#     "saved": 0
#   },
#   {
#     "permalink": "https://www.instagram.com/p/B4xnmtygmi-/",
#     "impressions": 297,
#     "engagement": 28,
#     "reach": 218,
#     "saved": 1
#   },
#   {
#     "permalink": "https://www.instagram.com/p/B4uyfrLgjVi/",
#     "impressions": 248,
#     "engagement": 21,
#     "reach": 194,
#     "saved": 0
#   },
#   {
#     "permalink": "https://www.instagram.com/p/B4nic12AFps/",
#     "impressions": 292,
#     "engagement": 15,
#     "reach": 219,
#     "saved": 0
#   }
# ]


texts: Sort three numbers using only if-statements

texts:
Beginner here, trying to make a small program that sorts three numbers from smallest to largest only by using ifs. Any thoughts on how to improve this?

#include <iostream>

using namespace std;
int main ()
{
    int num1, num2, num3;
    int smallest, middle, biggest;
    cin >> num1 >> num2 >> num3;

    cout << endl;

    if ((num1 < num2) && (num1 < num3))
    {
        smallest = num1;
        if (num2 > num3)
        {
            biggest = num2;
            middle = num3;
        }
    }
    if ((num1 < num2) && (num3 << num1))
    {
        smallest = num1;
        if (num2 < num3)
        {
            middle = num2;
            biggest = num3;
        }
    }
    if ((num1 > num2) && (num3 > num1))
    {
        middle = num1;
        if (num2 < num3)
        {
            smallest = num2;
            biggest = num3;
        }
    }
    if ((num1 < num2) && (num3 < num1))
    {
        middle = num1;
        if (num2 > num3)
        {
            biggest = num2;
            smallest = num3;
        }
    }
    if ((num1 > num2) && (num1 > num3))
    {
        biggest = num1;
        if (num3 > num2)
        {
            middle = num3;
            smallest = num2;
        }
    }

    if ((num1 > num2) && (num1 > num3))
    {
        biggest = num1;
        if (num2 > num3)
        {
            middle = num2;
            smallest = num3;
        }
    }

    cout << smallest << ", " << middle << ", " << biggest << endl;

    return 0;
}


texts:
Original post: nagios plugin webdav check

According to the good advice I have received I've made some modifications to the code:

#!/bin/bash
#
# check a WebDAV server
# connect using a username and password and upload & delete a test file

#Exit codes
STATE_OK=0
STATE_WARNING=1
STATE_CRITICAL=2
STATE_UNKNOWN=3

FILENAME=test_monitor
FQFN=/tmp/$FILENAME

# Verify the type of input and number of values
# Display an error message if the (input) is not correct
# Exit the shell script with a warning status
[ $# -ne 4 ] && { echo "Usage: $0 <hostname> <username> <password> <webdav_dir>"; exit $STATE_UNKNOWN; }

HOSTNAME=$1
USERNAME=$2
PASSWORD=$3
WEBDAVDIR=$4
BASEURL=http://$HOSTNAME/$WEBDAVDIR

# create temp file
truncate -s 1M $FQFN
if [ ! -f $FQFN ]; then
    echo "Test file not found!"; exit $STATE_UNKNOWN;
fi

# check if curl is installed
command -v curl >/dev/null 2>&1 || { echo >&2 "Curl is not installed. Script cannot run."; exit $STATE_UNKNOWN; }

function _curl {
curl --fail -u $USERNAME:$PASSWORD "$@"
}

# connect to server and upload file
_curl -s -T $FQFN $BASEURL/ > /dev/null

status=$?

case $status in
    0)
        echo "OK - File uploaded on WebDAV Server: $HOSTNAME"
        # remove test file
        _curl -X DELETE $BASEURL/$FILENAME
        exit $STATE_OK
        ;;
    1)
        echo "CRITICAL - Cannot upload file on $HOSTNAME"
        exit $STATE_CRITICAL
        ;;
    6)
        echo "CRITICAL - Could not resolve host $HOSTNAME"
        exit $STATE_CRITICAL
        ;;
    26)
        echo "CRITICAL - Cannot open $FQFN for upload"
        exit $STATE_CRITICAL
        ;;
    22)
        echo "CRITICAL - The requested URL returned error"
        exit $STATE_CRITICAL
        ;;
    127)
        echo "CRITICAL - Command not found"
        exit $STATE_CRITICAL
        ;;
    *)
        echo "UNKNOWN - "
        exit $STATE_UNKNOWN
esac

Do you have any more recommendations regarding syntax or script functionality?

I am thinking about the removal of the test file. It is done if the upload is successful, but can it be assumed that if the upload is successful, the delete will be also? In my tests this has always been the case.

Is there a chance for the delete command to fail? And should I modify the script somehow to accommodate for that?


texts:
I've written the following code to print all the permutations of a list. For example:

  \$[1, 2, 3]\$ has these permutations: \$[1,2,3]\$, \$[1,3,2]\$, \$[2,1,3]\$, \$[2,3,1]\$, \$[3,1,2]\$, and \$[3,2,1]\$.

def insert_each_position(self, nums, insert_one):
    res, len_of_nums = [], len(nums)
    for idx in range(len_of_nums+1):
        tmp = nums[:]
        tmp.insert(idx, insert_one)
        res.append(tmp)
    return res

def permute(self, nums):
    res, len_of_nums = [[]], len(nums)
    for idx in range(len_of_nums):
        cur_num = nums[idx]
        tmp = []
        for sub in res:
            tmp.extend(self.insert_each_position(sub, cur_num))
        res = tmp
    return res


texts: "Always stay connected" mechanism for socket connection

texts:
I'm calling Connect() for the first time I connect, I am then checking if the connection is still connected every 10 seconds if it is not connected it attempts to re-connect.

public class ClientHandler : ISocketHandler, IDisposable
{
    private readonly Socket _socket;
    private readonly byte[] _buffer;

    private ISession _session;
    private bool _hasConnected;

    public ClientHandler()
    {
        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        _buffer = new byte[8192];

        var timer = new Timer
        {
            Interval = 30000
        };

        timer.Elapsed += ElapsedTimer;
        timer.Enabled = true;
    }

    private void ElapsedTimer(object sender, ElapsedEventArgs e)
    {
        if (!CoreUtilities.IsConnected(_socket))
        {
            Connect();
        }
    }

    public void Connect()
    {
        var host = _session.ConfigHandler["server.host"];
        var port = short.Parse(_session.ConfigHandler["server.port"]);

        try
        {
            _socket.Connect(new IPEndPoint(IPAddress.Parse(host), port));
            _socket.BeginReceive(_buffer, 0, _buffer.Length, SocketFlags.None, OnIncomingData, _socket);

            CoreUtilities.LogToConsole("Successfully established a connection to the server.");
        }
        catch (SocketException)
        {
            CoreUtilities.LogToConsole("Failed to establish a connection with the server.");
        }
        finally
        {
            if (_socket.Connected && CoreUtilities.IsConnected(_socket))
            {
                Send(new SocketPasswordComposer(_session.ConfigHandler["server.password"]));
            }
        }
    }
}

Here is the method I use to determine if the socket is fully connected to the server.

public static bool IsConnected(Socket socket)
{
    return !(socket.Poll(1, SelectMode.SelectRead) && socket.Available == 0);
}

I feel that what I have coded above could be improved a lot.


texts:
I'm iterating through a list of possible values that reside in a named range on a worksheet. Since accessing ranges is slow, I wanted an easy way to convert them to an array and came up with the function below that does so. Is there a better way of setting my code up?

Public Function ConvertRangeIntoArray(ByVal convertRange As Range) As String()
    Dim temporaryVariant As Variant
    Dim is2DArray As Boolean
    Select Case True
        Case convertRange.Rows.Count = 1
            temporaryVariant = Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Transpose(convertRange))
        Case convertRange.columns.Count = 1
            temporaryVariant = Application.WorksheetFunction.Transpose(convertRange)
        Case Else
            temporaryVariant = convertRange
            is2DArray = True
    End Select

    Dim returnValue() As String
    Dim rw As Long
    Dim cl As Long
    If is2DArray Then
        ReDim returnValue(LBound(temporaryVariant) To UBound(temporaryVariant), LBound(temporaryVariant, 2) To UBound(temporaryVariant, 2))
        For rw = LBound(temporaryVariant) To UBound(temporaryVariant)
            For cl = LBound(temporaryVariant, 2) To UBound(temporaryVariant, 2)
                returnValue(rw, cl) = CStr(temporaryVariant(rw, cl))
            Next
        Next
    Else
        ReDim returnValue(LBound(temporaryVariant) To UBound(temporaryVariant))
        For cl = LBound(temporaryVariant) To UBound(temporaryVariant)
            returnValue(cl) = CStr(temporaryVariant(cl))
        Next
    End If

    ConvertRangeIntoArray = returnValue
End Function


texts: Implement a function to check if a linked list is a palindrome in c++

texts:
This is working example, I'm interested in mostly in knowing if there is any c++ related improvements you guys suggest? Also, do you think its better to solve this question iteratively or interviewer would prefer some recursive solution (assuming if that is possible)? Any other suggestions from interview point of view welcome?

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

template<typename valT>
struct node
{
  valT val;
  node<valT> *next;
  node() { next = nullptr; }
  node(valT v) : val(v),next(nullptr) { }
  ~node() { next = nullptr; }
};

using myNode = node<int>;
using myNodePtr = myNode *;
myNodePtr head = nullptr;

void showLL(myNodePtr head)
{
 std::cout << "Linked List =>";
 while(head){
   std::cout << head->val << ", ";
   head = head->next;
 }
 std::cout << std::endl;
}

int main(int argc, char **argv)
{
  myNodePtr prev = nullptr;
  for( int i = 1; i < argc ; i++ ) {
    myNodePtr tmp = new myNode(strtol(argv[i], NULL, 10));
    if(!head) {
      head = tmp;
    }
    if(prev){
      prev->next = tmp;
    }
    prev = tmp;
  }

  std::cout << "Input "  << std::endl;
  showLL(head);

  //Find middle
  //Push on stack until you find middle
  //Stop fast runner and pop back and compare and break if not same

  //Palindrome loop
  myNodePtr middleNode = nullptr;
  std::vector<int> stack;
  for(myNodePtr slowRunner = head, fastRunner = head; slowRunner; slowRunner = slowRunner->next) {
    if(!middleNode) {
      stack.push_back(slowRunner->val);

      if(fastRunner->next) {
        if(fastRunner->next->next) { //odd
          fastRunner = fastRunner->next->next;
          if(!fastRunner->next) {
            slowRunner = slowRunner->next;
          }
        } else { //even
          fastRunner = fastRunner->next;
        }
        if(!fastRunner->next) {
          middleNode = slowRunner;
          std::cout << "middle node =" << slowRunner->val << std::endl;
        }
      }
    } else {
      //even odd
      if( stack.back() != slowRunner->val) {
        std::cout << "Not a palindrom!" << std::endl;
        return 1; //delete all linked lists
      }
      stack.pop_back();
    }
  }

  std::cout << "is Palindrome"<< std::endl;
}


texts: Unit test for a method that populates a dictionary from an API call

texts:
I am building a unit test for a method that populates a dictionary from an API call (responding with JSON):

<TestMethod()> Public Sub GetListOfBadKPI_EmptyResponse_ReturnsEmptyDict()
        'Arrange
        Const scheduleName As String = "testSchedule"

        Const emptyResponseJSON As String = "{""data"":[{""r"":""N""}]}"
        Dim fakeResult As Data = JsonConvert.DeserializeObject(Of Data)(emptyResponseJSON)
        Dim fakeServer As MockServer = New MockServer With {.ReturnData = fakeResult}

        Dim CalculationSchedule As CalculationSchedule = New CalculationSchedule(scheduleName, fakeServer)

        'Act
        Dim resultDictionary As Dictionary(Of String, Integer) =
        CalculationSchedule.GetDictionaryOfBadCalculation()

        'Assert
        Assert.IsTrue(resultDictionary.Count = 0)
    End Sub

The fake server is used to return any data I need for the test, without actually connecting with the API:

Public Class MockServer
    Implements IServer

    Public Property ReturnData As Data

    Public Function ExecuteQuery(query As String, Optional server As String = Nothing) As Data Implements IServer.ExecuteSQLQuery
        Return ReturnData
    End Function
End Class

This setup allows me to simulate API responses to test different cases.

However, I am not happy with the way it is done, mainly since JSON strings have a lot of quotes " and dealing with those in VB.NET is daunting, since you have to double them up, it makes copy-pasting difficult, and so on.

Moreover, it does not feel very 'professional' to do it like this.

How could I improve this unit test?


texts: Binary Search given sorted array Unit test

texts:
I have implemented Binary search code for a given sorted array, written unit test too, Please review my BST unit test code and let me know your comments for improvements.

class BinarySearch {
    public int binSearch(int[] sortedArray, int key) {
        return search(0, sortedArray.length - 1, key, sortedArray);
    }

    private static int search(int start, int end, int key, int[] sortedArray) {
        int mid = start + ((end-start)/2);

        if (mid >= start && mid <= end) {
            if (sortedArray[mid] == key) {
                return mid;
            } else if (sortedArray[mid] > key) {
                return search(start, mid-1, key, sortedArray);
            } else if(sortedArray[mid] < key){
                return search(mid+1, end, key, sortedArray);
            }
        }

        return -1;
    }
}

public class BinarySearchTest {

    private BinarySearch binarySearchCUT;
    private static final int UNSUCCESSFUL = -1;

    @Before
    public void setUp(){
        binarySearchCUT = new BinarySearch();
    }

    @Test
    public void testShouldReturnUnsuccessfulOnEmptyArray() {
        assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{}, 0));
    }

    @Test
    public void testShouldReturnUnsuccessfulOnLeftBound() {
        assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 0));
    }

    @Test
    public void testShouldReturnUnsuccessfulOnRightBound() {
        assertEquals(UNSUCCESSFUL, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 101));
    }

    @Test
    public void testShouldReturnSuccessfulOnLeftBound() {
        assertEquals(0, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 1));
    }

    @Test
    public void testShouldReturnSuccessfulOnRightBound() {
        assertEquals(12, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 100));
    }

    @Test
    public void testShouldReturnSuccessfulOnMid() {
        assertEquals(7, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 19));
    }

    @Test
    public void testShouldReturnSuccessfulOnMidGreaterThanGivenNumber() {
        assertEquals(5, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 12));
    }

    @Test
    public void testShouldReturnSuccessfulOnMidLesserThanGivenNumber() {
        assertEquals(10, binarySearchCUT.binSearch(new int[]{1, 2, 4, 7, 8, 12, 15, 19, 24, 50, 69, 80, 100}, 69));
    }

}


texts: Using BigInt in JavaScript, write a factorial function that takes either a Number or BigInt and returns a BigInt

texts:
Is there anything missing or any pitfall when using BigInt?

// Assuming n is an integer and is 0 or greater
function factorial(n) {
    var i, result = BigInt(1);

    for (i = BigInt(2); i <= n; i++) {
        result *= i;
    }
    return result;
}

console.log(factorial(69));
console.log(factorial(200));

console.log(factorial(69n));
console.log(factorial(200n));

jsfiddle: https://jsfiddle.net/adr49tz2/


texts: Polynomial multiplication using Karatsuba method

texts:
I am trying to solve a problem, which requires me to output the xor of all coefficients in the product of 2 input polynomials. Having seen that the normal O(n^2) multiplication is not optimal, I tried to accomplish the same task by using the Karatsuba method which is equivalent to the one for numbers. It turned out that my code ran even slower in practice than the O(n^2) one, even though it gave me the correct answer.
#include <bits/stdc++.h>

using namespace std;

// In ra đa thức
// Print the polynomial coefficient
void print(vector<int> a) {
    for (int &i: a) cout << i << " ";
    cout << endl;
}

// Lũy thừa bậc 2 tiếp theo của 1 số
// The next power of 2 of a number
int nextPowerOf2(int n)
{
    n--;
    n |= n >> 1;
    n |= n >> 2;
    n |= n >> 4;
    n |= n >> 8;
    n |= n >> 16;
    n++;
    return n;
}

// Đưa 2 đa thức về cùng bậc, trả về bậc chung
// Make 2 polynomials to have the same degree
int equalize(vector<int> &a, vector<int> &b) {
    int x = a.size(), y = b.size();
    if (x > y) {
        b.resize(x);
        return x;
    }
    else if (x < y) {
        a.resize(y);
        return y;
    }
    return x;
}

// Loại bỏ các hệ số đa thức bậc cao nhất bằng 0
// Remove the highest degree coefficients which are equal
void cuttail(vector<int> &a) {
    while (a.back() == 0)
        a.pop_back();
}

// Hàm tính tổng 2 đa thức
// Sum of 2 polynomials
vector<int> sum(vector<int> a, vector<int> b) {
    int deg = equalize(a, b);
    vector<int> c(deg);
    for (int i = 0; i < deg; i++)
        c[i] = a[i] + b[i];
    return c;
}

// Hàm tính hiệu 2 đa thức
// Difference of 2 polynomials
vector<int> diff(vector<int> a, vector<int> b) {
    int deg = a.size();
    vector<int> c(deg);
    for (int i = 0; i < deg; i++)
        c[i] = a[i] - b[i];
    return c;
}

// Hàm tính tích 2 đa thức
// Product of 2 polynomials
vector<int> prod(vector<int> a, vector<int> b) {
    int deg = a.size();
    int hdeg = deg/2;
    if (deg == 1) return {a[0] * b[0]};
    vector<int> a1(hdeg), a2(hdeg), b1(hdeg), b2(hdeg), v(deg), u(deg), w(deg*2);
    for (int i = 0; i < deg/2; i++) {
        a1[i] = a[i];
        b1[i] = b[i];
        a2[i] = a[i + hdeg];
        b2[i] = b[i + hdeg];
    }
    u = prod(a1, b1);
    v = prod(a2, b2);
    w = prod(sum(a1, a2), sum(b1, b2));
    w = diff(diff(w, u), v);
    vector<int> wdeg(hdeg, 0), vdeg(deg, 0);
    w.insert(w.begin(), wdeg.begin(), wdeg.end());
    v.insert(v.begin(), vdeg.begin(), vdeg.end());
    return sum(u, sum(w, v));
};

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    int n, m;
    cin >> n;
    vector<int> a(n+1);
    for (int &i: a)
        cin >> i;
    cin >> m;
    vector<int> b(m+1);
    for (int &i: b)
        cin >> i;
    int deg = nextPowerOf2(equalize(a, b));
    a.resize(deg);
    b.resize(deg);
    vector<int> c = prod(a, b);
    cuttail(c);
    int result = 0;
    for (int i: c)
        result = result ^ i;
    cout << result;
    return 0;
}

I highly doubted that the vector allocation is behind the slow speed of multiplication, but I don't know how to fix it. I would appreciate if you can take a look at my code and give me some idea to improve it.
EDIT: As requested, I have a test case given here:
3 83 86 77 15
4 93 35 86 92 49
The 2 input polynomials are in the degree of 3 and 4 respectively: $$83 + 86x + 77x^2 + 15x^3$$ and $$93 + 35x + 86x^2 + 92x^3 + 49x^4$$
The output is 20731, which is the xor of all coefficients of the product of 2 input polynomials above (7719 xor 10903 xor 17309 xor 19122 xor 19126 xor 12588 xor 5153 xor 735 = 20731)


texts: Singleton model for modifying future .chart elements

texts:
I have written a singleton module which is to be used for some future modifications on .chart elements. Modification functions, such as colorArgumentButtons() are called recursively so that I don't have to iterate over all .chart elements in all functions.

Is my use of _ for private "class vars" proper? Otherwise they may conflict with my local vars.

Am I using the revealing module pattern correctly and is my namespace implementation okay? Feel free to comment on bad design choices!

var SuperHappy = (function (_parent, $) {

    var _my = _parent.Chart = _parent.Chart || {};

    // default settings
    var _settings = {
        autoFind: true,
        chartSelector: '.chart'
    };

    // jQuery vars
    var _$charts = $();

    _my.init = function (options) {
        /// <summary>
        /// Initializes the module.
        /// </summary>
        /// <param name="options">Custom JSON options</param>

        _settings = $.extend(_settings, options);

        if (_settings.autoFind) {
            _my.findCharts();
        }
    };

    var _applyFunctionToAll = function (func, $charts) {
        /// <summary>
        /// Applies the supplied function for each chart element in the collection.
        /// </summary>
        /// <param name="func">Function to be applied</param>
        /// <param name="$charts">Optional chart collection to apply function on</param>

        if (typeof $charts === 'undefined' && _$charts !== $()) {
            $charts = _$charts;
        }

        if ($charts.length === 1) {
            return false;
        }

        $charts.each(function () { // can this be converted to a for loop?
            func($(this));
        });

        return true;
    };

    _my.colorArgumentButtons = function (color, $chart) {
        /// <summary>
        /// Colors all argument buttons.
        /// </summary>
        /// <param name="color">Color to be used</param>
        /// <param name="$chart"></param>

        if (_applyFunctionToAll(_my.colorArgumentButtons.bind(null, color), $chart)) {
            return;
        }

        $chart.find('button').css('background-color', color);
    };

    _my.findCharts = function (selector) {
        /// <summary>
        /// Finds all chart elements.
        /// </summary>
        /// <param name="selector">Optional CSS selector for finding chart elements</param>

        selector = typeof selector !== 'undefined' ? selector : _settings.chartSelector;
        _$charts = $(selector);
    };

    return _parent;

})(SuperHappy || {}, jQuery);

jQuery(document).ready(function ($) {
    SuperHappy.Chart.init();
    SuperHappy.Chart.colorArgumentButtons('#f00');
});

http://jsfiddle.net/JrwRN/


texts: Printing the bits of an integer using bitfields and union

texts:
I am given a short int. I need to print the bits of it into two bytes. My code is as follows:

#include <stdio.h>

union info{
    short z;
    struct data{
        unsigned a:1;
        unsigned b:1;
        unsigned c:1;
        unsigned d:1;
        unsigned e:1;
        unsigned f:1;
        unsigned g:1;
        unsigned h:1;
  };
}t;

union byte{
short n;
struct inside{
    char p:8;
    char q:8;
  };
}v;

int main(void)
{
 short x;

 scanf("%hd",&x);

 v.n=x;

 t.z=v.q;

 printf("%d %d %d %d %d %d %d %d\n",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a);

 t.z=v.p;

 printf("%d %d %d %d %d %d %d %d",t.h,t.g,t.f,t.e,t.d,t.c,t.b,t.a);

 return 0;
}

My code gives the correct result. But I think that I've written an unnecessarily long code. Moreover, for larger bytes ( like in case of int ) , the process seems to be tiresome. Can I write the code in a simpler way ?


texts:
Seeking to learning and have fun, I wrote out this script (what I expected to be) self explanatory and would appreciate some comments on that.
I published it as a gist and tried to do my best on what I understand about object-orientation, documentation, code readability and python best practices, so to speak. The idea was practice and learn!
Any review in these or other concepts that could turn this result in a better solution is very welcome!
#!/usr/bin/python3
"""Update UNIX-like system user profile picture with its GitHub account's one

This script assumes same system and platform username, but a different one can be declared.
It downloads target GitHub account's picture and set it up to current system user
"""

import os
import requests
import configparser
import click

# Get system's logged username
USER = os.getlogin()

def save_github_picture(username, path):
    """Gets GitHub user account's profile picture and saves it into target path

    :param username: GitHub account username
    :param path: Picture's path destination
    """

    with open(path, "wb") as picture:
        gh_profile_picture = requests.get(f"https://github.com/{username}.png").content
        picture.write(gh_profile_picture)

def set_user_profile_picture(path):
    """Edits logged user AccountsService file to setup its profile picture path

    :param path: New profile picture path
    """

    # UNIX-like system user settings file
    accounts_service_path = f"/var/lib/AccountsService/users/{USER}"

    cfg = configparser.ConfigParser()
    cfg.read(accounts_service_path)
    cfg['User']['Icon'] = path

    with open(accounts_service_path, 'w') as accounts_service:
        cfg.write(accounts_service)

@click.command()
@click.argument('github_username', default=USER)
@click.option('--path', default=f"/home/{USER}/.face", help='define picture target path.')
def run(github_username, path):
    """Command line interface to define script's arguments

    :param github_username: GitHub account username (default: system user)
    :param path: New profile picture path (default: ~/.face)
    """
    try:
        save_github_picture(github_username, path)
        set_user_profile_picture(path)
    except Exception:
        raise
    else:
        print(f"User profile picture updated with {github_username}'s GitHub one")

if __name__ == '__main__':
    if os.geteuid() != 0:
        raise PermissionError("This action requires root privileges")
    else:
        run()


texts: Calculating unknown parts of a right triangle

texts:
I am in the process of creating a program that allows a user to input known parts of a right triangle and the calculates all of the unknown parts if it is possible.

I am using a class that I wrote in order to do the calculations. I wanted to know if there is a more efficient solution to this problem or if my code is good as is.

public class RightTriangle
{
    private double sideA; //Leg
    private double sideB; //Leg
    private double sideC; //Hypotenuse

    private double alpha;
    private double beta;

    private int numOfSides;
    private int numOfAngles;

    public RightTriangle(double a, double b, double c, double A, double B)
    {
        numOfSides=0;
        numOfAngles=0;

        sideA=a; if(sideA>0){numOfSides++;}
        sideB=b; if(sideB>0){numOfSides++;}
        sideC=c; if(sideC>0){numOfSides++;}

        alpha=A; if(alpha>0){numOfAngles++;}
        beta=B; if(beta>0){numOfAngles++;}

        if(numOfAngles<2)
        {
            findMissingAngles();
        }

        if(numOfSides<3)
        {
            findMissingSides();
        }

        if(!isPossible())
        {
            sideA=sideB=sideC=alpha=beta=0;
        }
    }

    private void findMissingAngles()
    {
        if(alpha==0)
        {
            calcAlpha();
        }

        if(beta==0)
        {
            calcBeta();
        }
    }

    private void findMissingSides()
    {
        if(sideA==0)
        {
            calcSideA();
        }

        if(sideB==0)
        {
            calcSideB();
        }

        if(sideC==0)
        {
            calcSideC();
        }
    }

    private void calcAlpha()
    {
        if(numOfAngles==1)
        {
            alpha=90-beta;
        }

        else
        {
            if(sideA>0 && sideB>0)
            {
                alpha=Math.toDegrees(Math.atan(sideA/sideB));
            }

            else if(sideB>0 && sideC>0)
            {
                alpha=Math.toDegrees(Math.acos(sideB/sideC));
            }

            else if(sideA>0 && sideC>0)
            {
                alpha=Math.toDegrees(Math.asin(sideA/sideC));
            }
        }
    }

    private void calcBeta()
    {
        beta=90-alpha;
    }

    private void calcSideA()
    {
        if(sideC>0)
        {
            sideA=Math.sin(Math.toRadians(alpha)) * sideC;
        }

        else if(sideB>0)
        {
            sideA=Math.tan(Math.toRadians(alpha)) * sideB;
        }
    }

    private void calcSideB()
    {
        sideB=sideA/Math.tan(Math.toRadians(alpha));
    }

    private void calcSideC()
    {
        sideC=sideA/Math.sin(Math.toRadians(alpha));
    }

    private boolean isPossible()
    {
        return ((alpha+beta+90)==180 && Math.abs(Math.sqrt(Math.pow(sideA, 2) + Math.pow(sideB, 2)) - sideC) < 1);
    }

    public void printInfo()
    {
        System.out.println("Triangle Info\n");
        System.out.println("Side A: " + String.format("%.02f", sideA));
        System.out.println("Side B: " + String.format("%.02f", sideB));
        System.out.println("Side C: " + String.format("%.02f", sideC) + "\n");
        System.out.println("Alpha: " + String.format("%.01f", alpha));
        System.out.println("Beta: " + String.format("%.01f", beta));
    }
}

Input

Enter Triangle Information (Enter 0 for missing parts)
Enter side A: 60
Enter side B: 60
Enter side C: 0

Enter angle Alpha: 0
Enter angle Beta: 0

Output

Triangle Info

Side A: 60.00
Side B: 60.00
Side C: 84.85

Alpha: 45.0
Beta: 45.0


texts: How to access a servlet in Tomcat Contanier using Java

texts:
I have a servlet deployed in a Tomcat Servlet Container in this link, http://localhost:9764/example/servlets/servlet/HelloWorldExample. I want to send a HTTP request to that servlet using Java. Just I want to get the return as a String. Currently I am using this code to do it, Is it OK to use this code?

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Client {

    public static void main(String[] args) {
        try {
            String webPage = "http://10.100.3.83:9764/example/servlets/servlet/HelloWorldExample";
            URL url = new URL(webPage);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.addRequestProperty("Name","andunslg");
            urlConnection.addRequestProperty("PW","admin");

            InputStream is = urlConnection.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);

            int numCharsRead;
            char[] charArray = new char[1024];
            StringBuffer sb = new StringBuffer();
            while ((numCharsRead = isr.read(charArray)) > 0) {
                sb.append(charArray, 0, numCharsRead);
            }
            String result = sb.toString();

            System.out.println("*** BEGIN ***");
            System.out.println(result);
            System.out.println("*** END ***");
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


texts:
I have created a quiz in Python that will generate a series of 10 questions to test the basic arithmetic skills of primary school children. To do this, I have used a while loop and random functions to generate random numbers and operations.

name = input("What is your name? ")
print("Hello, "+name+". You will be completing a quiz that will ask you 10 questions which will test you on adding, subtracting and multiplying two numbers together. Try your best at each question and good luck!")

import random
from operator import add, sub, mul

count = 0
score = 0
while count <= 9:
    ops = (add, sub, mul)
    op = random.choice(ops)
    x = random.randint(1,10)
    y = random.randint(1,10)

    if op == add:
        print("What is", x, "+",y, "? ")
        question_add = int(input())
        answer_add = op(x,y)
        if question_add == answer_add:
            print("Well done, this is correct!")
            score = score + 1
            count = count + 1
        else:
            print("Sorry, but this is incorrect.")
            count = count + 1

    elif op == sub:
        print("What is", x, "-", y, "? ")
        question_sub = int(input())
        answer_sub = op(x,y)
        if question_sub == answer_sub:
            print("Well done, this is correct!")
            score = score + 1
            count = count + 1
        else:
            print("Sorry, but this is incorrect.")
            count = count + 1

    elif op == mul:
        print("What is", x, "x", y, "? ")
        question_mul = int(input())
        answer_mul = op(x,y)
        if question_mul == answer_mul:
            print("Well done, this is correct!")
            score = score + 1
            count = count + 1
        else:
            print("Sorry, but this is incorrect.")
            count = count + 1

    if count == 10:
        print("Well done "+name+"! You have completed the quiz. Your final score out of 10 is "+str(score)+".")

I have done it, however, I do not think that this is the most efficient way to write this program. Can this program be condensed down further into fewer lines of code?


texts: Creating a proper workflow through version control and a Makefile

texts:
disclaimer: I've posted this around but the question keeps being put on hold for being inherently opinionated which I understand, just looking for some vague direction as to how a more experienced developer would approach this problem. I think this is the right place based on what I'm asking and I apologize if not.

So I've been working on creating a workflow for my buddy and I to use across the 2 projects and few servers we have. While at first I started with a shared group ownership option of the project files, I found this to be annoying and prone to human error.

I decided to convert the project to an svn controlled directory on a separate server where my production server and ourselves can pull from as needed, we can do local builds/testing and then tell the server to pull changes when we are ready to push to live, the concept is nice and seems pretty simple.

I have the svn system built out how I like it however I am struggling with how to set up my Makefile, my plan is to have a few commands:

clean - go and delete all extra artifacts created as you work
dev - spin up a local flask instance for testing purposes
venv - destroy and rebuild the virtual environment, used mainly for new setups
when you first pull the project
install - tell the production server to pull the most recent changes and then restart apache through an 'svn' user we all have access to

This is the simplest Makefile I can think of to do the jobs I want, as well as easily allowing for more support as time goes on if need be.

My problem is that I'm not exactly sure what the best way to approach 'make venv' and 'make install'. I have it set up manually right now and it works but it's just not graceful and I know it's becuase of my lack of knowledge in building a large python project like this. I've seen people use setuptools but I'm not sure if that's totally overkill for my project or not.

Does anyone have a similar workflow and/or have any suggestions on how I can improve my setup? I have my Makefile and install.sh script below for reference.

install.sh:

svn up

sudo /etc/init.d/apache2 restart

Makefile:

clean:
    find . -name \*~ -delete
    find . -name \*.pyc -delete

test:
    FLASK_APP=octlive/__init__.py \
    FLASK_DEBUG=1 \
    ../venv/bin/flask run --host=0.0.0.0

venv:
    virtualenv ../venv
    ../venv/bin/pip install -r require.txt

relclean: clean
    rm -rf ../venv

dev: relclean venv test

install:
    ssh user@server '/var/www/app/install.sh'

and just in case it's useful, my require.txt:

Flask
Flask-session
Flask-bootstrap
WTForms

I know this is not the best practice how I have my Makefile set up, specifically how I am using make to call install.sh on the production server. Has anyone taken a similar approach to what I've done and if so what suggestions do you have? I feel kind of lost in how to make this better while knowing it isn't that good to begin with.


texts: Detecting Windows Phone and Tablet clients

texts:
This is called from a VF page,

styleClass="{!IF(isWindows8Device, 'windows', 'not_windows')}"

So if it's a windows device, return true.

The best thing to do would be to add one method in DeviceDetectionCls to check for any windows device, instead of two methods.

For the purpose of this question though, I've to use both.

Could it be improved at all?

public Boolean isWindows8Device{
    get{
         String userAgent = System.currentPageReference().getHeaders().get('User-Agent');

         if(DeviceDetectionCls.isWindows8Phone(userAgent)){
            return true;
         }

         if(DeviceDetectionCls.isWindows8Tablet(userAgent)){
            return true;
         }

         return false;
    }
}


texts:
I have been learning Swift for the past day and thought I'd try a basic problem where I can do String manipulation. I am only on pg.100 of the Swift Programming Language on iBooks. Compared to python it seems to be quite difficult to actually modify individual characters as Swift is strongly typed/type safe.

  A Caesar cipher is used to encrypt a String by shifting each letter by x, where x is an integer, and replaces each letter withe the shifted letter. So encrypt("AB", 2) becomes "BC"

If anyone could point where I can reduce the number of lines or an easier way of doing/or idioms I have missed that'd be just what I am looking for.

import Cocoa

func encrypt(message: String, shift: Int) -> String {

    let scalars = Array(message.unicodeScalars)
    let unicodePoints = scalars.map({x in Character(UnicodeScalar(Int(x.value) + shift)!)})

    return String(unicodePoints)
}

let message = "Attack at dawn"
print(encrypt(message: message, shift: 2))


texts:
I have these lines of code in my view:

<?php
    $count = count($product->getTags());
    $tagsStr = '';
    foreach($product->getTags() as $key => $tag){
        $tagsStr.= " " . $tag->getTag();
        if(($key == 0 && $count < 1) || ($key == 0 && $count >1 && $key != $count)){
            $tagsStr .= ',';
        }
    } ?>

It prints strings like:

  Fish, Onions

Or

  Fish, Onions, Eggs

All these items are stored in an ArrayCollection $product->getTags();.

I find that these are a lot of lines for completing something this simple. I was wondering if you have ideas on simplifying this code.


texts: Effective usage of multiple joins in Eloquent dependent on variable

texts:
I have an Eloquent model that has multiple types of joins that is used to filter out different request to grab the data of movies e.g.: Actors, Directors, Writers, etc...

The joins are necessary because they use unconventional pivot tables. All the queries and eloquent here works and gives the desired returned data - however I'm breaking DRY (Don't Repeat Yourself) principle for each join filters I am creating within a controller.

Here are the code segments that I would like to tweak:

This is a call for all movies by actors:

public function getByActor($where, $limit, $offset)
{
    $movieData = array();

    $restrictedIdList = $this->getRestrictedIds();
    if (empty($restrictedIdList)) {
        $restrictedIdList = array(0);
    }

    $movieData = Movie::
        FilterByActorWithInnerJoin(urldecode($where['actorName']))
        ->selectRaw('movie.*')
        ->where('movie.status','=','active')
        ->whereNotIn('movie.id', $restrictedIdList)
        ->take($limit)
        ->skip($offset)
        ->get()
        ->toArray();
    return $movieData;
}

This is for Writers:

public function getByWriter($where, $limit, $offset)
{
    $movieData = array();

    $restrictedIdList = $this->getRestrictedIds();
    if (empty($restrictedIdList)) {
        $restrictedIdList = array(0);
    }

    $movieData = Movie::
        FilterByWriterWithInnerJoin(urldecode($where['writerName']))
        ->selectRaw('movie.*')
        ->where('movie.status','=','active')
        ->whereNotIn('movie.id', $restrictedIdList)
        ->take($limit)
        ->skip($offset)
        ->get()
        ->toArray();
    return $movieData;
}

As you can see the only difference is the FilterBy<filter type join>WithInnerJoin that I have created within my model.

Here are the joins of the model:

public function scopeFilterByWriterWithInnerJoin($query,$writerName)
{
    $query->join('movie_writers as mw', 'mw.movie_id', '=', 'movie.id')
        ->join('writers as w',function($join) use ($writerName){
            $join->on('w.id', '=', 'mw.writer_id')
                ->where('w.name','like','%'.$writerName.'%');
        });
}

public function scopeFilterByActorWithInnerJoin($query,$actorName)
{
    $query->join('movie_actors as ma', 'ma.movie_id', '=', 'movie.id')
        ->join('actors as a',function($join) use ($actorName){
            $join->on('a.id', '=', 'ma.actor_id')
                ->where('a.name','like','%'.$actorName.'%');
        });
}

I will have to do the same for producers, directors, etc.

Is there a more efficient way to do this?


texts: Perm-Missing-Elem: 100% functional score, but only 60% performance

texts:
I cannot figure out why I didn't get 100% success from the Codility's Perm-Missing-Element test even I solve with \$O(n)\$. I will appreciate any advice/answers.

You can see the problem, my code, and the scores on the Codility site, as well as here.

Problem Definition

  A zero-indexed array A consisting of N different integers is given. The array contains integers in the range [1..(N + 1)], which means that exactly one element is missing.
      Your goal is to find that missing element.
      Write a function:

class Solution { public int solution(int[] A); }

  that, given a zero-indexed array A, returns the value of the missing element.
      For example, given array A such that:

A[0] = 2
A[1] = 3
A[2] = 1
A[3] = 5

  the function should return 4, as it is the missing element.
      Assume that:
      N is an integer within the range [0..100,000];
      the elements of A are all distinct;
      each element of array A is an integer within the range [1..(N + 1)].
  Complexity:
      expected worst-case time complexity is O(N);
      expected worst-case space complexity is O(1), beyond input storage (not counting the storage required for input arguments).
      Elements of input arrays can be modified.

Solution

Here is the code I wrote as an answer:

public class Solution {

        public int solution(int[] A) {

            int N = A.length + 1;
            int total = N * (N + 1) / 2;

            for (int i : A) {

                total -= i;
            }

            return total;
        }
    }


texts: Implementation of Observable with multiple callback function signatures

texts:
I have been playing around with ways of implementing a generic class for supporting the observer pattern. I have already asked to review a basic approach here. Now I have come up with an Observable class that supports parametrizing with an arbitrary number of function signatures, in order for the subject class to register and notify observers interested in different kinds of events that require different kind of information to be transmitted.

Here is the code:

observable.h:

#include <functional>
#include <vector>
#include <tuple>

template<typename ... Funcs>
class Observable
{
public:
    using ObserverList = std::tuple<std::vector<std::function<Funcs>>...>;

    template<unsigned int eventidx, typename Callable>
    void AttachObserver(Callable c)
    {
        std::get<eventidx>(observers).push_back(c);
    }

    template<unsigned int eventidx, typename ... T>
    void NotifyObserversOfEvent(T ... args)
    {
        for(auto f: std::get<eventidx>(observers))
        {
            f(std::forward<T>(args)...);
        }
    }

private:
    ObserverList observers;
};

Sample Test code

main.cpp:

#include <iostream>
#include <functional>
#include <vector>

#include "observable.h"

class A : public Observable<
                            void(void),
                            void(int,std::string),
                            void(int,int),
                            >
{
public:
    enum Event : unsigned
    {
        Event0,
        Event1,
        Event2
    };

private:
    int a;
    std::string s;
};

class B
{
public:
    void EventZeroHappened()
    {
        std::cout << "B has observed event zero\n";
    }

    void EventOneHappened(int a, std::string s)
    {
        std::cout << "B has observed event one with params: " << a << " and " << "\"" << s << "\"" <<'\n';
    }

    void EventTwoHappened(int a, int b)
    {
        std::cout << "B has observed event two with params: " << a << " and " << b <<'\n';
    }
};

int main()
{
    A a;
    B b;

    a.AttachObserver<A::Event::Event0>([&b](){b.EventZeroHappened();});
    a.AttachObserver<A::Event::Event1>([&b](int i, std::string s){b.EventOneHappened(i,s);});
    a.AttachObserver<A::Event::Event2>([&b](int i, int j){b.EventTwoHappened(i,j);});

    a.NotifyObserversOfEvent<A::Event::Event0>();
    a.NotifyObserversOfEvent<A::Event::Event1>(37,"Hello There");
    a.NotifyObserversOfEvent<A::Event::Event2>(182,150);
}

Basically the idea I wanted to implement is that the user of the observable class, simply writes in the template parameter list, the function signatures of the callback it supports. Instead of forcing the observer to implement an abstract interface and derive from it, which pollutes the observer code and creates an unnecessary dependency. The only draw back is that in order to select which event the observer wants to subscribe to (and which event the subject wants to transmit) it has to be done via integral constant, which is made a bit nicer in the example with an enum. I'm still searching for a better way to do this part.

The reason behind that is that, even in the old way of implementing observer, where you hard-code in a *.h file a pure abstract class and tell other classes that want to observe: "please overload this virtual functions if you want to observe me". And the meaning of each of the events you are going to notify is encoded in the names of the functions. I thought this example was a more general and flexible way of transmitting the same information. Plus being a bit easier to modify to add new events.

As always, I would welcome any comments, corrections criticisms and suggestions.


texts:
There are some things that smell about this code, for instance multiple checking, length both returning value and changing some other variable. But I can't for the moment figure how to make it nicer, or if that's even possible. Converting it to stack-based solution seems to be making it a bit too-complicated.

Please provide a review of this code, what do you think could be improved, if possible, both in terms of readability and performance or possible problems.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    boolean isBalanced = true;

    public boolean isBalanced(TreeNode root) {
        length(root);
        return isBalanced;
    }

    public int length(TreeNode a) {
        if (a == null) {
            return 0;
        }
        if (isBalanced == false) {
            return 0;
        }
        int x = length(a.left);
        if (isBalanced == false) {
            return 0;
        }
        int y = length(a.right);
        if (isBalanced == false) {
            return 0;
        }
        if (Math.abs(x - y) > 1) {
            isBalanced = false;
            return 0;
        }
        return Math.max(x, y) + 1;
    }
}

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.


texts: Python - How to efficiently bin multiple dependent variables to a common independent variable?

texts:
Setup: I have ~30 parameters (dependent variables) measured simultaneously along a common time axis with ~1Hz resolution (independent variable). I need to calculate bin averages for all parameters, with a bin width of 10 seconds on the time axis. Potentially also other statistical parameters like standard deviation and median are desired. Binning should be lower limit included, upper excluded, with the last digit of the binned time axis ending to 5. I need to do this quite often (>3M entries total for one parameter set), so I look for an efficient solution.

Context: Binned data I need is an intermediate data product, meaning it's just read data --> binning --> write binned data. That makes me believe something 'high-level' like pandas might bring too much overhead. I've read some posts on the topic on Stackoverflow, e.g. here or here. Also, I know there is scipy.stats.binned_statistic (see here) but that would call binning of the time axis for every parameter, thus being inefficient imho.

What I've done so far:

# example input time axis t:
# note #1: there can be 'gaps' when data recording is interrupted
# note #2: t is guaranteed to be strictly increasing
t = np.concatenate((np.linspace(13, 24, 12), np.linspace(56, 100, 45)))

# 'binned' time axis:
tmin, tmax = np.rint(t[0]), np.rint(t[-1])
t_binned = np.arange((tmin-tmin%10)+5, (tmax-tmax%10)+6, 10)
# array([ 15,  25,  35,  45,  55,  65,  75,  85,  95, 105])

# calculate bin starting indices and bins
binstarts = np.append(t_binned-5, t_binned[-1]+5)
# since t is strictly increasing, I use np.searchsorted which is slightly faster than np.digitized
bins = np.searchsorted(binstarts, t, side='right')

# remove elements from the binned time axis that would not map to any values:
t_binned = t_binned[np.bincount(bins-1).astype(bool)]
# array([ 15,  25,  55,  65,  75,  85,  95, 105])

now that I have the bins, I can apply it to any parameter v_i from my input data with parameters v_n:

v_i = np.random.rand(t.size)
v_i_binavg = []
for bin_no in np.unique(bins):
    v_i_binavg.append(np.nanmean(v_i[bins == bin_no]))
    # potentially also other calculations here, like stdev or median

This works in principle but feels a bit hacky and I think efficiency could be improved, e.g. by getting rid of the for loop in the last step. I found this to be a bottleneck in this approach (which is basically what I do now as well). Any suggestions?

p.s. for regular, 1D binning (avg or sum), I found this approach to be very efficient - however, that excludes the whole 'mapping to a time axis' problem.


texts: Assigning zero to random cells in a pandas.DataFrame

texts:
I am trying to assign 0 to random cells in a one dimensional pandas.DataFrame.
The below code is the best way I could think of doing this, however I believe there may be a neater approach to this problem.

import numpy as np
import pandas as pd
from random import randint

df = pd.DataFrame(np.random.randint(20, size=(10, 1)), columns=list('A'))
col_size = len(df.columns)
row_size = len(df.index)
df[df.columns[randint(0, col_size-1)]][randint(0, row_size-1)] = 0

Could someone please review and suggest if this is a good approach or there are better ways to do this?


texts: Making a semi-random order of an array, based on a string

texts:
I made code to shuffle an array in a semi-random way. That is, it has to be random based on a string, but for the same string, it should return the same order.

Is there a better way of doing it?

function djbHash(s) {
    let hash = 5381;

    for (let c of s) {
        hash = hash * 33 + c.charCodeAt(0);
    }
    return hash;
}

function mapToValues(s, values) {
    return values[djbHash(s) % values.length];
}

var randomArray=[];
var myArray = [0,1,2,3,4,5,6,7,8,9];
var string  = "bigcat";
var length = myArray.length;
for(var i=0;i<length;i++){
    console.log(myArray)
  var item = mapToValues(string, myArray);
    var removed = myArray.splice(myArray.indexOf(item),1);
  console.log(removed);
  randomArray.push(removed[0]);
}
console.log(randomArray);

jsFiddle