texts:
I'm learning Data structures and came across this problem - merging two sorted linked list. I have gone through the recursive solution, and it seems pretty straight forward. I wanted to try an iterative solution and came up with this.

private static Node mergeListsIterative(Node headA, Node headB) {

        if (headA == null) {
            return headB;
        }

        if (headB == null) {
            return headA;
        }

        Node head;

        if (headA.data < headB.data) {
            head = headA;
            headA = headA.next;
        } else {
            head = headB;
            headB = headB.next;
        }

        Node temp = head;
        while (headA != null && headB != null) {
            if (headA.data < headB.data) {
                temp.next = headA;
                headA = headA.next;
            } else {
                temp.next = headB;
                headB = headB.next;
            }
            temp = temp.next;
        }

        if (headA == null) {
            temp.next = headB;
        } else {
            temp.next = headA;
        }

        return head;
    }

I saw this post on SO which uses an iterative approach. I feel that my code is simpler. Please review my code and tell me if it can be simplified.


texts: Finding the number of pairs in an integer Array

texts:
This function returns the number of pairs of the same elements in the array

It takes, array length and the array as the parameter

    n: Length of array

    ar: Array of integers for example

    4 6 7 8 7 6 6 7 6 4

  returns 4

fun getNumberOfPairs(n: Int, ar: Array<Int>): Int {
    val enteries = HashSet<Int>()
    var pairs = 0

    for (i in 0 until n) {
        if (!enteries.contains(ar[i])) {
            enteries.add(ar[i])
        } else {
            pairs++
            enteries.remove(ar[i])
        }
    }

    println(pairs)
    return pairs
}

How can we write this code in a better way for readability/performance?


texts:
I wrote the following snipet code within Cumulocity platform.

  runForTenant

must be in a separate thread. What is your an opinion about my code. is there any need for optimization? Thanks

LinkedList<CompletableFuture<Void>> asyncThreads = new LinkedList<CompletableFuture<Void>>();
        CompletableFuture<Iterable<ManagedObjectRepresentation>> response = new CompletableFuture<>();

        subscriptions.runForEachTenant(() -> {
            String tenant = subscriptions.getTenant();
            asyncThreads.add(CompletableFuture.runAsync(() -> {
                subscriptions.runForTenant(tenant, () -> {
                    Iterable<ManagedObjectRepresentation> objects = inventoryApi
                            .getManagedObjectsByFilter(customInventoryFilter).get().allPages();
                    if (!ObjectUtils.isEmpty(objects)) {
                        response.complete(objects);
                    }

                });
            })); // end of runAsync()
        });

        boolean allThreadsAreDone = true;
        do { // until all threads are done ...
            try {
                return response.get(50, TimeUnit.MILLISECONDS); // wait for first result
            } catch (TimeoutException e) {
                // device with UUID Not found in time

                // check all threads are done/closed/stopped in all fashions
                allThreadsAreDone = true;
                for (int i = 0; allThreadsAreDone && i < asyncThreads.size(); i++) {
                    allThreadsAreDone = asyncThreads.get(i).isDone();
                }
            } catch (ExecutionException execExc) {
                logger.error("Error on lookup: " + execExc.getLocalizedMessage());
            } catch (InterruptedException interExc) {
                logger.error("Error on lookup: " + interExc.getLocalizedMessage());
            }

        } while (!allThreadsAreDone);

I want to optimize the last path of the code:

boolean allThreadsAreDone = true;
    do { // until all threads are done ...
        try {
            return response.get(50, TimeUnit.MILLISECONDS); // wait for first result
        } catch (TimeoutException e) {
            // device with UUID Not found in time

            // check all threads are done/closed/stopped in all fashions
            allThreadsAreDone = true;
            for (int i = 0; allThreadsAreDone && i < asyncThreads.size(); i++) {
                allThreadsAreDone = asyncThreads.get(i).isDone();
            }
        } catch (ExecutionException execExc) {
            logger.error("Error on lookup: " + execExc.getLocalizedMessage());
        } catch (InterruptedException interExc) {
            logger.error("Error on lookup: " + interExc.getLocalizedMessage());
        }

    } while (!allThreadsAreDone);


texts: Is this use of macros to trace program flow portable and free of major pitfalls?

texts:
The program below defines macros START and END that expand to the left and right curly bracket
symbols plus some example tracing code. Is this a portable use of a macro and are there any obvious major problems with this? It compiles fine under gcc --pedantic
#include <stdio.h>

#define TRACE

#ifdef TRACE

#define START       {TRACE_START
#define END         TRACE_END}
#define TRACE_START     printf("ENTERING %s\n", __func__);
#define TRACE_END       printf("LEAVING %s\n", __func__);

#else

#define START   {
#define END }

#endif

int func()
START
    printf ("Hello World %s\n");
END

int main()
START
    func();
END

which produces the output
ENTERING main
ENTERING func
Hello World

LEAVING func
LEAVING main


texts:
My Google Maps Script v1

Using the Google Maps JavaScript API v3.

Does my script have any room for improvement (naming, readability, oop, etc.)?

I'm going to pair it with some live time functionality, so that whenever the map its location changes the time would be updated accordingly.

I've added this script to my HTML code right after the last DOM node it needs to work.

google-maps.js

(function (window, document) {
    'use strict';

    var MAP_DEFAULT_ADDRESS = 'Paris, France',
        MAP_CANVAS_ID = 'map-canvas',
        ADDRESS_INPUT_ID = 'address-input',
        SEARCH_BUTTON_ID = 'search-button';

    var googleMap,
        currentLocation,
        googleGeocoder = new google.maps.Geocoder(),
        addressInput = document.getElementById(ADDRESS_INPUT_ID),
        markers = [];

    googleGeocoder.geocode({ 'address': MAP_DEFAULT_ADDRESS }, function (results, status) {
        if (status !== google.maps.GeocoderStatus.OK) {
            throw new Error('Geocode was unsuccessful: ' + status);
        }

        googleMap = new google.maps.Map(document.getElementById(MAP_CANVAS_ID), {
            // required
            center: results[0].geometry.location,
            zoom: 10,
            // disable direct GUI interaction
            disableDefaultUI: true,
            navigationControl: false,
            mapTypeControl: false,
            scaleControl: false,
            scrollwheel: false,
            draggable: false,
            zoomControl: false,
            disableDoubleClickZoom: true,
            suppressInfoWindows: true
        });

        currentLocation = results[0].geometry.location;

        addressInput.value = results[0].formatted_address;

        addMarker(results[0].geometry.location);
    });

    // center map responsively
    window.addEventListener('resize', function () {
        var center = googleMap.getCenter();

        google.maps.event.trigger(googleMap, 'resize');

        googleMap.setCenter(center);
    });

    addressInput.onkeydown = function (e) {
        if (e.keyCode === 13) {
            addressInput.blur();

            processAddressInput();
        }
    };

    document.getElementById(SEARCH_BUTTON_ID).onclick = function () {
        processAddressInput();
    }

    function addMarker(location) {
        var marker = new google.maps.Marker({
            map: googleMap,
            position: location
        });

        marker.setAnimation(google.maps.Animation.DROP);

        markers.push(marker);

        google.maps.event.addListener(marker, 'click', function () {
            if (marker.getAnimation() !== null) {
                marker.setAnimation(null);
            } else {
                marker.setAnimation(google.maps.Animation.BOUNCE);
            }
        });
    }

    function deleteAllMarkers() {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
    }

    function processAddressInput() {
        googleGeocoder.geocode({ 'address': addressInput.value }, function (results, status) {
            if (status !== google.maps.GeocoderStatus.OK) {
                if (status === google.maps.GeocoderStatus.ZERO_RESULTS) {
                    return;
                }

                throw new Error('Geocode was unsuccessful: ' + status);
            }

            if (results[0].geometry.location.equals(currentLocation)) {
                addressInput.value = results[0].formatted_address;

                return;
            }

            deleteAllMarkers();

            googleMap.fitBounds(results[0].geometry.viewport);
            googleMap.setCenter(results[0].geometry.location);

            currentLocation = results[0].geometry.location;

            addressInput.value = results[0].formatted_address;

            addMarker(results[0].geometry.location);
        });
    }
}(window, document));


texts:
I am learning dynamic programming. I read articles for the rod cutting problem and I applied it in cpp, and I got a doubt, does the below code solves the problem through memoization (say, previously rod(3) was solved, then if same function was called with same parameters) has the answer, or will it use tabulation (rodMax array), or uses both?

Since I read two different articles explaining different methods(memoization and tabulation, and read as two different methods to solve a dynamic problem), kind of confused on which method the below code runs.

#include <iostream>

using namespace std;

int max(int a, int b){

    if(a > b)
        return a;

    return b;
}

int arr[5] = {2, 4, 1, 2, 7};

int rodMax[5] = {-1, -1, -1, -1, -1};

int rod(int n){

    if(n <=0)
        return 0;

    if(rodMax[n - 1] != -1){
        return rodMax[n];
    }

    int max_val = -1;
    for(int i = 0; i < n; i++){

        max_val = max(max_val, arr[n-i-1]+rod(n-1));
    }
    //cout<<"\nmax "<<max_val<<endl;
    rodMax[n - 1] = max_val;

    return max_val;
}

