texts: Sorting an array of strings using pointers (followup)

texts:
This is a follow-up to this post.

Things I've changed:

The number of strings is checked.
I'm using pointers now.

I'll use fgets in more mission critical situations. For a lab assignment, the scanf approach will suffice I hope.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LEN 100
#define WID 80

void sort(char *s[], int n);

void display(char *s[], int n);

int main()
{
    int n, i;
    char *s[LEN];
    printf("Enter number of strings : ");
    scanf("%d", &n);
    printf("Enter strings one by one :\n");
    if (n > LEN) {
        printf("Sorry, maximum strings allowed is %d. Defaulting.", LEN);
        n = LEN;
    }
    for (i = 0; i < n; i++) {
        printf("%d : ", i + 1);
        s[i] = (char *) malloc(WID * sizeof(char));
        scanf(" %s", s[i]);
    }

    printf("The initial elements are:\n");
    display(s, n);
    sort(s, n);
    printf("The elements after sorting are:\n");
    display(s, n);

    return 0;
}

void sort(char *s[], int n)
{
    char *temp;
    int item, i;

    for (item = 1; item < n; item++) {
        temp = s[item];
        for (i = item; i > 0 && strcmpi(s[i - 1], temp) > 0; i--);
        memcpy(&s[i + 1], &s[i], (item - i) * sizeof(char *));
        s[i] = temp;
    }
}

void display(char *s[], int n)
{
    int i;
    printf("\n\n");
    for (i = 0; i < n; i++) {
        printf("%s ", s[i]);
    }
    printf("\n\n");
}

Any alternative or more elegant approach is welcome.


texts: Finding the comic ID of the last XKCD comic published

texts:
I decided to sidetrack and create a XKCD viewer. For certain functionality, I needed to be able to find the ID of the last comic published. This was my attempt. I'm using Enlive here to parse the page itself.

I struggled with trying to find a CSS selector to get the text node, then finally gave up and decided to do some manual parsing. It got long, and ugly, but it works! The problem is that the only place I can concretely find page IDs is as a note at the bottom of the page:

  Permanent link to this comic: https://xkcd.com/1988/

To parse that ID at the end of the link out, I need to find the text node, then parse the String. The latter was easy. The former took me a little under an hour due mostly to inexperience with CSS selectors.

What I'm looking for:

Is there a way to get the text node directly via Enlive CSS-like selectors?
Anything else that may simplify this. It's quite a series of transformations. I obviously could separate it down into a few function, but I can't see ever needing the functionality anywhere else, and it's fairly simple to test as is. Any recommendations here?

Use as of posting this:

(find-last-id)
=> 1988

(ns xkcd-viewer.mcve
  (:require [net.cgrand.enlive-html :as e])
  (:import (java.net URL)))

(def base-url "https://xkcd.com/")

; I actually use this a couple time in the real code. It doensn't seem as useful here though.
(defn parse-id?
  "Returns the str-n parsed as a long, or nil if it's unparsable."
  [str-n]
  (try
    (Long/parseLong str-n)

    (catch NumberFormatException _
      nil)))

