texts: OpenVPN Login Bash Shell script for DD-WRT router

texts:
This script is made to run on DD-WRT as I am running an OpenVPN server on it just to securely connect to my home network when I'm on the go. Basically, the input ($1) that goes into this script is a .tmp file generated by OpenVPN when some user wishes to log into the server. The .tmp file consists of 2 lines where the 1st line is the username and the 2nd line is the password.

In this day and age, I'm afraid that potential hackers could inject unintended malicious arguments into the username or password which could exploit my script with the intention to take control over the DD-WRT router (in a way similar to SQL-Injection). So far I have made some huge improvements to the script but I'm not sure if I am finished yet.

#!/bin/sh

#This script was made with OpenVPN via-file in mind

#Location of the Approved Username/Password File
USERS="/somefolder/users"

#Check to see if username and password in the OpenVPN file has any special characters line by line
#Terminate script if special characters are used
while IFS= read -r line
do
    case "$line" in *[!-_a-zA-Z0-9]*) exit 1 ;; esac
done < "$1"

Username=`awk 'NR==1' "$1"`
Password=`awk 'NR==2' "$1"`

        HASHPASS=`echo -n "$Username$Password" | md5sum | sed s'/\  -//'`
        i=0
        while [ $i -lt 10 ]; do
                HASHPASS=`echo -n $HASHPASS$HASHPASS | md5sum | sed s'/\  -//'`
                i=`expr $i + 1`
        done

    if grep -q "$Username:$HASHPASS" $USERS; then
        echo "User Authenticated."
        exit 0
    fi

echo "Login credentials failed."
exit 1


texts:
I'm working on website with a parallax effect. The jQuery code is working, but I wonder if there could be made any improvements made to the code. At the moment it works totally smooth in Firefox, but in other browsers it seems to be a little bit jumpy. Also, the effect is not working in IE 9.

(function($) {

var $container = $(".parallax");
var $divs = $container.find("div.parallax-background");
var scrolledElement =  document.body;
var liHeight = $divs.eq(0).closest("li").height();
var diffHeight = $divs.eq(0).height() - liHeight;
var len = $divs.length;
var i, div, li, offset, scroll, top, transform;

var offsets = $divs.get().map(function(div,d){
    return $(div).offset();
    });

var render = function() {

    top = scrolledElement.scrollTop;
    for(i=0;i<len;i++) {

        //get the DOM object
        div=$divs[i];

        //our offset
        offset=top - offsets[i].top;

        //our transform string
        scroll= ~~(offset /liHeight*diffHeight);

        //our transform string
        transform ='translate3d(0px, ' + scroll + 'px, 0px)';

        //apply
        div.style.webkitTransform = transform;
        div.style.MozTransform = transform;
        div.style.msTransform = transform;
        div.style.OTransform = transform;
        div.style.transform = transform;
        }
};
//Paul Irish http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
(function() {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
    window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
    window.cancelAnimationFrame = window[vendors[x]+'CancelAnimationFrame']
                               || window[vendors[x]+'CancelRequestAnimationFrame'];
    }

    if (!window.requestAnimationFrame)
        window.requestAnimationFrame = function(callback, element) {
            var currTime = new Date().getTime();
            var timeToCall = Math.max(0, 16 - (currTime - lastTime));
            var id = window.setTimeout(function() { callback(currTime + timeToCall); },
              timeToCall);
            lastTime = currTime + timeToCall;
            return id;
        };

    if (!window.cancelAnimationFrame)
        window.cancelAnimationFrame = function(id) {
            clearTimeout(id);
        };
}());

(function loop(){
    requestAnimationFrame(loop);
    render();
    })();

})(jQuery);


texts: Conway's Game of Life in JavaScript sprawling iterative function

texts:
I'm new to JS, React and functional programming and am trying to make the Game of Life in React. My cycle function looks like iterative sprawl but all my attempts to refactor have been equally bad. The full code is here.

Any recommendations to make the function more elegant or efficient or best practices tips?

cycle() {
    //a large array representing the grid with "X" for alive and "O" for dead
    let s = this.state.squares;
    let adjacents = [];
    let neighborCount = 0;
    let n = Math.sqrt(this.size);
    let births = [];
    let deaths = [];

    for (let i=0; i<s.length; i++) {

        //finds the eight neighboring squares for each square
        adjacents.push(i-1, i+1, i-n-1, i-n, i-n+1, i+n-1, i+n, i+n+1);
        for (let j=0; j<adjacents.length; j++) {
            if (s[adjacents[j]] == "X") {
              neighborCount++;
            }
        }

        //determines if the central square will be born or die in this round
        if (s[i] == "O" && neighborCount == 3) {
          births.push(i);
        }
        else if ((s[i] == "X" && neighborCount < 2)
        || (s[i] == "X" && neighborCount > 3))
        {
          deaths.push(i);
        }
        neighborCount = 0;
        adjacents = [];
    }

    //the grid array updates after all births and deaths for the round have been computed
    for (let k=0; k<births.length; k++) {
      s[births[k]] = "X";
    }

    for (let k=0; k<deaths.length; k++) {
      s[deaths[k]] = "O";
    }

    births = [];
    deaths = [];

    this.setState({
    squares: s
    })
}