int main() {

    cout<<"ans "<<rod(5)<<endl;
    //cout<<"ans "<<rod(3)<<endl;
    //for(int i = 0; i <5; i++)
    //  cout<<rodMax[i]<<" ";
}
```


texts:
I wrote this JS code with some jQuery and got a one-click-text-selection. Maybe someone can improve this code, because I think it's not "clean" and short engough ;) But I don't want to use an input field. Let me know if you have some ideas!

function SelectText(element) {
    var doc = document,
        text = doc.getElementById(element),
        range,
        selection;
    if (doc.body.createTextRange) {
        range = document.body.createTextRange();
        range.moveToElementText(text);
        range.select();
    } else if (window.getSelection) {
        selection = window.getSelection();
        range = document.createRange();
        range.selectNodeContents(text);
        selection.removeAllRanges();
        selection.addRange(range);
    }
}
$(function() {
    $('p').click(function () {
        SelectText('autoselect');
    });
});

And this is the HTML part:

Some cool text!

Here's the code in a fiddle.


texts: Function to test for different conditions in input data

texts:
I have the following function that checks a data record to see if it has met certain criteria specified separately in configuration settings. The configurations are set up as a list of dictionaries with certain trigger keywords that are used by the condition check function ('in','not in', etc).

The condition checker has a lot of duplicated code, but it's just different enough that a better setup is not obvious to me. I would appreciate any feedback.

Here is a minimal working example to illustrate:

def check_if_condition_was_met( row, condition ):
    condition_met = True
    for key, val in condition.iteritems():
        if key == 'in':
            for condition_key, condition_val in val.iteritems():
                if row[condition_key] in condition_val:  # IN
                    continue
                else:
                    condition_met = False
                    break
        elif key == 'not in':
            for condition_key, condition_val in val.iteritems():
                if row[condition_key] not in condition_val:  # NOT IN
                    continue
                else:
                    condition_met = False
                    break
        elif key == 'max':
            for condition_key, condition_val in val.iteritems():
                if not row[condition_key]:
                    condition_met = False
                    break
                if int(row[condition_key]) <= int(condition_val): # MAX (<=)
                    continue
                else:
                    condition_met = False
                    break
        elif key == 'min':
            for condition_key, condition_val in val.iteritems():
                if int(row[condition_key]) >= int(condition_val): # MIN (>=)
                    continue
                else:
                    condition_met = False
                    break
    return condition_met

if __name__ == '__main__':
    # data
    test_data = [
         {'Flag1':'Y', 'Flag2':'Canada','Number':35}
        ,{'Flag1':'Y', 'Flag2':'United States','Number':35}
        ,{'Flag1':'N', 'Flag2':'United States','Number':35}
        ,{'Flag1':'N', 'Flag2':'England','Number':35}
        ,{'Flag1':'N', 'Flag2':'Canada','Number':35}
        ,{'Flag1':'N', 'Flag2':'Canada','Number':5}
    ]

    # configuration
    test_conditions = [
         { 'in':{'Flag1':['N'], 'Flag2':['United States']} }
        ,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'max':{'Number':7} }
        ,{ 'in':{'Flag1':['Y'],'Flag2':['Canada']}, 'min':{'Number':7} }
        ,{ 'not in':{'Flag1':['Y']}, 'min':{'Number':7} }
    ]

    for condition_id, condition in enumerate(test_conditions):
        print
        print 'now testing for condition %i' % condition_id
        for data_id, data in enumerate(test_data):
            print '%s | %s' % ( data_id, check_if_condition_was_met(data,condition) )


texts: Very basic "sleep calculator" algorithm in C using cs50 library

texts:
I've been following along with CS50 online and tried my first shot at making a program from scratch and without guidelines. I hope you may be able to rip it to shreds for me.

//
// this program determines how many hours you slept last night.
// it assumes that:
// you're using a 12 hour clock
// you sleep for a maximum of 24 hours
//

#include <stdio.h>
#include <cs50.h>

int main(void)
{   // get user bedtime
    printf("When did you go to bed last night?\n");
    int bedtime = GetInt();
    // determine AM or PM
    printf("AM [1]\nor\nPM [2]\n");
    int b = GetInt();
    // get user wake up time
    printf("When did you wake up this morning?\n");
    int wakeup = GetInt();
    // determine AM or PM
    printf("AM [1]\nor\nPM [2]\n");
    int w = GetInt();
    // interpret inputs and determine how to calculate hours slept
    {if ((b == 1) && (w == 1))
    {
        int slept = wakeup-bedtime;
        printf("You slept for %i hours last night\n",slept);

    }
    else if (((b == 1) && (w == 2)) || ((b == 2) && (w == 1)))
    {
        int slept = 12-bedtime+wakeup;
        printf("You slept for %i hours last night\n",slept);

    }
    else
    {
        int slept = (12-bedtime)+12+wakeup;
        printf("You slept for %i hours last night\n",slept);
    }
    }
}


texts: Mouseover effects for five buttons which may be enabled or disabled

texts:
function prepareEventHandlers() {
    var sectionButton1 = document.getElementById("sectionButton1");
    var sectionButton2 = document.getElementById("sectionButton2");
    var sectionButton3 = document.getElementById("sectionButton3");
    var sectionButton4 = document.getElementById("sectionButton4");
    var sectionButton5 = document.getElementById("sectionButton5");

    var enabled1 = true;
    var enabled2 = false;
    var enabled3 = false;
    var enabled4 = false;
    var enabled5 = false;

    function checkEnabled() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonEnabled");
        }
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonEnabled");
        }

    }

    checkEnabled();
    sectionButton1.onmouseover = function() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton1.onmouseout = function() {
        if (enabled1) {
            sectionButton1.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton2.onmouseover = function() {
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton2.onmouseout = function() {
        if (enabled2) {
            sectionButton2.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton3.onmouseover = function() {
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton3.onmouseout = function() {
        if (enabled3) {
            sectionButton3.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton4.onmouseover = function() {
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton4.onmouseout = function() {
        if (enabled4) {
            sectionButton4.setAttribute("class", "sectionButtonEnabled");
        }
    };
    sectionButton5.onmouseover = function() {
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonOver");
        }
    };
    sectionButton5.onmouseout = function() {
        if (enabled5) {
            sectionButton5.setAttribute("class", "sectionButtonEnabled");
        }
    };
}

window.onload = function() {
    prepareEventHandlers();
};


texts: Catching exceptions arised by different senarios and handle them differently

texts:
I am learning exception handling in java. Every time I am writing a function, I wonder if I should put the entire function code in a try catch block.

What the function does:

In the below function, i am checking for file upload failures that could be caused by multiple issues.e.g. file too big, not a supported format and so on.

In the function, i add try/catch just to a small part because it sometime throws some network exceptions e.g. connection timeout, socket timeout, network unreachable and so on.

What improvements i am looking for:

I want the network exceptions to be handled by the already present try catch and add a new try/catch that should take care of exceptions that may arise from other parts of function.

public void checkFile(FacesContext ctx, UIComponent comp, Object value) throws IOException {
        file = (Part) value;
        if (file != null) {
            String originalFileName = FileUtil.getFileName(file);
            String fileContentType = file.getContentType();

            if (file.getSize() > MAX_UPLOAD_SIZE) {
                msgs.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, "File too big.", "The given file was too big." +
                        " Maximum size allowed is: " + MAX_UPLOAD_SIZE / 1024 / 1024 + " MB"));
                throw new ValidatorException(msgs);
            }

            if (fileContentType.matches("application/x-msdownload|application/x-ms-installer|application/x-elf|application/x-sh|text/x-perl|text/x-python")) {
                msgs.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Not a permissible file type", "The uploaded file is " +
                        "an executable file."));
                throw new ValidatorException(msgs);
            }
            try {
                if (FileUtil.checkVirusClamAV(ProjectConfig.get().getFileUploader(), file.getInputStream())) {
                    msgs.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, "File possibly infected",
                            "The uploaded file triggered a virus warning and therefore has been rejected."));
                    throw new ValidatorException(msgs);
                }
            } catch(Exception e) {
                msgs.add(new FacesMessage(FacesMessage.SEVERITY_ERROR, "File possibly infected",
                        "The uploaded file triggered a virus warning and therefore has been rejected."));

                generateAntiVirusExceptionMessages(e.getMessage());
                throw new ValidatorException(msgs);
            }

            if ((originalFileName != null) && (!FilenameUtils.getExtension(originalFileName).equals("xml"))) {
                //Generate validation message for non-xml files
                generateValidationMessages(validationMessageType.nonXmlSuccess);
            }

            if (originalFileName != null && FilenameUtils.getExtension(originalFileName).equals("xml")) {
                //Do validation only for xml files
                validateXmlFiles();
            }
        }
    }


texts:
I'm using this Game Messenger as an instant messaging tool in my game. Just wondering peoples on thoughts on it.
Thank you!
    enum class eGameMessageType
{
    AddItemGUI = 0,
    RemoveItemGUI,
    UpdateSelectionBoxGUI,
    UpdateItemQuantityGUI,
    DestroyCubeSetPosition,
    DestroyCubeReset,
    SelectedCubeSetPosition,
    SelectedCubeSetActive,
    SpawnPickup,
    PlayerDisgardPickup,
    AddToPlayerInventory,
    Max = AddToPlayerInventory
};

struct Listener : private NonCopyable
{
    Listener(const std::function<void(const void*)>& fp, const void* ownerAddress)
        : m_listener(fp),
        m_ownerAddress(ownerAddress)
    {
        assert(ownerAddress);
    }
    Listener(Listener&& rhs) noexcept
        : m_listener(rhs.m_listener),
        m_ownerAddress(rhs.m_ownerAddress)
    {
        rhs.m_listener = nullptr;
        rhs.m_ownerAddress = nullptr;
    }
    Listener& operator=(Listener&& rhs) noexcept
    {
        m_listener = rhs.m_listener;
        m_ownerAddress = rhs.m_ownerAddress;

        rhs.m_listener = nullptr;
        rhs.m_ownerAddress = nullptr;

        return *this;
    }

    std::function<void(const void*)> m_listener;
    const void* m_ownerAddress;
};

class GameMessenger : private NonCopyable, private NonMovable
{
public:
    static GameMessenger& getInstance()
    {
        static GameMessenger instance;
        return instance;
    }

    template <typename GameMessage>
    void subscribe(const std::function<void(const GameMessage&)>& gameMessage, const void* ownerAddress)
    {
        auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
        assert(!isOwnerAlreadyRegistered(listeners, GameMessage::getType(), ownerAddress));

        listeners.emplace_back(reinterpret_cast<std::function<void(const void*)> const&>(gameMessage), ownerAddress);
    }

    template <typename GameMessage>
    void unsubscribe(const void* ownerAddress)
    {
        auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
        assert(isOwnerAlreadyRegistered(listeners, GameMessage::getType(), ownerAddress));

        auto iter = std::find_if(listeners.begin(), listeners.end(), [ownerAddress](const auto& listener)
        {
            return listener.m_ownerAddress == ownerAddress;
        });

        assert(iter != listeners.end());
        listeners.erase(iter);
    }

    template <typename GameMessage>
    void broadcast(GameMessage gameMessage)
    {
        const auto& listeners = m_listeners[static_cast<int>(GameMessage::getType())];
        for (const auto& listener : listeners)
        {
            reinterpret_cast<std::function<void(const GameMessage&)> const&>(listener.m_listener)(gameMessage);
        }
    }

private:
    GameMessenger() {}
    std::array<std::vector<Listener>, static_cast<size_t>(eGameMessageType::Max) + 1> m_listeners;

    bool isOwnerAlreadyRegistered(const std::vector<Listener>& listeners, eGameMessageType gameMessageType, const void* ownerAddress) const
    {
        assert(ownerAddress != nullptr);

        if (!listeners.empty())
        {
            auto result = std::find_if(listeners.cbegin(), listeners.cend(), [ownerAddress](const auto& listener)
            {
                return listener.m_ownerAddress == ownerAddress;
            });

            return result != listeners.cend();
        }
        else
        {
            return false;
        }
    }
};


texts:
I have a method that generates some HTML, but it looks ugly to me. Maybe there are some better solutions for this?

 public static string GetReview(Quiz quiz)
    {
        StringBuilder sb = new StringBuilder();

        string questionSection = string.Format(
            "
" +
                "{0}" +
            "
", quiz.Question.GetText());

        string correctAnswer = quiz.Answer.GetText();
        string userAnswer = quiz.UserAnswer?.GetText() ?? string.Empty;

        string answerSection;
        if (correctAnswer == userAnswer) {
            answerSection = string.Format(
                "
" +
                    "Your correct answer:" +
                 "
" +
                 "
" +
                    "{0}" +
                 "
", correctAnswer);
        } else {
            answerSection = string.Format(
                @"
" +
                    "The correct answer was:" +
                 "
" +
                 "
" +
                    "{0}" +
                 "
" +
                 "
" +
                 "You had selected: " +
                 "{1}", correctAnswer, userAnswer);
        }

        string explanationSection = ForQuiz(quiz);

        sb.AppendFormat("
{0}

{1}

{2}
", questionSection, answerSection, explanationSection);

        return sb.ToString();
    }


texts: Bookmarklet for selecting code snippets on StackExchange in 2021

texts:
The following code will add to each code block on https://codereview.stackexchange.com/ or https://stackoverflow.com/ a 'Select Code' button that will select the code belonging to that block.
This was originally written in 2013, I adjusted it to the new CSS and exchanged var with let, otherwise I think it looks fine. However JS has changed a lot, so I am submitting it again.
The original code was reviewed here 7 years ago.
In order to use this, visit http://codereviewcommunity.github.io/CodeReviewBookmarklet/
javascript: $('pre.s-code-block').not('button + *').each(function createButton() {
    /* Thank you http://stackoverflow.com/a/2838358/7602 */
    function selectCode(el, win) {
        win = win || window;
        let doc = win.document,
            sel, range;
        if (win.getSelection && doc.createRange) {
            sel = win.getSelection();
            range = doc.createRange();
            range.selectNodeContents(el);
            sel.removeAllRanges();
            sel.addRange(range);
        } else if (doc.body.createTextRange) {
            range = doc.body.createTextRange();
            range.moveToElementText(el);
            range.select();
        }
    }
    let buttonText = 'Select Code',
        length = buttonText.length,
        codeBlock = this,
        $link = $('<button type=\'button\'>' + buttonText + '</button>').click(function buttonListener() {
            console.log($(codeBlock).text().substring(length));
            selectCode(codeBlock);
        });
    $(codeBlock).before($link);
});
/* Cross browser bookmarklet sorcery */
void(0);


texts: Generic LinkedList with add/exists/delete/dlear/iteration functionality

texts:
I've just been going through core data structures and algorithms recently, wanting to get back in touch with the core fundamentals. I'm starting simple with a LinkedList implementation in C#. The functionality works and was able to test it. I'm just wondering if yo see anything with the code that could be improved.

using System.Collections;
using System.Collections.Generic;

namespace DataStructuresAndAlgorithms.DataStructures.LinkedList
{
    public class SinglyLinkedList<T> : IEnumerable<T>
    {
        public SinglyLinkedListNode<T> Head { get; set; }
        public SinglyLinkedListNode<T> Tail { get; set; }

        public void AddToEnd(T value)
        {
            var newNode = new SinglyLinkedListNode<T>
            {
                Value = value,
                Next = null
            };
            if (Head == null && Tail == null)
            {
                Head = newNode;
                Tail = newNode;
            }
            if (Head == Tail)
            {
                Head.Next = newNode;
                Tail = newNode;
            }
            else
            {
                var existingLast = Tail;
                existingLast.Next = newNode;
                Tail = newNode;
            }
        }

        public void AddToBeginning(T value)
        {
            var newNode = new SinglyLinkedListNode<T>
            {
                Value = value,
                Next = null
            };
            if (Head == null && Tail == null)
            {
                Head = newNode;
                Tail = newNode;
            }
            else
            {
                var existingHead = Head;
                Head = newNode;
                Head.Next = existingHead;
            }
        }

        public bool Exists(T value)
        {
            var head = Head;
            while(head != null)
            {
                if (head.Value.Equals(value))
                {
                    return true;
                }
                head = head.Next;
            }
            return false;
        }

        public void Delete(T value)
        {
            var head = Head;
            SinglyLinkedListNode<T> previous = null;
            while(head != null)
            {
                if (head.Value.Equals(value))
                {
                    if (previous == null)
                    {
                        Head = Head.Next;
                    }
                    else
                    {
                        previous.Next = head.Next;
                    }
                }
                previous = head;
                head = head.Next;
            }
        }

        public void Clear()
        {
            Head = null;
            Tail = null;
        }

        public IEnumerator<T> GetEnumerator()
        {
            var head = Head;
            while(head != null)
            {
                yield return head.Value;
                head = head.Next;
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }

    public class SinglyLinkedListNode<T>
    {
        public T Value { get; set; }
        public SinglyLinkedListNode<T> Next { get; set; }
    }
}


texts: Java method to add daily interest to bank account after month is over

texts:
For an assignment, I am told to write two methods: incrementDay() and incrementMonth():

  incrementDay()

  This method takes no input and returns nothing. If the previous
  month's balance was not paid in full, the credit card charges interest
  on the current balance after each day. To do this, the class will need
  two additional fields, a variable that keeps track of the interest
  charged so far and a boolean variable that is a paid-in-full flag that
  keeps track of whether the user has paid the balance in full.

  incrementDay works as follows: If the paid-in-full flag is false then
  sum the account balance and the interest charged so far, then multiply
  this sum by the interest rate divided by 365, and add this value to
  the interest charged so far.

  If the paid-in-full flag is true, then there is nothing to do.

  incrementMonth()

  This method takes no input and returns nothing. Add the interest
  charged so far to the account balance. Reset the interest charged so
  far to 0.

  If the total payment this month is greater than or equal to the
  monthly payment, set the paid-in-full flag to true, otherwise set the
  flag to false.

  If the minimum monthly payment is smaller than the monthly payment and
  the total payment this month is less than the minimum monthly payment,
  add the late payment penalty to the current balance.

  Set the total payment this month to 0.

  Set the monthly payment equal to the current balance.

I'm just asking for someone to read my code and tell me if the logic and tests work in all cases.

public void incrementDay()
  {
    if(!paidInFullFlag)
    {
      interestCharged += (this.balance + interestCharged) * (interestRate/365);
    }
  }

  /*Method adds interestCharged to balance and checks whether or not account has been paid in full for month*/
  public void incrementMonth()
  {
    this.balance += interestCharged;
    this.interestCharged = 0;
    if(this.sumPayment >= this.monthlyPayment)
    {
      this.paidInFullFlag = true;
    }
    else
    {
      this.paidInFullFlag = false;
    }

    if(minMonthly < monthlyPayment && sumPayment < minMonthly)
    {
      this.balance += latePaymentPenalty;
    }
    this.sumPayment = 0;
    this.monthlyPayment = this.balance;
  }

Test:

> CreditCardAccount c = new CreditCardAccount()
> c.setCreditLimit(100)
> c.setInterestRate(.08)
> c.setLatePaymentPenalty(3)
> c.setMinMonthlyPayment(20)
> c.charge(30)
true
> c.getBalance()
30.0
> c.payment(5) //pay 5 dollars towards balance
> c.incrementDay()
> c.incrementMonth()
> c.getBalance() //flag is initially set to true, so no late payment penalty or interest is charged, but flag is set to false for next month
25.0
> c.payment(5)
> c.charge(20)
true
> c.getBalance()
40.0
> c.incrementMonth() //late payment penalty is charged
> c.getBalance()
43.0
> c.incrementDay()
> c.getBalance()
43.0
> c.incrementMonth()
> c.getBalance() //interest AND late payment penalty is added
46.00942465753425


texts: Mapping a CSV with UTF-8 encoding to JSON in Python

texts:
I'm not a programmer, just a guy who needs to solve particular things using code.

I needed to create a JSON from a CSV with predefined headers. I'm downloading an attachment from JIRA (REST API), parsing the file and then mapping each value to a dictionary. The CSV has UTF-8 values.

# First I prepare my dic
    extracted_info = []
    mydic = {   'Ticket': None,
                'Dominio': None,
                'Tipo': None,
                'Ruta': None,
                'Version': None,
                'Componente': None,
                'Comentario': None
                }

    # Mapping values from CSV to Dictionary
    #
    def mappingThoseValues(d, a):
       # print i
        if d != "" :
            if a == 1 :
                mydic['Ticket'] = d
            elif a == 2:
                mydic['Dominio'] = d
            elif a == 3:
                mydic['Tipo'] = d
            elif a == 4:
                mydic['Ruta'] = d
            elif a == 5:
                mydic['Version'] = d
            elif a == 6:
                mydic['Componente'] = d
            elif a == 7:
                mydic['Comentario'] = d
                extracted_info.append(mydic.copy())

    # Parse CSV
    #
    # If URL isn't empty
    if attachment_final_url != "" :
        with open(runbookname) as csvfile:
            spamreader = csv.reader(csvfile, delimiter='\t')
            a= 0
            for row in spamreader:
                for i in row :
                    d = i.decode('iso-8859-1').encode('utf8')
                    a = a + 1
                    mappingThoseValues(d,a)
                    if a == 7 :
                        a = 0
        csvfile.close()
    else :
        status_compara_rn_jira = error_format_tab + 'ERROR: No attachments in : ' + myTicket

I solved what I needed, but I would like to learn how to do this properly, and maybe someday become a real programmer.

The CSV has 7 columns. In order to identify which one I'm parsing, I've added the variable a which increments each time. When I reach the 7th column I reset the value to 0, until the end of the file.

The CSV file doesn't contain headers for each column.


texts: Filtering queries based on the current user state

texts:
I have a Symfony2 project. I have an Entity Asset which can have relations with Category. I store a categoryCount-field within the Asset to determine if an asset has one, to select those fast via a DQL-query depending on the current user state.

Now found myself writing something along the lines of this in my AssetRepository:

/**
 * @param string $orderBy
 * @param int $mode
 *
 * @return \Doctrine\ORM\Query
 */
public function getQueryForAll($orderBy = 'DESC', $mode = self::FILTER_WITHOUT_QUARANTINED)
{
    $qb = $this->createQueryBuilder('asset');
    $qb->orderBy('asset.updatedAt', $orderBy);

    $filter = $this->getQuarantinedCriteria($mode);

    if ($filter) {
        $qb->addCriteria($filter);
    }

    return $query = $qb->getQuery();
}

/**
 * @param int $mode
 *
 * @return Criteria|null
 */

protected function getQuarantinedCriteria($mode = self::FILTER_WITHOUT_QUARANTINED) {
    $filter = null;

    if ($mode === self::FILTER_WITHOUT_QUARANTINED) {
        $filter = Criteria::create()
            ->andWhere(Criteria::expr()->gt('categoryCount', 0));
    } else if ($mode === self::FILTER_ONLY_QURANTINED) {
        $filter = Criteria::create()
            ->andWhere(Criteria::expr()->eq('categoryCount', 0));
    }

    return $filter;
}

This doesn't feel right to me. The $mode flag triggers my code smell alarm, I also am worrying about passing it into each asset querying method.

Furthermore, since I will have to set the mode depending on the state of the current logged in user, I also am worried that I will produce code duplications by doing a lot of if-user-has-the-rights-checks in my actions or services:

/**
 * @Route("/all_assets/{page}",
 *         name="get_paginated_assets",
 *         requirements={"page" = "\d+"},
 *         defaults={"page" = "1"},
 *         options={"expose"=true}
 * )
 */

public function getPaginatedAssetActions($page)
{
    $repo = $this->getAssetRepository();

    $isAllowedToViewRestrictedAssets =  $this->getCurrentUser()->isAdmin();

    if ($isAllowedToViewRestrictedAssets) {
        $mode = Entity\AssetRepository::FILTER_SHOW_ALL;
    }

    $query = $repo->getQueryForAll($mode);

    $pagerfanta = new Pagerfanta(new DoctrineORMAdapter($query));
    $data = $this->getCurrentPagedResults($pagerfanta, $page);

    $view = $this->view();
    $view->setFormat('json');
    $view->setData($data);

    return $view;
}

Is this the right way to implement the logic to enable filters in a Repository? Feedback on whether there is a more decoupled way would be highly appreciated.


texts: Maximum product of 3 integers in an int array using Python

texts:
This is an interview question from Interview Cake:

  Given a list_of_ints, find the highest_product you can get from three of the integers.
  The input list_of_ints will always have at least three integers.

I'm looking for feedback on how to improve readability, space, time complexity, using Python idiomatic code and general feedback.

import unittest

def highest_product(list_of_ints):
    pos = [0, 0, 0]
    neg = [0, 0]

    for x in list_of_ints:
        if x > 0 and x > pos[0]:
            pos[2], pos[1], pos[0] = pos[1], pos[0], x
        elif x > 0 and x > pos[1]:
            pos[2], pos[1] = pos[1], x
        elif x > 0 and x > pos[2]:
            pos[2] = x
        elif x < 0 and x < neg[0]:
            neg[1], neg[0] = neg[0], x
        elif x < 0 and x < neg[1]:
            neg[1] = x

    if neg[1] < 0:
        max_product = max([x * neg[0] * neg[1] for x in pos])
        max_product = max(pos[0] * pos[1] * pos[2], max_product)
    else:
        max_product = pos[0] * pos[1] * pos[2]

    return max_product

class TestHighestProduct(unittest.TestCase):
    def test_highest_product(self):
        self.assertEqual(highest_product([6, -1, -1, -2, 0]), 12)

if __name__ == '__main__':
    unittest.main(verbosity=2)


texts:
I have this problem with my interview. I was asked to implement a stack using a linked list.

Gist

#!python

from linkedlist import LinkedList

# Implement LinkedStack below, then change the assignment at the bottom
# to use this Stack implementation to verify it passes all tests
class LinkedStack(object):

    def __init__(self, iterable=None):
        """Initialize this stack and push the given items, if any."""
        # Initialize a new linked list to store the items
        self.list = LinkedList()
        if iterable is not None:
            for item in iterable:
                self.push(item)

    def __repr__(self):
        """Return a string representation of this stack."""
        return 'Stack({} items, top={})'.format(self.length(), self.peek())

    def is_empty(self):
        """Return True if this stack is empty, or False otherwise."""
        return self.list.is_empty()
        # TODO: Check if empty

    def length(self):
        """Return the number of items in this stack."""
        return self.list.size
        # TODO: Count number of items

    def push(self, item):
        """Insert the given item on the top of this stack.
        Running time: O(1) – Just does an append, which is O(1)"""
        self.list.append(item)

def peek(self):
    """Return the item on the top of this stack without removing it,
    or None if this stack is empty."""
    if self.is_empty():
        return
    return self.list.get_at_index(self.length() - 1)

def pop(self):
    """Remove and return the item on the top of this stack,
    or raise ValueError if this stack is empty.
    Running time: O(n) – It will always loop through whole list before
    finding the item at the end"""
    if self.is_empty():
        raise ValueError("Cannot pop from an empty stack")
    item = self.peek()
    self.list.delete(item)
    return item

My code passed the following 6 tests. I make sure that my code works a pretty comprehensive following unit test cases, and it passed against all test cases, so the code seems to be working fine.

#!python

from LLstack import Stack
import unittest

class StackTest(unittest.TestCase):

    def test_init(self):
        s = Stack()
        assert s.peek() is None
        assert s.length() == 0
        assert s.is_empty() is True

    def test_init_with_list(self):
        s = Stack(['A', 'B', 'C'])
        assert s.peek() == 'C'
        assert s.length() == 3
        assert s.is_empty() is False

    def test_length(self):
        s = Stack()
        assert s.length() == 0
        s.push('A')
        assert s.length() == 1
        s.push('B')
        assert s.length() == 2
        s.pop()
        assert s.length() == 1
        s.pop()
        assert s.length() == 0

    def test_push(self):
        s = Stack()
        s.push('A')
        assert s.peek() == 'A'
        assert s.length() == 1
        s.push('B')
        assert s.peek() == 'B'
        assert s.length() == 2
        s.push('C')
        assert s.peek() == 'C'
        assert s.length() == 3
        assert s.is_empty() is False

    def test_peek(self):
        s = Stack()
        assert s.peek() is None
        s.push('A')
        assert s.peek() == 'A'
        s.push('B')
        assert s.peek() == 'B'
        s.pop()
        assert s.peek() == 'A'
        s.pop()
        assert s.peek() is None

    def test_pop(self):
        s = Stack(['A', 'B', 'C'])
        assert s.pop() == 'C'
        assert s.length() == 2
        assert s.pop() == 'B'
        assert s.length() == 1
        assert s.pop() == 'A'
        assert s.length() == 0
        assert s.is_empty() is True
        with self.assertRaises(ValueError):
            s.pop()

if __name__ == '__main__':
    unittest.main()


texts: Get the width and height of a shape as user input

texts:
I made this program to understand inheritance better.

Now that I'm at this basic level it's not really a problem but I can see this coming in the future and so I'm asking what's the best method to ask the user to insert the width and height of a rectangle (in this case).

The code I'm providing includes the simple way, by simply asking the user and inserting the number in a variable, then passing the variable to the setter inside the object (rect1).

I think when I will add up more shapes this can become a little confusing, is there a better way I can ask the user to input the number?

Since I'm asked to provide more context:
I'm generally asking what's the best or a better method to ask input from the user that is going inside an object.

This is my version of it, that I think is good in this simple level but it will get messy with more shapes or generally more classes, I use 2 variable to ask for 2 dimensions, I will need 1 variable for every dimension and when I will create an object if I pass the wrong variable the program will work anyway, giving the wrong result.

Another way that I thought is insert an "askSomething" method in each class so that I don't need variables and every time a new object is created the io stream will be asked automatically.
The "AskSomething" method is identical to a setter except it has cout and cin already inside

I don't really came up with other ideas.

The code I'm providing is a simple program that by asking height and width of a Rectangle calculate its Area, but of course by the class name Rectangle, the member names height and width and the method name getArea was pretty obvious.

main.cpp:

int main() {
    Rectangle rect1;
    int width, height;

    std::cout << "Insert the width of the rectangle: ";
    std::cin >> width;

    std::cout << "Insert the height of the rectangle: ";
    std::cin >>height;

    rect1.setHeight(height);
    rect1.setWidth(width);

    std::cout << "The area of the rectangle is: " << rect1.getArea() << std::endl;

    std::cout << "Drawing: " << std::endl;
    std::cout << " ";
    for (int i = 0; i < width+1; ++i) {
        std::cout << "-";
    }
    std::cout << std::endl;
    for (int j = 0; j < (height+1)/2; ++j) { // divided by 2 to have a better proportion
        std::cout << "|";
        for (int i = 0; i < width+1; ++i) {
            std::cout << " ";
        }
        std::cout << "|";
        std::cout << std::endl;
    }
    std::cout << " ";
    for (int i = 0; i < width+1; ++i) {
        std::cout << "-";
    }

    return 0;
}

Shape.h:

class Shape {
public:
    int getWidth() const {
        return width;
    }

    void setWidth(int width) {
        Shape::width = width;
    }

    int getHeight() const {
        return height;
    }

    void setHeight(int height) {
        Shape::height = height;
    }

protected:
    int width, height;
};

Rectangle.h:

class Rectangle: public Shape {
public:
    int getArea(){
        return width*height;
    }
};

Thanks to everyone! :)


texts: If a message is there, but you cannot see it, is it really there?

texts:
I have created a space encoder program, because it is fun to generate invisible messages. (This programme is not cryptographically secure, it is just for fun)

import doctest

def to_spaces(text):
    """
    Each char with ASCII code x gets converted to a
    line of x spaces.

    >>> to_spaces('a').count(' ')
    97
    >>> to_spaces("hello").count(' ')
    532
    """
    return '\n'.join((' '*ord(char) for char in text))

def from_spaces(spaces):
    """
    Each line of x spaces gets converted to the
    char of ASCII code x.

    >>> from_spaces(' '*97)
    'a'
    """
    return ''.join((chr(len(i)) for i in spaces.splitlines()))

def encode_and_print_file():
    filename = input("Where do you want to save the encrypted text? ")
    content = input("Enter your secret message: ")
    with open(filename,"w+") as f:
        f.write(to_spaces(content))

def decode_and_print_file():
    filename = input("Which file do you want to read decoded? ")
    with open(filename) as f:
        print(from_spaces(f.read()))

def user_interface():
    while True:
        choice = input("\nDo you want to encode or decode? ")
        encode_and_print_file() if 'en' in choice.lower() \
                                else decode_and_print_file()

if __name__ == "__main__":
    doctest.testmod()
    user_interface()


texts: SQL procedure with cursor to check if values in table 1 are also in table 2

texts:
The problem is that I'm checking if result from cursor exists in CDN.ZamNag table for every iteration. Is there any better way to check if values in table 1 are also in table 2?

Time of executing below procedure takes 1 minute and 30 seconds - I'm searching for any ideas which will make executing shorter.

IF (SELECT object_id('TempDB..#temp_table')) IS NOT NULL
BEGIN
DROP TABLE #temp_table
END

DECLARE @Seria_Nazwa VARCHAR(15)
DECLARE @Magazyn_id INT
DECLARE @Magazyn_Kod varchar(15)
DECLARE @Zlozono varchar(12)
DECLARE @dzisiaj varchar(30)
SET @dzisiaj = @data --datetime = convert(datetime,DATEADD(DAY, 0, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP)),120)
Declare @jutro datetime = convert(datetime,DATEADD(DAY, 1, @dzisiaj),120)

CREATE TABLE #temp_Table (
seria varchar(15),
magazynkod varchar(15),
zlozono varchar(5),
data varchar(30)
)
DECLARE @get CURSOR
------------------------------------------------------
SET @get = CURSOR FOR
    SELECT Ser_Nazwa,Mag_GidNumer,Mag_Kod
    FROM CDN.Serie, CDN.Magazyny
    WHERE Mag_Kod in('1406','1407','1408')
    and SER_Nazwa like 's%'
    and  SER_Nazwa not like 'sk%'
    and  SER_Nazwa not like 'sa%'
    and  SER_Nazwa not like 'st%'
    and  SER_Nazwa not like 'su%'
    and  SER_Nazwa not like 's14/%'
    and  SER_Nazwa not like 's'
    and  SER_Nazwa not like 's10'
    and  SER_Nazwa not like 's24'
    and  SER_Nazwa not like 's07'
    and  SER_Nazwa not like 's28'
    and  SER_Nazwa not like 's32'
    and  SER_Nazwa not like 's61'

    OPEN @get
    FETCH NEXT
    FROM @get into @Seria_Nazwa,@Magazyn_Id,@Magazyn_Kod
    WHILE @@FETCH_STATUS = 0
    BEGIN
        IF (EXISTS(
        SELECT ZaN_MagNumer,Zan_ZamSeria,Zan_DataRealizacji
        FROM CDN.ZamNag
        WHERE
        Zan_MagNumer = @Magazyn_Id
        and ZaN_ZamSeria = @Seria_Nazwa
        and DateAdd(day, ZaN_DataRealizacji,CONVERT(DATETIME,'1800-12-28',120)) >= @dzisiaj
        AND DateAdd(day, ZaN_DataRealizacji,CONVERT(DATETIME,'1800-12-28',120)) <  @jutro
        ))
    SET @zlozono = 'tak'
    ELSE SET @zlozono = 'nie'
    INSERT INTO #temp_Table VALUES(@Seria_Nazwa,@Magazyn_Kod,@Zlozono,@dzisiaj)
    FETCH NEXT
    FROM @get INTO @Seria_Nazwa,@Magazyn_Id,@Magazyn_Kod
END
CLOSE @get
DEALLOCATE @get

select * from #Temp_Table
order by seria

END


texts:
I'm parsing commandline arguments in lua with a command parser library (penlight lapp). This works fine, is easy to design and flexible enough for me.
However, now I have a table containing all the parsed arguments, so I'm still stuck with the processing, that is calling functions or changing settings etc. within my program. Some of these options are checks or similar operations that abort normal program behaviour, so I need to exit the main program before entering the normal routines. To implement such behaviour, I'm essentially using a large if-elseif chain, which is complex and hard to maintain.

Here is some code, but my question is of a general nature: Most not-trivial-utilities-with-more-than-two-arguments need to solve this, there has to be a way to do this somewhat elegantly and non-complex. How?

local cmdargs = [[
    Utility

    --foo       enables foo
    --bar       check for bar, then exit
]]
local args = parse_args(cmdargs)

if args.foo then
    set_switch()
end
if args.bar then
    check_something()
    exit(0)
end
do_main_stuff()

My example has only two arguments, but with 20+ arguments this style becomes really unreadable.


texts: Splitting a list based on a delimeter into n chunks in Haskell. How can I write my functions more effeciently?

texts:
Split: Write a function split that takes a delimiter value “c” and a list “iL”, and it splits the input list with respect to the delimiter “c”.
Example output:
split 0 [1,2,3,0,4,0,5,0,0,6,7,8,9,10]
[[1,2,3],[4],[5],[],[6,7,8,9,10]]

My split function:
split :: Eq a => a -> [a] -> [[a]]
split a iL = let
             helper a [] buf = (reverse buf):[]
             helper a (x:xs) buf = if x==a
                                   then (reverse buf):(helper a xs [])   -- reverse
                                   else (helper a xs (x:buf))
             in helper a iL []  -- use helper

nSplit: Write a function nSplit that takes a delimiter value “c”, an integer “n”, and a list “iL”, and it splits the input list with respect to the delimiter “c” up to “n” times.
Example output:
nSplit 0 3 [1,2,3,0,4,0,5,0,0,6,7,8,9,10]
[[1,2,3],[4],[5],[0,6,7,89,10]]

My nSplit function:
nSplit :: (Ord a1, Num a1, Eq a2) => a2 -> a1 -> [a2] -> [[a2]]
nSplit a2 a1 iL = let
                  helper a2 a1 [] buf = (reverse buf):[]
                  helper a2 a1 (x:xs) buf = if x==a2&&a1/=0
                                            then (reverse buf):(helper a2 (a1-1) xs [])
                                            else (helper a2 a1 xs (x:buf))
                  in helper a2 a1  iL []  -- use helper

Is there any possible way I can make improvements to this code since I did these to the best of my ability with barely any knowledge of Haskell. My professor approved of my code but he said it could be condensed somehow. Does anyone have any ideas of what changes I could make to my code if there are even any? They seem to pass all the provided test he gave us.


texts: C program to read data from text file and write it to a binary one

texts:
This program will read data in the form of:

Number Name

In each line of a text file, then it will write it to a binary file and print the resulting binary file.

I am getting a warning in line 73, but I don't think it's an issue as null is converted into 0, right?

while(((fread((char*)&student, 1, sizeof(student), binary_file)) != NULL))

I'm talking about this line above

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 50

void create_binary_file(const char *dest, const char *src);
void print_binary_file(const char *dest);

int main(void){
    const char ascii[MAX_SIZE] = "text.txt";
    char binary[MAX_SIZE];
    puts("Enter the name of the binary file");
    fgets(binary, sizeof(binary), stdin);
    binary[strlen(binary)-1] = '\0';

    create_binary_file(binary, ascii);
    print_binary_file(binary);

    return 0;
}

void create_binary_file(const char *dest, const char *src){
    struct student_tem{
        int ID;
        char name[MAX_SIZE];
    };

    struct student_tem student;

    FILE *text_file;
    FILE *binary_file;

    if((text_file = fopen(src, "r")) == NULL){
        perror(src);
        exit(EXIT_FAILURE);
    }

    if((binary_file = fopen(dest, "wb")) == NULL){
        perror(dest);
        exit(EXIT_FAILURE);
    }

    while(!feof(text_file)){
        if(1 != fscanf(text_file, "%i", &student.ID)){
            fprintf(stderr, "Error reading student number");
            exit(EXIT_FAILURE);
        }
        if(1 != fscanf(text_file, "%s", student.name)){
            fprintf(stderr, "Error reading student name");
            exit(EXIT_FAILURE);
        }
        fwrite(&student, 1, sizeof(student), binary_file);
    }

    fclose(text_file);
    fclose(binary_file);
}

void print_binary_file(const char *dest){
    struct student_tem{
        int ID;
        char name[MAX_SIZE];
    };

    struct student_tem student;
    FILE *binary_file;
    if((binary_file = fopen(dest, "rb")) == NULL){
        perror(dest);
        exit(EXIT_FAILURE);
    }

    while(((fread((char*)&student, 1, sizeof(student), binary_file)) != NULL)){
        printf("%i %s\n", student.ID, student.name);
    }
}


texts: Registering all functions that implement an interface and allowing a passed-in context to invoke the applicable function (command)

texts:
I have a Lambda function that processes incoming messages and sends emails based on an enum type property in the message. I have N number of "handlers", one per type, and this number grows from time to time. I could register them in a simple object or Map, but I'd prefer to register them all automatically in a store the same way we'd register models in an ORM, for example:

[models/Order.js]
module.exports = Sequelize.define('Order', {properties...methods...etc});

[models/LineItem.js]
module.exports = Sequelize.define('LineItem', {properties...methods...etc});

and then anywhere we want to access our models, we'd be able to grab Sequelize.models.Order or even generically Sequelize.models[type].

This is the sort of typical parent-child OOP interface that I'd know how to handle in PHP via interfaces and an app-wide class registry or factory of "commands" for a given domain. In node it's a little less clear how to get this with less boilerplate code, and I seem to run into this problem often. Here's what I have working now, simplified for clarity:

app.js

// Configure handlers.
const handlers = require(path.join(__dirname, 'handler/index.js'));

exports.lambda = async (event, context) => {

    ...

    // Parse message.
    const msg = JSON.parse(event.Records[0].body);

    // Get handler.
    const handler = handlers.get(msg.type);
    if (!handler) throw new Error(`Unknown type ${msg.type}.`);

    // Run handler.
    await handler.handle(msg, emailParams, vars);

    ...
};

handler/index.js

const fs = require('fs');
const path = require('path');

module.exports = new Map();

fs.readdirSync(path.join(__dirname)).forEach(file => {
    if (file !== 'index.js') {
        const handler = require(path.join(__dirname, file));
        module.exports.set(handler.type, handler);
    }
});

handler/SendInvoice.js (one example of a "handler")

module.exports = {
    type: 'SEND_INVOICE',
    handle: async (msg, emailParams, vars) => {

        // Configure email.
        emailParams.Destination.ToAddresses = [msg.email];
        emailParams.Message.Subject.Data = `Invoice #${msg.invoiceNum}`;

        // Set variables.
        vars.email = msg.email;
        vars.invoiceNum = msg.invoiceNum;
        vars.salespersonName = msg.salespersonName;
        vars.salespersonEmail = msg.salespersonEmail;
    },
    tpl: `
        <mjml>
            <mj-body background-color="#ffffff">
                <mj-section>
                    <mj-column>
                        ...msg content...
                    </mj-column>
                </mj-section>
            </mj-body>
        </mjml>
    `,
};