(defn find-last-id []
  (let [digit? #(Character/isDigit ^Character %)

        id-container (-> (e/html-resource (URL. base-url))
                         (e/select [:#middleContainer])
                         (first)
                         (:content))

        raw-id (->> id-container
                    ; The text node to find is surrounded by <br>s, so
                    (drop-while #(not= (:tag %) :br)) ; get rid of everything before the first br,
                    (drop 1) ; then the br itself,
                    (first) ; then get the text node, then
                    (drop-while (comp not digit?))
                    (take-while digit?)
                    (apply str))] ; then turn the digits into a string to be parsed.

    (if-let [parsed (parse-id? raw-id)]
      parsed
      (throw (RuntimeException.
               (str "Parser broken! Did XKCD change their site?\nFound ID: " raw-id))))))


texts: A simple data class based on an existing collection (Scala)

texts:
I'm fairly new to Scala and I would like to learn it properly. My current task is to create a type to represent a heap, as seen in interpreters: a mapping from addresses in memory to values stored there.

A heap of that kind is very much like Map, but I would like to hide implementation details and only expose the interface consisting of a few methods, which in pseudo code would be:

* update :: address value -> Heap
* free :: address -> Heap
* alloc :: value -> (Heap, Address)
* addresses :: () -> Set[Address]
* lookup :: address -> [Value]

Here is what I came up with:

trait Heap[T] {

  def update(address: Address, value: T): Heap[T]

  def free(address: Address): Heap[T]

  def alloc(value: T): (Heap[T], Address)

  def addresses(): Set[Address]

  def lookup(address: Address): Option[T]
}

private case class HeapImpl[T](map: Map[Address, T]) extends Heap[T] {
  override def update(address: Address, value: T): Heap[T] = HeapImpl[T](map.updated(address, value))

  override def free(address: Address): Heap[T] = HeapImpl[T](map.removed(address))

  override def alloc(value: T): (Heap[T], Address) = {
    val nextFreeAddress = addresses().maxOption.getOrElse(0) + 1
    (HeapImpl(map.updated(nextFreeAddress, value)), nextFreeAddress)
  }

  override def addresses(): Set[Address] = map.keys.toSet

  override def lookup(address: Address): Option[T] = map.get(address)
}

object Heap {
  def apply[T](): Heap[T] = HeapImpl(Map())
}

I would like to know if this is proper idiomatic Scala or should I approach it differently.


texts: A Summation Function For Arbitrary Nested Vector Implementation In C++

texts:
I am trying to deal with some calculations on nested vector data in C++. The nested vector data may be like std::vector<long double>, std::vector<std::vector<long double>>, or std::vector<std::vector<std::vector<long double>>>. I want to focus on summation here, and the calculation of summation could be done with the Sum function implemented here. Is there any possible improvement of this code?
The function declaration part is as below.
template <class T>
static long double Sum(const std::vector<T> inputArray);
static long double Sum(long double inputNumber);

The function implementation part is as below.
template<class T>
inline long double Sum(const std::vector<T> inputArray)
{
    long double sumResult = 0.0;
    for (auto& element : inputArray)
    {
        sumResult += Sum(element);
    }
    return sumResult;
}

inline long double Sum(long double inputNumber)
{
    return inputNumber;
}

Test for this sum function:
std::vector<long double> testVector1;
testVector1.push_back(1);
testVector1.push_back(1);
testVector1.push_back(1);
std::cout << std::to_string(Sum(testVector1)) + "\n";

std::vector<std::vector<long double>> testVector2;
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
testVector2.push_back(testVector1);
std::cout << std::to_string(Sum(testVector2)) + "\n";

std::vector<std::vector<std::vector<long double>>> testVector3;
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
testVector3.push_back(testVector2);
std::cout << std::to_string(Sum(testVector3)) + "\n";

Oct 18, 2020 Update
Reference:

The follow-up question:
A Summation Function For Various Type Arbitrary Nested Iterable Implementation in C++

The further implementation with c++-concepts:
https://stackoverflow.com/q/64414869/6667035


texts:
I wrote an implementation for a simple queue in C++ (for practice, since there's an stl queue).  I've been trying to focus on memory management and the rule of three.  Any suggestions/improvements?

(Personally, I feel like there has to be a better way to overload the copy assignment operator).

#ifndef QUEUE_H
#define QUEUE_H

#include "assert.h"

#define NULL 0

template <typename T>
class Queue
{
 public:
  Queue();
  Queue(const Queue& other);
  ~Queue();

  void enqueue(T data);
  T    dequeue();

  bool isEmpty() { return (front_ == back_); }

  Queue& operator=(const Queue& other);

 private:
  struct node
  {
    T     data;
    node* next;
  };

  node* front_;
  node* back_;
};

template <typename T>
Queue<T>::Queue()
{
  front_ = new node();
  back_  = front_;
}

template <typename T>
Queue<T>::Queue(const Queue<T>& other)
{
  front_     = new node();
  back_      = front_;
  node* temp = other.front_;

  while (temp != other.back_)
  {
    enqueue(temp->data);
    temp = temp->next;
  }
}

template <typename T>
Queue<T>::~Queue()
{
  while (!isEmpty()) { dequeue(); }
}

template <typename T>
void Queue<T>::enqueue(T data)
{
  back_->data = data;
  back_->next = new node();
  back_       = back_->next;
}

template <typename T>
T Queue<T>::dequeue()
{
  assert(!isEmpty());

  node* temp = front_;
  T     data = front_->data;
  front_     = front_->next;

  delete temp;
  return data;
}

template <typename T>
Queue<T>& Queue<T>::operator=(const Queue<T>& other)
{
  if (this != &other)
  {
    node* temp = other.front_;

    while (!isEmpty()) { dequeue(); }
    while (temp != other.back_)
    {
      enqueue(temp->data);
      temp  = temp->next;
    }
  }
  return *this;
}

#endif


texts:
I am using the below code in Python to input a N*N matrix in its original form:

n = int(input())
l=[]
for i in range(n):
    x=input().split()
    c=[]
    for j in range(n):
        c.append(int(x[j]))
    l.append(c)

print(l)

Here's the output:

2 #input n

1 3 #input row

1 5. # input another row

[[1, 3], [1, 5]] # final matrix

How can this code be improved? Is there a better way to take a matrix as input?


texts:
Base64 is a widely used encoding mechanism to allow arbitrary binary content to be transferred as printable text.  This program is designed to take binary file as input and produce a Base64-encoded binary file as output.

#include <stdlib.h>
#include <stdio.h>

void enblock( int len, char *in, char *base64, FILE *outputFILE)
{
    fprintf(outputFILE, "%c", base64[in[0] >> 2]);
    fprintf(outputFILE, "%c", base64[((in[0] & 3) << 4) | ((in[1] & 240) >> 4)]);
    if (len > 1)
    {
        fprintf(outputFILE,"%c", base64[((in[1] & 15) << 2) | ((in[2] & 192) >> 6)]);
    }
    else
    {
        fprintf(outputFILE, "%c", '=');
    }
    if (len > 2)
    {
        fprintf(outputFILE, "%c", base64[(in[2] & 63)]);
    }
    else
    {
        fprintf(outputFILE, "%c",'=');
    }
}

void endecode (FILE *inputFILE, FILE *outputFILE)
{
    static char base64[]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    int len = 0;
    int i = 0;
    char buffer[3] = {0};
    while ((len = fread(buffer,sizeof(char),3,inputFILE)) >= 1)
    {
        for (i = len; i < 3; i++)
            buffer[i] = 0;
        enblock(len, buffer, base64 ,outputFILE );
    }
}

int main()
{
    FILE *file1 = NULL;
    FILE *file2 = NULL;
    if (NULL == (file1 = fopen("INPUT.txt", "r")))
    {
        printf("Can't open INPUT file!");
        return -1;
    }
    if (NULL == (file2 = fopen("OUTPUT.base64", "wb")))
    {
        printf("Can't create OUTPUT file");
        return -1;
    }
    endecode(file1,file2);
    fclose(file1);
    fclose(file2);
    return 0;
}


texts:
I'm trying to sketch out a stripped down generic form validation example.  I started by creating Plain Old PHP Objects (referred as POPOs) for form input with some classes such as a validator and html renderer class, that I then reduced to explicit functions.

The POPOs are useful in as much as you can comment and glance at expected properties.  Looking at the code, one starts to wonder if I'd be better off with well defined arrays as inputs and not bother with the plain objects, as some of the object wrangling (the popo functions) are effectively just wrappers for array functions, and perhaps an array would just do.

Are these plain objects muddying the waters?

Any comments welcome.

<?php
class UserForm
{
    public $email;
}

class UserFormErrors extends UserForm
{}

function map_array_to_popo(array $array, $object)
{
    foreach($object as $key => $value)
        $object->$key = isset($array[$key])
            ? $array[$key]
            : null;

    return $object;
}

function popo_has_empty_values($object)
{
    $array = (array) $object;

    return empty(array_filter($array));
}

function user_form_validate(UserForm $input)
{
    $errors = new UserFormErrors;
    if($input->email == '') {
        $errors->email[] = 'Email address is required.';
    } elseif(filter_var($input->email, FILTER_VALIDATE_EMAIL) === false) {
        $errors->email[] = 'Email address must be valid.';
    }

    return $errors;
}

function user_form_html_render(
        $action = '',
        UserForm $values,
        UserFormErrors $errors
    )
{
    $escape = function($string) {
        return htmlspecialchars($string);
    };
    $error = function($messages) use ($escape) {
        return
            empty($messages)
            ? ''
            : '

' .
            implode('

', array_map($escape, $messages)) .
            '

';
    };
    ?>
    <form method='POST' action="<?= $action ?>">
        Email address:
        <input type="text" name="email" id="email" value=
        "<?= $escape($values->email) ?>">
        <?= $error($errors->email) ?>
        <input type="submit">
    </form>
    <?php
}

if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $input   = array_filter($_POST, 'is_string');
    $input   = array_map('trim', $input);
    $values  = map_array_to_popo($input, new UserForm);
    $errors  = user_form_validate($values);
    $valid   = popo_has_empty_values($errors);

    if($valid) {
        // Form values look good, do what you want with values.
        echo 'Email address entered is: ' . $values->email;
    } else {
        // Display form with data and errors
        user_form_html_render('', $values, $errors);
    }
} else {
    user_form_html_render('', new UserForm, new UserFormErrors);
}


texts:
I need to sort a list of lists. The following is a compare function:

def compare(lhs, rhs): # lhs&rhs are lists
    delta = len(lhs) - len(rhs)
    if delta > 0:
        return 1
    elif delta < 0:
        return -1
    if lhs < rhs:
        return 1
    elif lhs > rhs:
        return -1
    return 0

It looks pretty wordy. Is there a way to rewrite the function without performance penalty?


texts:
I have the following struct:

public struct VolumeIssue
{
    public readonly string Volume;

    public readonly string Issue;

    public VolumeIssue(string volume, string issue)
    {
        this.Volume = volume;
        this.Issue = issue;
    }

    public bool IsNullOrWhiteSpace()
    {
        return string.IsNullOrWhiteSpace(this.Volume) && string.IsNullOrWhiteSpace(this.Issue);
    }

    public override string ToString()
    {
        StringBuilder stringRep = new StringBuilder("");

        if (!string.IsNullOrWhiteSpace(this.Volume))
        {
            stringRep.AppendFormat("v. {0}", this.Volume);
            if (!string.IsNullOrWhiteSpace(this.Issue))
            {
                stringRep.AppendFormat(" iss. {0}", this.Issue);
            }
        }

        return stringRep.ToString();
    }
}

Overall I am happy with it. But being still a relatively inexperienced developer, I would like some input on the design of this struct. Ideas on how to flesh it out are also greatly appreciated.

In order to add more context, here is one of the use cases:

public class IssueRangeCoverage
{
    public VolumeIssue Start { get; set; }

    public VolumeIssue End { get; set; }

    public override string ToString()
    {
        if (this.Start.IsNullOrWhiteSpace() && this.End.IsNullOrWhiteSpace())
        {
            return "";
        }

        string endString = this.End.ToString();

        if (string.IsNullOrWhiteSpace(endString))
        {
            endString = "Current";
        }
        return this.Start.ToString() + " - " + endString;
    }
}


texts: Optimisation potential when using deferred/promises and looping

texts:
I am fairly inexperienced when it comes to jQuery/JavaScript, so although the following code works, I am just looking to understand if my use of looping, deferred/promises etc could be optimised at all.
Purpose of code
This is just part of a larger script, which I have written to load images and its written details into a viewer. This code loads the initial image, or if an image hasn't been previously preloaded.
The deferred part of the code specification is to allow multiple images (on the single slide of the viewer) to be loaded before the slide is shown.
$galleryImageDetails.css({ 'opacity' : '0' });
$galleryImage.css({ 'opacity' : '0' });

$('.loader').show();

if ( preloadedArray[entryId] ) {

    beingPreloaded = entryId;

} else {

    $('.image-title h1').html(entryTitle);

    if ( entryProcess ) {
        $('.image-process span').html(entryProcess);
        $('.image-process').show();
    } else {
        $('.image-process').hide();
    }

    if ( entryDimensions ) {
        $('.image-dimensions p').html(entryDimensions);
        $('.image-dimensions').show();
    } else {
        $('.image-dimensions').hide();
    }

    $('.image-price p').html(entryPrice);

    preloadedArray[entryId] = [];

    preloadedArray[entryId].push($(''));

    $.each(entryVariants, function (key, val) {

        var variant = $('');

        preloadedArray[entryId].push(variant);

    });

    $('.image-variants .wrapper').empty();

    var preloadedArrayLength = preloadedArray[entryId].length;

    var preloadsComplete = [];

    $.each( preloadedArray[entryId], function( key, value ) {

        var result = $.Deferred();
        preloadsComplete.push(result.promise());

        preloadedArray[entryId][key].on('load', function() {

            if ( key == 0 ) {

                var imageWrap = '';

                $galleryImage.html(preloadedArray[entryId][key]);
                $('.gallery-image > img').wrap(imageWrap);

            }

            if ( key > 0 ) {

                variantLarge = entryVariants[key][1];
                variantName = entryVariants[key][2];

                var variantWrap = '

';

                $('.image-variants .wrapper').append(preloadedArray[entryId][key])

                $('.image-variants .wrapper > img').wrap(variantWrap);

            }

            result.resolve();

        });

    });

    $.when.apply($, preloadsComplete).done(function () {

        $('#item'+entryId).attr('data-image-loaded', 'y');
        imagePreload();

        $('.loader').hide();

        $galleryImageDetails.css({ 'opacity' : '1' });
        $galleryImage.css({ 'opacity' : '1' });

        prevNextLock = false;

    });

}


texts:
I'm solving the "Balanced Parenthesis" problem in Ruby, and I came up with this solution.

def balanced?(string)
  return false if string.length.odd?

  pairs = { '{' => '}', '[' => ']', '(' => ')' }

  string.chars.each_with_object([]) do |bracket, stack|
    if pairs.keys.include?(bracket)
      stack << bracket
    elsif pairs.values.include?(bracket)
      return false unless pairs[stack.pop] == bracket
    else
      return false
    end
  end

  true
end

The first check is for the length of the string: If it's odd, the can't be balanced.

I then iterate over the chars of the string:

If I find an opening bracket, I add it to an array.
If I find a closing bracket, I remove the last element from the array and check if the brackets are a pair.
If I find neither an opening or a closing bracket, the string must be invalid.

Are there any edge cases I'm missing? Also, this doesn't seem efficient: First, there's an added dictionary. Second, there is a linear search on each iteration to check either the keys or the values of the dictionary. There's an \$O(n)\$ on the array resulting from the string, as well, but I'm not sure if we can avoid this.


texts:
We have a pretty big code base that made use of RSVP which we are moving to node 4.3.2+. The only RSVP feature we use frequently that's not in the native js Promise api is the hash() function. I expected to either use the RSVP source or find something on stack overflow. Most people appear to be be solving the problem with different constraints & requirements which makes existing solutions I found somewhat complex so I whipped up my own:

function hash (hashOfPromises) {
  var keys = Object.keys(hashOfPromises);
  return Promise.all(keys.map(function (key) {
    return hashOfPromises[key];
  })).then(function (list) {
    return list.reduce(function (hashOfResolved, value, i) {
      hashOfResolved[keys[i]] = value;
      return hashOfResolved;
    }, {});
  });
}


texts: Converting unsigned integer value into byte array

texts:
I have a function that takes an unsigned value and transforms it into a std::vector<std::uint8_t>. The requirements (and post conditions) are as follows:

The code must utilize "modern C++" up to C++14
The focus is on readability/maintainability first, performance second
The most significant byte must be at index 0.
The lease significant byte must be at index size()-1.
The return type cannot be changed; this is a requirement stemming from other code not shown in this context (larger application requirement). Also avoids a conversion from one container to std::vector.
The resulting vector must be as compact as possible. For values that decompose into fewer bytes than sizeof(unsigned), the resulting vector must not contain unnecessary MSB's (that is, zero value bytes).
The code must be endianness-agnostic and portable to various other architectures and platforms.

Here is the current implementation I have:

using BinaryStreamByteVector = std::vector<std::uint8_t>;

BinaryStreamByteVector CreateMultiByteInteger(unsigned value)
{
    BinaryStreamByteVector value_bytes;

    while (value != 0)
    {
        std::uint8_t byte = value & 0xFF;
        value_bytes.insert(value_bytes.begin(), byte);

        value >>= 8;
    }

    return value_bytes;
}

(Live Sample on Coliru)

I can't think of a better implementation for CreateMultiByteInteger, so I'm hoping for other ideas that meet the requirements above.


texts: Calculating direction based on index of array

texts:
I am comparing the index of the current component displayed in the viewport against an array of all the components on the screen to determine to direction the user in scrolling.

Does this function have too many concerns? and can the if statements be reduced to something cleaner?

function getDirection(component) {
    let direction;
    if (!this.lastComponentInViewport) {
      direction = "none";
    } else {
      let oldIndex = this.components.indexOf(this.lastComponentInViewport);
      let newIndex = this.components.indexOf(component);

      if (newIndex === oldIndex) direction = "none";

      if (newIndex > oldIndex) direction = "next";

      if (newIndex < oldIndex) direction = "previous";
    }
    return direction;
  }),


texts: Take a result set and organize it into a dictionary

texts:
I'm trying to take a result set and organize it into a dictionary then assign the dictionary values to variables that are publicly accessible from my controller. My issue is I have to check if there is a key, if there is a key, assign it to a variable manually, if there isn't set the variable to 0. Is there a better dynamic way of doing this? The code works but I suspect there is a better implementation.

public class OtherTimeTypes
     {
    private PersonnelManagementEntities db = new    PersonnelManagementEntities();
    private string _usrName;
    public double takenCompHours { get; private set; }
    public double takenBereavementHours { get; private set; }
    public double takenJuryDutyHours { get; private set; }
    //generate the different DayTypes in a dictionary for key/value processing. Key = variable name, Value = DayTypeID
    private Dictionary<string, int> dayType = new Dictionary<string, int>
    {
        { "takenCompHours", 7 },
        { "takenBereavementHours", 3 },
        { "takenJuryDutyHours", 4 }
    };

    public OtherTimeTypes(string userName)
    {
        //set the AD user name in constructor
        _usrName = userName;
        //Setup dictionary to store results
        Dictionary<string, double> hoursCount = new Dictionary<string, double>();
        //initalize base line hours
        double returnedHours = 0;
        // iterate through dictionary with linq queries
        foreach (KeyValuePair<string, int> pair in dayType)
        {
            var result = db.TimeRequests
                           .Include(t => t.User)
                           .Where(t => t.DayTypeID == pair.Value)
                           .Where(t => t.User.ADUserName == _usrName)
                           .Where(t => t.UserSubmitDate.Year == DateTime.Now.Year)
                           .ToList();

            //make the hours calculation and store it in dictionary.
            foreach (TimeRequest hours in result)
            {
                returnedHours = returnedHours + (((hours.eDateTime - hours.sDateTime).TotalDays + 1) * (int)hours.HoursRequested);
                //If the dictionary does not contain a K/V add it
                if (!hoursCount.ContainsKey(pair.Key))
                {
                    hoursCount.Add(pair.Key, returnedHours);
                }
                //If it does contain a value for the day type add it to the value compDay1 = 2 hrs, compDay2 = 4 hrs = compDayVariable=6
                else
                {
                    hoursCount[pair.Key] = hoursCount[pair.Key] + returnedHours;
                }
                returnedHours = 0;
            }
        }
//THIS IS THE PORTION OF CODE I DISLIKE
        //assign dictionary values to public variables for the TimeOffViewModel
        if (hoursCount.ContainsKey("takenCompHours"))
        { takenCompHours = hoursCount["takenCompHours"]; }
        else { takenCompHours = 0; }

        if (hoursCount.ContainsKey("takenBereavementHours"))
        { takenBereavementHours = hoursCount["takenBereavementHours"]; }
        else { takenCompHours = 0; }

        if (hoursCount.ContainsKey("takenJuryDutyHours"))
        { takenJuryDutyHours = hoursCount["takenJuryDutyHours"]; }
        else { takenJuryDutyHours = 0; }
    }
}


texts: Evaluating result for mastermind comparison

texts:
I'm implementing a Java version of the game Mastermind.

My version uses numbers to represent colors, for example 2315. This function compares a string of numbers to the secret code the object stored. It works, but I'm wondering if this could be done in a more elegant way.

public Answer evaluate(String guess) {
    boolean[] codeUsed = new boolean[code.length()];
    boolean[] guessUsed = new boolean[guess.length()];

    int correct = 0;
    int match = 0;

    // Compare correct color and position
    for (int i = 0; i < code.length(); i++) {
        if (code.charAt(i) == guess.charAt(i)) {
            correct++;
            codeUsed[i] = guessUsed[i] = true;
        }
    }

    // Compare matching colors for "pins" that were not used
    for (int i = 0; i < code.length(); i++) {
        for (int j = 0; j < guess.length(); j++) {
            if (!codeUsed[i] && !guessUsed[j] && code.charAt(i) == guess.charAt(j)) {
                match++;
                codeUsed[i] = guessUsed[j] = true;
                break;
            }
        }
    }

    return new Answer(guess, correct, match, guess.length() - correct - match);
}


texts:
I want to make a simple wrapper for sklearn models. The idea is that the wrapper automatically takes care of factors (columns of type "object") replacing them with the average value of the target, while preserving the syntax of sklearn models.

If the factor is too scarce, it is replaced by the overall average value of the target. It seems simple but issues arise when a factor is in the test set and was not in the train set. I came up with the following solution, that looks really awkward to me.

class ModelEmbedder :

    def __init__(self, model, rare_threshold) :
        self.model = model
        self.means = {}
        self.rare_threshold = rare_threshold
        self.train = None
        self.origin_train = None
        self.average = 0

    def fit(self,train,target):
        self.origin_train = train.copy().fillna(-1)
        self.train = train.copy()
        self.train = self.train.fillna(-1)
        self.train['target'] = target
        self.average = target.mean()

        for feat in train.columns:
            if feat != 'target' :
                if self.train[feat].dtype=='object' :
                    self.train.loc[self.train[feat].value_counts()[self.train[feat]].values <  self.rare_threshold, feat] = "RARE"
                    self.origin_train.loc[self.origin_train[feat].value_counts()[self.origin_train[feat]].values <  self.rare_threshold, feat] = "RARE"
                    self.means[feat] = self.train.groupby([feat])['target'].mean()
                    self.means[feat]["RARE"] = self.average

                    self.train[feat] = self.train[feat].replace(self.means[feat], inplace=False)

        del self.train['target']

        self.model.fit(self.train,target)

    def _pre_treat_test(self,test) :
        test = test.copy()
        test = test.fillna(-1)

        for feat in self.origin_train.columns:
            if self.origin_train[feat].dtype=='object' :
                test.loc[self.origin_train[feat].value_counts()[self.origin_train[feat]].values  <  self.rare_threshold, feat] = "RARE"

                criterion = ~test[feat].isin(set(self.origin_train[feat]))

                test.loc[criterion,feat] = self.average

                test[feat]  = test[feat].replace(self.means[feat], inplace=False)

        return test

    def predict_proba(self,test) :
        test = self._pre_treat_test(test)
        return self.model.predict_proba(test)

    def get_params(self, deep = True):
        return self.model.get_params(deep)

Then, every model can be wrapped:

rf = ensemble.ExtraTreesClassifier(n_jobs=7,
    n_estimators = n_estimators,
    random_state = 11)

rf_embedded = model_embedder.ModelEmbedder(rf,10)

and sent to a cross-validation loop or any pipeline.


texts:
I am good at logic and most of the time I write working code. But I want to learn writing code which follows best practices and is very efficient. I tried to implement some of them in my code but it still looks very unclean.
Could anyone please explain how I can make this code better and make it production standard code.

This is my ruby code:

class Items
  @@items = {}
  def initialize(name, price)
    @@items[name] = price
  end

  def self.all
    @@items
  end
end

class SaleItems
  @@sale_items = {}
  def initialize(name, units, price)
    @@sale_items[name] = { 'units' => units, 'price' => price}
  end

  def self.all
    @@sale_items
  end
end

class PriceCalculator

  def start_billing
    input = get_input
    @purchased_items = input.split(',').map(&:strip)
    if !@purchased_items.empty?
      quantity = count_items
      price = calculate_bill(quantity)
      billing_items = quantity.each_with_object(price) { |(k,v), billing_items|
        billing_items[k] = {'units' => v, 'price' => price[k]}
      }
      display_bill(billing_items, quantity)
    else
      puts "Sorry! no items were given to process the bill"
    end
  end

  private

    def get_input
      puts "Please enter all the items purchased separated by a comma"
      input = gets.chomp
    end

    def count_items
      @purchased_items.inject(Hash.new(0)){ |quantity, item|
          quantity[item] += 1
          quantity
      }
    end

    def calculate_bill quantity
      price = {}
      quantity.each { |item,value|
        if SaleItems.all[item].nil?
          price[item] = quantity[item]*Items.all[item]
        else
          price[item] = (((quantity[item]/SaleItems.all[item]['units']).floor)*SaleItems.all[item]['price']) + ((quantity[item]%SaleItems.all[item]['units'])*Items.all[item])
        end
        }
        price
    end

    def display_bill billing_items, quantity
      total_price = billing_items.inject(0){ |tot, (item,v)|
        tot + v['price']
      }

      actual_price = quantity.inject(0){ |tot, (item,units)|
        tot + (units * Items.all[item])
      }

      puts "Item          Quantity          Price"
      puts "------------------------------------------"

      billing_items.each{ |item, v|
        puts "#{item.ljust(20)} #{v['units']}           $#{v['price']}"
      }
      puts "Total price : #{total_price.round(3)}"
      puts "You saved #{(actual_price - total_price).round(3)} today."
    end

end

begin
  # creating inventory of items
  Items.new('milk', 3.97)
  Items.new('bread', 2.17)
  Items.new('banana', 0.99)
  Items.new('apple', 0.89)

  # creating sale items
  SaleItems.new('milk',2,5.00)
  SaleItems.new('bread',3,6.00)

  pc = PriceCalculator.new
  puts pc.start_billing
end
```


texts:
Introduction
As a Python neophyte, I implemented the Hangman game as a practice, which operates case-insensitively on the 26 English letters.
My biggest concern at the moment is my use of bytearray to store the word, but I might have made other beginner mistakes as well.  I'd like to locate them and improve accordingly.
Code
import itertools

class Hangman:

    def __init__(self, target, guesses):
        assert target.isascii() and target.isalpha()

        self.target = bytearray(target.lower(), 'utf-8')
        self.guesses = guesses
        self.display = bytearray(itertools.repeat(ord('_'), len(target)))

    def run(self):
        while True:
            print()
            print()
            print(''.join(chr(byte) for byte in self.display))
            print()
            print(f'Remaining guesses: {self.guesses}')

            guess = input('Guess a letter: ')

            if len(guess) != 1:
                print('Invalid guess.')
                continue
            elif not guess.isascii() or not guess.isalpha():
                print('Non-letter guessed.')
                continue

            guess = ord(guess)

            if self.display.count(guess) != 0:
                print('Already guessed this letter.')
                continue

            if self.target.count(guess) == 0:
                self.guesses -= 1
            else:
                self.display = bytearray(
                    (
                        guess if target_c == guess else display_c
                    ) for display_c, target_c in zip(self.display, self.target)
                )

            if self.display == self.target:
                print()
                print()
                print(''.join(chr(byte) for byte in self.target))
                print('You won.')
                break
            elif self.guesses == 0:
                print()
                print()
                print(''.join(chr(byte) for byte in self.target))
                print()
                print('You lost.')
                break

if __name__ == '__main__':
    # Merriam-Webster Word of the Day: October 2, 2020
    hangman = Hangman('pachyderm', 6)
    hangman.run()

Example session
$ python hangman.py

_________

Remaining guesses: 6
Guess a letter: a

_a_______

Remaining guesses: 6
Guess a letter: e

_a____e__

Remaining guesses: 6
Guess a letter: i

_a____e__

Remaining guesses: 5
Guess a letter: o

_a____e__

Remaining guesses: 4
Guess a letter: u

_a____e__

Remaining guesses: 3
Guess a letter: r

_a____er_

Remaining guesses: 3
Guess a letter: y

_a__y_er_

Remaining guesses: 3
Guess a letter: c

_ac_y_er_

Remaining guesses: 3
Guess a letter: h

_achy_er_

Remaining guesses: 3
Guess a letter: p

pachy_er_

Remaining guesses: 3
Guess a letter: d

pachyder_

Remaining guesses: 3
Guess a letter: m

pachyderm
You won.


texts: Is this a reasonable way to implement promises in node.js?

texts:
I'm using passport to setup login in an express site. The site is just a playground for me to learn. The code inside login was exhibiting the arrow anti pattern so I decided it was time to learn to use promises.

But I don't know if what I've arrived at is good, bad, idiomatic, or idiotic. Any and all feedback appreciated!

var passport = require('passport');
var LocalStrategy = require('passport-local').Strategy;
var Promise = require('bluebird');
var bcrypt = require('bcrypt');
var db = require('./db').db; //users are stored in mongo

//I'm using bluebird.js for promises
var users = Promise.promisifyAll(db.users);
var compare = Promise.promisify(bcrypt.compare);

//I think this helps when responding to the db user load completing
function NoMatchedUserError(message) {
  this.name = "NoMatchedUserError";
  this.message = message || "Incorrect username.";
}
NoMatchedUserError.prototype = new Error();
NoMatchedUserError.prototype.constructor = NoMatchedUserError;

//this strategy is used by passport to handle logins
module.exports.localStrategy = new LocalStrategy(function(username, password, done) {
  var matchedUser;

  var comparePassword = function(user){
    if(!user) {
      throw new NoMatchedUserError();
    }

    //memoise the loaded user so it can be returned below
    matchedUser = user;
    return compare(password, matchedUser.password);
  };

  users.findOneAsync({ username: username })
    .then(comparePassword)
    .then(function(isMatch) {
      return isMatch
        ? done(null, matchedUser)
        : done(null, false, { message: 'Incorrect password.' });
    })
    .catch(NoMatchedUserError, function() {
      return done(null, false, { message: 'Incorrect username.' });
    })
    .error(function(err) {
      return done(err);
    });
});


texts:
I'd like this reviewed.

public sealed class FibonacciHeap<TKey, TValue>
{
    readonly List<Node> _root = new List<Node>();
    int _count;
    Node _min;

    public void Push(TKey key, TValue value)
    {
        Insert(new Node {
            Key = key,
            Value = value
        });
    }

    public KeyValuePair<TKey, TValue> Peek()
    {
        if (_min == null)
            throw new InvalidOperationException();
        return new KeyValuePair<TKey,TValue>(_min.Key, _min.Value);
    }

    public KeyValuePair<TKey, TValue> Pop()
    {
        if (_min == null)
            throw new InvalidOperationException();
        var min = ExtractMin();
        return new KeyValuePair<TKey,TValue>(min.Key, min.Value);
    }

    void Insert(Node node)
    {
        _count++;
        _root.Add(node);
        if (_min == null)
        {
            _min = node;
        }
        else if (Comparer<TKey>.Default.Compare(node.Key, _min.Key) < 0)
        {
            _min = node;
        }
    }

    Node ExtractMin()
    {
        var result = _min;
        if (result == null)
            return null;
        foreach (var child in result.Children)
        {
            child.Parent = null;
            _root.Add(child);
        }
        _root.Remove(result);
        if (_root.Count == 0)
        {
            _min = null;
        }
        else
        {
            _min = _root[0];
            Consolidate();
        }
        _count--;
        return result;
    }

    void Consolidate()
    {
        var a = new Node[UpperBound()];
        for (int i = 0; i < _root.Count; i++)
        {
            var x = _root[i];
            var d = x.Children.Count;
            while (true)
            {
                var y = a[d];
                if (y == null)
                    break;
                if (Comparer<TKey>.Default.Compare(x.Key, y.Key) > 0)
                {
                    var t = x;
                    x = y;
                    y = t;
                }
                _root.Remove(y);
                i--;
                x.AddChild(y);
                y.Mark = false;
                a[d] = null;
                d++;
            }
            a[d] = x;
        }
        _min = null;
        for (int i = 0; i < a.Length; i++)
        {
            var n = a[i];
            if (n == null)
                continue;
            if (_min == null)
            {
                _root.Clear();
                _min = n;
            }
            else
            {
                if (Comparer<TKey>.Default.Compare(n.Key, _min.Key) < 0)
                {
                    _min = n;
                }
            }
            _root.Add(n);
        }
    }

    int UpperBound()
    {
        return (int)Math.Floor(Math.Log(_count, (1.0 + Math.Sqrt(5)) / 2.0)) + 1;
    }

    class Node
    {
        public TKey Key;
        public TValue Value;
        public Node Parent;
        public List<Node> Children = new List<Node>();
        public bool Mark;

        public void AddChild(Node child)
        {
            child.Parent = this;
            Children.Add(child);
        }

        public override string ToString()
        {
            return string.Format("({0},{1})", Key, Value);
        }
    }
}


texts: Rails query for all questions in tournaments that a user participates in

texts:
I'm new to rails and this is the situation I'm in: I have a User model that has many tournaments, a Tournament has many users and questions and a Question belongs to a tournament. I'm trying to write a query for all questions that are in tournaments the user is a part of, for example if we have the user A in tournament 1 which has questions alpha, beta, gamma and another tournament 2 with questions omega and delta, I want to display alpha, beta and gamma. So far this is what I've come up with:

def user_questions
  first_questions = scope.joins(:tournament)\
                         .merge(Tournament.where(id: user.tournaments.first.id))
  user.tournaments.each do |tournament|
    current_questions = scope.joins(:tournament)\
                             .merge(Tournament.where(id: tournament.id))
    first_questions = first_questions.or(current_questions)
  end

  first_questions
end

(Imagine scope is Question) Now this works but even I can see this code isn't that good, to put it mildly. I'm looking for suggestions on how to improve it.


texts: DotNetZip: Adding files to archive faster in web app

texts:
I'm looking for ways to speed up the process of adding entries to a zip-archive, in a web app, using DotNetZip.

The problem currently is that the response times out before all files has been added to the archive. There can potentially be between 200 - 500 entries in each archive, each entry between 1 - 4 meg in size. I've tried a sample of 100 files which is too slow.

Compression is not necessary since all files are .mp3-files.

I currently have this code:

private readonly IDictionary<string, Stream> _files = new Dictionary<string, Stream>();

public bool CreateZip(ref MemoryStream result, bool compress = true)
{
    using (ZipFile zip = new ZipFile())
    {
        zip.UseZip64WhenSaving = Zip64Option.AsNecessary;

        if (!compress)
            zip.CompressionLevel = CompressionLevel.None;

        if (_files.Any())
        {
            foreach (var file in _files)
            {
                ZipEntry entry = zip.AddEntry(file.Key, file.Value);
                entry.Comment = file.Key;
            }
        }

        zip.Save(result);
        result.Seek(0, SeekOrigin.Begin);
        result.Flush();
    }
    return true;
}

The files are first added to a dictionary (as streams from a RavenFS/RavenFileStorage) and then added to the archive. The zip itself is also saved to a stream.

I thought about threading but it seems that is not supported by the lib when adding entries to the archive.

Am I using the lib correctly or is any method faster?


texts: Adding Combinations of Numbers in an Array

texts:
Could someone help me optimize this code for time complexity? What is the best way to do this that doesn't include nested for loops?

  Take an array of integers and return a list of sums of every combination
  of 2 numbers. So, for this array [1,2,3], spit out "3,4,5 (1+2, 1+3, 2+3)."

Here is a possible solution using \$O(n^2)\$ time complexity:

static List<int> returnSums(int[] integers)
{
    List<int> sums = new List<int>();
    for (int x = 0; x < integers.Length; x++)
    {
        for (int y = x + 1; y < integers.Length; y++)
        {
            sums.Add(integers[x] + integers[y]);
        }
    }
    return sums;
}

Is there a way to write this with \$O(n)\$?


texts: OOP design of code representing units of measurement

texts:
I am developing a meta-data framework for monitoring systems such that I can easily create data adapters that can pull in data from different systems. One key component is the unit of measurement. To compare datasets which have different units I need to convert them to a common unit. To build adapters I need to have a system capable of describing complicated situations.

Units are just strings that define what the numbers mean e.g. 102 kWh is 102 kiloWatt hours, this can be converted to the SI unit for energy (Joules) by multiplying by a conversion factor (3600000 in this case).

Some data sources have built in conversion systems and provide me with data to a base unit that they specify, e.g. one database will give me energy data measured in various units (one may be called 'kWh*0.01', another 'Btu*1000'). These data will be provided along with a conversion factor to calculate the 'base unit' for that system which is e.g. GJ.

Here is my code to define units

class Unit(object):
    def __init__(self, base_unit, coefficient, name, suffix):
        self.name = name
        self.suffix = suffix
        self.base_unit = base_unit
        self.coefficient = float(coefficient)

    def to_base(self, value):
        return value * self.coefficient

    def from_base(self, value):
        return value / self.coefficient

    def to_unit(self, value, unit):
        if unit.base_unit != self.base_unit:
            raise TypeError, "Units derived from %s and %s are incompatible." % (self.base_unit, unit.base_unit)
        return unit.from_base(self.to_base(value))

    def __repr__(self):
        return "%s (%s)" % (self.name, self.suffix)

class BaseUnit(Unit):
    def __init__(self, name, suffix):
        super(BaseUnit, self).__init__(self, 1.0, name, suffix)

I use these classes to represent the unit information pulled from the source database. In this case, I pass in a record from the 'units' table and use the appropriate fields to construct a unit with the given description and abbreviation that can then be converted into the base unit provided by the system (GJ for energy, M3 for water).

def convert_unit(unit):
    """Convert a provided unit record into my unit"""
    desc = unit.description.strip()
    suffix = unit.abbreviation.strip()
    if unit.type == 'energy':
        base = BaseUnit("GigaJoules", "GJ")
        return Unit(base, float(unit.units_per_gj), desc, suffix)
    elif unit.type == 'water':
        base = BaseUnit("Cubic metres", "m3")
        return Unit(base, float(unit.units_per_m3), desc, suffix)
    else:
        return BaseUnit(desc, suffix)

When designing my classes I had in the back of my mind an idea to enforce a common base unit (e.g. Joules) for energy across multiple data sources, I think I can do this by adding another tier and simply making the current base unit a unit with a given base (may require hard coding the conversion factor between my base unit and GJ).

def convert_unit(unit):
    """Convert a provided unit record into my unit"""
    desc = unit.description.strip()
    suffix = unit.abbreviation.strip()
    if unit.type == 'energy':
        base = BaseUnit("Joules", "J")
        source_base = Unit(base, 1000000000, "GigaJoules", "GJ")
        return Unit(source_base, float(unit.units_per_gj), desc, suffix)
    elif unit.type == 'water':
        base = BaseUnit("Cubic metres", "m3")
        return Unit(base, float(unit.units_per_m3), desc, suffix)
    else:
        return BaseUnit(desc, suffix)

The to_base, from_base and to_unit methods are intended for use with numpy arrays of measurements. I typically use the unit classes inside a dataset class that holds data as a numpy array and a unit instance.

How does this look? It feels neat to me. Are there any style issues?


texts:
Just started to clean up an old code base.
I'm interested in your perspective and ways that you would change the following function.

    private void MarkSelectedRow()
    {
        Object obj = Bankkonto1.Value;
        if ((obj != null) && (myBankkonten.Contains(obj.ToString())))
        {
            foreach (UltraGridRow myRow in Bankkonto1.Rows)
            {
                if (myRow.Cells[STR_Id].Text != obj.ToString())
                    continue;

                myRow.Selected = true;
                try
                {
                    hV_OPPanel1.SetBankListe(myBankkonten, Bankkonto1.SelectedRow.Index);
                }
                catch
                {}
                return;
            }
            if (Bankkonto1.Rows.Count > 0)
                Bankkonto1.Rows[0].Selected = true;
        }
        else
            SelectDefaultBank();

        try
        {
            Bankkonto2.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
            BankkontoS.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
            AutoBank.Rows[Bankkonto1.SelectedRow.Index].Selected = true;
            hV_OPPanel1.SetBankListe(myBankkonten, Bankkonto1.SelectedRow.Index);
        }
        catch
        {}
    }

    public void SetBankListe(BankAccountList bankliste, int SelectedIndex)
    {

        if (OPBankkonto.DataSource != bankliste)
            OPBankkonto.SetDataBinding(bankliste, "");

        OPBankkonto.ValueMember = "Id";
        OPBankkonto.DisplayMember = "DisplayText";
        OPBankkonto.DataBind();
        OPBankkonto.Rows[SelectedIndex].Selected = true;
    }

Thanks,
Alex


texts: Function that normalizes a vector of double

texts:
I have written the following function in order to normalize a container of double, so that it sums up to 1.0:

/**
 * @brief This function normalizes a container so that it sums to 1.0.
 *
 * @param begin The beginning of the range to normalize.
 * @param end The end of the range to normalize.
 * @param out The beginning of the output range (can be the same as begin).
 */
template <typename InputIterator, typename OutputIterator>
void normalizeProbability(InputIterator begin, InputIterator end, OutputIterator out) {
    double norm = static_cast<double>(std::accumulate(begin, end, 0.0));
    std::transform(begin, end, out, [norm](decltype(*begin) t){ return t/norm; });
}

Is it possible to do better, or having a more precise result?


texts:
I'm starting to learn Clojure and as an exercise I've implemented the following functions (written in Java) in Clojure:

private int[] SwapValues(int val1, int val2, int[] array) {
    int[] result = new int[array.length];
    for (int i = 0; i < array.length; i++) {
        if (array[i] == val1) {
            result[i] = val2;
        } else if(array[i] == val2) {
            result[i] = val1;
        } else {
            result[i] = array[i];
        }
    }

    return result;
}

public int[][] PartialCross(int[] subject1, int[] subject2, final int begin, final int end) {
    int[][] result = new int[2][subject1.length];
    int[] child1 = subject1.clone();
    int[] child2 = subject2.clone();

    for (int i = begin; i < end; i++) {
        child1 = SwapValues(subject1[i], subject2[i], child1);
        child2 = SwapValues(subject1[i], subject2[i], child2);
    }

    result[0] = child1;
    result[1] = child2;

    return result;
}

My result is:

(def chromosone1 [5 8 1 7 6 4 9 3 2])
(def chromosone2 [5 3 2 6 1 8 7 4 9])

(defn extract [input i j]
  (filter #(not (nil? %1))
          (map-indexed #(if (and (>= %1 i) (< %1 j)) %2) input)))

(defn chrossover-swap [input i]
  (let [i1 (first i)
        i2 (last i)]
    (map #(cond
           (= %1 i1) i2
           (= %1 i2) i1
           :else %1) input)))

(defn crossover [input1 input2]
  (let [i1 (extract input1 3 5)
        i2 (extract input2 3 5)
        i3 (partition 2 (interleave i1 i2))]
    (loop [to-swap i3
           o1 input1
           o2 input2]
      (if (zero? (count to-swap))
        [o1 o2]
        (do
          (def i (first to-swap))
          (recur (rest to-swap) (chrossover-swap o1 i) (chrossover-swap o2 i)))))))

(print (crossover chromosone1 chromosone2))

The code works, but I may have made it more complicated than it needs to be. I'm a beginner in functional programming and would like to know if this could be written in a simpler or more efficient way.


texts: Compound assignment operators in Python's NumPy library

texts:
The "vectorizing" of fancy indexing by Python's NumPy library sometimes gives unexpected results.

For example:

import numpy
a = numpy.zeros((1000,4), dtype='uint32')
b = numpy.zeros((1000,4), dtype='uint32')
i = numpy.random.random_integers(0,999,1000)
j = numpy.random.random_integers(0,3,1000)

a[i,j] += 1
for k in xrange(1000):
    b[i[k],j[k]] += 1

It gives different results in the arrays 'a' and 'b' (i.e. the appearance of tuple (i,j) appears as 1 in 'a' regardless of repeats, whereas repeats are counted in 'b').

This is easily verified as follows:

numpy.sum(a)
883
numpy.sum(b)
1000

It is also notable that the fancy indexing version is almost two orders of magnitude faster than the for loop.

Is there an efficient way for NumPy to compute the repeat counts as implemented using the for loop in the provided example?


texts:
Here's a snippet of code I use to examine the functionality of Python decorator(@memorize). An example of Fibonacci computation:

def memorize(f):
    memo = {}
    def helper(*args):
        if args not in memo:
            memo[args] = f(*args)
        return memo[args]
    return helper

def fib(n):
    if n==0:
        return 0
    elif n==1:
        return 1
    else:
        return fib(n-1) + fib(n-2)

Here's the problem:

Different naming is causing a huge speed difference, why is it?

Execution 1:

s = time.time()
fib = memorize(fib)
a = fib(40)
e = time.time()
print(a)
print(e-s)

returns

  102334155

  7.319450378417969e-05

Execution 2:

s = time.time()
memo_fib = memorize(fib)
a = memo_fib(40)
e = time.time()
print(a)
print(e-s)

returns

  102334155

  46.79982662200928

Edited:

A screen copy from running the code

Edited:

Unless running the two executions seperately, to obtain aforementioned results, "Execution 2" must be run before "Execution 1".


texts: How to optimize a nested foreach loop which is creating same data object (with different values)

texts:
I have following code which gets MastrSegments from repository(entity framework). It's working but I think I am  violating DRY (though not sure).

MastrSegments conatins collection of SegReqs and SegReq contains collection Routes. And I am looping through them to update RootObject

    foreach (var MastrSegment in MastrSegments)
    {

        var segReqCount = MastrSegment.segReqs.Count();

        var MastrSegmentRow = new Row
        {
            c = new RootObject[] { new RootObject { v = MastrSegment.Name }, new RootObject { v = "TopClient" }, new RootObject { v = segReqCount }, new RootObject { v = 12 } }

        };

        foreach (var segReq in MastrSegment.segReqs)
        {

            var routesCount = segReq.routess.Count;
            Row segReqRow;

            if (segReq.Name != MastrSegment.Name)
            {
                segReqRow = new Row
                {
                    c = new RootObject[] { new RootObject { v = segReq.Name }, new RootObject { v = MastrSegment.Name }, new RootObject { v = routesCount }, new RootObject { v = -26 } }

                };
            }
            else
            {
                throw new NotSupportedException("MastrSegment name and  segReq name can not be same !!");
            }

            foreach (var routes in segReq.routess)
            {
                var circuitsCount = routes.Circuits.Count;
                Row routesRow = null;

                if (routes.Name != segReq.Name)
                {
                     routesRow = new Row
                    {
                        c = new RootObject[] { new RootObject { v = routes.Name }, new RootObject { v = segReq.Name }, new RootObject { v = circuitsCount }, new RootObject { v = 16 } }

                    };
                }
                else
                {
                    throw new NotSupportedException("segReq name and  routes name can not be same !!");
                }

                rows.Add(routesRow);
            }

            rows.Add(segReqRow);
        }

        rows.Add(MastrSegmentRow);
    }

    var returnData = rows.ToArray();


texts: A clock and a fortune: a full screen clock with random quotes in Tcl/Tk

texts:
I've written a small Tcl/Tk script for a friend that displays the current time, as well as a quote. He uses it in some project with a Raspberry Pi, and since I didn't want to cobble up something up in Qt, PyQt, or some kind of website, I tried to write something in Tcl/Tk.

Demo

Here is how it looks in the end:

Requirements

This script assumes that you have fortune available an in your $PATH.

Script

#!/usr/bin/env tclsh

proc every {ms body} {
    eval $body
    after $ms [info level 0]
}

label .time -bg black -fg white -font {Arial 150} -textvar ::time -pady 30
every 1000 { set ::time [clock format [clock sec] -format "%T"] }

label .fortune -bg black -fg white -font {Arial 15}  -textvar ::fortune
every 30000 { set ::fortune [exec fortune -s] }

pack .time -fill both
pack .fortune -fill both -expand 1

. configure -bg black

wm attributes . -fullscreen 1

bind . <q> exit

What to review

This is my first script in Tcl/Tk. Feel free to commend on anything, especially if there's some kind of common style I'm missing.


texts:
I wrote a function to read and replace words by words written in a form in angularjs. I would like to know your opinions to optimize it
Knowing that I have to perform the changes in two files.

 function openFile(infile) {
                fs.open(infile, 'r', function (err, fd) {
                    changeFile(fd);
                });
            }

        function changeFile(fd) {
            var out = '';
            var buf = new Buffer(1024);
            buf.fill(0);
            try {
                fs.read(fd, buf, 0, 1024, null, function (err, bytesRead, buffer) {
                    if (bytesRead === 0) {
                        writeFile(out);
                        return;
                    }
                    var str = buffer.toString('utf8', 0, bytesRead);

                    for (var i in req.body.tpl.title) {
                        str = str.replace('${' + req.body.tpl.title[i].id + '}', req.body.tpl.title[i].value);
                    }
                    for (var i in req.body.tpl.content) {
                        str = str.replace('${' + req.body.tpl.content[i].id + '}', req.body.tpl.content[i].value);
                    }
                    for (var i in req.body.tpl.image) {
                        str = str.replace('${' + req.body.tpl.image[i].id + '}', '../../../' + req.body.tpl.image[i].path);
                    }
                    for (var i in req.body.tpl.video) {
                        str = str.replace('${' + req.body.tpl.video[i].id + '}', '../../../' + req.body.tpl.video[i].path);
                    }
                    out += str;
                    changeFile(fd);
                });
            } catch (err) {
                console.error(err);
            }
        }

        function writeFile(str) {
            fs.writeFile(infile, str, function (err, written, buffer) {
                fs.rename(infile, infile);
            });
        }

Thanks for you solution


texts:
Exercise 2.57.  Extend the
  differentiation program to handle sums
  and products of arbitrary numbers of
  (two or more) terms. Then the last
  example above could be expressed as

  (deriv '(* x y (+ x 3)) 'x)

  Try to do this by changing only the
  representation for sums and products,
  without changing the deriv procedure
  at all. For example, the addend of a
  sum would be the first term, and the
  augend would be the sum of the rest of
  the terms.

I wrote the following solution.

(define (deriv exp var)
  (cond ((number? exp) 0)
        ((variable? exp)
         (if (same-variable? exp var) 1 0))
        ((sum? exp)
         (make-sum (deriv (addend exp) var)
                   (deriv (augend exp) var)))
        ((product? exp)
         (make-sum
          (make-product (multiplier exp)
                        (deriv (multiplicand exp) var))
          (make-product (deriv (multiplier exp) var)
                        (multiplicand exp))))
        ((exponentiation? exp)
         (make-product (exponent exp)
                       (make-exponentiation (base exp) (- (exponent exp) 1))))
        (else
         (error "unknown expression type -- DERIV" exp))))

(define (variable? x) (symbol? x))

(define (same-variable? v1 v2)
  (and (variable? v1) (variable? v2) (eq? v1 v2)))

(define (make-sum . a)
  (define (iter sum rest)
    (cond ((null? rest) (if (zero? sum) '() (list sum)))
          ((=number? (car rest) 0) (iter sum (cdr rest)))
          ((number? (car rest)) (iter (+ sum (car rest)) (cdr rest)))
          (else (cons (car rest) (iter sum (cdr rest))))))
  (let ((result (iter 0 a)))
    (if (= (length result) 1)
        (car result)
        (cons '+ result))))

(define (=number? exp num)
  (and (number? exp) (= exp num)))

(define (make-product . a)
  (define (iter product rest)
    (cond ((null? rest) (if (= 1 product) '() (list product)))
          ((=number? (car rest) 1) (iter product
                                         (cdr rest)))
          ((number? (car rest)) (iter (* product (car rest))
                                      (cdr rest)))
          (else
           (let ((result (iter product (cdr rest))))
             (if (and (pair? result) (eq? (car result) 0))
                 (list 0)
                 (cons (car rest) result))))))
  (let ((result (iter 1 a)))
    (if (= (length result) 1)
        (car result)
        (cons '* result))))

(define (sum? x)
  (and (pair? x) (eq? (car x) '+)))

(define (addend s) (cadr s))

(define (augend s) (if (> (length s) 3)
                       (cons '+ (cddr s))
                       (caddr s)))

(define (product? x)
  (and (pair? x) (eq? (car x) '*)))

(define (multiplier p) (cadr p))

(define (multiplicand p) (if (> (length p) 3)
                             (cons '* (cddr p))
                             (caddr p)))

(define (exponentiation? x)
  (and (pair? x) (eq? (car x) '**)))
(define (base s) (cadr s))
(define (exponent s) (caddr s))
(define (make-exponentiation m1 m2)
  (cond ((=number? m2 0) 1)
        ((= m2 1) m1)
        (else (list '** m1 m2))))

Can it be improved?  In particular, look closely at make-product and make-sum.


texts: Angularjs CRUD views, controllers, navigation

texts:
I just started to learn AngularJS. I created a simple site using ASP.NET MVC as a backend.

I created 1 main view and 4 partial views for the CRUD operations with a Company Entity.

In the main page I have this element:

 I load here the required partial view.

I created 2 angular controllers, one for the list of Companies and another one for the update, delete and create operations. I did this based on this answer.

In my list view I can navigate to the other views. My list view is this (only a part of it):

        {{Company.Id}}
        ...
        {{Company.HREmail}}

            <button type="button" ng-click="ChangeView(CRUDOperationEnum.Update, Company)">Go to edit</button>

The CRUDOperationEnum is an object that I have attached to the $scope of the controller so that I can use to way above.

The object is the following:

var CRUDOperationEnum = {
    Create: 0,
    Read: 1,
    Update: 2,
    Delete: 3
};

My ChangeView function is the folowing:

$scope.ChangeView = function (CRUDOperationValue, selectedCompany) {

    if (CRUDOperationValue != CRUDOperationEnum.Create) {
        CompanyShareFactory.SelectedCompany = selectedCompany;
    }
    else {
        CompanyShareFactory.SelectedCompany = { Id: 0, Name: '', HRName: '', HREmail: '' };
    }

    switch(CRUDOperationValue) {
        case CRUDOperationEnum.Create:
            nextViewPath = '/CreateCompany'
            break;
        case CRUDOperationEnum.Delete:
            nextViewPath = '/DeleteCompany'
            break;
        case CRUDOperationEnum.Read:
            nextViewPath = '/Companies'
            break;
        case CRUDOperationEnum.Update:
            nextViewPath = '/EditCompany'
            break;
        default:
            throw "Error: Invalid CRUD operation";
    }

    CompanyShareFactory.CRUDOperationValue = CRUDOperationValue;
    $location.path(nextViewPath);
};

This way the controller decides where to navigate based on what is the required action.

The CompanyShareFactory is injected to the controller and used to store the selected entity so that the client does not have to create another request to get the selected entity by id after changing views. The other controller (that is for delete, update, create) reads it from the factory. This controller also decides what is the current operation based on the CompanyShareFactory.CRUDOperationValue.

Is this a good way to follow using Angular? Please tell me if my approach is wrong, since I just try to find out a good way to perform crud with Angular.


texts: Elegant and secure way to create a dynamic query

texts:
I want to create a dynamic query to display:

all the invoices if the user has moderator rank
only his invoices if the user is a simple member

code

 public function getAllBill($user_rank, $user_id){

  $sql = 'SELECT * FROM invoice_user
  INNER JOIN users on users.user_id = invoice_user.user_id';

  $sql_clause = 'WHERE user_id = :user_id)';
  $sql_group  = 'GROUP BY invoice_number ORDER BY invoicedate DESC';

  if ($user_rank === 'member') {
    $final_sql = $sql.' '.$sql_clause.' '.$sql_group;
    $parameters = array(':user_id' => $user_id);
  }
  else if ($user_rank === 'moderator'){
    $final_sql = $sql.' '.$sql_group;
    $parameters = array();
  }
  else {
    $error = TRUE;
  }

  if (!isset($error)) {
    $request = $this->bdd->prepare($final_sql);
    $request->execute($parameters);
    return $request->fetchAll();
  } else return array();

}

script

<?php
$table = getAllBill($_SESSION ['rank'], $_SESSION ['id']);

foreach ($table as $row) {
  # code...
}

I would like to know if there is a more elegant way to do this, but especially to know if everything is safe knowing that the rank and the ID come from the user session ($_SESSION ['rank'], $_SESSION ['id'])

Does it pose a problem not to put my parameter table in a condition?

PS : I use MySQL


texts:
I'm currently running through some Cracking the Coding Interview questions and my solution to 4-4 is quite different from any of the given solutions.

The question asks to determine if a given binary tree is balanced; more specifically, if the difference between the maximum and minimum depths within the tree is less than or equal to 1.

public static bool IsBalanced(Node node)
{
    var mm = new DepthMinMax();
    mm.Min = int.MaxValue;
    mm.Max = int.MinValue;

    FindMinMax(mm, node, 0);

    return (mm.Max - mm.Min <= 1) ? true : false;
}

private static void FindMinMax(DepthMinMax mm, Node node, int depth)
{
    if (node == null) return;

    FindMinMax(mm, node.L, depth + 1);
    FindMinMax(mm, node.R, depth + 1);

    // At a terminating node
    if (node.L == null || node.R == null)
    {
        if (mm.Min > depth) mm.Min = depth;
        if (mm.Max < depth) mm.Max = depth;
    }
}

public class Node
{
    public Node L { get; set; }
    public Node R { get; set; }
}

public class DepthMinMax
{
    public int Min { get; set; }
    public int Max { get; set; }
}

This works for my test cases, but they were far from exhaustive and I can't really conclude if my solution works for all cases / is efficient. My solution feels far too simple, which leads me to believe I've missed some kind of gotcha.


texts:
Using Python 2.7 and here is my code to calculate ROC/AUC and I compare my results of tpr/fpr with threshold, it is the same result of whay scikit-learn returns.

My questions, (1) any ideas for improvements (especially for performance in my existing code) (2) any smart ideas to calculate of AUC?

import numpy as np
from sklearn import metrics

def homeMadeROC(scores, targets):
    totalPositive = sum(targets)
    totalNegative = len(targets) - totalPositive
    sortedTargets = []
    tprs = []
    fprs = []

    # order by score desc, and get related target
    for (s,t) in sorted(zip(scores, targets), reverse=True):
        sortedTargets.append(t)
    sortedScores = sorted(scores, reverse=True)
    predictedTruePositiveSofar = 0
    predictedFalsePositiveSofar = 0

    for i in range(len(sortedScores)):
        if sortedTargets[i] == 1:
            predictedTruePositiveSofar += 1
        else:
            predictedFalsePositiveSofar += 1
        tprs.append(float(predictedTruePositiveSofar)/totalPositive)
        fprs.append(float(predictedFalsePositiveSofar)/totalNegative)

    print fprs
    print tprs
    print sortedScores

if __name__ == "__main__":

    y = np.array([0, 0, 1, 1])
    pred = np.array([0.1, 0.4, 0.35, 0.8])
    fpr, tpr, thresholds = metrics.roc_curve(y, pred)
    print fpr
    print tpr
    print thresholds
    print metrics.auc(fpr, tpr)

    print "======"

    homeMadeROC([0.1, 0.4, 0.35, 0.8],[0, 0, 1, 1])


texts: Formatting the opposite of some numbers, with decimal alignment

texts:
Background

I have a list of strings containing numbers. Each string is 8 characters long. For example :

'-123.456'
' -12.345'
'  -1.234'
' 123.456'
'  12.345'
'   1.234'

The longest number possible is ' 999.999' ; the smallest number is '   0.000' and there always are 3 numbers in the decimal.

What I want to do is compute the opposite of each number, and return it as a string of length 8, with the opposite sign next to the number.

For example :

'-123.456' should yield ' 123.456'
' -12.345' should yield '  12.345'
'  -1.234' should yield '   1.234'
' 123.456' should yield '-123.456'
'  12.345' should yield ' -12.345'
'   1.234' should yield '  -1.234'

What I did

I wrote the following code, which works :

def opposite(x):
    if x.startswith('  -'):
        xopp = '   ' + x[3:]
    elif x.startswith(' -'):
        xopp = '  ' + x[2:]
    elif x.startswith('-'):
        xopp = ' ' + x[1:]
    elif x.startswith('   '):
        xopp = '  -' + x[3:]
    elif x.startswith('  '):
        xopp = ' -' + x[2:]
    elif x.startswith(' '):
        xopp = '-' + x[1:]
    return xopp

My question

I feel like this code is completely "unpythonic" and could be replaced by a one-liner. So the question is: does anyone have an idea to make it more pythonic or even a one-liner ?


texts: List with object and index filtering out the object depends upon the index present at list

texts:
I have a following list which indicates the indexes.

 List<Integer> integerList = Arrays.asList(1, 3, 5, 6); // index

I have the following collection of objects.

Collection<Test> testCollection = new ArrayList<>();

Test test01 = new Test(0, "A"); // 0
Test test02 = new Test(1, "B"); // 1
Test test03 = new Test(2, "C"); // 2
Test test04 = new Test(3, "D"); // 3
Test test05 = new Test(4, "E"); // 4
Test test06 = new Test(5, "F"); // 5

testCollection.add(test01);
testCollection.add(test02);
testCollection.add(test03);
testCollection.add(test04);
testCollection.add(test05);
testCollection.add(test06);

The integerList has indexes which are present on testCollection. I want to filter out the testCollection which will have object consisting the index 1, 3, 5. Index 6 is not present on object collection.

I wrote the code as below example. Is there any better as like Java 8 way?

List<Test> testList = new ArrayList<>(testCollection);
List<Test> newTestList = new ArrayList<>();

for (Integer integer : integerList) {

  for (int j = 0; j < testList.size(); j++) {

    if (integer == j) {
      newTestList.add(testList.get(j));
    }
  }
}
System.out.println(newTestList);

It will have the following output as result:

[Test{id=1, name='B'}, Test{id=3, name='D'}, Test{id=5, name='F'}]

The class Test has following information.

class Test {
  private int id;
  private String name;
}


texts: Micro-optimize variable byte encoding/decoding

texts:
Disclaimer: This question was originally asked on Stack Overflow but the community advised to post it here.

I have written routines to encode and decode signed 32-bit-integers into variable byte code:

public class VariableByteCoder
{
    public static byte[] Encode(int n)
    {
        if (n >= 0 && n <= 63) return new byte[] { (byte)(0b01000000 + n) };
        if (n < 0 && n >= -63) return new byte[] { (byte)(0b00000000 - n) };
        if (n == -2147483648) return new byte[] { 0b10001000, 0b10000000, 0b10000000, 0b10000000, 0b00000000 };

        bool isPositive = n >= 0;
        if (n < 0) n = -n;
        byte[] bytes = new byte[5];
        int shift = n;
        bool last = true;
        int i = 4;
        while (shift > 63)
        {
            byte b = (byte)(shift & 0b01111111);
            if (last) last = false; else b |= 0b10000000;
            bytes[i] = b;
            shift = shift >> 7;
            i--;
        }
        byte head;
        head = (byte)((isPositive ? 0b11000000 : 0b10000000) + shift);
        bytes[i] = head;
        byte[] result = new byte[5 - i];
        for (int j = i; j < 5; j++) result[j - i] = bytes[j];
        return result;
    }

    public static int Decode(byte[] bytes)
    {
        if (bytes.Length == 5 && bytes[0] == 0b10001000 && bytes[1] == 0b10000000 && bytes[2] == 0b10000000 && bytes[3] == 0b10000000 && bytes[4] == 0b00000000) return -2147483648;
        int n = 0;
        for (int i = bytes.Length - 1; i > 0; i--)
        {
            n |= ((bytes[i] & 0b01111111) << 7 * (bytes.Length - i - 1));
        }
        n |= ((bytes[0] & 0b00111111) << 7 * (bytes.Length - 1));
        if ((bytes[0] & 0b01000000) == 0) n = -n;
        return n;
    }
}

On my machine encoding and decoding the entire integer range takes 236 seconds, measured using the following code:

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = -2147483648; i < 2147483647; i++)
{
    byte[] compressed = VariableByteCoder.Encode(i);
    int decompressed = VariableByteCoder.Decode(compressed);
    if (decompressed != i) throw new Exception(string.Format("a problem occured during encoding or decoding of integer-value {0}, decoding gave {1}", i, decompressed));
}
sw.Stop();
Console.WriteLine(string.Format("Total duration: {0}ms", sw.ElapsedMilliseconds));

I already tuned it a little but from now on it's black magic to me.

Can anyone help me optimizing the code for more speed?


texts:
The input pointer *data contains the data that needs to be split into different arrays and put in yuvInput.  Each pixel is 32 bytes 4 * 8.  Note the (j*4) to break it up per pixel segment.  The 4th byte is the alpha channel which gets skipped (the reason there is no idx+3).

This method needs optimization.  If anyone is willing to help, please do.

void SplitYUVPlanes(int width, int height, unsigned char *data, int size, unsigned char *yuvInput[3])
{
    // live input *data is YUV444 Packed
    // Conversion from 444 Packed -> 444 Planar
    int index = 0;
    int srcStride = size;

    // need to flip image from bottom-up to top-down
    int revheight = height - 1;

    unsigned char* pLuma = yuvInput[0];
    unsigned char* pChromaU = yuvInput[1];
    unsigned char* pChromaV = yuvInput[2];

    for (int i = 0; i < height; ++i)
    {
        // read bottom line first
        int line = (revheight - i) * srcStride;

        for (int j = 0; j < width; ++j)
        {
            int idx = line + (j * 4);
            pLuma[index] = data[idx + 2]; //Y
            pChromaV[index] = data[idx + 1]; //V
            pChromaU[index] = data[idx + 0]; //U
            index++;
        }
    }
}


texts: Add an entry to every element in a nested data structure

texts:
I currently use a data structure like this:

(def sample-board
  [[{:mine true} {:warn 2   } {:warn 1} {          }]
   [{:warn 2   } {:mine true} {:warn 1} {          }]
   [{:warn 1   } {:warn 1   } {:warn 2} {:warn 1   }]
   [{          } {          } {:warn 1} {:mine true}]])

Now I want to create a copy of the first structure and each element should be supplemented with :explored true.

My approach so far looks like this:

(def sample-board-solved
  (map (partial map
                (partial conj {:explored true}))
       sample-board))

I don't find the approach very appealing though. I thought about using for instead or maybe recur in combination with update-in but I did not bring it to work yet.

I'd be glad on suggestions how to improve the code.


texts:
I'm trying to determine if this code could be a memory hog with huge files. Can anyone tell me if there is anything I can do to make this more memory efficient, or is this how java.crypto works?

private byte[] symmetricDecryptAttachment(byte[] encryptedAttachmentBytes, byte[] keyBytes) throws IOException, GeneralSecurityException, EIPException {
    byte[] decryptedValue = null;

    // TODO: change to use non-deprecated method ConfigurationManager:getParsedStringValue() instead of getStringValue() which is deprecated
    String decryptionAlgorithm = manager.getStringValue(SymmetricDecryptionAlgorithm);
    String cipherBlockMode = manager.getStringValue(SymmetricDecryptionBlockCipherMode);
    String padding = manager.getStringValue(SymmetricDecryptionPadding);

    // Key bytes are only the first 16 bytes
    final int KEY_BYTES_STARTING_BYTE = 0;
    final int KEY_BYTES_ENDING_BYTE = 16;

    // IV bytes are only the first 16 bytes
    final int IV_BYTES_STARTING_BYTE = 0;
    final int IV_BYTES_ENDING_BYTE = 16;

    // Cipher bytes are everything after first 16 bytes (iv bytes)
    final int CIPHER_BYTES_STARTING_BYTE = IV_BYTES_ENDING_BYTE;

    try {
        // 1. Get the cipher ready to start doing the AES transformation
        Cipher cipher = Cipher.getInstance(decryptionAlgorithm + "/" + cipherBlockMode + "/" + padding);

        // 2. Only take the first 16 bytes so that it is 128 bits as we are doing AES 128 bit decryption
        //      *Note: if this is not 128 bit decryption then you might have to change this ...
        byte[] trimmedKeyBytes = Arrays.copyOfRange(keyBytes, KEY_BYTES_STARTING_BYTE, KEY_BYTES_ENDING_BYTE);

        // 3. Start the decryption process by creating a key spec object
        SecretKeySpec keySpec = new SecretKeySpec(trimmedKeyBytes, decryptionAlgorithm);

        // 4. The initialization vector (IV) is the first 16 bytes/octets of the cipher value in the body.
        // 4.1 To recover the IV, Base64 decode the CipherValue
        byte[] cipherBytes = Base64.decodeBase64(encryptedAttachmentBytes);

        // 4.2 The remainder after the first 16 bytes is the encrypted message
        //      -do +2 from start because we want to remove \r\n at the beginning and -2 to remove \r\n from the end
        // Remove the new line and carriage returns from beginning and end, if they are there
        byte[] encryptedBytes = null;
        byte[] ivBytes = null;
        if( encryptedAttachmentBytes[0] == '\r' &&
                encryptedAttachmentBytes[1] == '\n' &&
                encryptedAttachmentBytes[encryptedAttachmentBytes.length-2] == '\r' &&
                encryptedAttachmentBytes[encryptedAttachmentBytes.length-1] == '\n') {
            encryptedBytes = Arrays.copyOfRange(encryptedAttachmentBytes, CIPHER_BYTES_STARTING_BYTE + 2, encryptedAttachmentBytes.length - 2);

            // 4.2a And take bytes 2 thru 18 instead of 0 thru 16 to account for extra \r \n's
            ivBytes = Arrays.copyOfRange(encryptedAttachmentBytes, IV_BYTES_STARTING_BYTE + 2, IV_BYTES_ENDING_BYTE + 2);
        }else{
            encryptedBytes = Arrays.copyOfRange(encryptedAttachmentBytes, CIPHER_BYTES_STARTING_BYTE, encryptedAttachmentBytes.length);

            // 4.2b And take the first 16 bytes from encrypted text to get the IV bytes
            ivBytes = Arrays.copyOfRange(encryptedAttachmentBytes, IV_BYTES_STARTING_BYTE, IV_BYTES_ENDING_BYTE);
        }

        // 5. Create the IV Parameter spec from the ivBytes obtained above
        IvParameterSpec iv = new IvParameterSpec(ivBytes);

        // 6. Initialize the cipher using the key spec and iv we just initialized
        cipher.init(Cipher.DECRYPT_MODE, keySpec, iv);

        // 7. Finish the decryption process
        decryptedValue = cipher.doFinal(encryptedBytes);
    } catch (Exception e) {
        System.err.println("Exception occurred in symmetricDecryptAttachment() of SOAPDecryptionProcessor: \n" + e.getMessage());
        throw new EIPException(e.getMessage());
    }

    return decryptedValue;
}


texts:
This is a simple pool allocator, based (to at least some degree) on a previous answer. The basic idea is pretty simple: allow a user to allocate objects of some type quickly (in relatively large contiguous chunks) and only free objects when the allocator itself is freed, then destroy all the objects and free the memory they occupy.

#include <iostream>
#include <vector>

template <class T, size_t T_per_page = 200>
class Allocator {
    const size_t pool_size = T_per_page * sizeof(T);
    std::vector<T *> pools;
    size_t next_pos;

    void alloc_pool() {
        next_pos = 0;
        void *temp = operator new(pool_size);
        pools.push_back(static_cast<T *>(temp));
    }

public:
    Allocator() {
        alloc_pool();
    }

    T* operator()(T const &x) {
        if (next_pos == T_per_page)
            alloc_pool();

        T *ret = new(pools.back() + next_pos) T(x);
        ++next_pos;
        return ret;
    }

    ~Allocator() {
        while (!pools.empty()) {
            T *p = pools.back();
            for (size_t pos = T_per_page; pos > 0; --pos)
                p[pos - 1].~T();
            operator delete(static_cast<void *>(p));
            pools.pop_back();
        }
    }
};

#ifdef TEST

struct list_node {
    int val;
    list_node *next;

    list_node(int x) : val(x), next(nullptr) {}

    friend std::ostream &operator<<(std::ostream &os, list_node const &n) { return os << n.val; }
};

Allocator<list_node> alloc;

int main() {
    for (int i = 0; i < 20; i++) {
        list_node *j = alloc(i + 1000);
    }
}

#endif

I'd welcome any and all suggestions (including adding specialization to avoid executing destructors on trivially destructible types). I'm also wondering (sort of thinking out loud) whether it would make sense to use a geometric allocation strategy, similar to std::vector's, to (perhaps) fit allocation time to size more effectively.


texts: Count the number of inversions using Binary Indexed Tree in an array

texts:
Original Problem: HackerRank

I am trying to count the number of inversions using Binary Indexed Tree in an array. I've tried to optimise my code as much as I can. However, I still got TLE for the last 3 test cases. Any ideas that I can further optimise my code?

# Enter your code here. Read input from STDIN. Print output to STDOUT
#!/usr/bin/python

from copy import deepcopy

class BinaryIndexedTree(object):
    """Binary Indexed Tree
    """
    def __init__(self, n):
        self.n = n + 1
        self.bit = [0] * self.n

    def update(self, i, k):
        """Adds k to element with index i
        """
        while  i <= self.n - 1:
            self.bit[i] += k
            i = i + (i & -i)

    def count(self, i):
        """Returns the sum from index 1 to i
        """
        total = 0
        while i > 0:
            total += self.bit[i]
            i = i - (i & -i)
        return total

def binary_search(arr, target):
    """Binary Search
    """
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = left + ((right - left) >> 1)
        if target == arr[mid]:
            return mid
        elif target < arr[mid]:
            right = mid - 1
        else:
            left = mid + 1

    # If not found, return -1.
    return -1

T = input()
for iterate in xrange(T):
    n = input()
    q = [ int( i ) for i in raw_input().strip().split() ]
    answer = 0
    # Write code to compute answer using x, a and answer

    # Build a Binary Indexed Tree.
    bit = BinaryIndexedTree(n)

    # Copy q and sort it.
    arr = sorted(deepcopy(q))

    # index array.
    index = map(lambda t: binary_search(arr, t) + 1, q)

    # Loop.
    for i in xrange(n - 1, -1, -1):
        answer += bit.count(index[i])
        bit.update(index[i] + 1, 1)
    print answer


texts: Encrypt and decrypt a serializable object

texts:
I want to make sure that the code I have for encrypting and decrypting a serializable object makes sense and is proper. Does it look right too?

Here's what I have so far:

public static void encrypt(Serializable object, String path) throws IOException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException {

          try {

            // Length is 16 byte
            SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                    "AES/ECB/PKCS5Padding");

            // Create cipher
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, sks);
            SealedObject sealedObject = new SealedObject(object, cipher);
            // Wrap the output stream
            CipherOutputStream cos = new CipherOutputStream(new BufferedOutputStream(new FileOutputStream(path)), cipher);
            ObjectOutputStream outputStream = new ObjectOutputStream(cos);
            outputStream.writeObject(sealedObject);
            outputStream.close();
        }
        catch(IllegalBlockSizeException e){

            e.printStackTrace();

        }
        }

public static void decrypt(Serializable object, String path) throws IOException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException {

        SecretKeySpec sks = new SecretKeySpec("MyDifficultPassw".getBytes(),
                "AES");

        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, sks);

        CipherInputStream cipherInputStream = new CipherInputStream( new BufferedInputStream( new FileInputStream(path) ), cipher );
        ObjectInputStream inputStream = new ObjectInputStream( cipherInputStream );
        SealedObject sealedObject = null;
        try {
            sealedObject = (SealedObject) inputStream.readObject();
            TransferData td = (TransferData) sealedObject.getObject( cipher );

        }
          catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        }

    }


texts:
I have a resource (e.g., current program configuration) that I want to handle in a single class instance, but want to hide the fact that there is, in effect, a singleton class by using a proxy class.

Reasons for not using a singleton directly include: don't want users of the class to have to change code if I move away from singleton implementation, and want to be able to have control over initialization and destruction order (which would be difficult with static classes, for example).

Additionally, this is a multithreaded application, so new instances of the Proxy class may be created at the same time (thus the mutex protecting creation of the Implementation).

The Proxy class is the proxy, and Impl class is the hidden singleton implementation. Note that I don't do anything special to Impl to make it a singleton. It is only a singleton because I track its existence in Proxy with a static member variable.

Proxy.h

#pragma once
#include <memory>
class Proxy {
 public:
   Proxy();
   void method1() //inline dispatch to hidden single class
   {
      data_->method1();
   }
 private:
   class Impl { //this class will be created once only
   public:
      void method1();
      Impl();
      ~Impl() = default;
   };
   std::shared_ptr<Impl> Make_Impl() const;
   const std::shared_ptr<Impl> data_{};
   inline static std::weak_ptr<Impl> impls_{}; //tracks whether Impl is created
};

Proxy.cpp

#include "Proxy.h"
#include <mutex>

Proxy::Proxy() : data_(Make_Impl()) {}

std::shared_ptr<Proxy::Impl> Proxy::Make_Impl() const
{ // note that impls_ may be accessed by another thread with non-const member function
  // (assignment) if it is running slightly ahead of this thread with an uninitialized impls_ so
  // need mutex before shared_ptr.lock call. if we use an atomic weak pointer (C++20) can call
  // shared_ptr.lock before mutex, check for success, and only run mutex (and try lock again) after
  // failure
   static std::mutex mtx;
   auto lock = std::lock_guard(mtx);
   std::shared_ptr<Impl> internal_data = impls_.lock(); //if implementation exists, assign to shared_ptr
   if (!internal_data) { //need to create implementation
      const auto new_impl(std::make_shared<Impl>());
      internal_data = new_impl;
      impls_ = new_impl;
   }
   return internal_data;
}

Proxy::Impl::Impl()
{
   // constructor for Impl here
}

void Proxy::Impl::method1()
{
   // the real method1 for the implementation
}

General comments welcome. Specific questions include:

is there a way to eliminate the pointer dereference that will occur with each call intended for the underlying implementation? (For example, When Proxy::method1 is called, that redirects to the underlying singleton class.)
Instead of using a static weak_ptr, is there a better way of tracking whether the Implementation exists?
Have others done anything like this? I'm concerned that I haven't seen this pattern (with smart pointers) documented anywhere. It makes me feel like I've gone "off the rails" with this code and have overlooked some problems with this approach.


texts: Check whether two JavaScript arrays are equal, using basic library only

texts:
I am writing a function that takes in two arrays and a test name and outputs statements (console.log) saying whether the two arrays are equal. I don't want to convert the arrays to strings or use non-core libraries to do this. I am also new to writing JS so I wanted to get a code review here.

Usage: FAILURE CASE:
var expected = [1, 1, 2, 3, 5, 8, 13];
var actual = [2, 3, 5, 8, 13, 21, 34];
assertArraysEqual(actual, expected, 'generates first 7 Fibonacci
numbers');

console output:
 FAILED [generates first 7 Fibonacci numbers] Expected "1, 1, 2, 3, 5,
8, 13", but got "2, 3, 5, 8, 13, 21, 34"

function assertArraysEqual(actual, expected, testName) {

  var lengthsEqual = (actual.length === expected.length)
  var contentsEqual = true
  for (var i=0; i<actual.length; i++)
  {
    if (actual[i] !== expected[i]) contentsEqual=false
  }
  if(contentsEqual && lengthsEqual){
   console.log("passed")
  }
  else{
    console.log('FAILED [' + testName + '] Expected "' + expected + '", but got "' + actual + '"');
  }
}


texts:
I'm receiving data from a serial port in C, using Serial Programming Guide for POSIX Operating Systems as a guide.

The data I receive should be always 10 bytes in length but I want to be sure that, if there is any error (more or less bytes received), reading will clear buffer before the next data arrive, so that there is always proper data in the buffer to be processed. I'm using select to monitor serial file descriptor and local socket. I figured out that I can clean serial buffer in case there was something left from previous transmission, when device is not sending for some period of time.

Question is: is this the right solution?

main.c:

loop_num=0;
si_processed=0;
while(TRUE) {
    /* copy fd_set for select */
    tmp_input=input;

    n = select(max_fd,&tmp_input,NULL,NULL,NULL/*&timeout*/);

    /* See if there was an error */
    if (n<0)
        perror("select failed");
    else {
        /* We have input */
        if (FD_ISSET(serial_fd, &input)) {
            if(!process_serial(serial_fd))
                loop_num++;
        }
        if (FD_ISSET(local_socket, &input))
            process_socket(local_socket);
    }
    if(loop_num>10) {
        /* clear buffer */
        si_processed=0;
        loop_num=0;
    }
    fflush(stdout);
    usleep(20000);
}

serial_port.c

char serial_buffer[256];

int process_serial(int serial_fd) {
    int bytes;
    int n,i;
    char tmp_buffer[32];

    ioctl(serial_fd, FIONREAD, &bytes);
    if(!bytes)
        return 0;

    n=read(serial_fd, tmp_buffer, sizeof(tmp_buffer));
    for(i=0;i<n;i++) {
        serial_buffer[si_processed+i]=tmp_buffer[i];
    }
    si_processed+=n;
    if(si_processed>=INPUT_BYTES_NUM/* defined as 10 */) {
        serial_buffer[si_processed]='\0';
        printf("read:%s\n",serial_buffer);
        si_processed=0;
        fflush(stdout);
    }
    return 1;
}

Some more info. I'm querying device every 5 seconds for data, and it should always respond with 10 bytes packets: so data should come fairly quickly into serial buffer, and then a few seconds of silence; sometimes however the device can send data on its own, I don't know when, but also as a 10 bytes packets.

I was doing some test with my program and minicom connected on the other side.

Until I was sending data like

1234567890

1234567890

program was reading what it supposed to read:

1234567890

Problem arises when I send on minicom:

12345678901234567890

Usually what was read was:

1234567890123456

so next, when I wrote on minicom proper data:

1234567890

program was reading

7890123456

and every next read was bad because of leftovers in buffer from previous read.

When I added clearing buffer after 1 or 2 seconds when nothing is read, then I'm sure any leftovers are cleared before next transmission.

I read about this VMIN settings but decided against because of this leftovers.

Also this data 1234567890 is just an example. In fact 10 bytes consist of:

Byte #1 - always some constant to mark begining of transmission like 0xA5
Byte #2 through #9 byte - data
Byte #10 - control sum from all previous bytes.

So after I have 10 bytes packet received I can verify if it has proper data or is somehow corrupted: so if one transmission fails, I should be ok, especially when I can clear the buffer before next data coming in.


texts: My attempt at a weighted search in JavaScript

texts:
I tried to make a weighted search function in JavaScript. I've been improving my JS lately but still not sure about some best practices, wondering if there's any improvements I could make, or if I've ended up doing it completely wrong.

The intention is to keep it quite flexible so it can take an array of filter functions, each with its own weight, it also takes a property on which to sort items with equal weights.

The search function is

function weightedSearch(array, weightedTests, sortProperty) {
        return array.map(function (e) {
            return {
                element: e, weight: weightedTests.map(function (weightedTest) {
                    var testResult = weightedTest.test(e);
                    return testResult * weightedTest.weight;
                }).reduce(function (previousValue, currentValue) { return previousValue + currentValue; }, 0)
            };
        }).filter(function (element) {
            return element.weight > 0;
        }).sort(function (obj1, obj2) {
            //sort first by weight
            if (obj1.weight > obj2.weight) {
                return -1;
            } else if (obj1.weight < obj2.weight) {
                return 1;
            }

            // Else by chosen property
            if (obj1.element[sortProperty] < obj2.element[sortProperty]) {
                return -1;
            } else if (obj1.element[sortProperty] > obj2.element[sortProperty]) {
                return 1;
            } else {
                return 0;
            }
        }).map(function (e) {
            return e.element;
        });
    }

A weighted test is an object of the form:

{test: function(element){}, weight: relativeWeightOfTheTest}

And would be used in a manner such as:

var search = "test";
var results = weightedSearch(arrayToSearch, [
        { test: function (testElement) { return testElement.title.toLowerCase().indexOf(search) >= 0; }, weight: 2 },
        { test: function (testElement) { return testElement.description.toLowerCase().indexOf(search) >= 0; }, weight: 0.5 }
    ], "title")

This would return an array where either the title or description contain "test" and ordered by:

Appearing in title and description
Appearing in title only
Appearing in description only

Any results with the same weighting are then ordered by their title. Obviously this is a simple test case, you could easily have a test that adds up instances of the search string, the test could check it against a list of synonyms before counting etc.

Here's a JSbin with some test data and a quick Knockout usecase.

http://jsbin.com/figay/1/edit?html,js,output


texts: How to use the value of a method result based on a test?

texts:
I have some Java like this:

if (!fooclass.getInfoText().equals(""))
{
    this.setInfoText(fooclass.getInfoText());
}

Is there a neater way of setting one value based on the test results of another value? It seems nasty to me that the method is run twice, but putting the result in a variable when it may be empty and not used at all seems equally messy.

In PHP I might do:

if (($foo = $bar->baz()) !== "")
{
    $this->set_info_text = $foo;
}

But I know some people are quite strongly for and against this method, though I can't recall a good justification against it.