texts:
I have written a Common Lisp implementation of Scheme's s-expression comments (SRFI 62):
(eval-when (:compile-toplevel
            :load-toplevel
            :execute)

  (defun handle-s-expression-comment (stream char n)
    (declare (ignore char))
    (when n
      (error "Infix parameter not allowed in s-expression comment."))
    (read stream)  ; Discard the next s-expression.
    (values))

  (set-dispatch-macro-character #\# #\; #'handle-s-expression-comment))

With s-expression comments:

(+ 1 #;(* 2 3) 4) returns 5
(list 'x #;'y 'z) returns (x z)
(* 3 4 #;(+ 5 6)) returns 12
(#;sqrt abs -123) returns 123

Is my implementation correct? What improvements can I make?


texts: Polling an API endpoint with timeout using channels

texts:
I have written a simple API client for my app in Go.
The client is very simple, it wraps http.Client and has some convenience methods.

The one method I am trying to get some feedback on, does endpoint polling with timeout. It blocks, and returns when either a timeout is reached or status returned by API is successful or in error.

My questions are in comments of the function itself.
I have omitted some parts (structs, the "constructor method") that are not relevant to discussion.

caller (in main)

log.Printf("polling status, id: %d", sid)
status, err := api.PollStatus(sid, 1*time.Second, 5*time.Second)
if err != nil {
    log.Fatalf("PollStatus error: %+v", err)
}

log.Print(status)

the method

// PollStatus will keep 'pinging' the status API until timeout is reached or status returned is either sucesfull or in error.
// NOTES:
//   - this function will block the caller
// QUESTIONS:
//  - is the design/functionality of this method idiomatic Go or is there a better way?
//  - do I need to close ticker and timeout channels? If so how?
//  - is it safe to 'defer ticker.Stop()' at the start of goroutine or do I have to call it before each return?
func (client *APIClient) PollStatus(id int, pollInterval time.Duration, pollTimeout time.Duration) (*Status, error) {
    var status *Status
    var err error
    var wg sync.WaitGroup
    ticker := time.NewTicker(pollInterval)
    timeout := time.After(pollTimeout)
    tickerCounter := 0

    // increment the WaitGroup counter for number of goroutines to wait for...
    wg.Add(1)

    go func() {
        defer ticker.Stop()
        // decrement the counter when the goroutine completes.
        defer wg.Done()

        for {
            select {

            case tout := <-timeout:
                log.Printf("polling timeout of '%s' reached at '%s'...", pollTimeout, tout.Format(time.RFC3339))
                //ticker.Stop()
                return

            case tick := <-ticker.C:
                status, err = client.GetStatus(id)
                tickerCounter++
                if err != nil {
                    //ticker.Stop()
                    return
                }
                log.Printf("tick #%d at '%ss', %s", tickerCounter, tick.Format("05"), status)
                if status.IsErrorStatus() {
                    err = errors.New("error while polling for status")
                    //ticker.Stop()
                    return
                }
                if status.IsCompletedStatus() {
                    err = nil
                    //ticker.Stop()
                    return
                }

            }
        }
    }()

    // wait for polling to complete (or time out)
    wg.Wait()

    if err != nil {
        return nil, err
    }
    if status == nil {
        return nil, errors.New("unable to get status")
    }

    return status, nil
}


texts: AJAX call with repetitive success/failure handlers

texts:
There's some repetition in here. I tried making it into a function but then the response wasn't filling up the #project-container div. Is there a way to condense this code to make it more elegant?

// Activate projects
$('.post-link').click(function(e) {
    e.preventDefault();

    var post_id = $(this).attr('rel'),
        ajaxURL = site.ajaxurl; // Ajax URL localized from functions.php

    function projectShow() {

        // Initiate the Ajax call
        $.ajax({
            type: 'POST',
            url: ajaxURL,
            data: {'action': 'load-content', post_id: post_id },
            beforeSend: function() {
                $('').insertBefore($(e.currentTarget));
            },
            success: function(response) {
                $('.loading-icon').remove();

                if ($(window).scrollTop() != 0) {
                    $('html, body').animate({
                        scrollTop : 0
                    },200, function() {
                        $('#project-wrapper').addClass('activated');

                        // Keep the rest of the projects grey while #project-wrapper is activated
                        $('article').addClass('grayscale grayscale-fade').css('opacity', '0.4');

                        // Load up the response from the Ajax call
                        $('#project-container').html(response);

                        // Make the max-height of the container exact for smoother animations
                        var containerHeight = $('#project-container').outerHeight();
                        $('#project-wrapper.activated').css('max-height', containerHeight);

                        // CSS effects
                        $('.post-container').addClass('fadeInUp');
                        $('.close-button').addClass('fadeInDown');

                        // Remove pesky, sticky 'hover' class
                        $('article').removeClass('hover');

                        // Shuffle letters and update the title of the page
                        $('#project-wrapper .entry-title').shuffleLetters({
                            callback:function(){
                                var title = $(e.currentTarget).closest('#main').find('h1').text();
                                $('head').find('title').text('Keebs | ' + title);
                            }
                        });
                    });
                } else {
                    $('#project-wrapper').addClass('activated');

                    // Keep the rest of the projects grey while #project-wrapper is activated
                    $('article').addClass('grayscale grayscale-fade').css('opacity', '0.4');

                    // Load up the response from the Ajax call
                    $('#project-container').html(response);

                    // Make the max-height of the container exact for smoother animations
                    var containerHeight = $('#project-container').outerHeight();
                    $('#project-wrapper.activated').css('max-height', containerHeight);

                    // CSS effects
                    $('.post-container').addClass('fadeInUp');
                    $('.close-button').addClass('fadeInDown');

                    // Remove pesky, sticky 'hover' class
                    $('article').removeClass('hover');

                    // Shuffle letters and update the title of the page
                    $('#project-wrapper .entry-title').shuffleLetters({
                        callback:function(){
                            var title = $(e.currentTarget).closest('#main').find('h1').text();
                            $('head').find('title').text('Keebs | ' + title);
                        }
                    });
                }

                return false;
            }
        });
    }

    // The call
    projectShow();
});


texts:
I've recently been learning and adopting Promises, async/await, and unit testing for my JavaScript server project.  I just finished a unit test for some pubsub code that was more convoluted than anything I'd done before, and I feel like I'm missing some idiom or pattern that could make it a little simpler.

Context

I'm using Google Pub/Sub API.  I wrote publish and listen wrappers, and wrote a unit test to exercise both in tandem - mostly because testing either in isolation is essentially impossible, since I want to test correct usage of the real API, not mocks.  (The logic is simple, it's the correct API usage that is in question and must be verified.)

The Wrappers

pubsub.js

const pubsub = require('@google-cloud/pubsub')()

module.exports = (log) => ({

    listen: function (subscription, message_handler) {
        const sub = pubsub.subscription( subscription )

        const error_handler = error => log.error(error)
        sub.on( 'message', message_handler )
        sub.on( 'error',   error_handler   )

        return () => {
            sub.removeListener( 'message', message_handler )
            sub.removeListener( 'error',   error_handler   )
        }
    },

    publish: async function (topic, data) {
        const [ ids ] = await pubsub.topic(topic).publish( data )
        return ids[0]
    },

    simple_handler: function ( processor ) {
        return async (message) => {
            await processor(message)
            message.ack()
        },
    }

}

The Test

test_pubsub.js

test( 'test__listen_and_publish', async t => {
    const data = 'foo'
    return new Promise( async (resolve, reject) => {
        try {
            let published_id_p, stop_listening

            const processor = async (message) => {
                const published_id = await published_id_p
                if ( message.id === published_id ) {
                    t.is( message.data, data )
                    stop_listening()
                    resolve()
                }
            }
            const handler = pubsub.simple_handler( processor, { name: 'listen_and_publish' } )

            stop_listening = pubsub.listen(  'test-sub', handler )
            published_id_p = pubsub.publish( 'test',     data    )
        } catch (error) { reject(error) }
    })
})

The code works.  It listens for messages until it gets the test one it sent, in case there are leftover unacknowledged messages from previous failed test runs.  Once it receives the test message, it resolves the promise which ends the test successfully.

The code is ugly, though.  I'm creating callbacks that refer to variables I've declared already (so they're in context) but won't initialize until several lines later.

BTW - This is my first time creating a Promise, rather than building on one returned to me for a library.  I didn't know how else to wire up test success to the receiving of the correct message.

PS - My unit test framework is AVA.


texts:
I am trying to compare two Log lines based on some conditions, in order to sort them:

Code:

public static final Comparator<String> HTMLcomparator = new Comparator<String>()
    {
        @Override
        public int compare(String line1, String line2)
        {
            HTMLLogLine htmlLogLine1 = new HTMLLogLine(line1);
            HTMLLogLine htmlLogLine2 = new HTMLLogLine(line2);
            int fullCompare = 0;

            String requestId1 = htmlLogLine1.getRequestId();
            String requestId2 = htmlLogLine2.getRequestId();

            if(requestId1 != null && requestId2 != null)
            {
                fullCompare = requestId1.compareTo(requestId2);
            }
            else if(requestId1 == null && requestId2 != null)
            {
                fullCompare = -1;
            }
            else if(requestId1 != null)
            {
                 fullCompare = 1;
            }
            else
            {
                fullCompare = 0;
            }

            if(fullCompare == 0)
            {
                String security1 = htmlLogLine1.getSecurity();
                String security2 = htmlLogLine2.getSecurity();
                if(security1 != null && security2 != null)
                {
                    fullCompare = security1.compareTo(security2);
                }
                else if(security1 == null && security2 != null)
                {
                    fullCompare = -1;
                }
                else if(security1 != null && security2 == null)
                {
                    fullCompare = 1;
                }
                else
                {
                    fullCompare = 0;
                }
            }

            if(fullCompare == 0)
            {
                String scenario1 = htmlLogLine1.getScenario();
                String scenario2 = htmlLogLine2.getScenario();

                if(scenario1 != null && scenario2 != null)
                {
                    fullCompare = scenario1.compareTo(scenario2);

                }
                else if(scenario1 == null && scenario2 != null)
                {
                    fullCompare = -1;
                }
                else if(scenario1 != null)
                {
                    fullCompare = 1;
                }
                else
                {
                    fullCompare = 0;
                }
            }

            if(fullCompare == 0)
            {
                Optional<Instant> timestamp1 = htmlLogLine1.getTimestamp();
                Optional<Instant> timestamp2 = htmlLogLine2.getTimestamp();

                if(timestamp1.isPresent() && timestamp2.isPresent())
                {
                    fullCompare = timestamp1.get().compareTo(timestamp2.get());
                }
                else if(!timestamp1.isPresent() && timestamp2.isPresent())
                {
                    fullCompare = -1;
                }
                else if(timestamp1.isPresent() && !timestamp2.isPresent())
                {
                    fullCompare = 1;
                }
                else
                {
                    fullCompare = 0;
                }

            }

            return fullCompare;
        }
    };

How can I reduce the duplicate code and make this compare method concise?


texts: Bash script to download sequentially numbered images

texts:
This is a pretty basic bash script (3.2 on Mac). I am downloading 584 images from a site in order to create an album.

#!/bin/bash

urlFirst="http://150.216.68.252:8080/adore-djatoka/resolver?url_ver=Z39.88-2004&rft_id=http://150.216.68.252/ncgre000/00000012/00011462/00011462_ac_0"
urlSecond=".jp2&svc_id=info:lanl-repo/svc/getRegion&svc_val_fmt=info:ofi/fmt:kev:mtx:jpeg2000&svc.format=image/jpeg&svc.level=6"

for i in {1..584}
do
    printf -v j "%03d" $i

    url=$urlFirst$j$urlSecond

    wget $url -O $j".jpeg"

done

What improvements should be made to this?

I understand that I could remove the variables in most cases but for debug purposes it was helpful to have them, as I could add basic echo statements.

I'm not very well versed in Bash scripting though (lots of basic scripts) - any improvements or best practices from Bash I'm missing would be appreciated.


texts:
I want to improve the code, in which you can enter a grey bitmap and it will return you a colored one.

function ChangeBaseGrey(bitmap, color)
{
var canvas = document.getElementById("imagesColored");
var ctx = canvas.getContext("2d");
var dataBitmap = bitmap.data;

var r0 = (color >> 16) & 0xff,
    g0 = (color >> 8) & 0xff,
    b0 = color & 0xff;

for(var c = 0; c < dataBitmap.length; c += 4)
{
    var r1 = dataBitmap[c],
        g1 = dataBitmap[c + 1],
        b1 = dataBitmap[c + 2];

    if(dataBitmap[c + 3] > 0 && (r1 == g1 && r1 == b1 && g1 == b1))
    {
        var co = color;
        dataBitmap[c] = colorRGBBound(r0 * (r1 / 255));
        dataBitmap[c + 1] = colorRGBBound(g0 * (g1 / 255));
        dataBitmap[c + 2] = colorRGBBound(b0 * (b1 / 255));
    }
}

ctx.putImageData(bitmap, 0, 0);

var finalImage = new Image();
finalImage.src = canvas.toDataURL("image/png");

return finalImage; // Colored Image Output
}


texts:
You are given a string of lowercase letters. Your task is to figure out the index of the character whose removal will result in a palindrome. There will always be a valid solution.

Here is my quick solution:

public class Main {

    private static final String AAA = "aaa";

    public static void main(String[] args) {
        System.out.println(palindromeIndex(AAA));
    }

    /**
     * Returns whether a word is palindromic or not
     * @param word
     * @return true if the word is palindromic, false otherwise
     */
    public static boolean isPalindrome(String word) {
        return word.equals(new StringBuffer().append(word).reverse().toString());
    }

    public static int palindromeIndex(String word) {
        if(isPalindrome(word)) {
            return -1;
        }

        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < word.length(); i++) {
            sb.append(word);
            sb.deleteCharAt(i);
            if(isPalindrome(sb.toString())) {
                return i;
            }
            sb.delete(0, word.length());
        }

        /**the question said that there will always be a valid answer
         * so this shouldn't be necessary
         */
        return - 1;
    }
}

Additionally, out of a little dissatisfaction, I came up with an alternative method of figuring out whether a word is a palindrome:

public static boolean isPalindromeAlt(String word) {
    char[] chars = word.toCharArray();
    int wordEnd = word.length() - 1;
    for(int i = 0; i < chars.length; i++) {
        if(chars[i] != chars[wordEnd]) {
            return false;
        }
        wordEnd--;
    }

    return true;
}

But my question is, after actually thinking about it, is the way I have handled the palindrome index part efficient? I don't really like the fact that I am clearing a the stringbuffer after each iteration and using one, I thought that it might be more efficient to use an array or something, could someone please comment on whether my solution is efficient and whether there could be a more efficient way.

I could probably write a more efficient one in Python, I like how Strings are handled as arrays in it.


texts: Finding all delivery orders with multiple purchase orders

texts:
I have a SQL query to find all delivery orders with multiple purchase orders (one-to-many). Is there a better or shorter way to write this?

SELECT * FROM GR_data
WHERE doNo IN
(
    SELECT dt.doNo FROM
    (
        SELECT doNo, po_number FROM GR_data
        WHERE DATALENGTH(Mat_No)<=0
        GROUP BY doNo, po_number
    )AS dt
    GROUP BY dt.doNo
    HAVING COUNT(dt.doNo)>1
)
ORDER BY doNo, po_number


texts: Varying a second drop-down's options based on a first selection

texts:
I have some JavaScript code that allows users to select a plan which triggers the second select box to populate with options. The code works, however, it seems to be very inefficient. Any advice on improving the efficiency?

JavaScript:

var term = 0;
var price = 0;
var additional = 0;
var fix = 0;
var plan = document.getElementById('billing-plan');
plan.addEventListener('change', enableBilling, false);
var select = document.getElementById('billing-price');
select.addEventListener('change', updatePrice, false);

var basic = {
    "Option" : ["$200/month for 1-yr", "$250/month"],
    "Value" : [300, 350]
}
var prime = {
    "Option" : ["$300/month for 1-yr", "$350/month"],
    "Value" : [400, 450]
}
var gold = {
    "Option" : ["$400/month for 1-yr", "$450/month"],
    "Value" : [500, 550]
}

function populateBilling(planName) {
    //RESET BILLING PERIOD OPTIONS AND TOTALS
    select.options.length = 1;
    document.getElementById('payment-total').innerText = 0 + additional;
    document.getElementById('payment-rebill').innerText = 0 + additional;
    //FILL BILLING PERIOD WITH PLAN OPTIONS AND VALUES
    if (planName == "basic") {
         for (i = 0; i < basic.Option.length; i++){
             var temp = document.createElement('option');
             temp.value = basic.Value[i];
             temp.text = basic.Option[i];
             select.appendChild(temp);
         }

    } else if (planName == "prime") {
        for (i = 0; i < basic.Option.length; i++){
            var temp = document.createElement('option');
            temp.value = prime.Value[i];
            temp.text = prime.Option[i];
            select.appendChild(temp);
         }
    } else {
         for (i = 0; i < basic.Option.length; i++){
             var temp = document.createElement('option');
             temp.value = gold.Value[i];
             temp.text = gold.Option[i];
             select.appendChild(temp);
         }
    }
 }

 function enableBilling(e) {
      document.getElementById('billing-price').disabled=false;
      var planName = plan.options[plan.selectedIndex].text.toLowerCase();
      populateBilling(planName);

}

function updatePrice(e) {
      price = parseFloat(select.value);
      fix = 100;
      if (price == select.options[2].value){
          term = 1;
      }
      document.getElementById('payment-total').innerText = price + additional;
      if (price == select.options[2].value){
      document.getElementById('payment-rebill').innerText = 0 + additional;
      } else {
      document.getElementById('payment-rebill').innerText = price + additional - fix;
      }
}

Here it is in a jsfiddle: http://jsfiddle.net/aGq9q/13/


texts: How could this "complex method" for codeclimate be refactored?

texts:
I'm trying to figure out how to refactor some code based on what codeclimate is telling me.  So far it seems that any method that is longer than 5 lines or has an if statement is "complex". In this instance, I'm trying to create an event for a calendar based off of a meeting record.

Here is the Event model:

class Event < ActiveRecord::Base
  validates :title, :eventcolor_id, presence: true
  belongs_to :meeting
  belongs_to :eventcolor

  def self.create_from_meeting(meeting, eventcolor)
    meeting.meeting_date_end ||= meeting.meeting_date_start
    Event.find_or_initialize_by(meeting_id: meeting.id) do |e|
      e.title = meeting.title
      e.datetime_start = Time.zone.local_to_utc(meeting.meeting_date_start)
      e.datetime_end = Time.zone.local_to_utc(meeting.meeting_date_end)
      e.location = meeting.location
      e.address1 = meeting.address1
      e.address2 = meeting.address2
      e.city = meeting.city
      e.state = meeting.state
      e.zip = meeting.zip
      e.description = (!meeting.description.blank?) ? meeting.description : ''
      e.eventcolor_id = eventcolor
      e.save
      e.committees << meeting.committee if !meeting.committee.nil?
    end
  end
end

which is called from my meetings_controller with this line:

Event.create_from_meeting(meeting, params[:eventcolors_select])


texts: Scraping lunar/solar eclipse data with BeautifulSoup

texts:
I created a script to scrape this website and gather the eclipse data (date, type, and location):

class Eclipse():

    def __init__(self, eclipse_date, eclipse_type, eclipse_location):
        self._eclipse_date = eclipse_date
        self._eclipse_type = eclipse_type
        self._eclipse_location = eclipse_location

    @property
    def get_eclipse_date(self):
        return self._eclipse_date

    @property
    def get_eclipse_type(self):
        return self._eclipse_type

    @property
    def get_eclipse_location(self):
        return self._eclipse_location

    def __str__(self):
        return "Date: {0} Type {1} Location: {2}" .format(self._eclipse_date,self._eclipse_type,self._eclipse_location)

Main class:

import requests
from bs4 import BeautifulSoup
from Eclipse import Eclipse
from collections import namedtuple

def generate_eclipse_data(eclipse_info):

    eclipse_list = []

    for info in eclipse_info:
       eclipse_date_and_type = info.find('a').text
       retrieved_date_and_type = generate_date_and_type(eclipse_date_and_type)
       eclipse_location = info.find('p').text
       retrieved_location_data = generate_location(eclipse_location)
       eclipse_data = Eclipse(retrieved_date_and_type.date,retrieved_date_and_type.type,retrieved_location_data.location)
       eclipse_list.append(eclipse_data)
    return eclipse_list

def generate_location(info_to_clean):
   clean_location = namedtuple("Clean_Location",["location"])
   cleanup_location = info_to_clean.split(" New Features")[0]
   location_data = clean_location(cleanup_location)
   return location_data

def generate_date_and_type(info_to_split):
   date_and_type = namedtuple("Date_Type", ["date", "type"])
   eclipse_split_data = info_to_split.split("—")
   eclipse_date = eclipse_split_data[0]
   eclipse_type = eclipse_split_data[1].strip()
   eclipse_data = date_and_type(eclipse_date,eclipse_type)
   return eclipse_data

def write_data_to_file(filename, data):
    with open(filename, 'w') as eclipse_writer:
        for info in data:
            eclipse_writer.write(str(info))
            eclipse_writer.write("\n")

def main():

    eclipse_time_date = requests.get("https://www.timeanddate.com/eclipse/")
    soup = BeautifulSoup(eclipse_time_date.text, 'html.parser')
    eclipse_info = soup.find_all("div", class_= "six columns art__eclipse-txt")
    eclipse_filename = 'eclipse.txt'

    if (len(eclipse_info) > 0):
        eclipse_data =  generate_eclipse_data(eclipse_info)
        write_data_to_file(eclipse_filename, eclipse_data)
    else:
        print("No data available")

if __name__ == "__main__":
    main()

Output:

Date: July 13, 2018
Type: Partial Solar Eclipse
Location: South in Australia, Pacific, Indian Ocean

Date: July 27, 2018
Type: Total Lunar Eclipse
Location: Much of Europe, Much of Asia, Australia, Africa, South in North America, South America, Pacific, Atlantic, Indian Ocean, Antarctica

Questions:

I tried to be as descriptive as I can when naming my variables and functions. Are they clear enough?
Can I improve the script any further?


texts:
I've read this article about Mean Average Precision (MAP).

Now, in my C++ code I have an std::vector<std::string> queries, where queries[i] is the identifier of the i-th query.

In addition, I have a std::vector<std::vector<std::string> truePositives where truePositives[i][z] is the z-th true positive correspondent to the i-th query. Since the actual order in truePositives[i] isn't important, I could have used std::vector<std::set<std::string>>, but whatever...

Finally, I have a std::vector<std::string> topkTest where topkTest[j] is the j-th element in the top-k ranked list returned by the system for the given query, where k = min(data set size, 10k) (following the suggestion in this question).

Here you can find my code to compute the MAP. I post it here because there is no actual way to say if the returned result (the map value) is correct or not.

    float map = 0;
    for(size_t i=0; i<queries.size(); i++){
        std::vector<std::string> topkTest;
        //populate topkTest somehow using k
        float correct = 0;
        float ap = 0;
        for(size_t j=0; j<topkTest.size(); j++){
            //if topkTest[j] belongs to the true positives, increment the number of correct images
            if(std::find(truePositives.begin(), truePositives.end(), topkTest[j]) != queries.end())
                ap += ++correct / (j+1);
        map += ap / topkTest.size();
    }
    map /= queries.size(),

What do you think about this?


texts: Vectorized numpy version of arange with multiple start stop

texts:
Given a single start and stop, numpy.arange is a good solution for building a NumPy array of evenly spaced values.  However, given an array of start and an array of stop values, I would like to build an array of concatenated evenly spaced values, and do so in C speed (no looping).  Here is my current solution, though I am wondering if there is a NumPy/SciPy function I missed that already does this.

def vrange(starts, lengths):
    """ Create concatenated ranges of integers for multiple start/length

    Args:
        starts (numpy.array): starts for each range
        lengths (numpy.array): lengths for each range (same length as starts)

    Returns:
        numpy.array: concatenated ranges

    See the following illustrative example:

        starts = np.array([1, 3, 4, 6])
        lengths = np.array([0, 2, 3, 0])

        print vrange(starts, lengths)
        >>> [3 4 4 5 6]

    """

    # Repeat start position index length times and concatenate
    cat_start = np.repeat(starts, lengths)

    # Create group counter that resets for each start/length
    cat_counter = np.arange(lengths.sum()) - np.repeat(lengths.cumsum() - lengths, lengths)

    # Add group counter to group specific starts
    cat_range = cat_start + cat_counter

    return cat_range

If you are curious why I need this, it's for building a 1-to-many mapping of intervals to contained positions.


texts: A more efficient enqueue algorithm in Java

texts:
So I have this simple code in Java. It enqueue (adds) and element to the end of the queue (implemented by an ArrayList) without changing the original queue.

public class MyQueue<T>{
    private List<T> body;

    // some constructors and helper functions.

    //copy constructor
    public MyQueue(List<T> list){
        this.body = list;
    }

    //this is the function
    public MyQueue<T> enqueue(T obj){
        List<T> temp = new ArrayList<T>(body);
        temp.add(obj);
        return new Queue<T>(temp);
    }

The whole idea is to make enqueue faster and more efficient, and again, as you notice, without changing the value of the original queue.  Any ideas?

UPDATE
For the sake of completing the idea.

1- This is an assignment so university, the skeleton provided is not to be changed, the task is to make the function enqueue faster (i do realize i am copying twice and thats the slow part).

2- As for the helper functions, they are simple:

public T peek(){
if(body.isEmpty()){
   thrown new NoSuchElementException();
}
return body.get(0);
}

public int size(){
return body.size();
}


texts:
numerator: Value being divided.

denominator: Divisor value.

method so far:

def calc_percentage(numerator, denominator)
  ((numerator/ (denominator.to_f.nonzero? || 1 )) * 100)
end

What are the bad practices you see in the code above?  How can I improve it or write it in a better way ?


texts:
I have done some research about intentions of UnitOfWork pattern. In short, what I understood is that UoW is needed for transactions. But I saw some code examples where people use UoW as factory for Repository objects as well, one example is DbContext from EF. My first thought about it doesn't it break single responsibility principle?
In my current project I am using both UoW and Repository patterns. Here are my interfaces:

UnitOfWork:

public interface IUnitOfWork : IDisposable
{
    void Commit();
    void Rollback();
    IRepository<T> GetRepository<T>() where T : class;
}

Repository interface:

public interface IRepository<T> where T : class
{
    IQueryable<T> FindAll();
    IQueryable<T> Find(Expression<Func<T, bool>> predicate);
    T FindById(Id id);
    void Add(T newEntity);
    void Remove(T entity);
}

My concern is GetRepository<T> method in IUnitOfWork interface. Should this method be here at all? Or should I move it somewhere else? What would you suggest?

PS
I am using NHibernate as my ORM tool, but I think this should not make any difference


texts: Wrapper for boolean type to reduce the use of if statements

texts:
I want to create wrapper for boolean type to not use more if statements. Can you tell me that this class make sense?

public final class Bool {

    private boolean value;

    private Bool(boolean value) {
        this.value = value;
    }

    public static final Bool of(boolean value) {
        return new Bool(value);
    }

    public static final Bool ofFalse() {
        return new Bool(false);
    }

    public static final Bool ofTrue() {
        return new Bool(true);
    }

    public OrElse ifTrue(Procedure procedure) {
        if (value)
            procedure.invoke();
        return new OrElse(!value);
    }

    public OrElse ifFalse(Procedure procedure) {
        if (!value)
            procedure.invoke();
       return new OrElse(value);
    }

    public class OrElse {
        private boolean value;

        private OrElse(boolean value) {
            this.value = value;
        }

        public void orElse(Procedure procedure) {
            if (value)
                procedure.invoke();
        }
    }
}

Example usage:

public Bool findElement(String name) {
    for(Element el : elements) {
       if(el.getName().equals(name)) return Bool.ofTrue();
    }
    return Bool.ofFalse();
}

// And now in other place of code I may use:
findElement("el").ifTrue(() -> doSomething).orElse(() -> doSomethingElse)


texts: Directory that lists employee information

texts:
I'm working on a directory that lists employee information.  Each employee can belong to multiple departments and each employee can have multiple job titles.  I have 5 MySQL tables that I am pulling information out of, including:

employee
employee_has_department
department
employee_has_jobTitle
jobTitle

The employee table has a many-to-many relationship with department and jobTitle.  I currently have nested queries, as follows:

$stmt = $mysqli->prepare("SELECT employeeId, firstName, middleName, lastName, suffix, profilePhoto FROM employee");
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($employeeId, $firstName, $middleName, $lastName, $suffix, $profilePhoto);
while($stmt->fetch()){

  echo "
$firstName
";

  $stmt2 = $mysqli->prepare("SELECT jobName FROM jobTitle INNER JOIN employee_has_jobTitle ON jobTitleId = jobTitle_jobTitleId WHERE employee_employeeId = ?");
  $stmt2->bind_param("i", $employeeId);
  $stmt2->execute();
  $stmt2->store_result();
  $stmt2->bind_result($jobName);
  while($stmt2->fetch()) {
    echo "$jobName
";
  }

  $stmt3 = $mysqli->prepare("SELECT departmentName, departmentURL FROM department INNER JOIN employee_has_department ON departmentId = department_departmentId WHERE employee_employeeId = ?");
  $stmt3->bind_param("i", $employeeId);
  $stmt3->execute();
  $stmt3->store_result();
  $stmt3->bind_result($deptName, $deptURL);
  while($stmt3->fetch()) {
      echo "$deptName";
  }
}

Clearly the output needs formatting, but it's getting the information and outputting as expected.  I know that this can probably be done in a single sql statement, but the complexity and ugliness of performing a join on 5 separate tables with multiple many-to-many relationships leaves me wondering.  Would taking the time to figure out such a query worth the hassle, or is this an "acceptable" way of handling the situation?


texts:
This is my second day in learning Scala and I still need to develop a taste of functional programming, I often find myself doing imperative coding. Below is the result of my TDD practice.

Code

class DNA(dnaSequence: String) {
  var count = collection.mutable.Map('A' -> 0, 'T' -> 0, 'C' -> 0, 'G' -> 0)

  dnaSequence.foreach { (i: Char) =>
    validate(i)
    count = count.updated(i, count.get(i).getOrElse(0) + 1)
  }

  def nucleotideCounts() = count

  def nucleotideCounts(nucleotide: Char) = {
    validate(nucleotide)
    count.get(nucleotide).getOrElse(0)
  }

  private def validate(chr: Char) = {
    if (!count.contains(chr)) throw new RuntimeException()
  }
}

Test Suite

import org.scalatest._

class NucleotideCountSpecs extends FlatSpec with Matchers {
  "empty dna string" should "have no adenine" in {
    new DNA("").nucleotideCounts('A') should be (0)
  }

  it should "have no nucleotides" in {
    val expected = Map('A' -> 0, 'T' -> 0, 'C' -> 0, 'G' -> 0)
    new DNA("").nucleotideCounts should be (expected)
  }

  "a repetitive sequence" should "count cytosine" in {
    new DNA("CCCCC").nucleotideCounts('C') should be (5)
  }

  it should "have only guanine" in {
    val expected = Map('A' -> 0, 'T' -> 0, 'C' -> 0, 'G' -> 8)
    new DNA("GGGGGGGG").nucleotideCounts should be (expected)
  }

  "a mixed dna string" should "count only thymine" in {
    new DNA("GGGGGTAACCCGG").nucleotideCounts('T') should be (1)
  }

  it should "count a nucleotide only once" in {
    val dna = new DNA("CGATTGGG")
    dna.nucleotideCounts('T')
    dna.nucleotideCounts('T') should be (2)
  }

  it should "not change counts after counting adenine" in {
    val dna = new DNA("GATTACA")
    dna.nucleotideCounts('A')
    val expected = Map('A' -> 3, 'T' -> 2, 'C' -> 1, 'G' -> 1)
    dna.nucleotideCounts should be (expected)
  }

  it should "validate nucleotides" in {
    a [RuntimeException] should be thrownBy new DNA("GACT").nucleotideCounts('X')
  }

  it should "validate dna not rna" in {
    a [RuntimeException] should be thrownBy new DNA("ACGU")
  }

  it should "validate dna" in {
    a [RuntimeException] should be thrownBy new DNA("John")
  }

  it should "count all nucleotides" in {
    val s = "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC"
    val dna = new DNA(s)
    val expected = Map('A' -> 20, 'T' -> 21, 'G' -> 17, 'C' -> 12)
    dna.nucleotideCounts should be (expected)
  }
}

Source


texts: Make a new design of Stack with a new function

texts:
I am doing some coding exercise, and I am not sure if I have met the requirement. Can someone help me to figure it out?

How would you design a stack which, in addition to push and pop, also has a function min which returns the minimum element? Push, pop and min should all operate in O(1) time.

public class Question {
private Node top;
private Node min;

public void push(int data) {
    Node newNode = new Node(data);
    Node newMin = new Node(data);
    if (top == null) {
        this.top = newNode;
        this.min = newMin;
    } else {
        newNode.next = this.top;
        this.top = newNode;
        if (newMin.data < this.min.data) {
            newMin.next = this.min;
            this.min = newMin;
        }
    }
}

public int pop() {
    if (top == null) {
        return -1;
    }
    int tempInt = this.top.data;
    if (this.top.data == this.min.data) {
        this.min = this.min.next;
    }
    this.top = this.top.next;
    return tempInt;
}

public int min() {
    return this.min.data;
}
public String toString(){
    return "Current top is: " + this.top.data + ", current min is: " + this.min();
}

class Node {
    Node next;
    int data;

    public Node(int data) {
        this.data = data;
    }
}

public static void main(String[] args){
    Question tempQue = new Question();
    for(int i = 100; i > 0; i--){
        tempQue.push(i);
        System.out.println(tempQue);
    }
    for(int i = 0 ; i < 99; i++){
        tempQue.pop();
        System.out.println(tempQue);
    }
}
}

I have tested this code but I am not sure if the Operating time meets the requirement \$O(1)\$.


texts: How can I remove this for-loop in this competitive FizzBuzz code?

texts:
I'v written this code snippet that's part of a code competition.

I want to do the trick without the for-loop, or simply find a way to optimize this code for speed.

for ( i=1; i<=N; i++ )

How is it possible, if it is?  What do I need to modify to speed up this code considering a very large input file?

Here is the competition summary:

  Players generally sit in a circle. The player designated to go first
  says the number "1", and each player thenceforth counts one number in
  turn. However, any number divisible by 'A' e.g. three is replaced by
  the word fizz and any divisible by 'B' e.g. five by the word buzz.
  Numbers divisible by both become fizz buzz. A player who hesitates or
  makes a mistake is either eliminated.

  Write a program that prints out the the pattern generated by such a
  scenario given the values of 'A'/'B' and 'N' which are read from an
  input text file. The input text file contains three space delimited
  numbers i.e. A, B, N. The program should then print out the final
  series of numbers using 'F' for fizz, 'B' for 'buzz' and 'FB' for fizz
  buzz.

  Print out the series 1 through N replacing numbers divisible by 'A' by
  F, numbers divisible by 'B' by B and numbers divisible by both as
  'FB'. Since the input file contains multiple sets of values, your
  output will print out one line per set. Ensure that there are no
  trailing empty spaces on each line you print.

Input file:

3 5 10
2 7 15

Output:

1 2 F 4 B F 7 8 F B
1 F 3 F 5 F B F 9 F 11 F 13 FB 15

Here my code:

int main(int argc, const char * argv[])
{
  NSString* filename      = [NSString stringWithCString:argv[1] encoding:NSASCIIStringEncoding];
  NSString* content       = [NSString stringWithContentsOfFile:filename encoding:NSASCIIStringEncoding error:nil];
  NSScanner* scanner      = [NSScanner scannerWithString:content];
  while ( ![scanner isAtEnd] )
  {
    NSString* line;
    [scanner scanUpToString:@"\n" intoString:&line];

    NSArray *nums = [ line componentsSeparatedByString:@" " ];
    int A         = [[nums objectAtIndex:0] intValue];
    int B         = [[nums objectAtIndex:1] intValue];
    int N         = [[nums objectAtIndex:2] intValue];

    int i=0;
    for ( i=1; i<=N; i++ )
    {
      NSString *str = [ NSString stringWithFormat:@"%d", i ];

      if ( i%A == 0 ) str = @"F";
      if ( i%B == 0 ) str = @"B";
      if ( i%A == 0 && i%B == 0 ) str = @"FB";

      printf( "%s ", [str UTF8String] );
    }
    printf("\n");
  }
  return 0;
}


texts: Split string into "n" lengths with padding

texts:
I quickly wrote a short program to split a string into \$n\$ lengths with variable-character padding:

#include <iostream>
#include <algorithm>

std::string getString();
int getBlockSize();
char getPaddingChar();
std::string addPadding(std::string str, int blockSize, char paddingChar);
std::string tokenize(std::string str, int blockSize);

int main(){
    std::string str = getString();
    int blockSize = getBlockSize();
    char paddingChar = getPaddingChar();

    str.erase(std::remove(str.begin(), str.end(), ' '), str.end());
    str = addPadding(str, blockSize, paddingChar);
    str = tokenize(str, blockSize);

    std::cout << str;

    std::cout << '\n';
    return 0;
}

std::string getString(){
    std::cout << "Input string: ";

    std::string str;
    std::getline(std::cin, str);

    return str;
}

int getBlockSize(){
    std::string inputStr;
    int blockSize;

    do{
        try{
            std::cout << "Block size: ";
            std::getline(std::cin, inputStr);
            blockSize = std::stoi(inputStr);
        } catch(...){
            blockSize = 0;
        }
    } while(blockSize < 1);

    return blockSize;
}

char getPaddingChar(){
    char paddingChar;

    do{
        std::cout << "Padding character: ";
        std::cin >> paddingChar;
        std::cin.ignore(std::numeric_limits<std::streamsize>::max(),'\n');
    } while(std::cin.fail());

    return paddingChar;
}

std::string addPadding(std::string str, int blockSize, char paddingChar){
    while(str.length() % blockSize != 0){
        str += paddingChar;
    }
    return str;
}

std::string tokenize(std::string str, int blockSize){
    for(int i = blockSize; i < str.length(); i += blockSize+1){
        str.insert(i, 1, ' ');
    }
    return str;
}

This code firstly gets the input string (str), gets the size of the block (blockSize), and then gets the character that is to be used as padding (paddingChar).

It then removes all spaces from input string, adds padding, and then tokenizes the string by splitting it into blockSize pieces.

Example output:

Input string: Tis' but a scratch!
Block size: 11
Padding character: X
Tis'butascr atch!XXXXXX

The splitting of a stream of characters into blocks is common in cryptography. While there certainly are many, many Code Review questions on tokenization, I was unable to find one that was exactly like this and in C++, so I felt that this area should also be covered in that aspect.

I tried to use the helpful suggestions from my previous Code Review questions to improve the quality of my code as best I could. Despite that, there is always room to improve the way that I write code.

How can I improve this code?


texts: Design for container that holds multiple instances of same base class

texts:
I have four different classes. First being a base class for the second and third. The fourth being a container class that holds instances of second and third (stored as first).

My base class for PC and Companion

public class Controllable
{
    protected String name;
    protected int x;

    public Controllable (String name) {
        this.name = name;
    }

    public void move () {
        x++;
    }
}

public class PC extends Controllable
{
    private int someUniqueVariable;

    public PC (String name, int someUniqueVariable) {
        super (name);
        this.someUniqueVariable = someUniqueVariable;
    }
}

public class Companion extends Controllable
{
    public Companion (String name) {
        super (name);
    }
}

And finally the wrapper/container class.

public class Party
{
    private PC pc;
    private List<Controllable> members;

    public Party () {
        PC = new PC ("PC", 1); // edit #1: should be pc, bad copy-paste
        members = new ArrayList<Controllable>();
        members.add (PC);
        members.add (new Companion ("Companion1");
        members.add (new Companion ("Companion2");
    }

    public moveAll () {
        for (Controllable m : members) {
            m.move();
        }
    }

    public getPC () {
        return pc;
    }
}

Now if I want to move all Controllable I will iterate over members. If there are pc  specifics I will simply call the PC and use its move function. PC will be more separated from Companion later on.

I would mostly like feedback on the design of my code.

Edit #1:

The most critical area were I want feedback is this. Most things are shared between Companion and PC, however there are some unique features of PC. In 99% I want to be able to iterate over all of the party members In more rare cases I want to only access the Companions and sometimes I only want to access the PC.

public Party () {
    pc = new PC ("PC", 1);
    members = new ArrayList<>();
    members.add (PC);
    members.add (new Companion ("Companion1");
    members.add (new Companion ("Companion2");
}

Minor edit to show an error in the code.


texts: Click n times on image to match with random number n

texts:
Challenge

Create a page with

An element for number,
An image
An unordered list tag for list of images
A 'Check result' button
A text element to show result

Generate random number and put it in (i)
On click the image it add an li with the image inside UL tag
On click check result button, compare random with number of images inside UL, if both are same show Correct answer else wrong answer in result box.

Codepen URL

Random number and Image

HTML

Select  s

      <button id="btnResult" class="btn btn-primary">Check Result</button>

jQuery

$(function() {
    var elements = {
        random: $("#randomNumber"),
        item: $("#item"),
        sourceImage: $("#actionImage"),
        targetImage: $(""),
        imageList: $("#imgList"),
        list: $("
"),
        btnResult: $("#btnResult"),
        output: $("#output")
    },
    data = {
        random: Math.floor(9 * Math.random() + 2),
        image: elements.sourceImage.attr("src"),
        item: elements.sourceImage.attr("alt")
    },
    events = {
        init: function() {
            elements.random.text(data.random), elements.item.text(data.item), elements.targetImage.attr({
                alt: "list image",
                src: data.image
            }),
            elements.list.append(elements.targetImage),
            elements.sourceImage.click(events.addImage),
            elements.btnResult.click(events.showResult);
        },
        addImage: function() {
            elements.imageList.append(elements.list.clone());
        },
        showResult: function() {
            var result = "Correct Answer";
            elements.imageList.children().length !== data.random &&
            (result = "Wrong Answer"), elements.output.text(result);
        }
    };
    events.init();
});


texts: Iterate through a 2D array. Kotlin extension method

texts:
Simple extension method for Kotlin. Should perform an action on every element in a 2d array. i.e. An array of arrays.

I have made the assumption that because the receiver type is defined as an array of arrays of type T, that I do not need to do any checks or casts.

fun <T> Array<Array<T>>.forEach2d(action: (T) -> Unit): Unit {
    for (outer in this) {
        for (inner in outer) {
            action(inner)
        }
    }
}


texts: Arbitrary precision Euler-Mascheroni constant via a Brent-McMillan algorithm with no math module

texts:
Utilizing the below relation, I am able to compute the Euler constant to great precision on a single thread quickly and simply.

My process is to compute the natural log via the AGM(utilizing Pi an the Ln(2)), and apply the result to the BMM algorithm.

\$\gamma=\lim_{n\to\infty}\mathscr{G}_n=\lim_{n\to\infty}\frac{\sum\limits_{k=0}^\infty \left(\frac{n^k}{k!}\right)^2 (H_k-\log\,n)}{\sum\limits_{k=0}^\infty \left(\frac{n^k}{k!}\right)^2}\$

where \$H_k=\sum\limits_{j=1}^k \frac1{j}\$ is a Harmonic number.

This process is much more efficient than my previous post.

import decimal
from tqdm import tqdm

def agm(a, b):
    """Arithmetic Geometric Mean"""
    a, b = D(a),D(b)
    for x in tqdm(range(prec)):
        a, b = (a + b) / 2, (a * b).sqrt()
    return a

def pi_agm():
    """Pi via AGM and lemniscate"""
    print('Computing Pi...')
    a, b, t = 1, D(0.5).sqrt(), 1/D(2)
    p, pi, k = 2, 0, 0
    while 1:
        an    = (a+b)/2
        b     = (a*b).sqrt()
        t    -= p*(a-an)**2
        a, p  = an, 2**(k+2)
        piold = pi
        pi    = ((a+b)**2)/(2*t)
        k    += 1
        if pi == piold:
            break
    return pi

def lnagm(x):
    """Natural log of via AGM"""
    if x == D(1):
        return 0
    if x == D(2):
        return lntwo()
    m = prec*2
    ln2 = lntwo()
    decimal.getcontext().prec = m
    pi = pi_agm()
    print('Computing Ln({0})...'.format(x))
    twoprec = (D(2)**(2-m))/x
    den = agm(1, twoprec)*2
    diff = m*ln2
    result = ((pi/den) - diff)
    logr = D(str(result)[:m//2])
    decimal.getcontext().prec = prec
    return logr

def lntwo():        #Fast converging Ln 2
    print('Computing Ln(2)...')
    def lntwosum(n, d, b):
        logsum, logold, e = D(0), D(0), 0
        while True:
            logold = logsum
            logsum += (1/((D(b**e))*((2*e)+1)))
            e += 1
            if logsum == logold:
                return (D(n)/D(d))*logsum
    logsum1 = lntwosum(14, 31, 961)
    logsum2 = lntwosum(6, 161, 25921)
    logsum3 = lntwosum(10, 49, 2401)
    ln2 = logsum1 + logsum2 + logsum3
    return ln2

def gamma():
    n = D(prec)
    a = u = -lnagm(n)
    b = v = D(1)
    i = D(1)
    while True:
        k = (n/i)**2
        a *= k
        b *= k
        a += (b/i)
        if (u+a) == u or (v+b) == v:
            break
        u += a
        v += b
        i += 1
    return D(str(u/v)[:prec-3])

if __name__ == "__main__":
    """Setting precision plus 5 to accomodate error"""
    prec = int(input('Precision: '))+5
    decimal.getcontext().prec = prec
    D = decimal.Decimal
    print(gamma())


texts: Angular console like window - first directive

texts:
I've asked question on SO how to rewrite jQuery code to Angular. Because I got no answers I've tried to create something by my own.
This is my version of code:

(function() {
  'use strict';

  angular
    .module('misiu.directives', [])
    .directive('console', ['$rootScope', function($rootScope) {
      return {
        restrict: 'E',
        template: [
          '
',
          '
',
          '{{event.data}}1" class="count">{{event.count}}',
          '
',
          '
'
        ].join(''),
        link: function($scope, element) {

          $scope.events = [];

          $rootScope.$on('Log', function(event, data) {

            if ($scope.events[0] !== undefined && $scope.events[0].type === "log" && $scope.events[0].data === "Log :: " + data) {
              $scope.events[0].count++;
            } else {
              $scope.events.splice(0, 0, {
                type: 'log',
                data: "Log :: " + data,
                count: 1
              });
            }

          });

          $rootScope.$on('Error', function(event, data) {

            if ($scope.events[0] !== undefined && $scope.events[0].type === "error" && $scope.events[0].data === "Error :: " + data) {
              $scope.events[0].count++;
            } else {
              $scope.events.splice(0, 0, {
                type: 'error',
                data: "Error :: " + data,
                count: 1
              });
            }

          });
        }
      };
    }])
})();

and Plunker showing demo (move mouse over console div to add entries)

Because this is my first directive I'd like to ask for code review.

I'm adding new items to my console using one of those lines:

$rootScope.$emit("Log", "Something");
$rootScope.$emit("Error", "Terrible error");

I must add $rootScope as dependency to every controller if I want to use my directive there. Maybe factory would be better? This way I could for example add a way to remove everything except last 20 entries.

I'd like my directive to be optimized for speed. I've tested it for a while, but I'm not sure I did everything properly.

I need only single way binding and the thing that can change it only top most element (counter can increase), rest of element don't need binding. Maybe this can be also optimized.

Any other comments on what is wrong are welcome.

EDIT
I've created another code review request that includes same control, but using provider.


texts: Creating a server for user Internet orders

texts:
I've been learning the basics of node over the last couple of days and finally hooked up what I needed.  I'm just after someone to comment on if I have gone the right way around this task.

It creates a server which users access to get updates to Orders through server side events.
The events are published through redis which I subscribe to the queue.

var redis = require('redis'),
    http = require('http'),
    os = require("os"),
    PHPUnserialize = require('php-unserialize');

function sendServerSendEventForInternetOrders(req, res) {
    req.socket.setTimeout(0); // let request last as long as possible
    var hostname;
    if(os.hostname() == "kipos"){
        hostname = os.hostname()+".dev";
    }else{
        hostname = os.hostname();
    }
    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive',
        'Access-Control-Allow-Origin': 'http://'+hostname
    });

    res.write('\n');

    var phpSession = req.url.match('\/internetOrders\/(.*)')[1];

    console.log(phpSession + " - created client");
    var redisClient = redis.createClient();

    // In case we encounter an error...print it out to the console
    redisClient.on("error", function (err) {
        console.log(phpSession + " - Redis Error: " + err);
    });

    var phpSession = req.url.match('\/internetOrders\/(.*)')[1];

    var taID;
    var takeaway;

    redisClient.get("PHPREDIS_SESSION:" + phpSession, function (err, reply) {
        if (reply != null || err != null) {
            taID = PHPUnserialize.unserializeSession(reply).LoggedIn.TaID;
            console.log(phpSession + " - " + taID);
            startSub();
        } else {
            res.end();
            console.log(phpSession + " - exit");
        }
    });
    function startSub() {
        redisClient.select(1, function () {
            redisClient.get(taID + "T", function (err, reply) {
                if (reply == null) {
                    res.end();
                    console.log(phpSession + " - exit");
                    return;
                }
                takeaway = JSON.parse(reply);
                console.log(phpSession + " - "+takeaway.TaWebName);
            });

            redisClient.subscribe(taID + "IOU");

            // When we receive a message from the redis connection
            redisClient.on("message", function (channel, message) {
                sendMessage(message);
            });

            req.on("close", function () {
                redisClient.unsubscribe();
                redisClient.quit();
                console.log(phpSession + " - exit");
            });
        });
    }
    function sendMessage(data){
        res.write("data: " + data + '\n\n'); // Note the extra newline
        console.log(phpSession + " - data: " + data);
    }
};

http.createServer(function (req, res) {
    console.log(req.url);
    if (req.headers.accept && req.headers.accept == 'text/event-stream') {
        if (req.url.match('\/internetOrders\/(.*)')) {
            sendServerSendEventForInternetOrders(req, res);
        }
        else if (req.url == '/windowsApp') {
            res.writeHead(404);
            res.end();
        }
        else {
            res.writeHead(404);
            res.end();
        }
    } else {
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end("Hello Kipos!"); // Kept this in for checking node server is up!
    }
}).listen(8080);


texts: Implementing Sample Abstract Factory Pattern using Smart Pointers in C++

texts:
Was trying to implement and example code to smart pointer from link.
Is it a good practice? To go with all unique pointers or should we use shared pointers in this case? How can i improve this ?

#include <iostream>
#include <string>
#include<memory>

void LOG(std::string strText)
{
    std::cout << strText << std::endl;
}

class Widget {
public:
    virtual void draw() = 0;
};

class WindowsBtn : public Widget
{
public:
    void draw() {
        LOG("Windows Button");
    }
};

class WindowsMenu : public Widget
{
public:
    void draw() {
        LOG("Windows Menu");
    }
};

class LinuxBtn : public Widget
{
public:
    void draw() {
        LOG("Linux Button");
    }
};

class LinuxMenu : public Widget
{
public:
    void draw() {
        LOG("Linux Menu");
    }
};
/*
class WidgetFactory
{
public:
    virtual Widget* CreateButton() = 0;
    virtual Widget* CreateMenu() = 0;
};

class WindowsFactory : public WidgetFactory{
public:
    Widget* CreateButton() {
        return (new WindowsBtn);
    }

    Widget* CreateMenu() {
        return (new WindowsMenu);
    }

};

class LinuxFactory : public WidgetFactory{
public:
    Widget* CreateButton() {
        return (new LinuxBtn);
    }

    Widget* CreateMenu() {
        return (new LinuxMenu);
    }

};

class Client
{
    WidgetFactory * factory;
public:
    Client(WidgetFactory* factory) :factory(factory)
    {}

    void draw(){
        Widget * wd = factory->CreateButton();
        wd->draw();
        display1();
        display2();
    }
    void display1()
    {
        Widget * w[] = {
            factory->CreateButton(),
            factory->CreateMenu()
        };
        w[0]->draw();
        w[1]->draw();
    }
    void display2()
    {
        Widget * w[] = {
            factory->CreateMenu(),
            factory->CreateButton()
        };
        w[0]->draw();
        w[1]->draw();
    }

};
*/
class SmartWidgetFactory
{
public:
    virtual std::unique_ptr<Widget> CreateButton() = 0;
    virtual std::unique_ptr<Widget> CreateMenu() = 0;
};

class SmartWindowsFactory : public SmartWidgetFactory {
public:
    std::unique_ptr<Widget> CreateButton() {
        return std::make_unique<WindowsBtn>();
    }

    std::unique_ptr<Widget> CreateMenu() {
        return  std::make_unique<WindowsMenu>();
    }
};

class SmartLinuxFactory : public SmartWidgetFactory {
public:
    std::unique_ptr<Widget> CreateButton() {
        return  std::make_unique<LinuxBtn>();
    }

    std::unique_ptr<Widget> CreateMenu() {
        return std::make_unique<LinuxMenu>();
    }
};

class SmartClient
{
    std::unique_ptr<SmartWidgetFactory> factory;
public:
    SmartClient(std::unique_ptr<SmartWidgetFactory> oFactory)
    {
        factory = std::move(oFactory);
    }

    void draw() {
        std::unique_ptr<Widget> wd = factory->CreateButton();
        wd->draw();
        display1();
        display2();
    }
    void display1()
    {
        std::unique_ptr<Widget> w[] = {
            factory->CreateButton(),
            factory->CreateMenu()
        };
        w[0]->draw();
        w[1]->draw();
    }
    void display2()
    {
        std::unique_ptr<Widget> w[] = {
            factory->CreateMenu(),
            factory->CreateButton()
        };
        w[0]->draw();
        w[1]->draw();
    }
};

int _tmain(int argc, _TCHAR* argv[])
{

    /*WidgetFactory *factory;
    factory = new LinuxFactory;
    Client *c = new Client(factory);
    c->draw();*/

    std::unique_ptr< SmartWidgetFactory > oFactory = std::make_unique<SmartLinuxFactory>();
    std::unique_ptr<SmartClient> oClient = std::make_unique<SmartClient>( std::move(oFactory) );
    oClient->draw();

    return 0;
}


texts:
So I have a list of files which names are something like this

long_boring_filename_del_1.tex
long_boring_filename_del_2.tex
long_boring_filename_del_3.sty
long_boring_filename_del_4.tex

I want to cycle through these filenames using some mapping defined in vim. Meaning if I have long_boring_filename_del_2.tex open and hit the mapping it should take me to the next file long_boring_filename_del_3.sty. It should also loop, meaning long_boring_filename_del_4.tex should take me back to long_boring_filename_del_4.tex.

In addition I want to be able to cycle thorugh the files in both directions.

After obtaining a bit of help over at vi and vim I was able to come up with the following solution (which works).

function! s:next_del()

    " do nothing if current filename doesn't match "
    if @% !~# 'del-\v[1234]\.'
        return
    endif

    " open next file "
    let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)%4+1', '')
    if filereadable(fnameA)
        exec 'echo'
        exec 'e ' . fnameA
    else
        " if the .tex file does not exist check if the .sty versions does "
        let fnameB = substitute(fnameA, '\.tex', '\.sty', '')
        if filereadable(fnameB)
            exec 'e ' . fnameB
        else
            " if the above fails, check if changing sty to tex works "
            let fnameB = substitute(fnameA, '\.sty', '\.tex', '')
            if filereadable(fnameB)
                exec 'e ' . fnameB
            endif
        endif
    endif
endfunction

" Same as s:next_del() except this cycles in the opposite direction "
function! s:prev_del()

    " do nothing if current filename doesn't match "
    if @% !~# 'del-\v[1234]\.'
        return
    endif

    " open previous file "
    let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)-1', '')
    let fnameA = substitute(fnameA, '\v[0]\ze\.', '\=submatch(0)+4', '')
    if filereadable(fnameA)
        exec 'e ' . fnameA
    else
        " if the .tex file does not exist check if the .sty versions does "
        let fnameB = substitute(fnameA, '\.tex', '\.sty', '')
        if filereadable(fnameB)
            exec 'e ' . fnameB
        else
            " if the above fails, check if changing sty to tex works "
            let fnameB = substitute(fnameA, '\.sty', '\.tex', '')
            if filereadable(fnameB)
                exec 'e ' . fnameB
            endif
        endif
    endif
endfunction

nnoremap <silent> <localleader>w :call <sid>next_del()<CR>
nnoremap <silent> <localleader>q :call <sid>prev_del()<CR>

While it work I would love to get some pointers on how to improve the code as I am very much a beginner when it come to vimscript. Here are the major points in the code that needs improvement:

Can the two functions s:next_del() and s:prev_del() be combined into one?
My method of cycling backwards is very barbaric.

let fnameA = substitute(@%, '\v[1234]\ze\.', '\=submatch(0)-1', '')
let fnameA = substitute(fnameA, '\v[0]\ze\.', '\=submatch(0)+4', '')

I did it in this fashion because apparently you  can't separate the
leading \ and = , as otherwise it's a pure string. I would like to get some pointers on how to improve it.
Lastly my method of "checking" whether I have a sty file or tex file is strange at best. I do not really check, just change sty to tex and see if it works. I tried to get some regex going by using (tex|sty) but for some reason vimscript did not accept it. I would like to learn a better method of alternating between the sty and tex files.


texts:
This is the Cheapest Flights Within K Stops problem from leetcode.com:

  There are \$n\$ cities connected by \$m\$ flights. Each fight starts from city \$u\$ and arrives at \$v\$ with a price \$w\$.

  Now given all the cities and fights, together with starting city \$src\$ and the destination \$dst\$, your task is to find the cheapest price from \$src\$ to \$dst\$ with up to \$k\$ stops. If there is no such route, output \$-1\$.

I have a naive implementation that fails on efficiency. I had a feeling this would happen, but I took this approach to implement my first ever iterative deepening depth first search (IDDFS). Since it fails on runtime, I don't know if my code is 100% valid from an implementation standpoint

My algorithm:

Enumerate all paths of depth less than \$K + 1\$ using IDDFS, add to priority queue by path cost
If the queue isn't empty, a path exists that makes at most \$K\$ stops, extract min from priority queue.

Obviously step 1 grows exponentially and isn't at all efficient.

What I would like help reviewing is whether my iterative deepening depth first search is from an implementation standpoint correct.

def findCheapestPrice(self, n, flights, src, dst, K):
        """
        :type n: int
        :type flights: List[List[int]]
        :type src: int
        :type dst: int
        :type K: int, K + 1 = max search depth, K + 2 = amount of visited nodes
        :rtype: int
        """
        from collections import defaultdict
        import heapq
        adj = defaultdict(list) # u : (v, cost)

        for u,v,c in flights:
            adj[u].append((v,c))

        paths = [] # pqueue

        def enumerateAllPaths(u, goal, visited, path, pathcost, depthLimit):
            visited[u] = True
            path.append(u)

            if u == goal:
                heapq.heappush(paths, (pathcost, len(path), path))
            elif depthLimit == 0:
                path.pop()
                visited[u] = False
                return
            else:
                for v,c in adj[u]:
                    if not visited[v]:
                        enumerateAllPaths(v, goal, visited, path, pathcost + c, depthLimit - 1)
            path.pop()
            visited[u] = False

        visited = [False for s in range(len(n))]
        path = []

        enumerateAllPaths(src, dst, visited, path, 0, K + 1)

        # (length of path, pathcost, path)
        bestcost = 2**63 - 1 # best cost decreases if a better path is found

        if paths:
            pathcost, pathlen, path = heapq.heappop(paths)
            bestcost = pathcost

        if bestcost != 2**63 - 1:
            return bestcost
        else:
            return -1


texts: Improving the speed of creation for three Perlin Noise Maps in Python?

texts:
I am interested in learning how I can improve the speed of the code in this pygame file. I iterate over 6400 * 1800 * 3 or 34,560,000 elements of various numpy arrays here to apply noise values to them. The noise library I'm using can be found on GitHub here.

I am calling static variables from a class called ST here. ST.MAP_WIDTH = 6400 and ST.MAP_HEIGHT = 1800. All other ST attributes called here are assigned in the code. They are the noise-maps I'm making.

from __future__ import division
from singleton import ST
import numpy as np
import noise
import timeit
import random
import math

def __noise(noise_x, noise_y, octaves=1, persistence=0.5, lacunarity=2.0):
    """
    Generates and returns a noise value.

    :param noise_x: The noise value of x
    :param noise_y: The noise value of y
    :return: numpy.float32
    """

    value = noise.pnoise2(noise_x, noise_y,
                          octaves, persistence, lacunarity,
                          random.randint(1, 9999))

    return np.float32(value)

def __elevation_mapper(noise_x, noise_y):
    """
    Finds and returns the elevation noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    return __noise(noise_x, noise_y,  8, 0.9)

def __climate_mapper(y, noise_x, noise_y):
    """
    Finds and returns the climate noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    # find distance from bottom of map and normalize to range [0, 1]
    distance = math.sqrt((y - (ST.MAP_HEIGHT >> 1))**2) / ST.MAP_HEIGHT

    value = __noise(noise_x, noise_y,  8, 0.7)

    return (1 + value - distance) / 2

def __rainfall_mapper(noise_x, noise_y):
    """
    Finds and returns the rainfall noise for the given noise_x and
    noise_y parameters.

    :param noise_x: noise_x = x / ST.MAP_WIDTH - randomizer
    :param noise_y: noise_y = y / ST.MAP_HEIGHT - randomizer
    :return: float
    """
    return __noise(noise_x, noise_y,  4, 0.65, 2.5)

def create_map_arr():
    """
    This function creates the elevation, climate, and rainfall noise maps,
    normalizes them to the range [0, 1], and then assigns them to their
    appropriate attributes in the singleton ST.
    """

    start = timeit.default_timer()

    elevation_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
    climate_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)
    rainfall_arr = np.zeros([ST.MAP_HEIGHT, ST.MAP_WIDTH], np.float32)

    randomizer = random.uniform(0.0001, 0.9999)

    # assign noise map values
    for y in range(ST.MAP_HEIGHT):
        for x in range(ST.MAP_WIDTH):
            noise_x = x / ST.MAP_WIDTH - randomizer
            noise_y = y / ST.MAP_HEIGHT - randomizer

            elevation_arr[y][x] = __elevation_mapper(noise_x, noise_y)
            climate_arr[y][x] = __climate_mapper(y, noise_x, noise_y)
            rainfall_arr[y][x] = __rainfall_mapper(noise_x, noise_y)

    # normalize to range [0, 1] and assign to relevant ST attributes
    ST.ELEVATIONS = (elevation_arr - elevation_arr.min()) / \
                    (elevation_arr.max() - elevation_arr.min())

    ST.CLIMATES = (climate_arr - climate_arr.min()) / \
                  (climate_arr.max() - climate_arr.min())

    ST.RAINFALLS = (rainfall_arr - rainfall_arr.min()) / \
                   (rainfall_arr.max() - rainfall_arr.min())

    stop = timeit.default_timer()
    print("GENERATION TIME: " + str(stop - start))


texts: Trying to Store EditText Values in SharedPrefs using a Single addTextChangedListener

texts:
The code  is completely functional but I'd rather not call two functions when I know it can be done more efficiently. My goal is to store EditText values in SharedPrefs using a single addTextChangedListener.  Any advice is much appreciated!

fun preserveText() {

    val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

    field_1.setText(sharedPref.getString("autoSave", ""))
    field_1.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable) {
            sharedPref.edit().putString("autoSave", s.toString()).apply()

        }
    })
}

fun preserveText2() {

    val sharedPref: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)

    field_2.setText(sharedPref.getString("autoSave2", ""))
    field_2.addTextChangedListener(object : TextWatcher {
        override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

        }

        override fun afterTextChanged(s: Editable) {
            sharedPref.edit().putString("autoSave2", s.toString()).apply()

        }
    })
}


texts: Find the first reoccuring char from a String

texts:
Can anyone give me advice on how I can improve my answer?
I have tested it out using "ABCA", "BCABA" and "ABC".
Two things I would like help on.
1.How can I move this code into a method
where it returns the reoccurring char? I know how to return the char once it has been found but what about the case where there is not char what do I return back in that case? Since I cannot return char.
2. Is using the break statement bad practice? I noticed that the code would with "BCABA" both "B" and "A" are printed.

Thanks.

  public static void main(String[] args) {
    String testString = "BCABA";

    Map<Character, Integer> recurringCharsMap = new HashMap<>();
    for (char character : testString.toCharArray()) {
        if (recurringCharsMap.containsKey(character)) {
            System.out.println("Recurring char is: " + character);
            break;
        } else {
            recurringCharsMap.put(character, 1);
        }
    }
}


texts: Check for the presence of multiple files

texts:
Given the following code, I have written a for loop that returns a key and value (0 or 1) of file names passed. 1 means present, and 0 means not present.

Is there a way to construct a flat map without having to use into?

(defn kind-stat
  [filename expected-type]
  (let [f (File. filename)
        s (cond
              (.isFile f)      "f"
              (.isDirectory f) "d"
              (.exists f)      "o"
              :else            "n" )]

      (if (= expected-type s)
        0
        1)))

(defn look-for
  [filename expected-type]
    (let [find-status (kind-stat filename expected-type)]
      find-status))

(defn all-files-present?
"Takes a list of real file names, and returns a sequence of maps
 indicating the file name and its availability status 1 for present
 and 0 for not present. Please note look-for returns 0 for success,
 so its return logic needs to be reversed for the return sequence
 of maps."
  [file-seq]
  (for [fnam file-seq
    :let [stat-map {(keyword fnam)
       (if (= (look-for fnam "f") 0)
           1
           0)}]]
   stat-map))

(into {}
 (all-files-present? '("Makefile" "build.sh" "real-estate.csv")))

{:Makefile 1, :build.sh 1, :real-estate.csv 0}


texts:
Does exist a cleaner way to call a static method inside ES6 Array.filter function ?

mine(input = '') {
    var translatedAnswers = this.constructor.translate(this._defaultAnswers);
    var self = this;
    return translatedAnswers.filter(function (answer) {
        return self.constructor.match(input, answer);
    });
}


texts: Ruby-ize for loop - counting all the n-digit numbers that contain the digit 5 anywhere

texts:
I wrote this a while back when my fiance was taking a Number Theory class. I wrote about it here and it recently came back to my attention. Anytime I write a for loop in Ruby I feel kind of dirty. I would like to "Ruby-ize" this routine if there is a more Ruby way to do it. Also, is this the most efficient algorithm for this?

Original Problem:

  How many numbers less than 10000 that contain the digit 5 anywhere?

(Even thought the original problem was for < 10000, I've run this much farther out)

The algorithm:

  \$f(x) = 9y + \dfrac{x}{10}\$

  Where \$y\$ is the previous result and \$x\$ is the power of 10 we're checking against.

  i.e. \$y = 1\$ and \$x = 100\$, or \$y = 19\$ and \$x = 1000\$

or, for the more mathematically inclined

  \$f(10^n)=9f(10^{n-1})+10^{n-1}\$

The code:

def numbersContaining5(pwr)
# Prints on screen the count of numbers containing a "5"
#    for each power of ten up and including the one passed in.
# pwr = the power of ten you wish to calculate to

    prev = 0
    for i in 1..pwr
        prev = (prev*9) + (10**i)/10
        puts prev
    end
end

#call function
numbersContaining5(4) # 10^4 = 10000


texts: Decode Cæsar Cypher by Checking all Keyspaces

texts:
This function produces a decoded string, decoded, for all keyspaces against a given cæsar cipher ciphertext. Punctuation is not changed and string.upper() is used to make working with ord() easier.

I am looking for a more Pythonic way to work with my decoded variable. I keep finding myself assigning empty strings or None or 0 to use as a placeholder and I think it looks ugly. I'd also like to know if there is a better way to avoid writing c = ord(c).

def testCaesar(ciphertext):
    for testkey in range(0,25):
        decoded = ''   # <--- uglyness
        for c in ciphertext.upper():
            if not c.isalpha():
                decoded += c
                continue
            c = ord(c) # this is here to improve readability of line below. Is there a better way?
            decoded += chr(c + testkey if c + testkey < 90 else c - testkey)
        print('{0} : Rot{1} Caesar').format(decoded, str(testkey))
        checkMatch(decoded, testkey, 'Caesar')


texts:
Intro

During a CTF I encountered a dompdf LFI vulnerability, which is explained at exploitdb.

However when I executed that vulnerability it gave it to me in PDF form, and it was a pain to constantly (read, strip, and base64 decode)  to read the contents of files. So I made a little bash script to do these things automatically.

I am happy with the result, but I thought there maybe was a way to resolve those double sed into one Regex capture. It works because the [( ... )] is unique in the resulting string.

Code

#!/bin/bash
if [ -z "$1" ] || [ -z "$2" ]; then
    echo "Usage ./read_dompdf [url_to_dompdf] [path/to/file]"; exit
fi
URL="$1/dompdf.php?input_file=php://filter/convert.base64-encode/resource=$2"
echo `curl --silent $URL` | sed 's/.*\[(//' | sed 's/)\].*//' | base64 -d


texts:
I do not have an intention to ask for an answer, but I want to know if my answer is good for a two-week Python beginner?

Question: (Automate the Boring Stuff with Python/ page 102)

Comma Code

Say you have a list value like this:

spam = ['apples', 'bananas', 'tofu', 'cats']

  Write a function that takes a list value as an argument and returns a
  string with all the items separated by a comma and a space, with and
  inserted before the last item. For example, passing the previous spam
  list to the function would return:

    apples, bananas, tofu, and cats

  But your function should be able to work with any list value passed to
  it.

My Answer:

spam = ['apples', 'bananas', 'tofu', 'cats']
def sentence(i):
    for n in range(0, len(spam) - 1):
        print(spam[n], end=', ')
    print('and ' + spam[-1])
sentence(spam)


texts: Does this PDO process look protected from SQL injection?

texts:
Does this process look protected from SQL injection attacks?

Is there something I could possibly change to make it more protected?

<?php
  include("../include/database.php");

  if(isset($_POST['details']))
  {
    $values = $_POST['details'];

    $param1 = htmlspecialchars(trim($values['param1']));
    $param2 = htmlspecialchars(trim($values['param2']));

    $conditions = [];
    $parameters = [];

    if (!empty($param1))
    {
        $conditions[] = 'COLUMN1 LIKE ?';
        $parameters[] = $param1."%";
    }
    if (!empty($param2))
    {
        $conditions[] = 'COLUMN2 = ?';
        $parameters[] = $param2."%";
    }

    try {
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        $select = "SELECT COLUMN1, COLUMN2 FROM table";

        if ($conditions)
        {
            $select .= " WHERE ".implode(" AND ", $conditions);
        }

        $stmt = $conn->prepare($select);
        $stmt->execute($parameters);

        $out = array();

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $out[] = $row;
        }

        echo json_encode($out);
    }
    catch(PDOException $e)
    {
        echo "Error: " . $e->getMessage();
    }

    $conn = null;
  }
?>


texts: Tools for transferring data from an API to a database

texts:
I explain everything on my current code but this question is more general "HOW TO" work correctly with this in this case but even next time.

I have 4 methods in my class, each does something but in general this code just takes data from some API and insert it to another database in the right format:

// Getting data from API
public function getData()
{
    $url = manufacturerEndpoint;
    $data = array('token' => apiToken);

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',
            'content' => http_build_query($data),
        ),
    );
    $context  = stream_context_create($options);
    $result = file_get_contents($url, false, $context);

    return $result;
}

// Truncate oild data in new table
private function truncate() {
    try{
        $con = new PDO( DB_HOST, DB_USER, DB_PASS );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "truncate r_vehicle_manufacturer CASCADE";
        $stmt = $con->prepare( $sql );
        $stmt->execute();
        }catch(PDOExeption $e){
            echo $e->getMessage();
            echo $con->errorInfo();
        }
}

// Inset new data to database
public function insertToDb($code, $name)
{
    try {
        $con = new PDO( DB_HOST, DB_USER, DB_PASS );
        $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
        $sql = "INSERT INTO r_vehicle_manufacturer(code, name, country_code) VALUES(:code, :name, :country_code)";
        $stmt = $con->prepare( $sql );
        $stmt->bindValue( 'code', $code, PDO::PARAM_STR );
        $stmt->bindValue( 'name', $name, PDO::PARAM_STR );
        $stmt->bindValue( 'country_code', 'CZE', PDO::PARAM_STR );
        $stmt->execute();
        }
    catch( PDOException $e ) {
            echo $e->getMessage();
        }
}
// Last method which basicly just call others:
        public function workWithData()
    {
        // Truncate data from last month
        $this->truncate();
        $json = $this->getData();
        $json_output = json_decode($json);
        foreach ( $json_output as $data )
        {
            $this->insertToDb($data->AX_CODE, $data->NAME);
        }
    }

I'm not sure if this is correct way but until now it seems right for me. But now I just have to change $url (call this method with multiple URL base on user INPUT) sometimes but it's not easy to edit if I don't want to pass the same argument to 2 methods.

My question is how should I correctly design methods to avoid as many changes as I can while respecting the fact I will have to change something in feature?


texts: Properly storing error messages and displaying them with OOP

texts:
I have a class that I am using to initialize a form for editing. Once the form is submitted, data validation is done through the setters of my class. Good or bad input will be set in order to re-display them in the form (is this bad?). Everything works fine, but I am not too happy with how I am storing and displaying the error messages.

Any suggestions on how I can improve?

Course.class.php

<?php
class Course {
    protected $_code;
    protected $_name;
    protected $_errors = array();

    public function __constructor($id) {
        if (is_int($id)) {
            $this->_load($id);
        }
    }

    public function getCode() { return $this->_code; }

    public function setCode($value) {
        $this->_code = $value;
        if (empty($value)) {
            $this->setError('code', 'Enter a code.');
        } else if (strlen($value) > 10) {
            $this->setError('code', 'The code you provided must be less than 10 characters.');
        }
    }

    public function getName() { return $this->_name; }

    public function setName($value) {
        $this->_name = $value;
        if (empty($value)) {
            $this->setError('name', 'Enter a name.');
        } else if (strlen($value) > 50) {
            $this->setError('name', 'The name you provided must be less than 50 characters.');
        }
    }

    public function getError($name) {
        return isset($this->_errors[$name]) ? $this->_errors[$name] : '';
    }

    public function setError($name, $value) {
        $this->_errors[$name] = $value;
    }

    public function hasErrors() {
        return !empty($this->_errors);
    }

    public function _load($id) {
        // load record from database
    }

    public function save() {
        if (!this->hasErrors()) {
            // save record to database
        }
    }
}
?>

I have looked around and many have suggest to use exceptions. However, I don't quite get how I can use them because wouldn't throwing an exception in one setter cause the subsequent setters from not being called.

OOP Design Question - Validating properties
Validate on entry or before saving?

Here is how I am currently using my class:

edit_course.php

<?php
$filter = array(
    'hidSubmit' => FILTER_VALIDATE_BOOLEAN,
    'code' => FILTER_SANITIZE_STRING,
    'name' => FILTER_SANITIZE_STRING
);

$c = filter_input(INPUT_GET, 'c', FILTER_VALIDATE_INT);
$course = new Course($c);

$inputs = filter_input_array(INPUT_POST, $filter);
if ($inputs['hidSubmit']) {
    $course->setName($inputs['name']);
    $course->setDescription($inputs['description']);
    $course->save();
    refreshPage();
}

require_once 'header_admin.php';
?>

<form id="editForm" name="editForm" action="" method="post">
<fieldset>
<legend>Edit Course</legend>
    Code
    <input type="text" name="code" value="<?php echo $course->getCode(); ?>" maxlength="10" size="8" />
    <?php echo $course->getError('code'); ?>
    Name
    <input type="text" name="name" value="<?php echo $course->getName(); ?>" maxlength="45" size="25" />
    <?php echo $course->getError('name'); ?>
    <input type="submit" value="Save" />
    <input type="hidden" name="hidSubmit" value="1" />
</fieldset>
</form>

<?php
require_once 'footer_admin.php';
?>


texts: Is this a good way of handling item reservations?

texts:
I have a site were we sell unique items. When a user clicks to buy an item we have to reserve it. This prevents other buyers from purchasing the item while the first buyer is checking out.

When a buyer clicks the "Buy" button, he is redirected to the orders controller. The orders controller executes the following steps:

Verify item is available (not reserved, or sold).

If available, the item is marked as reserved, and its id is stored in the session.
If no, check if it is reserved, and if the current session has the item id (meaning the current user has made the reservation). If both conditions are true the buyer can complete his purchase. Otherwise, the buyer notified and presented with alternatives.

If buyer navigates away from the orders controller, the item is released back to the catalogue.

Are there any obvious pitfalls in my approach?

I have reservations about using the session to indicate the current user has reserved an item. Users don't have to register to check out.

I also feel like I'm repeating myself with @item.reserve!, the reserve! in item_reserver.rb.

Thoughts? Feedback?

application_controller.rb

include ItemReservation
before_action :release_item

items_controller.rb

# ensures item is available
before_action :verify_item_is_available, only: :show

orders_controller.rb

# ensures item is available
before_action :verify_item_is_available, only: [:new, :create]

def new
  reserve! @item
  @order = Order.new
end

controllers/concerns/item_reserver.rb

# before filter
def verify_item_is_available
  unless @item.available?
    redirect_to similar_item_path(@item) unless @item.reserved? && session[:reserved_item_id] == @item.id
  end
end

# before filter
def release_item
  if session[:reserved_item_id].present? && controller_name != 'orders'
    release! session[:reserved_item_id]
  end
end

def reserve!(item)
  if item.available?
    session[:reserved_item_id] = item.id if item.reserve!
  end
end

def release!(item_id)
  item = Item.find(item_id)
  if item.reserved?
    session[:reserved_item_id] = nil if item.release!
  end
end

item.rb

  def reserve!
    update!(availability: 'reserved')
  end

  def release!
    update!(availability: 'available')
  end

  def purchase!
    update!(availability: 'sold')
  end


texts:
So I've got an assignment which sounds like this:

  Given a number n, calculate the result of this sum, modulo 10,234,573:
  12 + 22 + 32 + … + n2

This is what I've come up with :

 #include <iostream>
 using namespace std;

 int main()
 {
     uint n;
     cin >> n;

     uint num{10234573};
     uint64_t sum{0};
     for (uint i = 1; i <= n; ++i) {
         sum += (i*i)%num;
         sum %= num;
     }

     cout << sum;

     return 0;
 }

And I can check my algorithm on a website, but it tells me that it is "too slow"... How can I optimise it so it will be faster?
I know there is a formula for this, but the given number n can be as big as 2,000,000,000, so it will obviously overflow...


texts: SDL Initialization and Management wrappers

texts:
I am using SDL2 for window management and rendering, but it can be a little verbose. And because of how SDL2 works under the hood, the SDL_Renderer is tied to image resource loading.

So, I am setting out to write a wrapper around the SDL initialization and window/renderer management.

The core of it is called SDLContext, which is responsible for initializing SDL, as well as being where the SDL_Window and SDL_Renderer will reside.

It is initialized with a helper struct, SDLOpts, which just holds any initialization values.

SDLOpts

struct SDLOpts {
  int flags = SDL_INIT_EVERYTHING;

  struct SDLWindowOpts {
    int flags = 0;
    int w = 600;
    int h = 480;
  } window_opts;

  struct SDLRendererOpts {
    int flags = 0;
  } renderer_opts;
};

SDLContext.h

struct SDL_Window;
struct SDL_Renderer;
class SDLContext {
public:
  explicit SDLContext(SDLOpts const& options) noexcept;
  ~SDLContext() noexcept;

  SDLWindow sdlWindow() const noexcept;
  SDLRenderer sdlRenderer() const noexcept;

private:
  SDLOpts options_ {};
  SDL_Window* sdlwindow_ {nullptr};
  SDL_Renderer* sdlrenderer_ {nullptr};

};

SDLContext.cpp

struct SDL_Window;
struct SDL_Renderer;
class SDLContext {
public:
  explicit SDLContext(SDLOpts const& options) noexcept;
  ~SDLContext() noexcept;

  SDLWindow sdlWindow() const noexcept;
  SDLRenderer sdlRenderer() const noexcept;

private:
  SDLOpts options_ {};
  SDL_Window* sdlwindow_ {nullptr};
  SDL_Renderer* sdlrenderer_ {nullptr};

};

One thing I am on the fence about is throwing in the constructor marked noexcept.
I don't want program execution to continue if I can't initialize SDL/create a window/create a renderer, and I also want to avoid using an Init function (trying to make it fit into RAII). But, I don't see any other alternatives.

SDLWindow and SDLRenderer are pretty bare-boned right now.
They just exist as a wrapper around all of the SDL_* functions that relate to SDL_Window or SDL_Renderer.

One decision I did make was to make their default constructor private, and mark SDLContext as a friend class. This way, the only way to create an SDLWindow or SDLRenderer is from within the SDLContext class. They should not be created outside of it, because there should only be one window and one renderer.

SDLRenderer.h

struct SDL_Renderer;
class SDLRenderer {
  friend class SDLContext;
public:
  ~SDLRenderer() = default;

  //...
  //Functions that draw or change the rendering properties (IE, color)
  //...
private:
  explicit SDLRenderer(SDL_Renderer* renderer) noexcept;

  std::experimental::observer_ptr<SDL_Renderer> sdlrenderer_ {nullptr};
};

SDLWindow.h

struct SDL_Window;
class SDLWindow {
  friend class SDLContext;
public:
  ~SDLWindow() noexcept = default;

  //...
  //Functions that modify the windows width and height
  //...
private:
  explicit SDLWindow(SDL_Window* window) noexcept;

  std::experimental::observer_ptr<SDL_Window> sdlwindow_ {nullptr};
};

Any suggestions to what I've done so far? Any alternatives to stopping program execution outside of throw in a noexcept / using an Init function? Is it sane to mark SDLContext as a friend class to SDLRenderer and SDLWindow in order to prevent them from being created wherever?