I'm bothered that I seem to have to re-invent this quite often, and that I don't have a clear picture of the "best" way to implement. Do I module.export a definition? Or should the module be responsible for registering itself? I could extend the prototype of a parent "handler" class (or use ES6 classes) but that doesn't give me a registry of commands to pull from. If it does register itself, can I lazy-load it the way I can PHP classes or must I write boilerplate code to load all files in a folder everywhere I do this kind of thing? I suppose this is the command pattern, but the question remains of where/how to store the registry of commands in javascript?

You can see I'm perplexed. Thanks for any insight and clarity!


texts: Splitting a String and Returning Converted Data

texts:
I have 2 Classes, the first one is only used as Container,
and the second Class Splits a GpsString, Converts it to suitable data types and returns the Container Class.

The String to analyze looks about like this:

("$GPGGA,120003.533,7926.184,N,02222.419,W,1,12,1.0,88.5,M,0.0,M,,*71")

Now i want to know if this is good practice in ObjectOriented Programming,
or if there is a better way for this Problem.

final class GpsData {
    int Hours;
    int Minutes;
    double Seconds;
    double Lattitude;
    char DirectionLattitude; // North or South
    double Longitude;
    char DirectionLongitude; // North or South
    int Quality;
    int Satelites;
}

class ProtocolAnalyzer {
    private GpsData AnalyzedData = new GpsData();
    boolean AnalyzeData(String GpsData){
        GpsData Gps = new GpsData();
        int Attribute = 0;
        StringBuilder WorkString = new StringBuilder();
        int beginIndex = 0;
        int length = GpsData.length();
        for (int i = 0;i<=length;i++){
            if(i == GpsData.length() ||
            GpsData.charAt(i) == ','){
            String Data = GpsData.substring(beginIndex,i);
            boolean bool = ConvertData(Data,Attribute,Gps);
            if(!bool) return false;
            beginIndex = i + 1;
            Attribute ++;
        }
    }
    setAnalyzedData(Gps);
    return true;
}
private boolean ConvertData(String Data,int Attribute,GpsData Gps){
boolean b = false;
switch (Attribute) {
    case 0: // §GPGGA
        if(Data.equals("$GPGGA")) {
            b = true;
        }
        break;
    case 1: //HHMMSS.sss
        if(Data.length() == 10) {
            b = true;
            String split = Data.substring(0,2);
            Gps.Hours = Integer.parseInt(split);
            split = Data.substring(2,4);
            Gps.Minutes = Integer.parseInt(split);
            split = Data.substring(4,10);
            Gps.Seconds = Double.parseDouble(split);
        }
        break;
    case 2: //BBBB.BBBB
        if (Data.length() != 0) {
            b = true;
            Gps.Lattitude = Double.parseDouble(Data);
        }
        break;
    case 3: //b
        if (Data.length() != 0) {
            char DirLat = Data.charAt(0);
            if (DirLat == 'N' ||
                    DirLat == 'S') {
                b = true;
                Gps.DirectionLattitude = DirLat;
            }
        }
        break;
    case 4: //LLLLL.LLLL
        if (Data.length() != 0) {
            b = true;
            Gps.Longitude = Double.parseDouble(Data);
        }
        break;
    case 5: //l
        if (Data.length() != 0) {
            char DirLong = Data.charAt(0);
            if (DirLong == 'E' ||
                    DirLong == 'W') {
                b = true;
                Gps.DirectionLongitude = DirLong;
            }
        }
        break;
    case 6: //Q
        if (Data.length() != 0) {
            int Quality = Integer.parseInt(Data);
            Gps.Quality = Quality;
            if(Quality != 0) {
                b = true;
            }
        }
        break;
    case 7: //NN
        if (Data.length() != 0) {
            int Satellites = Integer.parseInt(Data);
            Gps.Satelites = Satellites;
            if(Satellites > 3) {
                b = true;
            }
        }
        break;
}
return b;
}

private void setAnalyzedData(GpsData LogData) {
    this.AnalyzedData = (LogData);
}

GpsData getAnalyzedData() {
    return AnalyzedData;
}
}


texts:
I've got this code to work, but being really new to PHP, I don't know if this is proper. I've sorted a CPT loop by a custom date.

I'm displaying items from most recent (or future date) to oldest
if the custom date is in the future I display an additional HTML element that says Coming Soon. I've used strtotime for the custom date and compared it to today.

I'm most interested in knowing a better method for converting and comparing time, and if this loop is a proper method of using orderby with a custom date.

get_field() is from the Advanced Custom Fields WordPress plugin.

<?php

    //Loop arguments

    $today = date('Ymd');
    $args = array(
                'post_type' => 'release',
                'showposts' => 6,
                'meta_key'  => 'release_date',
                'orderby'   => 'meta_value_num', // orderby meta field date
                'order'     => 'DESC'
            );
    // query and loop
    $release_query = new WP_Query( $args );

    // $release_date = get_field('release_date');

    while ( $release_query->have_posts() ) : $release_query->the_post();
    // don't duplicate featured posts
    if ( in_array($post->ID, $do_not_duplicate) ) continue;
        update_post_caches( $posts );
?>

    <div class="cd"
        <?php

            $image = get_field('cd_cover');

            if( !empty($image) ): ?>

                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" />

            <?php endif; ?>

            <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
                <?php the_title(); ?>

        <?php
        $cd_date = get_field('release_date');
        $release_date = date('Ymd', strtotime($cd_date)); // convert custom date to something manageable?
        if ( $release_date > $today ) {
            echo '
Coming Soon!
';
        }

        ?>

    <?php
        //release loop ends
        endwhile;
        // reset
        wp_reset_postdata();
    ?>


texts: Merge some child values back into the parent multidimensional array

texts:
This is a wonky PHP function I came up with to merge some select values from child arrays into the original.  It could really use some help simplifying / making it more elegant.

Is there a built-in method I'm overlooking?  array_push didn't work for me because the data needed to be flat.

The problem

What I've got:

array(
    array(
         'nice_value' => 'yup',
         'nice_value2' => 'yup again',
         'ono' => array(
              'nice_value3' => 'yup yup yup',
              'bad value' => 'nope'
          )

    ),
    // array with the same format
    [...]

);

What I need:

array(
    array(
         'nice_value' => 'yup',
         'nice_value2' => 'yup again',
         'nice_value3' => 'yup yup yup'
    ),
    // array with the same format
    [...]

);

The wonky solution

// calling in multidimensional array from an api
            $lists = $all_lists['data'];
// keys to merge into the parent array, 'key_to_be' => 'key_that_is'
            $keys_to_merge = array('members' => 'member_count');
// init the function
            $newList = merge_selected_values($lists, $keys_to_merge);

// start writing our function
            function merge_selected_values($list, $keys_to_merge) {
// initialize our return array
            $newList = array();
// start a counter
            $ii = 0;
// begin loop
            foreach($list as $key => $value) {
// get first series of array, this is what we want to merge into
                if (is_array($value)) {
// loop through these values
                   foreach ($value as $kk => $vv) {
// find all arrays that are children of our parent array
                      if (is_array($vv)) {
// loop through these child arrays
                          foreach ($vv as $stats_key => $stats_value) {
// start looping through the keys that we want to merge
                             foreach ($keys_to_merge as $keys => $vals) {
// if the key matches
                                 if ($stats_key === $vals) {
// create a variable to hold it
                                     ${$vals} = $stats_value;
                                 }
                             }
                         }
                      }
                   }
// start looping through keys to merge again
                   foreach ($keys_to_merge as $keys => $vals) {
// find the keys we merged
                       if (${$vals}) {
// create an array that is the merger, merge to existing array if it .. exists
                           if($newList[$ii]) {
                               $newList[$ii] = array_merge($newList[$ii], array($keys => ${$vals}));
                            }  else {
                              $newList[$ii] = array_merge($value, array($keys => ${$vals}));
                           }
                       }
                   }
               }
              $ii++;
            }
            return $newList;
            }


texts:
The code works well and does what I intend for it to do. In essence, it opens a file referenced as 'resource'. This is a .csv file. I then searches for the keys in the dictionary and for each key that it encounters, it replaces it with the value - the dictionary being 'rep'. It then exports this to a new .csv file.

The above just seems slightly cumbersome and so I just wonder if there is a slicker / more pythonistic way of achieving the above? I think the non-slick part of my code is the writing of the amended data to a new file but I seek any feedback regarding improving my code.

with open(resource,'rb') as f:
   data = f.read()
   rep = {"Incoming Call" : "Voice (in)",
          "Outgoing Call" : "Voice (out)",
          "Incoming SMS" : "SMS (in)",
          "Outgoing SMS" : "SMS (out)"}
   for i, j in rep.iteritems():
      print i, j
      data = data.replace(i, j)
   with open("output.txt", "w") as outputfile:
      outputfile.write(data)
      outputfile.close()


texts: Powershell to quickly ping a number of machines

texts:
I came up with the below code to improve the peformance of pinging a large number of machines.
At present it's fairly basic, but thought I should see what people thought before proceeding further.

NB: This is my first time playing with workflows, so I've probably committed a few faux-pas there.

cls
workflow Test-ConnectionQuickly {
    [cmdletbinding()]
    param(
        [Parameter(Mandatory = $true)]
        [string[]]$computers
    )
    $computerGroups = InlineScript {
        #group computers to throttle the number of threads
        [psobject]$itemCounter = [pscustomobject]@{itemNo=0;groupSize=10} #alter groupSize per your preference
        $itemCounter | Add-Member -MemberType ScriptMethod -Name 'groupNo' -Value {
            [math]::Floor($this.itemNo++ / $this.groupSize)
        }
        write-output $using:computers | Group-Object -Property {$itemCounter.groupNo()}
    }
    ForEach -parallel ($computerGroup in $computerGroups) {
        $computerGroup | select -ExpandProperty group | %{
            $pingable = (Test-Connection $_ -Count 2 -Quiet -ErrorAction SilentlyContinue)
            write-output (new-object -type psobject -property @{Name=$_;Online=$pingable})
        }
    }
}

[string[]]$computers = (1..100 | %{("Server{0:000}" -f $_)}) #here's where we'd read in the computere from file
Test-ConnectionQuickly $computers | select Name, Online #here's where we'd pipe the output to file

Design Notes:

The InlineScript is used to group servers into small sets (of 10; an arbitrary size) in the hope of balancing serial's performance for small sets against parallel's performance for large sets of computers.
The $itemCounter variable's an attempt at making grouping into defined set sizes simpler to read
-count 2 is specified on the test-connection so that we have some tolerence for network glitches without too much affect on performance.
-Quiet is specified because we don't need output / and not having output will help performance.


texts: Remove words from an exclude list in each row of a pandas.Series

texts:
I am trying to remove all occurrences of the words I collect in the list exclude from every text note. This is my approach.

import operator,re

exclude=[]
for i in range(len(freq_select)):
  if freq_select[i][1]<=25:
    exclude.append(freq_select[i][0])

def remove_nonfrequent(note):
  print(remove_nonfrequent.i)
  sentences=[]
  for sent in note.split('.'):
    words=sent.split(' ')
    #print("Before:",len(words))
    for word in words:
      for j in exclude:
        if j==word:
          #print(j,word)
          words.remove(word)
    #print("After:",len(words))
    sent=' '.join(words)
    sentences.append(sent)
  note='. '.join(sentences)
  remove_nonfrequent.i+=1
  return '. '.join([i for i in note.split('.') if i!=''])

remove_nonfrequent.i=0
jdf.NOTES=jdf.NOTES.apply(remove_nonfrequent)

I was initially looping over all the notes in pandas series. But now I am using apply() and I can say performance increased little bit. But it still takes a very long time.

Each note in the pandas.Series is of variable length. However, an average note can contain somewhere between 3000-6000 words. One note even has 13000 words.

I would like to get some help in this.


texts: Solution to Project Euler Problem #37 in C++: Truncatable Primes

texts:
I was recently looking at some of my old Project Euler solutions, and saw that my implementation for Problem 37 could be improved drastically.
The problem reads as follows:

The number 3797 has an interesting property. Being prime itself, it is possible to continuously remove digits from left to right, and remain prime at each stage: 3797, 797, 97, and 7. Similarly we can work from right to left: 3797, 379, 37, and 3.
Find the sum of the only eleven primes that are both truncatable from left to right and right to left.
NOTE: 2, 3, 5, and 7 are not considered to be truncatable primes.

Here is my C++ solution to the problem:
#include <vector>
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <string>

std::vector<long long int> primesUpto(long long int limit) // Function that implements the Sieve of Eratosthenes
{
    std::vector<bool> primesBoolArray(limit, true);
    std::vector <long long int> result;

    primesBoolArray[0] = primesBoolArray[1] = false;
    long long int sqrtLimit = std::sqrt(limit) + 1;

    for (size_t i = 0; i < sqrtLimit; ++i)
    {
        if (primesBoolArray[i])
        {
            for (size_t j = (2 * i); j < limit; j += i)
            {
                primesBoolArray[j] = false;
            }
        }
    }
    for (size_t i = 0; i < primesBoolArray.size(); ++i)
    {
        if (primesBoolArray[i])
        {
            result.push_back(i);
        }
    }
    return result;
}

bool isTruncPrime(long long int number, const std::vector<long long int>& primeList)
{
    std::string numberString = std::to_string(number);
    for (int i = 1; i < numberString.size(); ++i)
    {
        std::string truncLeft = numberString.substr(0, i); // The truncated prime from the left
        std::string truncRight = numberString.substr(i, numberString.size() - 1); // The truncated prime from the right
        if (!
            (
                std::binary_search(primeList.begin(), primeList.end(), std::atol(truncLeft.c_str())) &&
                std::binary_search(primeList.begin(), primeList.end(), std::atol(truncRight.c_str()))
            )   // If either of the two truncated sides are not prime
        )
        {
            return false;
        }
    }
    return true; // All truncated parts are prime, so the number is a truncatable prime
}

int main()
{
    const std::vector<long long int> primesUptoMillion = primesUpto(1'000'000LL); // Represents all the primes up to 1 million

    int numberTruncatablePrimes = 0;
    long long int currentNumber = 9; // 2, 3, 5, and 7 are not included in the search for truncatable primes
    long long int truncatablePrimeSum = 0;

    while (numberTruncatablePrimes != 11)
    {
        if (
            std::binary_search(primesUptoMillion.begin(), primesUptoMillion.end(), currentNumber) && // If the number itself is prime
            isTruncPrime(currentNumber, primesUptoMillion) // If the number is also a truncatable prime
        )
        {
            ++numberTruncatablePrimes; // Increase amount of truncatable primes
            truncatablePrimeSum += currentNumber; // Add the number's sum
        }
        currentNumber += 2; // Only odd numbers can be prime other than 2, so no need to look at every number
    }
    std::cout << truncatablePrimeSum << "\n";
}

Here is how I run the code:
g++ Problem037.cpp -std=c++14 -O2

Here is code for execution, timing, and output:
$ time ./a.out
748317

real    0m0.042s
user    0m0.040s
sys     0m0.004s

Here are the things I want from this Code Review:

The function isTruncPrime() does a lot of string manipulation to verify its parameter. Is there a way to improve the algorithm?
While the code does run pretty quickly, is there any code that slows down the rest significantly that I could improve on?
Are there any better or more idiomatic ways to format/structure my program so it follows C++ style?


texts: Loading components on startup, with timing measurements

texts:
I was just wondering, is there a way to load these better and log the times they each took? It seems like a headache having to write about 90+ stopwatches, which is what I will have to do as I have about 100 of these to load.

// PacketManager
var packetManagerStopwatch = Stopwatch.StartNew();
_packetManager = new PacketManager();
packetManagerStopwatch.Stop();
Logger.Trace("Loaded PacketManager [took " + packetManagerStopwatch.ElapsedMilliseconds + "ms]");

// Achievements
var achievementStopwatch = Stopwatch.StartNew();
_achievementManager = new AchievementManager();
achievementStopwatch.Stop();
Logger.Trace("Loaded Achievements [took " + achievementStopwatch.ElapsedMilliseconds + "ms]");

// Talents
var talentsStopwatch = Stopwatch.StartNew();
_talentTrackManager = new TalentTrackManager();
talentsStopwatch.Stop();
Logger.Trace("Loaded Talents [took " + talentsStopwatch.ElapsedMilliseconds + "ms]");

// Badges
var badgeStopwatch = Stopwatch.StartNew();
_badgeManager = new BadgeManager();
badgeStopwatch.Stop();
Logger.Trace("Loaded Badges [took " + badgeStopwatch.ElapsedMilliseconds + "ms]");

// ClientManager
var clientManagerStopwatch = Stopwatch.StartNew();
_clientManager = new GameClientManager();
clientManagerStopwatch.Stop();
Logger.Trace("Loaded GameClientManager [took " + clientManagerStopwatch.ElapsedMilliseconds + "ms]");

// ModerationManager
var moderationManagerStopwatch = Stopwatch.StartNew();
_moderationManager = new ModerationManager();
moderationManagerStopwatch.Stop();
Logger.Trace("Loaded ModerationManager [took " + moderationManagerStopwatch.ElapsedMilliseconds + "ms]");

// ItemDataManager
var itemManagerStopwatch = Stopwatch.StartNew();
_itemDataManager = new ItemDataManager();
itemManagerStopwatch.Stop();
Logger.Trace("Loaded ItemDataManager [took " + itemManagerStopwatch.ElapsedMilliseconds + "ms]");


texts: Extension pattern in a flask controller using importlib

texts:
I am trying to load a module according to some settings. I have found a working solution but I need a confirmation from an advanced python developer that this solution is the best performance wise as the API endpoint which will use it will be under heavy load.

The idea is to change the working of an endpoint based on parameters from the user and other systems configuration. I am loading the correct handler class based on these settings. The goal is to be able to easily create new handlers without having to modify the code calling the handlers.

This is a working example:

./run.py:

from flask import Flask, abort
import importlib
import handlers

app = Flask(__name__)

@app.route('/')
def api_endpoint():
    try:
        endpoint = "simple" # Custom logic to choose the right handler
        handlerClass = getattr(importlib.import_module('.'+str(endpoint), 'handlers'), 'Handler')
        handler = handlerClass()
    except Exception as e:
        print(e)
        abort(404)

    print(handlerClass, handler, handler.value, handler.name())

    # Handler processing. Not yet implemented

    return "Hello World"

if __name__ == "__main__":
    app.run(host='0.0.0.0', port=8080, debug=True)

One "simple" handler example. A handler is a module which needs to define an Handler class:

./handlers/simple.py:

import os

class Handler:
    def __init__(self):
        self.value = os.urandom(5)

    def name(self):
        return "simple"

If I understand correctly, the import is done on each query to the endpoint. It means IO in the filesystem with lookup for the modules, ...

Is it the correct/"pythonic" way to implement this strategy?

The answer so far from the previous Stack Overflow exchange:

  I would whitelist if possible.

I already whitelist when I fill in the endpoint variable with my custom logic.

It does not seem to be a very clean solution. Each handler needs to define an Handler class (same name for different class). I am searching for a cleanest "extension mecanism". How would you clean it up?

Based on @netme answer, this is the 2.0 version


texts: Finding the max subset of non-overlapping intervals

texts:
How could this code become cleaner?  I think that the way I handle the interfaces and binary search could be improved.  I am trying to understand how to structure such a code (and usage of APIs) in a cleaner and more efficient manner.

This code solves the problem of finding the max subset of non-overlapping intervals.  I especially believe the way I handle the binary search result is error-prone.

private boolean nonOverlapping(Pair interval, SortedSet<Pair> selectedIntervals) {
    if(selectedIntervals.isEmpty())
        return true;
    if(selectedIntervals.contains(interval)){
        return true;
    }
    Pair[] sortedSelections = selectedIntervals.toArray(new Pair[0]);
    int pos = Arrays.binarySearch(sortedSelections, interval, new Comparator<Pair>() {

        @Override
        public int compare(Pair o1, Pair o2) {
            return o1.getStart() - o2.getEnd();
        }
    });
    pos = (-pos) -1;
    if(pos == sortedSelections.length){
        if(sortedSelections[pos - 1].getEnd() < interval.getStart()){
            return true;
        }

    }
    else if(sortedSelections[pos].getEnd() > interval.getStart()){
        if(pos + 1 < sortedSelections.length){
            if(sortedSelections[pos + 1].getEnd() < interval.getStart()){
                return false;
            }
        }
        if(pos - 1 >= 0){
            if(sortedSelections[pos - 1].getEnd() < interval.getStart()){
                return false;
            }
        }
        return true;
    }

    return false;
}


texts:
There is an Employee table with data like:

ID    FIRST_NAME     END_DATE                      CITY
23    Manoj       24-JUL-16 08.45.02.000000 AM    Bangalore
22    Abhishek    24-JUL-16 08.45.01.000000 AM    Bangalore
24    Nilu        24-JUL-16 08.46.01.000000 AM    Bangalore
25    Niroj       24-JUL-16 12.08.43.000000 PM    Bangalore
26    Tulu        24-JUL-16 10.47.01.000000 AM    Bangalore
29    Prashant    24-JUL-16 10.50.01.000000 AM    Bangalore
27    Tulu        24-JUL-16 01.32.01.000000 AM    Chennai
28    Panjvir     24-JUL-16 09.50.01.000000 AM    Bangalore

I need results like group by city and number the records for last minute, last sec, last hour and today with comparing to end date.

I am able to get the results with this query:

select e1.city,
       (select count(*) from Employee where end_date > (sysdate - interval '1' minute) and city = e1.city) as las_min,
       (SELECT count(*) FROM Employee WHERE end_date > (sysdate - interval '1' hour) and city = e1.city) as last_hours,
       (select count(*) from Employee where TRUNC(end_date) <= sysdate and city = e1.city) as today,
       (select count(*) from Employee where end_date between add_months(trunc(sysdate,'mm'),-1) and last_day(add_months(trunc(sysdate,'mm'),-1)) and city = e1.city) as last_months
 from Employee e1 group by e1.city;

Is there any better way to get the same results?


texts: Project Euler #14 in Swift - Longest Collatz sequence

texts:
I just finished Project Euler #14 in Swift, and since there is not any version yet on Code Review, I would like to have some comments on what I did to try to improve it.

  The following iterative sequence is defined for the set of positive
  integers:

  n → n/2 (n is even)

  n → 3n + 1 (n is odd)

  Using the rule above and starting with 13, we generate the following
  sequence:

  13 → 40 → 20 → 10 → 5 → 16 → 8 → 4 → 2 → 1

  It can be seen that this
  sequence (starting at 13 and finishing at 1) contains 10 terms.
  Although it has not been proved yet (Collatz Problem), it is thought
  that all starting numbers finish at 1.

  Which starting number, under one million, produces the longest chain?

  NOTE: Once the chain starts the terms are allowed to go above one
  million.

import Foundation

func collatzSequenceForNumber(var number:Int, inout steps:[Int]) -> Int {

    var numberOfSteps = 0
    var found = false
    let initialNumber = number

    while (found == false) {

        if number % 2 == 0 {
            number /= 2
        } else {
            number = (number * 3 + 1) / 2
            numberOfSteps++
        }

        found = number < steps.count ? steps[number] > 0 : false
        numberOfSteps++
    }

    numberOfSteps += steps[number]
    steps[initialNumber] = numberOfSteps

    return numberOfSteps
}

func longestCollatzSequence(maxNumber:Int) -> (Int, Int) {
    var collatzSequence = (number:0, steps:0)
    var steps:[Int] = [Int](count: maxNumber, repeatedValue: 0)
    steps[1] = 1

    for var number = 2; number < maxNumber; number++ {

        let steps = collatzSequenceForNumber(number, &steps)
        if steps > collatzSequence.steps {
            collatzSequence = (number, steps)
        }
    }

    return collatzSequence
}

func euler14() {

    let result:(number:Int, steps:Int) = longestCollatzSequence(999_999)

    println(result.number)
}

func printTimeElapsedWhenRunningCode(operation:() -> ()) {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    println("Time elapsed : \(timeElapsed) s")
}

printTimeElapsedWhenRunningCode(euler14)

The code executes in 0.07s.


texts: Filter dataframe based on unique values in multiple columns and drop rows based on index

texts:
I'm wondering if there is a more efficient way of filtering a dataframe down based on certain unique values in several columns. Once I have it filtered down, I then want to extract keep one the largest value and I do this by dropping all indexes from the original dataframe. However, this process is slow and as the iterations and number of items in the dataframe increase the speed becomes more of an issue.
import pandas as pd
import numpy as np
import timeit

data_len = 1000
half = int(data_len/2)
fifth = int(data_len/5)
ans = ['Cat'] * data_len
cols = ['White'] * half + ['Black'] * half
age = np.random.randint(1, 10, data_len)
breed = ['A'] * fifth + ['B'] * fifth + ['C'] * fifth + ['D'] * fifth + ['E'] * fifth
weights = np.random.uniform(1, 100, data_len)
heights = np.random.uniform(1, 100, data_len)

df = pd.DataFrame(columns=['Animal', 'Color', 'Age', 'Breed', 'Weight', 'Height'])

df['Animal'] = ans
df['Color'] = cols
df['Age'] = age
df['Breed'] = breed
df['Weight'] = weights
df['Height'] = heights

def get_largest(df):
    drop_id = []
    sort_cols = ['Weight', 'Height']
    for Animal in pd.unique(df['Animal']):
        animals_df = df.loc[np.in1d(df['Animal'], Animal)]
        for Color in pd.unique(animals_df['Color']):
            color_df = animals_df.loc[np.in1d(animals_df['Color'], Color)]
            for uid in pd.unique(color_df['Age']):
                age_df = color_df.loc[np.in1d(color_df['Age'], uid)]
                for vic in pd.unique(age_df['Breed']):
                    breed_df = age_df.loc[np.in1d(age_df['Breed'], vic)]
                    drop_id.extend(
                        breed_df.sort_values(by=sort_cols, ascending=[False] * len(sort_cols)).index[1:].values)
    df = df.drop(df.index[drop_id])
    return df

func = lambda: get_largest(df)
print(timeit.timeit(func, number=100))


texts: Is there any way to make this CoffeScript code simpler / smaller

texts:
I've just started with coffeescript,  and I saw  http://blog.8thlight.com/uncle-bob/2012/04/20/Why-Is-Estimating-So-Hard.html  which has a little programming problem,  so I figured I'd do it in coffeescript (which seemed easy enough to do... )

anyways, I ended up with :-

lineEndings = ( s, len ) ->
  words = s.split ' '
  line = ''
  result = ''
  words.map ( word ) ->
    if line.length == 0
      line = word
    else if line.length + 1 + word.length <= len
      line = line + ' ' + word
    else
      result = result + line + '\n'
      line = word
  result + line

getty = "Four score and seven years ago our fathers brought forth upon this continent a new nation, conceived in liberty and dedicated to the proposition that all men are created equal"
console.log lineEndings getty, 13

I'm looking for any ways I could make this simpler coffeescript.

( I just used nodejs with coffescript installed to test this )


texts: Performance of hashmap-based session object

texts:
Unfortunately, I can't use the Tomcat session for storing the key/value pairs for each user (restricted because it's an IVR domain-based project).

But I need the same functionality like a Tomcat session.

For every user I can get a unique id (call Id). So it's like the Tomcat sessionId.

I have developed the following class to achieve the Tomcat session functionality with my little knowledge of Java.

/** enum is used for Singleton instance  **/
public enum SessionObject {

    /** single instance  **/
    INSTANCE;

    /** ConcurrentHashMap to avoid external synchronization  **/
    /** Key as callId , value as HashMap to store the key value pairs  **/
    private ConcurrentHashMap<String , ConcurrentHashMap<String,String>> session =  new  ConcurrentHashMap<String , ConcurrentHashMap<String,String>>();

    /** Used to create a new Map when new call ivr is established in the first vxml file**/
    public void createSession(String callId){

        ConcurrentHashMap<String,String> callMap = new ConcurrentHashMap<String,String>();
        session.putIfAbsent(callId, callMap);
    }

    /** Used to get the existing stored values for the particular call Id **/
    public ConcurrentHashMap<String,String> getSession(String callId){

        return session.get(callId);
    }

    /** Used to remove the details of the particular call Id , when call is disconnected **/
    public void deleteSession(String callId){

        session.remove(callId);
    }

}

I think that the code above will be more fine tunable. Suggestions to improve the performance would be appreciated.


texts: Calculate permutation from Factorial representation of the K-th iteration of the N-th permutation

texts:
As a follow of a post I made on the Mathematics Stack Exchange I wrote out a simple program that computes the K-th permutation from 0 to N-1 where the number of permutations is N!. What I was wondering is could I get some pointers on how to improve and re-write the permutation function to be more efficient--e.g. possibly getting rid of the vector and the for-loop to calculate the factorial.

#include <iostream>
#include <vector>
#include <cmath>
using namespace std;

///<summary>Calculates the permutation of K in range of 0 to N!. (MAX of N = 20--2^61).</summary>
vector<size_t> factorial_permutation(size_t N, uint64_t K) {
    vector<size_t> Perm;

    uint64_t FactN = N,  //Factorial of N
        RmdrK = K, //Remainder of K/(N-1)!
        IterN = N, //Downward iterator for N
        PostK; //The factorial position of K for each sub permutation.

    for(uint64_t I = N-1; I > 1; I--)
        FactN *= I;
    for (uint64_t I = 1; I <= N; I++) {
        FactN /= IterN--;
        PostK = RmdrK / FactN;
        RmdrK = RmdrK - (PostK * FactN);
        Perm.push_back(PostK);
    }

    return Perm;
}

int main() {
    size_t N = 0;
    uint64_t K = 0;
    vector<size_t> c = factorial_permutation(N, K);
    vector<size_t> s; //The factorial permutation sequence
    vector<size_t> e; //The permutation built from the factorial sequence

    //Builds the basic order sequence 0 to N-1 before permutation.
    for(int i = 0; i < N; i++)
        s.push_back(i);

    //Pushes the final result converted from factorial permutation to real permutation. For each entry of sequence s[c[i]] is an index into e[i] to build the permutation.
    for (int i = 0; i < N; i++) {
        e.push_back(s[c[i]]);
        s.erase(s.begin() + c[i]);
    }

    // Outputs the final permutation.
    for (int i = 0; i < N; i++)
        cout << e[i];

    cin.get();
};

The function factorial_permutation calculates the factorial representation of K--the K-th iteration--in a sequence from 0 to (N-1)! possible permutations. The main() function does simple conversion from the factorial representation to building the actual sequence. I would like to combine the two and see if I can negate the vectors all together for the sake of performance.

I'm also aware that I can remove the vector in factorial_permutation by using a basic array, but I can't seem to negate the one in the main() function.


texts: Extending basic differentiator to handle more kinds of expressions

texts:
Exercise 2.56.

  Show how to extend the
  basic differentiator to handle more
  kinds of expressions. For instance,
  implement the differentiation rule

  $$ \frac{d(u^n)}{dr} = nu^{n-1}(\frac{du}{dr})$$

  by adding a new clause to the deriv
  program and defining appropriate
  procedures exponentiation?, base,
  exponent, and make-exponentiation.
  (You may use the symbol ** to denote
  exponentiation.) Build in the rules
  that anything raised to the power 0 is
  1 and anything raised to the power 1
  is the thing itself.

From the book:

(define (deriv exp var)
  (cond ((number? exp) 0)
        ((variable? exp)
         (if (same-variable? exp var) 1 0))
        ((sum? exp)
         (make-sum (deriv (addend exp) var)
                   (deriv (augend exp) var)))
        ((product? exp)
         (make-sum
           (make-product (multiplier exp)
                         (deriv (multiplicand exp) var))
           (make-product (deriv (multiplier exp) var)
                         (multiplicand exp))))

I added:

        ((exponentiation? exp)
         (make-product (exponent exp)
                       (make-exponentiation (base exp) (- (exponent exp) 1))))

Book:

        (else
         (error "unknown expression type -- DERIV" exp))))

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

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

(define (make-sum a1 a2)
  (cond ((=number? a1 0) a2)
        ((=number? a2 0) a1)
        ((and (number? a1) (number? a2)) (+ a1 a2))
        (else (list '+ a1 a2))))

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

(define (make-product m1 m2)
  (cond ((or (=number? m1 0) (=number? m2 0)) 0)
        ((=number? m1 1) m2)
        ((=number? m2 1) m1)
        ((and (number? m1) (number? m2)) (* m1 m2))
        (else (list '* m1 m2))))

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

(define (addend s) (cadr s))

(define (augend s) (caddr s))

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

(define (multiplier p) (cadr p))

(define (multiplicand p) (caddr p))

I added:

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

Can this be improved?


texts:
I have a method that reverse each word in a string. I want to know how I can increase it's performance and memory efficiency. Ideas I had in mind were simply using char[] instead of strings being that strings are immutable and each time I concatenate the Strings, I am creating a new String object which is not efficient at all.

Example:

hi there cow  --> ih ereht woc

Code:

public static String reverseWord(String str) {
    int len = str.length();
    String strResult = "";
    String strBuffer = "";
    for (int i = 0; i < len; i++) {
        if (str.charAt(i) != ' ') {
            strBuffer = str.charAt(i) + strBuffer;
        }
        else if (str.charAt(i) == ' ') {
            strResult += strBuffer + " ";
            strBuffer = "";
        }
    }
    strResult += strBuffer;
    return strResult;
}


texts:
I need to produce a list objCollector with some results:

objCollector = []

      allRows.each () ->
        obj =
          source: self.source
          url: ''
          host: ''

        currentTag = $(this)
        links = currentTag.find('a')
        getTextFromSpan = currentTag.find('span.lnk').text()
        extractedLink = links[0].attribs.href
        obj.url = self.baseUrl + extractedLink
        obj.host = getTextFromSpan

        objCollector.push obj

Instead of building the result by appending to an empty list, could this be done more elegantly by using something like map?


texts: Find out whether string A can be shifted to get string B

texts:
The task:

  Given two strings A and B, return whether or not A can be shifted some
  number of times to get B.

  For example, if A is abcde and B is cdeab, return true. If A is abc
  and B is acb, return false.

Solution 1:

const haveSameLength = (a, b) => a.length === b.length;
const isSame = (a, b) => a === b;
const isFullyShifted = a => a === 0;
const shiftStringBy = i => a => `${a.substring(i)}${a.substring(0, i)}`;

const isSameAfterShifting = (strA, strB, items) => {
  if (strA.length === 0 || strB.length ===0) { return false }
  if (!haveSameLength(strA, strB)) { return false }
  if (isSame(strA, strB)) { return true }
  if (isFullyShifted(items)) { return false }

  return isSameAfterShifting(strA, shiftStringBy(1)(strB), --items)
}

const str1 = 'abcde';
const str2 = 'cdeab';

console.log(isSameAfterShifting(str1, str2, str2.length));

Solution 2

const isSameAfterShifting2 = (strA, strB) => {
  if (strA.length === 0 || strB.length ===0) { return false }
  if (!haveSameLength(strA, strB)) { return false }
  const arrB = strB.split('');
  const firstLetterA = strA.substring(0, 1);

  let shiftIndex = arrB.indexOf(firstLetterA);
  if (shiftIndex === -1) { return false }
  while (shiftIndex < arrB.length) {
    const strBShifted = `${strB.substring(shiftIndex)}${strB.substring(0, shiftIndex)}`;
    if (strA === strBShifted) { return true }
    shiftIndex++;
  }
  return false;
}

console.log(isSameAfterShifting2('abc', 'acb'));

Which one is more readable and easier to understand for you?