texts: FIZZ BUZZ -challenge program with adjustable intervals

texts:
This is again a solution to the codeEval challenge #1. It was accepted by codeEval, but please let me know if I can improve it anyway somehow?

#include<iostream>
#include<vector>
#include<fstream>
#include<string>
#include<chrono>

struct input_rec{
    int first;
    int second;
    int last;
};

void parseRecord( std::string &record, input_rec& rec )
{
    int first  = 0;
    int second = 0;
    int last   = 0;
    bool good  = 0;

    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    first = std::atoi(record.substr(start,end-start).c_str());
    if( ( 1 <= first ) && ( first <= 20 ) )
    {
        good = 1;
    }
    else
    {
        return;
    }

    start = end + 1;
    end = record.find_first_of( " ", start );
    second = std::atoi( record.substr( start, end-start ).c_str() );
    if( good && ( ( 1 <= second ) && ( second <= 20 ) ) )
    {
         good=1;
    }
    else
    {
        return;
    }
    start = end + 1;
    last = std::atoi( record.substr( start, std::string::npos ).c_str() );
    if( good && ( (21 <= last ) && ( second <= 200 ) ) )
    {
        good=1;
    }
    else
    {
        return;
    }
    if(good)
    {
        rec.first=first;
        rec.second=second;
        rec.last=last;
    }
}
void readInputFile( std::string fileName, std::vector< input_rec > & rec )
{

    //std::cout<<"readInputFile: filename:"<< filename<<std::endl;
    std::ifstream infile( fileName );

    std::string record;
    input_rec temp;
    while( std::getline( infile, record ) )
    {

        parseRecord( record, temp );
        rec.emplace_back( temp );
    }
}
void checkfuzzbuzz( input_rec& rec )
{
    int x     = 1;
    int flag1 = 0;
    int flag2 = 0;

    while( x < rec.last )
    {
        if( ( x % rec.first ) == 0)
        {
            flag1 = 1;
        }
        if ( ( x % rec.second ) == 0 )
        {
            flag2 = 1;
        }

        if( ( flag1 + flag2 ) == 2 )
        {
            std::cout << "FB" << " ";
        }
        else if( flag1 == 1)
        {
            std::cout << "F" << " ";
        }
        else if( flag2 == 1 )
        {
            std::cout << "B" << " ";
        }
        else
        {
            std::cout << x << " ";
        }
        flag1 = 0;
        flag2 = 0;
        ++x;
    }
    if( x == rec.last )
    {
        if( ( x % rec.first ) == 0 )
        {
            flag1 = 1;
        }
        if ( ( x % rec.second ) == 0 )
        {
            flag2 = 1;
        }

        if( ( flag1 + flag2 ) == 2 )
        {
            std::cout << "FB";
        }
        else if( flag1 == 1)
        {
            std::cout << "F";
        }
        else if( flag2 == 1 )
        {
            std::cout << "B";
        }
        else
        {
            std::cout << x << " ";
        }
        flag1 = 0;
        flag2 = 0;
        ++x;
    }
    std::cout << "\n";
}
int main( int argc, char* argv[] )
{
    auto start = std::chrono::steady_clock::now();
    if( argc < 2 )
    {
        std::cout << "usage: fuuzbuzz fuuzbuzz.txt" << "\n";
        exit( 0 );
    }

    std::ios_base::sync_with_stdio( false );
    std::vector< input_rec > input;
    readInputFile( argv[ 1 ], input );
    for( auto &x : input)
    {
       checkfuzzbuzz(x);
    }
   auto end      = std::chrono::steady_clock::now();
   auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
   std::cout<< duration.count() << "\n";
   return 0;
}


texts: Project Euler #2: Even Fibonacci numbers

texts:
Each new term in the Fibonacci sequence is generated by adding the
  previous two terms. By starting with 1 and 2, the first 10 terms will
  be:

  \$1, 2, 3, 5, 8, 13, 21, 34, 55, 89...\$

  By considering the terms in the Fibonacci sequence whose values do not
  exceed \$N\$, find the sum of the even-valued terms.

  Input Format:

  First line contains \$T\$ that denotes the number of test
  cases. This is followed by \$T\$ lines, each containing an integer, \$N\$.

  Output Format:

  Print the required answer for each test case.

  Constraints:

  \$1 \le T \le 10^{5}\$
  \$10 \le N \le 4 \times 10^{16}\$

#include <iostream>

int main () {
    int nCases;
    std::cin >> nCases;
    for (int i = 0; i < nCases; i++) {
        unsigned long back = 1;
        unsigned long front = 2;
        unsigned long total = front;
        unsigned long maxNumber;
        std::cin >> maxNumber;
        while (true) {
            unsigned long frontPrime = front;
            front = (3 * front) + (2 * back);
            back = (2 * frontPrime) + back;
            if (front > maxNumber) {
                break;
            } else {
                total += front;
            }
        }
        std::cout << total << '\n';
    }
    return 0;
}

Commented and formatted:

#include <iostream>

int main () {
    int nCases;
    std::cin >> nCases;

    for (int i = 0; i < nCases; i++) {
        unsigned long back  = 1; // First number of the sequence
        unsigned long front = 2; // Second number of the sequence
        unsigned long total = front; // Since out of the 2, only front is even

        unsigned long maxNumber;
        std::cin >> maxNumber;

        // Keep on getting the even numbers until the number becomes
        // greater than the max
        while (true) {
            unsigned long frontPrime = front; // Need to store its original value for use later

            // We know that every 3rd number is even:
            // 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144...
            // o, o, e, o, o, e,  o,  o,  e,  o,  o,   e...
            // Since an odd plus an odd has to equal an even,
            // but an even and an odd is always odd.
            //
            // So using f(n+2) = f(n+1)        + f(n)
            //                 = f(n) + f(n-1) + f(n)
            //                 = 2f(n) + f(n-1)
            //
            // and      f(n+3) = f(n+2)               + f(n+1)
            //                 = f(n+1)        + f(n) + f(n) + f(n-1)
            //                 = f(n) + f(n-1) + f(n) + f(n) + f(n-1)
            //                 = 3f(n) + 2f(n-1)
            //
            // Where n = front, and n-1 = back,
            // we can save from iterating more than once.
            // n+2 is 3 spaces ahead of n-1, and n+3 is 3 spaces ahead of n,
            // thus we go to each even only and save a modulo check.

            front = (3 * front) + (2 * back);
            back  = (2 * frontPrime) + back;

            if (front > maxNumber) {
                break;
            } else {
                total += front;
            }
        }

        std::cout << total << '\n';
    }

    return 0;
}

I was wondering if there is anything I could do to improve the efficiency, both processor- and memory-wise, size (of the code itself not the comments), or general style.

I am also curious as to whether or not there would be a better way to do my algorithm so as not to store frontPrime.


texts: Beginner's Knight's tour in Python (BFS)

texts:
I wanted to implement this as short and effective as I could without using anything that is not basics, in order to improve my skills.

I would appreciate input about things like memory leaks I missed, simpler way of doing things instead reinventing the wheel, methods I should have used / implemented / not implemented (could have used built-ins and defaults...) and styling. In general, does this implementation follows common best practices?

import random as r
import itertools as it
import numpy as np

class P:

    up = 8
    down = 0

    def __init__(self,x=0,y=0,parent=None, random = False):
        self.x = x if not random else r.randint(P.down,P.up-1)
        self.y = y if not random else r.randint(P.down,P.up-1)
        self.parent = parent

    def __str__(self):
        return '({},{})'.format(self.x,self.y)

    def __repr__(self):
        return '({},{} [{},{}])'.format(self.x,self.y,self.parent.x if self.parent else '-',self.parent.y if self.parent else '-')

    def __eq__(self,other):
        return self.x == other.x and self.y == other.y

# for np.unique
    def __gt__(self,other):
        return self.x + self.y > other.x + other.y
# for np.unique
    def __lt__(self,other):
        return self.x + self.y < other.x + other.y

    def __hash__(self):
        return hash((self.x, self.y))

    def valid_moves(self):
        def valid(*num):
            # a better way to check if all number in num return True?
            # this seems nice and short to me, but I guess there is a better way
            return sum([n >= P.down and n < P.up for n in num]) // len(num)

        a,b = [1,-1,],[2,-2]
        # is there a way to shorten this list construction?
        t = [P(self.x + i, self.y + j, self) for i in a for j in b if valid(self.x+i,self.y+j)] + [P(self.x + i, self.y + j, self) for i in b for j in a if valid(self.x+i,self.y+j)]
        return np.unique(t)

s = P()
e = P(random = True)
print('findint shortest path from {} to {}'.format(s,e))

ls = s.valid_moves()

while True:
    if e in ls or e == s:
        print('found end node...')
        #find the end node that has parents - not the
        #original "e" that has no parents andt herefore
        #cannot be used to generate path
        curr = ls.pop(ls.index(e))
        path = [curr]
        print('generating path...')
        while curr != s:
            curr = curr.parent
            path += ['->']
            path += [curr]

        print('path: ',path)
        break

    tmp = [p.valid_moves() for p in ls]
    # flatten tmp into 1-d list
    ls = list(it.chain(*tmp))
    # Do I have any memory leaks?
    del tmp


texts: Python Unit Coversion Code Optimization in terms of Space and Time Complexity

texts:
Ok I am making unit converter and I have attached temperature conversion code below. The problem with this code I think is that I have written function for each and every single unit to convert to another unit.

So in code below there is one function to covert Celsius into Fahrenheit, Kelvin, Renkien and Newton. Then another function to convert Fahrenheit to Celsius,Kelvin, Renkien and Newton.

Now I do understand that every unit is related to one another. But I just can't think of a way if this conversion can be done using single function such that first you choose your source and then destination and using that without using five different function I can just finish in one.

Another way I thought of this was I can may be use dictionaries rather then using so many if else conditions but I would like know which one is more optimized in terms of both time and space complexity.

class TempConv:

def __init__(self,source,dest,val):
    self.frm=source
    self.to=dest
    self.x=val
    self.ans=0

def setFrm(self,arg):
    self.frm=arg

def setTo(self,arg):
    self.to=arg

def setX(self,arg):
    self.x=arg

def calculate(self):
    if self.x is "celc":
        self.ans=self.celcToAny()
    elif self.x is "farh":
        self.ans=self.farhToAny()
    elif self.x is "kel":
        self.ans=self.kelToAny()
    elif self.x is "renk":
        self.ans=self.renkToAny()
    elif self.x is "newt":
        self.ans=self.newtToAny()
    else:
        self.ans=self.x

#Celcius to Any
def celcToAny(self):
    if self.to is "farh":
        return (float(self.x)*1.8)+32
    elif self.to is "kel":
        return float(self.x)+273.15
    elif self.to is "renk":
        return (flaot(self.x)+273.15)*1.8
    elif self.to is "newt":
        return float(self.x)*0.33
    else:
        return self.x

#Fahrenheit to Any
def fahrToAny(self):
    if self.to is "celc":
        return (float(self.x)-32)*0.555555556
    elif self.to is "kel":
        return (float(self.x)+459.67)*0.555555556
    elif self.to is "renk":
        return float(self.x)+459.67
    elif self.to is "newt":
        return (float(self.x)-32)*0.183333333
    else:
        return self.x

#Kelvin to Any
def kelToAny(self):
    if self.to is "farh":
        return (float(self.x)*1.8)-459.67;
    elif self.to is "celc":
        return float(self.x)-273.15
    elif self.to is "renk":
        return float(self.x)*1.8
    elif self.to is "newt":
        return (float(self.x)-273.15)*0.33
    else:
        return self.x

#Rankine to Any
def renkToAny(self):
    if self.to is "farh":
        return float(self.x)-459.67;
    elif self.to is "celc":
        return (float(self.x)-491.67)*0.555555556
    elif self.to is "kel":
        return float(self.x)*0.555555556
    elif self.to is "newt":
        return (float(self.x)-491.67)0.183333333
    else:
        return self.x

#Newton to Any
def newtToAny(self):
    if self.to is "farh":
        return (float(self.x)*5.454545455)+32
    elif self.to is "kel":
        return (float(self.x)*3.030303030)+273.15
    elif self.to is "renk":
        return (flaot(self.x)*5.454545455)+491.67
    elif self.to is "celc":
        return float(self.x)*3.030303030
    else:
        return self.x


texts: Given an integer s and a list of integers ints finding (x,y) in ints such that s = x + y

texts:
The following function sum_pairs(ints, s) takes two inputs: ints is a list with integer values and s is a integer number. The function sum_pairs returns the values (x, y) in ints such that \$s = x + y\$ and the index of y is the lowest for the (x, y) in ints such that \$s = x + y\$. This is a problem taken from codewars. The function passes all the test cases. However, when I attempt to run the code for a big list, the server codewars gives me the following answer: "Process was terminated. It took longer than 12000ms to complete".

I am wondering whether the code I have written to solve the problem can be optimised or should I use a different approach to give a solution.

def sum_pairs(ints, s):

    begin = 1
    end = len(ints)
    memo = []

    while begin < end:
        try:
            memo.append([begin-1, ints.index(s - ints[begin-1], begin, end)])
            begin += 1
            end = memo[-1][1]
        except:
            begin +=1

    if memo == []:
        return None
    else:
        return [ints[memo[-1][0]], ints[memo[-1][1]]]

The function sum_pairs(ints, s) searches for \$y = s - x\$ in the list ints using the function index(). If a value of y is found the index for the pair (x,y) is added to memo, then the range for the search (begin, end) are updated. Else only the lower limit begin for the search is updated.


texts: Part 2: Send HTTP request for each row in Excel table

texts:
This script was previously reviewed here: Send HTTP request for each row in Excel table (Part 1)
I've made the changes that were suggested in the Code Review answers as well as added a few of my own.
The code is quite a bit different now. Are there any more improvements that should be made?

Description:

A custom function concatenates columns with parameters into the Concatenated Variables column.
Loops through each row in the table where Load? = y
Sends an HTTP request to an external system using the value in the URL column.
Returns a message (created, updated, or problem/error) and stores it in the Message column.

New code:
Option Explicit

Public Const tblName = "tblData"
Public Const colNameLoad = "Load?"
Public Const colNameMessage = "Message"
Public Const colNameURL = "URL"
Public Const colNameTimestamp = "Message Timestamp"

Function CodeName() As Worksheet
Set CodeName = DataSheet
End Function

Public Sub LoadRecords()
    Application.CalculateFull
    Dim message As String, response As String
    Dim n As Long

    'Keep an eye on unecessary calls to the ConcatVars function.
    With CodeName.ListObjects(tblName)
        .ListColumns(colNameMessage).Range.Interior.Color = rgbWhite
        .ListColumns(colNameMessage).Range.Font.Color = rgbLightGrey
        For n = 1 To .ListRows.Count
            If UCase(.ListColumns(colNameLoad).DataBodyRange(n).Value) = "Y" Then
                response = GetHTTP(.ListColumns(colNameURL).DataBodyRange(n).Value)
                .ListColumns(colNameMessage).DataBodyRange(n) = response
                .ListColumns(colNameMessage).DataBodyRange(n).Font.Color = rgbBlack
                .ListColumns(colNameTimestamp).DataBodyRange(n) = Now()

                With .ListColumns(colNameMessage).DataBodyRange(n)
                    message = Left(response, 7)
                    .Interior.Color = Switch(message = "Created", rgbLightGreen, message = "Updated", rgbSkyBlue, message = "Problem", rgbYellow, True, rgbOrangeRed)
                End With

            End If
        Next
    End With
End Sub

Public Function GetHTTP(ByVal url As String) As String

On Error GoTo ConnectionError:

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", url, False: .Send
        GetHTTP = VBA.StrConv(.responseBody, vbUnicode)
    End With

On Error GoTo 0
Exit Function
ConnectionError:
GetHTTP = "Problem with URL or server: " & Err.Number & " " & Err.Description

End Function

Function ConcatVars(RowNum As Integer) As String
    Dim Column As ListColumn
    Dim s As String

    For Each Column In CodeName.ListObjects(tblName).ListColumns
        If Column.Name Like "f_*" Then
            s = s & IIf(Len(s) > 0, "&", "") _
                & Mid(Column.Name & "=" & Column.Range.Cells(RowNum).Value, 3)
        End If
    Next
    ConcatVars = s
End Function

I have a follow-up question here: Create or update record via HTTP request  (Python/Jython).


texts:
I'm doing a CodeEval challenge, where the object is to find a famous writers name and a year, inside of a random given string.

You have a set of rows with names of famous writers encoded inside. Each row is divided into 2 parts by pipe char (|). The first part has a writer's name. The second part is a "key" to generate a name.
Your goal is to go through each number in the key (numbers are separated by space) left-to-right. Each number represents a position in the 1st part of a row. This way you collect a writer's name which you have to output.
Challenge input:
osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA rLclpg| 3 35 27 62 51 27 46 57 26 10 46 63 57 45 15 43 53
3Kucdq9bfCEgZGF2nwx8UpzQJyHiOm0hoaYP6ST1WM7Nks5XjrR4IltBeDLV vA| 2 26 33 55 34 50 33 61 44 28 46 32 28 30 3 50 34 61 40 7 1 31
Expected output:
Stephen King 1947
Kyotaro Nishimura 1930

I've successfully solved this problem and would like some critique on my work:
import sys

def find_a_writer(string, int_list):
    """ Find a famous writer and a year in a random string
    >>> print(find_a_writer("osSE5Gu0Vi8WRq93UvkYZCjaOKeNJfTyH6tzDQbxFm4M1ndXIPh27wBA rLclpg",
    >>> ['3', '35', '27', '62', '51', '27', '46', '57', '26', '10', '46', '63', '57', '45', '15', '43', '53']))
    Stephen King 1947"""
    results = []
    string_list = list(string)
    for i in int_list:
        results.append(string_list[int(i) - 1])
    return ''.join(results)

if __name__ == '__main__':
    with open(sys.argv[1]) as data:
        for line in data.readlines():
            data_arr = line.rstrip().strip().split("|")
            print(find_a_writer(data_arr[0].strip(), data_arr[1].strip().split(" ")))

What I would like to know:

What did I do well?
Is there anything I can do better?
Can I shorten the function?


texts: Sharing $scopes across Controllers with ScopeFactory

texts:
Previously, I use to always navigate through the $parent $scopes in order to send or change data from one Controller into/in another. I then created my own ScopeFactory as a way to storing each Controllers $scope and then getting those scopes from other Controllers.

Having not experienced any problems with using this method, I'm just curious if this is a good way to do it.

.factory('ScopeFactory', [function() {

    var notifications  = { that: this };
    var tagsPanel      = { that: this };
    var activityHeader = { that: this };

    var saveScope = function(type, vs) {
        switch(type) {
            case 'notifications':
                notifications.that = vs;
                break;
            case 'tagsPanel':
                tagsPanel.that = vs;
                break;
            case 'activityHeader':
                activityHeader.that = vs;
                break;
        }
    };

    var getScope = function(type) {
        switch(type) {
            case 'notifications':
                return notifications.that;
                break;
            case 'tagsPanel':
                return tagsPanel.that;
                break;
            case 'activityHeader':
                return activityHeader.that;
                break;
        }
    };

    return {
        saveScope : saveScope,
        getScope  : getScope
    };
}]);

Saving a scope:

// inside activityHeader Controller:
ScopeFactory.saveScope('activityHeader', vs);

Getting a scope from another Controller:

var activityHeader = {};

activityHeader = ScopeFactory.getScope('activityHeader');
activityHeader.chosenTicker   = initTicker;
activityHeader.companyName    = compName;
activityHeader.currentPrice   = price;
activityHeader.currentPercent = percent;
activityHeader.initialTickerLoaded(ticker);


texts:
I have this code that basically reads the DOM and sends the values to the server. I am looking for any possible flaws that I may have in this JavaScript code and any advice to make it better and bug-free!

$(document).ready(function () {
    $('.editButton').click(function () {
        var postData = {};
        var cData = {};
        cData.Balance = $(this).parent().children('.balance').text().replace("$", "");
        cData.desiredStatus = $(this).parent().children('.status').text() == "Disbled" ? "enable" : "disable";
        $('#currentBalance').html($(this).parent().children('.balance').text());
        $('#currentStatus').html($(this).parent().children('.status').text());
        $('#desiredStatus').html(cData);

        //set post view
        postData.code = $(this).parent().children('.code').text();
        postData.giftcardaccount_id = $(this).parent().children('.giftcardaccount_id').text();

        $("#dialog").dialog({
            title:"test box",
            modal:true,
            width:700,
            buttons:{
                'Confirm':function () {
                    postData.status = $('#currentStatus').html();
                    var balanceInqury = parseFloat($('#desiredBlance').val());
                    postData.balance = (balanceInqury == 'NaN') ? cData.Balance : balanceInqury;
                    $.ajax({
                        url:'/url/to/postto',
                        type:'POST',
                        data:{
                            postData:postData
                        },
                        success:function (data) {
                            console.log(data);
                            $("#dialog").dialog("close");

                        },
                        error:function () {
                        }
                    });
                },
                Cancel:function () {
                    $(this).dialog("close");
                }
            }
        });//dialog
    });

    $('#changeStatus').click(function () {
        var c = $('#currentStatus').html() == 'Disabled' ? 'Enabled' : 'Disabled';
        var d = $('#desiredStatus').html() == 'disable' ? 'enable' : 'disable';
        $('#currentStatus').html(c);
        $('#desiredStatus').html(d);

    });

});


texts: GetNeighborhood function for 3D cells structure in MATLAB

texts:
I am attempting to implement a GetNeighborhood function in order to get a specific region from inputCells by sizeInput and centralLocation parameters in 3D cells structure.
The experimental implementation
The experimental implementation of GetNeighborhood function is as below.
function [output] = GetNeighborhood(inputCells, sizeInput, centralLocation)
    %   Get neighborhood of fixed size and centered at centralLocation
    output = cell( sizeInput ,sizeInput ,sizeInput );
    X = centralLocation(1);
    Y = centralLocation(2);
    Z = centralLocation(3);
    for x = -sizeInput:sizeInput
        for y = -sizeInput:sizeInput
            for z = -sizeInput:sizeInput
                if X + x < 1
                    xLocation = 1;
                elseif X + x > size(inputCells, 1)
                    xLocation = size(inputCells, 1);
                else
                    xLocation = X + x;
                end

                if Y + y < 1
                    yLocation = 1;
                elseif Y + y > size(inputCells, 2)
                    yLocation = size(inputCells, 2);
                else
                    yLocation = Y + y;
                end

                if Z + z < 1
                    zLocation = 1;
                elseif Z + z > size(inputCells, 3)
                    zLocation = size(inputCells, 3);
                else
                    zLocation = Z + z;
                end

                output{sizeInput + x + 1, sizeInput + y + 1, sizeInput + z + 1} = ...
                    inputCells{xLocation, yLocation, zLocation};
            end
        end
    end
end

Test cases
For testing purpose, a simple test script is created as below.
clear all;
clc;
close all;
set(groot,'defaultFigureVisible','on');

%% Create test cells

testCellsSize = 10;

test = cell(testCellsSize, testCellsSize, testCellsSize);
for x = 1:size(test, 1)
    for y = 1:size(test, 2)
        for z = 1:size(test, 3)
            test{x, y, z} = [x * 100 + y * 10 + z];
        end
    end
end

%% Specify test parameters

NeighborhoodDist = 1;
centralLocation = [5 2 2];

%% Perform test

result = GetNeighborhood(test, NeighborhoodDist, centralLocation);
result

The output of the above testing code:

  3×3×3 cell array

result(:,:,1) =

    {[411]}    {[421]}    {[431]}
    {[511]}    {[521]}    {[531]}
    {[611]}    {[621]}    {[631]}

result(:,:,2) =

    {[412]}    {[422]}    {[432]}
    {[512]}    {[522]}    {[532]}
    {[612]}    {[622]}    {[632]}

result(:,:,3) =

    {[413]}    {[423]}    {[433]}
    {[513]}    {[523]}    {[533]}
    {[613]}    {[623]}    {[633]}

If there is any possible improvement about potential drawback or unnecessary overhead, please let me know.


texts:
I have a method to get the time parameter, is this code neat, can the return parameter use other data structures?

private Map<String, Object> getTimeCondition(long smallDaysToSubtract, long bigDaysToSubtract) {

    DateTimeFormatter format = DateTimeFormatter.ofPattern(DateUtil.yyyy_MM_dd);
    ZoneId zoneId = ZoneId.systemDefault();

    LocalDate startLocalDate = LocalDate.now().minusDays(smallDaysToSubtract);
    LocalDate endLocalDate = LocalDate.now().minusDays(bigDaysToSubtract);

    LocalDateTime startLocalDateTime = LocalDateTime.of(startLocalDate, LocalTime.MIN);
    LocalDateTime endLocalDateTime = LocalDateTime.of(endLocalDate, LocalTime.MAX);

    Instant startInstant = startLocalDateTime.atZone(zoneId).toInstant();
    Instant endInstant = endLocalDateTime.atZone(zoneId).toInstant();

    Date startTime = Date.from(startInstant);
    Date endTime = Date.from(endInstant);

    String startDateStr = startLocalDate.format(format);
    String endDateStr = endLocalDate.format(format);

    Map<String, Object> map = new HashMap<>();
    map.put("startTime", startTime);
    map.put("endTime", endTime);
    map.put("startDateStr", startDateStr);
    map.put("endDateStr", endDateStr);

    return map;
}


texts:
I am learning the Strategy pattern but hate the idea of passing a new object to the Context each time I need to change the desired algorithm. Instead I think it would be best to create an enum that holds all of the Concrete Strategy objects, and simply update them with a setter on the context. Below is my implementation. Please let me know if this is a good approach for Strategy?

Client

public class Client {

    public static void main(String args[]){

        IntroductionContext introductionContext = new IntroductionContext();
        introductionContext.setStrategy(ConcreteStrategies.HELLO);
        introductionContext.executeStrategy();
        introductionContext.setStrategy(ConcreteStrategies.GOODBYE);
        introductionContext.executeStrategy();
    }
}

Context

public class IntroductionContext {

    private IInteractionStrategy iInteractionStrategy;

    public void executeStrategy() {
        if(iInteractionStrategy == null){
            throw new RuntimeException("Context must set its strategy before invoking executeStrategy()");
        }
        this.iInteractionStrategy.interact();
    }

    public void setStrategy(ConcreteStrategies concreteStrategy){
        this.iInteractionStrategy = (IInteractionStrategy) concreteStrategy.getConcreteStrategy();
    }
}

Enum to hold all strategy objects

public enum ConcreteStrategies {

    HELLO(new HelloStrategy()), GOODBYE(new GoodByeStrategy());

    private Object concreteStrategy;

    private ConcreteStrategies(Object concreteStrategy){
        this.concreteStrategy = concreteStrategy;
    }

    public Object getConcreteStrategy(){
        return this.concreteStrategy;
    }
}

Strategy (Interface)

public interface IInteractionStrategy {

    public void interact();
}

Concrete Strategy

public class HelloStrategy implements IInteractionStrategy {

    @Override
    public void interact() {
        System.out.println("Hello!");
    }
}

Concrete Strategy

public class GoodByeStrategy implements IInteractionStrategy {

    @Override
    public void interact() {
        System.out.println("Goodbye!");
    }
}


texts:
So I've been working on a simple little hashing algorithm for Python that I like to call PRBHA-10 for short, or Pseudo-Random-Based Hash Algorithm. This is a hash algorithm in Python that is meant to be simplistic and secure. As you could see from the title, the algorithm implements a system with seeding the pseudo-random number generator to be able to produce the correct integer values when provided the correct password, therefore enabling the decryption of an encrypted byte sequence or string.

Here's the advantages of my method:

The functions are tiny and simple, unlike some hashing methods out there.
Despite the simplicity of the algorithm, it is secure due to the generation of large random numbers that scale with the password size.
There is no chance of revealing even part of the encrypted string without the full password due to the huge numbers created by the seeded PRNG and multiplication that completely messes up the string if the wrong password is entered.
It is fast. I have not done timeits yet, but the functions run in a trivial amount of time to generate their results.

The disadvantages:

A somewhat large password is required to ensure security - usually anything over seven characters is completely cryptographically secure.
It is vulnerable to the same brute-force attacks that any cryptographic encryption method is vulnerable to.
With larger passwords comes greater security, but also a larger hash. The hash size slightly increases with each character added onto the password.

Here's the whole module program, prhba.py:

"""Pseudo-Random Based Hash Algorithm (PRHBA-10) is a simple
Python cipher that uses the integer representation of a
string, along with taking advantage of the built-in
pseudo-random number generator to be able to securely encrypt
strings and bytearrays.

The algorithm uses the integer representation of byte sequences,
seeding the random number generator using the password to
create a predictable random number for later use, and a special
encoded form to turn any byte sequence into an ASCII string
using only the letters 'aceilnorst'. This is secure due to the
extremely large random number generated ensuring the security
of the result.

The result can be later decrypted using a special algorithm to
decipher the text into a large integer number. Then, the
password is used as a seed to once again get the random number
used earlier in the process. That integer is used to modify
the large integer to be able to get the integer form of the
original string, which can then be converted to a string.

This cipher currently only works in Python due to the specific
random number generation implementation in the `random` module.
"""

import math
import random

__all__ = ["encrypt", "decrypt"]

LETTERS = "aceilnorst"

def to_num(s):
  return int.from_bytes(s.encode(), 'little')

def from_num(n):
  return n.to_bytes(math.ceil(n.bit_length() / 8), 'little')

def encrypt(data, password):
  assert len(password) > 1, "Password length cannot be less than two"
  random.seed(to_num(password))
  unique_id = to_num(data) * random.getrandbits(len(password))
  chunk = []
  for digit in str(unique_id):
    chunk.append(LETTERS[int(digit)])
  return "".join(chunk)

def decrypt(encrypted_data, password):
  random.seed(to_num(password))
  partnum_digits = []
  for char in encrypted_data:
    partnum_digits.append(str(LETTERS.index(char)))
  partnum = int("".join(partnum_digits))
  return from_num(partnum // random.getrandbits(len(password)))

Here's the questions I have:

Is it PEP-8 compliant?
Are the variable names confusing?
Is there any parts that could be improved or further reduced?
Do you have any other suggestions?

Thanks in advance!


texts:
I would like to know, if my design of this class is good OOP.
Should I implement for every hash algorithm a separate class?
I'm asking this, because the HashService can be used with a KeyedHashAlgorithm which wouldn't work correctly?!

public class HashService : IDisposable
{
    public HashService(HashAlgorithm algorithm)
    {
        HashAlgorithm = algorithm;
        Encoder = Encoding.UTF8;
    }

    protected HashAlgorithm HashAlgorithm { get; set; }

    /// <summary>
    /// The size, in bits, of the computed hash code.
    /// </summary>
    public int HashSize
    {
        get { return HashAlgorithm.HashSize; }
    }

    /// <summary>
    /// Gets or sets the encoding for strings.
    /// </summary>
    public Encoding Encoder { get; set; }

    public string ComputeHash(string input)
    {
        byte[] bytes = Encoder.GetBytes(input);
        byte[] hash = ComputeHash(bytes);
        return ToHex(hash); // method impl. omitted
    }

    /// <summary>
    /// Computes the hash value for the specified byte array
    /// </summary>
    /// <param name="buffer">The input to compute the hash code for.</param>
    /// <returns>The computed hash code.</returns>
    public byte[] ComputeHash(byte[] buffer)
    {
        return HashAlgorithm.ComputeHash(buffer);
    }

    public byte[] ComputeHash(byte[] buffer, int offset, int count)
    {
        return HashAlgorithm.ComputeHash(buffer, offset, count);
    }

    public byte[] ComputeHash(Stream inputStream)
    {
        return HashAlgorithm.ComputeHash(inputStream);
    }

    #region Implementation of IDisposable

    // omitted

    #endregion

    // ReSharper disable InconsistentNaming
    public static HashService CreateMd5()
    {
        return new HashService(new MD5CryptoServiceProvider());
    }

    public static HashService CreateRIPEMD160()
    {
        return new HashService(new RIPEMD160Managed());
    }

    public static HashService CreateSHA256()
    {
        return new HashService(new SHA256Managed());
    }

    public static HashService CreateSHA384()
    {
        return new HashService(new SHA384Managed());
    }

    public static HashService CreateSHA512()
    {
        return new HashService(new SHA512Managed());
    }

    public static HashService CreateSHA1()
    {
        return new HashService(new SHA1Managed());
    }

    public static HashService CreateCrc32()
    {
        return new HashService(new Crc32Managed());
    }

    // ReSharper restore InconsistentNaming
}


texts: Find pairs in binary search tree in which sum of nodes keys is equal key

texts:
There is a task:

  Given a binary search tree of \$n\$ nodes, find all the pair of nodes whose sum is equal to a given number \$k\$ in \$O(n)\$ time and constant space.

Please let me know if you find bugs on any data set.

import java.util.*;
import java.lang.*;
import java.io.*;

class Main
{
    static class Node
    {
        Node(Node left, Node right, Node parent, int key)
        {
            this.left = left;
            this.right = right;
            this.parent = parent;
            this.key = key;
        }

        public Node left;
        public Node right;
        public Node parent;

        public int key;
    }

    public static void inOrder (Node node)
    {
        if(node.left != null) inOrder(node.left);
        System.out.println(node.key);
        if(node.right != null) inOrder(node.right);
    }

    public static Node successor (Node node)
    {
        Node successor = null;
        if(node.right != null)
        {
            node = node.right;
            while(node.left != null)
            {
                node = node.left;
            }
            successor = node;
        }
        else if(node.parent != null && node.parent.left == node) successor = node.parent;
        else if(node.parent != null && node.parent.right == node)
        {
            while(node.parent != null && node.parent.right == node)
            {
                node = node.parent;
            }
            successor = node.parent;
        }
        return successor;
    }

    public static Node predeccessor(Node node)
    {
        Node predecessor = null;
        if(node.left != null)
        {
            node = node.left;
            while(node.right != null)
            {
                node = node.right;
            }
            predecessor = node;
        }
        else if(node.parent != null && node.parent.right == node) predecessor = node.parent;
        else if(node.parent != null && node.parent.left == node)
        {
            while(node.parent != null && node.parent.left == node)
            {
                node = node.parent;
            }
            predecessor = node.parent;
        }

        return predecessor;
    }

    public static Node min (Node node)
    {
        while(node.left != null) node = node.left;
        return node;
    }

    public static Node max (Node node)
    {
        while(node.right != null) node = node.right;
        return node;
    }

    public static void main (String[] args) throws java.lang.Exception
    {
        Node root = new Node(null, null, null, 5);//      5
        Node a = new Node(null, null, null, 2);   //     / \
        Node b = new Node(null, null, null, 1);   //    2   8
        Node c = new Node(null, null, null, 3);   //   /\    \
        Node d = new Node(null, null, null, 8);   //  1  3    9
        Node e = new Node(null, null, null, 9);   //

        root.left = a;
        root.right = d;
        a.parent = root;
        d.parent = root;

        a.left = b;
        a.right = c;
        b.parent = a;
        c.parent = a;

        d.right = e;
        e.parent = d;

        int sum = 10;

        //find pairs in Binary Search Tree in which sum of nodes keys is equal 10

        Node minnode = min(root);
        Node maxnode = max(root);
        while(minnode.key <= maxnode.key && minnode != maxnode)
        {
            if (minnode.key + maxnode.key == sum)
            {
                System.out.println("Pair found: " + minnode.key + " " + maxnode.key);
                minnode = successor(minnode);
                maxnode = predeccessor(maxnode);
            }
            else if(minnode.key + maxnode.key < sum)
            {
                minnode = successor(minnode);
            }
            else
            {
                maxnode = predeccessor(maxnode);
            }
        }
    }
}


texts: Coursera: Calculating sum of numbers in the fibonacci sequence between two specific points in the series

texts:
Question

This is an assignment for a Coursera course.

This is the algorithm I wrote.

import java.util.*;

public class FibonacciPartialSum {
    private static long getFibonacciPartialSumNaive(long from, long to) {
        if (to <= 1)
            return to;

        long prev = 0;
        long cur = 1;
        long sum;

        if(from == 1) {
            sum = 1;
        }
        else {
            sum = 0;
        }

        for (long i = 2; i <= to; i++) {
            long temp_prev = prev;
            prev = cur;
            cur = (cur + temp_prev) % 10;

            if (i >= from) {
                sum = (sum + cur) % 10;
            }

        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        long from = scanner.nextLong();
        long to = scanner.nextLong();
        //long from = 1234;
        //long to = 12345;
        System.out.println(getFibonacciPartialSumNaive(from, to));
        scanner.close();
    }
}

When I submit it to auto grader in Coursera it states that I failed the time test.

Failed case #8/12: time limit exceeded Input: 1 10000000000

Your output:

stderr:

(Time used: 3.03/1.50, memory used: 26427392/536870912.)


texts: Change the limit from CakePHP 3 Paginator by click in link inside an

texts:
I'm using the CakePHP 3.0 to paginate some content, but I can't find a way to change the limit (user on browser choose the limit of content displayed on screen) using Paginator built-in method (like sort built-in), to do this I use javascript to change limit in URL.

Qustion: Exist any way to do this in cakephp style ?

Controller action that uses paginate

public $helpers = [
    'Paginator' => ['templates' => 'paginator-templates']
];

public function search()
{
    if($this->request->is('get'))
    {
        $search = $this->request->query['search'];
        @$limit = $this->request->query['limit'] ?: 3;

        $this->paginate = [
            'conditions' => ['product_name LIKE' => '%' . $search . '%'],
            'limit' => $limit,
            'contain' => ['Medias' => function($q){
                return $q->select(['path', 'product_id'])
                    ->where(['media_type_id' => 3]);
            }]
        ];

        $products = $this->paginate($this->Products);
     }
}

Select with pagination limits:

<select name="products-view" class="form-control products-view inline-pagination-menu" id="products-view">
    <option value="3">3</option>
    <option value="6">6</option>
    <option value="9">9</option>
</select>

Javascript responsible to change limit in URL

$('#products-view').change(function(){
    changeLimitPagination(this);
});

function changeLimitPagination(option){
    location.search = $.query.set('limit', option.value).toString();
}


texts: Program that moves characters in n steps to the next character in alphabet based on ASCII code

texts:
I made a variation on the program that moves the character to the next character. This version moves the characters n steps forward and takes care of white spaces in between. It works but wonder if there is a better way of coding this.
It only works with lowercase alphabet characters.

import java.util.Scanner;
public class NextCharacters{
    public static char nextCharacterInAlphabet(char character , int step)
    {
           char nextChar;
           int ascii = (int) character;

           if (ascii ==32)  //ascii code for a space is 32
                     /*space stays space that separates the different
                     strings seperated by the spaces */
                   nextChar = (char) ascii;
           /*at ascii 104=h remainder goes to zero so i have to add 104, have to add
           104 till ascii=122=z*/
            else if ((ascii +step) % 26>=0 && (ascii +step) % 26 <=18)
            {
                nextChar = (char) ( ((ascii +step) % 26)+104);
            }
            else
                    nextChar = (char) ( ((ascii +step) % 26)+78);
           /*first character is the 'a' with ascii value 97. Remainder of 97%26 is 19
           so to come up with 97 you have to add 78 to get the value for a.
           The same applies if you increase the number of positions you want the
           chars to move forward, have to this till it reaches ascii =104 where
           the remainder gets to 0 and have to add 104*/
        return nextChar;
    }

    public static void main(String[] args) {

        Scanner inputChars = new Scanner( System.in );

        Scanner inputSteps = new Scanner( System.in );

        StringBuilder sb = new StringBuilder();

        System.out.println("Please enter the characters ");
        String characterString = inputChars.nextLine();

        System.out.println("Please enter the number of positions you want each character to move forward");
        int numberOfMovesForward = inputSteps.nextInt();
        for (char c : characterString.toCharArray() )
        {
            sb.append(nextCharacterInAlphabet(c,numberOfMovesForward ));
        }
        System.out.println(sb.toString()) ;

    }

}


texts:
In order to practice my programming skills, I am trying to implement a Button class, to use in pygame. I know there are libraries like PGU, I do this to improve in programming.

I spent a bit of time creating a function to find a good font size for the text inside the button, depending on the length of the text and the dimensions of the button.

I came to this result, it's close enough to what I want. However, I am looking for advice to improve this function that looks wobbly:

def balanced_text_size_button(length, width, height):
    # sqrt(length) / length -> The higher the length is, the smaller this value become,
    # it decrease slower and slower as length increase (never reach 0).
    # pow(....., 1.6) -> The resulting value is multiplied,
    # the impact is more important on high value
    # (I don't think it makes much sense I found this empirically).
    length_factor = math.pow((math.sqrt(length) / length), 1.6)

    # If there is a lot of horizontal space for the text, the font will be big,
    # but if there is a lot of char to write it will be smaller.
    font_size = width * length_factor

    # This way the font is not too high
    if font_size > height:
        font_size = height * 0.9

    return int(font_size)

A preview of what it looks like:


texts: Optimizing regex alternation, ability to view which choice matched?

texts:
So I've got a regular expression parsing tcp responses from a music daemon. In case responses pile up I've come up with an expression to separate full responses from the data, however I'd like to also reference which choice was matched. Using capturing groups results in different numbers for each group, so is there a way to reference which alternation choice was matched besides that?

var patt = /((volume):\s\d+\n(.+\n)+?OK\n|OK\s(MPD)\s\d+\.\d+\.\d+|(OK)|(ACK).+\n)/;

This will match it, but I want to do different things with the separated response based on which match it was. I'd like to just have a switch case reference a single variable, but the only way I can think of to is:

var mycase = null;
var result = patt.exec(data);
if (result[2] == "volume")
    mycase= "volume";
else if (result[4] == "MPD")
    mycase= "MPD";
else if (result[5] == "OK")
    mycase= "OK";
else if (result[6] == "ACK")
    mycase= "ACK";

Is there a better way to do this?


texts: Find the letter 'z' within three characters after an 'a'

texts:
It works, just feel that my solution is too complicated.

# Write a method that takes a string in and returns true if the letter
# "z" appears within three letters **after** an "a". You may assume
# that the string contains only lowercase letters.
#
# Difficulty: medium.

def nearby_az(string)

  i = 0
  while i < string.length

    if string[i] == "a"
      a_index = i
    end

    if string[i] == "z"
      z_index = i
    end

    if (a_index) && (z_index) && (a_index < z_index) && ((z_index - a_index) <= 3)
      return true
    end
    i += 1
  end
  return false
end

# These are tests to check that your code is working. After writing
# your solution, they should all print true.

puts('nearby_az("baz") == true: ' + (nearby_az('baz') == true).to_s)
puts('nearby_az("abz") == true: ' + (nearby_az('abz') == true).to_s)
puts('nearby_az("abcz") == true: ' + (nearby_az('abcz') == true).to_s)
puts('nearby_az("a") == false: ' + (nearby_az('a') == false).to_s)
puts('nearby_az("z") == false: ' + (nearby_az('z') == false).to_s)
puts('nearby_az("za") == false: ' + (nearby_az('za') == false).to_s)


texts: Python Script: Converts .tsv to TFRecord

texts:
The python code below converts a tab spaced values file (.tsv) into a TFRecord in hopes that this approach expedites future time spent loading the data. Is the performance of this task correct and optimal, specifically in terms of run-time?

The .tsv file is of the following format, including spaces to make it more readable (SEMEVAL STS'17 training dataset): float_value_from_0_to_5 \t string1 \t string2. The desired TFRecord's entries should optimally store the previous values as float rate, string sent1, and string sent2 for proper implementation with any arbitrary Neural Network that will embed the words once loaded from the TFRecord.

import tensorflow as tf
import nltk
import os
import csv

def tsv_to_tfrec(file_path):
  with open(file_path, 'rb') as tsv, tf.python_io.TFRecordWriter(
        os.path.splitext(file_path)[0] + ".tfrecords") as tfrec:
    read_tsv = csv.reader(tsv, delimiter = '\t', quoting = csv.QUOTE_NONE)

    for row in read_tsv:
      if len(row) != 3:
        print("\nERROR in # of indicies: ", len(row))
        for i in range(len(row)):
          print(i, " =", row[i])
      else:
        example = tf.train.Example(features = tf.train.Features(feature = {
            "rate": tf.train.Feature(float_list=tf.train.FloatList(
                value = [float(row[0])])),
            "sent1": tf.train.Feature(bytes_list=tf.train.BytesList(
                value = nltk.word_tokenize(row[1]))),
            "sent2": tf.train.Feature(bytes_list=tf.train.BytesList(
                value = nltk.word_tokenize(row[2])))
            }))

        tfrec.write(example.SerializeToString())


texts: Calculating total sales from each member

texts:
I am building a new system that is using some tables from an old system.

For each user on this new system, I need to go to the old system and total up their sales.  Currently it takes between 2-5 minutes to load.

public static List<DailyTeamGoal> GetListDailyTeamGoals(int teamId)
{
    string teamGoal = "";
    List<ProPit_User> lstProPit_User = new List<ProPit_User>();
    using (ProsPitEntities db = new ProsPitEntities())
    {
        // Find the team
        Team team = db.Teams.Where(x => x.teamID == teamId).FirstOrDefault();

        if (team != null)
        {
            // Grab team goal
            teamGoal = Convert.ToString(team.goal);
        }
        // Make a list of all users who are on the team
        lstProPit_User = db.ProPit_User.Where(x => x.teamID == teamId).ToList();
    }

    List<DailyTeamGoal> lstDailyTeamGoal = new List<DailyTeamGoal>();
    using (TEntities db = new TEntities())
    {
        //have to get every day of the month
        DateTime dt = DateTime.Now;
        int days = DateTime.DaysInMonth(dt.Year, dt.Month);
        decimal orderTotal = 0m;
        for (int day = 1; day <= days; day++)
        {
            // For every day in the month total the sales
            DailyTeamGoal dtg = new DailyTeamGoal();
            dtg.Date = day.ToString(); //dt.Month + "/" + day; + "/" + dt.Year;
            dtg.TeamGoal = teamGoal;
            decimal orderTotalRep = 0m;
            foreach (var propit_User in lstProPit_User)
            {
                DateTime dtStartDate = Convert.ToDateTime(dt.Month + "/" + day + "/" + dt.Year);
                DateTime dtEndDate = dtStartDate.AddDays(1);
                var lstorderTotalRep = (from o in db.Orders
                                    where o.DateCompleted >= dtStartDate
                                    where o.DateCompleted <= dtEndDate
                                    where (o.Status == 1 || o.Status == 2)
                                    where o.Kiosk != 0
                                    where o.SalesRepID == propit_User.SalesRepID
                                    orderby o.OrderTotal descending
                                    select o.OrderTotal).ToList();

                foreach (var item in lstorderTotalRep)
                {
                    //orderTotalRep =+ item;
                    orderTotalRep += item;
                }
            }

            orderTotal += orderTotalRep;
            dtg.DailyTotal = orderTotal;

            lstDailyTeamGoal.Add(dtg);
        }
    }

    return lstDailyTeamGoal;
}

The above code will use my site to find the teamID the logged in person is on.  It will then find all members who are on that team.  For each member it finds it will calculate the total sales and then spit me back a list.  Any way to speed this up?


texts:
I need to write a VBA code routine with an efficient way to replace blank cells with values from another cell. For example, my worksheet has some blank cells on random rows in column D. I want to replace these with the value on the same row in column A. In other words, go down all the rows and if column D is blank, replace it with column A.

I wrote some code that "walks" down every row of the worksheet looking for blanks in column D and copying the values from A into D, but it's ridiculously slow (some of these worksheets have more than half a million rows!)

 .Range("D1", Range("D1048576").End(xlUp)).Select
            Set A = XL.Selection
                For Each B In A.Rows
                        If Len(B.Value & vbNullString) = 0 Then
                            B.FormulaR1C1 = "=RC[-3]"
                        End If
                    DoEvents
                Next

Any suggestions?


texts: String compression by using repeated characters count

texts:
My task was to perform a basic string compression by replacing consecutive repeated characters by one instance of the character and integer denoting the number of repetitions.
For example the string "aaaaabbcccdeee" should be reduced to "a5b2c3de3".
I have tried working in C# using a simple logic. Please see the below code. Also I have added the condition to not to add the count 1 in the compressed string if there is only single letter occurrence. E.g. if letter "d" is occurred only once in a string "aaabbcccdee" then function will give a compressed string as "a3b2c3de2" and not the "a3b2c3d1e2". To modify this requirement we can change the condition for this single count.
Please let me know about the comparative time and space complexity and other efficient way in C#.

class StringCompression
{
    static void Main(string[] args)
    {
        StringCompression sc = new StringCompression();

        sc.CompressionMethod("aaaaabbbccdeeeee");
        sc.CompressionMethod("aaabbccdddee");
        sc.CompressionMethod("a");
    }

    public void CompressionMethod(string originalString)
    {
        List<char> OriginalList = new List<char>();
        List<string> CompressedList = new List<string>();
        OriginalList.AddRange(originalString);
        // Convert to Character Array
        char[] charArray = OriginalList.ToArray();

        int i = 0;
        char character;
        int len = charArray.Length;

        while (i < len)
        {
            int n = 0;
            character = (charArray[i]);
            while (i < charArray.Length && charArray[i] == character)
            {
                n = n + 1;
                i++;
            }

            // add characters to the new list
            CompressedList.Add(character.ToString());

            // add character counts to the new list
            if (n == 1)
            {
                // Do nothing
            }
            else
            {
                CompressedList.Add(n.ToString());
            }
        }
        // CompressedList will contain compressed string
        foreach (string str in CompressedList)
        {
            Console.Write(str);
        }
        Console.Write("\n");
        Console.Write("\n");
    }
}


texts:
I have a Java/Swing/Guice application that uses multiple frames. When the application runs normally, I just want some of these frames to hide (and the "master" frame can unhide them).

When testing the view, I have various other main methods that can open just one frame, and perhaps populate them with sample data. However, then the test application has no way to close (because their normal operation is to be hidden). But, I don't want to mess around with the constructor because I don't want this testing functionality to affect appear anywhere else, I want the "normal operation" module to have no knowledge of this behavior, because it's for testing, only.

Note: this is View testing (like, does it look the way I want it to?), so it's not really appropriate for JUnit.

How is this solution? Is there a better one?

public class SubView {
    private JFrame frame;
    public SubView() {
        initialize();
    }
    private void initialize() {
        frame = new JFrame();
        // etc. note, I don't call frame.setDefaultCloseOperation
        // here, as hide is what I want
    }
    @Inject
    private void setCloser(Closer c) {
        frame.setDefaultCloseOperation(c.closeOperation);
    }
    private static class Closer {
        @Inject(optional=true) @Named("closeOperation")
        private int closeOperation = WindowConstants.HIDE_ON_CLOSE;
    }
}

And then in my test class:

public SubViewTester {
    public static void main(String... args) {
        Module testSpecific = new AbstractModule() {
            @Override
            protected void configure() {
                bindConstant().annotatedWith(Names.named("closeOperation"))
                        .to(WindowConstants.EXIT_ON_CLOSE);
            }
        };
        Injector inj = Guice.createInjector(/* maybeSomeOtherModule, */ testSpecific);
        SubView view = inj.getInstance(SubView.class);
        EventQueue.invokeLater(new Runnable() {
            view.setVisible(true);
        }
    }
}


texts: Adapter class to display songs in an Android ListView

texts:
I am learning Android with Udacity nanodegree (having no support) and this is my assignment of music app. It is just an interface and no music I have to add. So far so the app is running without any error but I wold like to get expert feedback to write code in better and optimized way to achieve the same result.
My entire project is in my Bitbucket repo.
SongAdapter.java
public class SongAdapter extends ArrayAdapter<Song> {

    int     playingIndex = -1;
    boolean currentTrack = false;

    public SongAdapter(@NonNull Context context, int resource, @NonNull List<Song> objects) {
        super(context, resource, objects);
    }

    @NonNull
    @Override
    public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {

        View             playlistItemView = convertView;
        final ViewHolder holder;

        if (playlistItemView == null) {
            playlistItemView = LayoutInflater.from(getContext()).inflate(R.layout.playlist_item, parent, false);

            holder = new ViewHolder();

            holder.albumCoverThumbnail = playlistItemView.findViewById(R.id.playlist_album_thumbnail);
            holder.songTitle = playlistItemView.findViewById(R.id.playlist_song_title);
            holder.songAlbumTitle = playlistItemView.findViewById(R.id.playlist_song_album_title);
            holder.songArtist = playlistItemView.findViewById(R.id.playlist_song_artist);
            holder.songPlayButton = playlistItemView.findViewById(R.id.playlist_play_button);

            playlistItemView.setTag(holder);
        } else {
            holder = (ViewHolder) playlistItemView.getTag();
        }

        final Song currentSong = getItem(position);

        // set data to the list item
        assert currentSong != null;
        holder.albumCoverThumbnail.setImageResource(currentSong.getSongAlbumCoverId());
        holder.songTitle.setText(currentSong.getSongTitle());
        holder.songAlbumTitle.setText(currentSong.getSongAlbumTitle());
        holder.songArtist.setText(currentSong.getSongSingers());

        // check the play status of the song item
        if (playingIndex == position) {
            holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
        } else {
            holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
        }

        // set song button action
        holder.songPlayButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);

                // pause current song on other click
                if (position == playingIndex) {
                    playingIndex = -1;
                } else {
                    playingIndex = position;
                    notifyDataSetChanged();
                }

                // pause play current track
                if (currentTrack) {
                    holder.songPlayButton.setImageResource(R.drawable.ic_play_arrow_black_24dp);
                    currentTrack = !currentTrack;
                } else {
                    holder.songPlayButton.setImageResource(R.drawable.ic_pause_black_24dp);
                }
                currentTrack = !currentTrack;
            }
        });

        return playlistItemView;
    }

    static class ViewHolder {
        ImageView   albumCoverThumbnail;
        TextView    songTitle;
        TextView    songAlbumTitle;
        TextView    songArtist;
        ImageButton songPlayButton;
    }
}


texts:
I think there must be a more pythonic way to achieve the lowercase-forcing that I need to do here.  The keys in my lookup (self.adjustments) are all lc, params sent in to function can be any case (data coming from third party).  Also, is it objectionable to have self.adjustments used here but not passed in?

def getRevenue(self, metric, productParam, platformParam):
    product = productParam.lower()  # better way to do this?
    platform = platformParam.lower()    # better way to do this?
    # get adjustment for product.platform, multiply by metric
    if product not in self.adjustments:
        raise Exception('Unknown adsense product: {}'.format(product))


texts:
Below is my recursive solution for the Knights Tour. The user can set the board size and the program will print the first legal knight's tour it finds.

As there are potentially millions of correct solutions to the knight's tour, only one solution is given.

def legal_moves(visited, position, sq):
    """Calculate legal moves"""
    legal_moves = [
        (-2, -1),
        (-2, 1),
        (-1, -2),
        (-1, 2),
        (1, -2),
        (1, 2),
        (2, -1),
        (2, 1),
    ]

    row = position // sq
    col = position % sq

    move_to = []
    for dx, dy in legal_moves:
        if 0 <= (row + dx) < sq and 0 <= (col + dy) < sq:
            new_position = (position + (sq * dx)) + dy
            if new_position not in visited and 0 <= new_position < (sq * sq):
                move_to.append(new_position)
    return move_to

def make_move(move_to, visited, current, route, sq):
    """Carry out the move"""
    for move in move_to:
        visited.add(current)
        new_route = route + f"{current}-"
        solution_found = next_move(visited, move, new_route, sq)
        visited.remove(current)
        if solution_found:
            return True
    return False

def next_move(visited, current, route, sq):
    """Find the next valid moves and instruct "make_move" to carry them out"""
    if len(visited) == (sq * sq) - 1:
        route += f"{current}"
        print(route)
        return True
    move_to = legal_moves(visited, current, sq)
    solution_found = make_move(move_to, visited, current, route, sq)
    if solution_found:
        return True

def start_tour(sq):
    """Calculate the knights tour for  grid sq*sq starting at all positions in range 0-sq"""
    for starting in range(sq * sq):
        visited = set()
        route = ""
        solution_found = next_move(visited, starting, route, sq)
        if solution_found:
            return
    print("No knights tour could be calculated")

if __name__ == "__main__":
    square_size = 8
    start_tour(square_size)

EDIT
I have added a print_route function which is called from inside next_move in place of the current print statement as follows:
print_route(route, sq)

def print_route(route, size):
    """Convert the 1D array into a 2D array tracking the movement on the knight"""
    import numpy as np

    steps = route.split("-")
    array = np.zeros(size * size)

    for index, item in enumerate(steps):
        array[int(item)] = index + 1
    array = array.reshape(size, size)

    print(array)


texts: Returning the length of a 'hidden' string within each of the sentences of another string

texts:
The following program is supposed to return the length of a 'hidden' string within each of the sentences of another string, using pointers and avoiding as much as possible the use of [] as a means to access strings. We were instructed on how to declare the functions, hence their declarations are a given.

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

int getHiddenString(const char * str1 , const char * str2);
int divideStringIntoSentences(char * string, char * sentences[]);
char* readLine();
int main()
{
char *ptrarr[20];
int i = 0;
printf ("Please enter a string:\n");
char *str1 = readLine();
printf ("Please enter a hidden string:\n");
char *str2 = readLine();
if (str2 == NULL) return EXIT_FAILURE;
int j = divideStringIntoSentences(str1, ptrarr);
for (; i <= j; i++)
printf ("Sentence %d contains hidden string prefix length %d\n", i,
    getHiddenString(*(ptrarr + i), str2));
free (str1);
free (str2);
return 0;
}

int getHiddenString(const char * str1 , const char * str2)
{
int hidlen = 0;
for (; *str1 != '\0' && *str2 != '\0'; str1++)
if (*str1 == *str2)
{
    hidlen++;
    str2++;
}
return (hidlen);
}

char* readLine()
{
int capacity = 1, index = 0;
char c;
char *str1 = (char*) malloc(capacity * sizeof(char));
if (str1 == NULL) return NULL;
for (c = getchar(); c != '\n' && capacity <= 100; c = getchar())
{
    if (index == capacity - 1)
    {
        str1 = (char*) realloc(str1, (++capacity) * 2 * sizeof(char));
        if (str1 == NULL) return NULL;
        capacity*=2;
    }
    *(str1 + index++) = c;
}
*(str1 + index) = '\0';
return str1;
}

int divideStringIntoSentences(char * string, char * sentences[])
{
int sentnum = 0;
*sentences = string;
for (; *string != '\0'; string++)
if (*string == '.')
{
    *string = '\0';
    *(++sentences) = (string + 1);
    sentnum++;
}
return (sentnum);
}


texts:
My MySQL query is loading very slowly (over 30 secs) and I was wandering what tweaks I can make to optimize it.

The query should return the last post with the string "?" of all threads.

SELECT FeedbackId, ParentFeedbackId, PageId, FeedbackTitle, FeedbackText, FeedbackDate
FROM ReaderFeedback as c
LEFT JOIN (SELECT max(FeedbackId) as MaxFeedbackId FROM ReaderFeedback where ParentFeedbackId IS NOT NULL GROUP BY ParentFeedbackId) as d ON d.MaxFeedbackId = c.FeedbackId
WHERE ParentFeedbackId IS NOT NULL
AND FeedbackText LIKE '%?%' GROUP BY ParentFeedbackId
ORDER BY d.MaxFeedbackId DESC LIMIT 50


texts: Add Default Rubberduck VBA Folder Annotation to VBProject.VBComponents

texts:
Currently Rubberduck VBA files all the VBProject VBComponents in that do not have a Folder Annotation in a Folder named after the VBProject.  It can be time consuming to manually organize the components for the first time and a inconvenient to add annotations to every Worksheet, Userform, Class, ...ect.  When ran my code will organize any unfiled component by ProjectName.ComponentType.
Before

After

You will need to add a reference to the Microsoft Visual Basic for Applications Extensibility 5.3 and from file options check "Trust access to VBA project object model".

Private Sub AddDefaultFolderAnnotationsToVBComponents()
    Dim Component As VBComponent
    Dim Project As VBProject

    Select Case Application.Name
    Case "Microsoft Access", "Microsoft Word"
        Set Project = IIf(True, Application, 0).VBE.ActiveVBProject

    Case "Microsoft Excel"
        Set Project = IIf(True, Application, 0).ActiveWorkbook.VBProject

    Case "Microsoft PowerPoint"
        Set Project = IIf(True, Application, 0).VBE.VBProjects(1)

    End Select

    Dim FolderName As String
    Dim HasFolder As Boolean

    For Each Component In Project.VBComponents
        With Component.CodeModule
            If .CountOfLines = 0 Then
                HasFolder = False
            Else
                HasFolder = InStr(.Lines(1, .CountOfLines), Chr(39) & "@Folder")
            End If
        End With

        If Not HasFolder Then
            Select Case Component.Type
                Case vbext_ComponentType.vbext_ct_StdModule
                    FolderName = Project.Name & ".Modules"
                Case vbext_ComponentType.vbext_ct_ClassModule
                    FolderName = Project.Name & ".Classes"
                Case vbext_ComponentType.vbext_ct_MSForm
                    FolderName = Project.Name & ".Forms"
                Case vbext_ComponentType.vbext_ct_ActiveXDesigner
                    FolderName = Project.Name & ".Designers"
                Case vbext_ComponentType.vbext_ct_Document
                    FolderName = Project.Name & ".Documents"
            End Select

            Component.CodeModule.InsertLines 1, Chr(39) & "@Folder(""" & FolderName & """)"
        End If
    Next
End Sub

Note: I purposely kept all the functionality in a single procedure for portability.
Kudos to the Rubberduck team the latest version Rubberduck VBA v2.5 is a C# WPF that follows the MVVM pattern to the letter!


texts: Recursive solution for Longest Substring Without Repeating Characters written in Elixir

texts:
Here's my recursive implementation of a sliding window algorithm to find the longest substring of a given string without repeating characters. Is there a more idiomatic-Elixir way to write this?

defmodule MyString do
  def length_of_longest_substring(string), do: string |> length_of_longest_substring(0, 0, 0, %{})

  defp length_of_longest_substring(string, start_index, end_index, longest, indexes) do
    if end_index >= String.length(string) do
      longest
    else
      currrent_char = String.at(string, end_index)
      previous_occurrence = Map.get(indexes, currrent_char, -1)
      updated_indexes = Map.put(indexes, currrent_char, end_index)

      cond do
        previous_occurrence >= start_index ->
          string |> length_of_longest_substring(previous_occurrence + 1, end_index, longest, updated_indexes)

        true ->
          longest = max(longest, end_index - start_index + 1)

          string |> length_of_longest_substring(start_index, end_index + 1, longest, updated_indexes)
      end
    end
  end
end


texts: Make all additional threads return from a method using Interlocked.Increment

texts:
I need to ensure a method is executed only by one thread at a time. Contrary to what most of the synchronization primitives do, I don't need other threads to wait, I want them to return from the method immediately if it is already executed by another thread. Additional complexity is that the method uses async/await calls.

I implemented it using Interlocked.Increment. I tested in a simple test scenario and it seems to be working. However, I'm not sure, is it a correct implementation and will it work in all cases? Or maybe there is a simpler way to achieve the same goal?

private int _threadsCount = 0;

public async Task Method()
{
    if (Interlocked.Increment(ref _threadsCount) > 1)
    {
        Interlocked.Decrement(ref _threadsCount);
        return;
    }

    try
    {
        await DoWork();
    }
    finally
    {
        Interlocked.Decrement(ref _threadsCount);
    }
}


texts:
I had already posted this question at here
and have tried to incorporate some of the suggestions given. Kindly let me know if there are still some concerns/suggestions/improvements in the code mentioned below.

#include"iostream"
#define MAX_SIZE 5
class Mystack
{
private:
    int A[MAX_SIZE];
    int top;
public:
    Mystack();
    void push(int x);
    int pop();
    int topElement();
    bool isEmpty();
    bool isFull();
    void print();
};
    Mystack::Mystack()
    {
        top = -1;
    }
    void Mystack::push(int x)
    {
        if(isFull())
        {
            std::cout << "Stack Overflow" << std::endl;
            return;
        }
        else
        {
            top++;
            A[top] = x;
        }
    }
    bool Mystack::isFull()
    {
        if (top == MAX_SIZE - 1)
        {
            std::cout << "Stack is full"<< std::endl;
            return true;
        }
        else
        {
            std::cout << "Stack is not full"<<std::endl;
            return false;
        }

    }
    int Mystack::pop()
    {
        if (isEmpty())
        {
            std::cout << "Stack Underflow" << std::endl;
            return 0;
        }
        else
        {
            std::cout << "The popped element is" << A[top];
            return A[top--];
        }
    }
    bool Mystack::isEmpty()
    {
        if (top == -1)
        {
            std::cout << "Stack is empty" << std::endl;
            return true;
        }
        else
        {
            std::cout << "Stack is not empty" << std::endl;
            return false;
        }
    }
    int Mystack::topElement()
    {
        std::cout<<"The top element is : "<< A[top];
        return A[top];
    }
    void Mystack::print()
    {
        for (int i = 0; i <=top; i++)
        {
            std::cout  << A[i]<< " ";
        }
    }
void main()
{
    Mystack s1;
    int num,choice = 1;
    while (choice >0)
    {
        std::cout << "\n1. PUSH"<< std::endl;
        std::cout << "2. TOP" << std::endl;
        std::cout << "3. IsEmpty" << std::endl;
        std::cout << "4. POP" << std::endl;
        std::cout << "5. EXIT" << std::endl;
        std::cout << "6. Print" << std::endl;
        std::cout << "7. IsFull" << std::endl;
        std::cout << "Enter the choice" << std::endl;
        std::cin >> choice;
        switch (choice)
        {
        case 1:
            std::cout << "Enter the number to be pushed" << std::endl;
            std::cin >> num;
            s1.push(num);
            break;
        case 2:
            std::cout << "Get the TOP Element" << std::endl;
            s1.topElement();
            break;
        case 3:
            std::cout << "Check Empty" << std::endl;
            s1.isEmpty();
            break;
        case 4:
            std::cout << "POP the element" << std::endl;
            s1.pop();
            break;
        case 5: exit(0);
        case 6:
            s1.print();
            break;
        case 7:
            s1.isFull();
            break;
        }
    }
    system("pause");
}


texts:
I'm writing a JavaScript/PHP file uploader and I want to start this project off on the right track. I've started with this, a JavaScript Uploader object which will handle Ajax calls, display progress, show error messages, etc. I'm just hoping to get some feedback on the way I'm setting up my scripts.

function Uploader(method) {

if(arguments.callee._singleton) return arguments.callee._singleton;
var _this = arguments.callee._singleton = this;

_this.opts = {
    form:"#uploader",
    filePath:"public/uploads/",
    errorCodes:{
        1:"No file/folder selected",
        2:"Invalid file/folder type",
        3:"File/folder exceeds upload size"
    }
}

_this.methods = {

    init: function(options) {
        for(var o in options) {
            _this.opts[o] = options[o];
        }

        _this.methods.setup();
    },

    setup: function() {

    }

}

if(_this.methods[method]) return _this.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
else if(typeof method === "object" || !method) return methods.init.apply(this, arguments);

}


texts: Optimizing priority queue streaming algorithm in C++

texts:
This is a sorting algorithm that I wrote for finding the maximum \$n\$ elements at any time in a stream of IDs and integers with unknown length. I primarily do my coding in Python, so I'm not too familiar with C++ best practices, but I wanted to write this in C++ to gain some efficiency and speed.

For all of you seasoned C++ programmers; am I following best practices here or not? If not, what improvements can I make to make this more professional? Lastly, are there any optimizations that I can make to increase its speed?

#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#include <map>
#include <chrono>

// Overload comparison operator to create a min heap
struct compare
{
  bool operator()(const int& l, const int& r)
  {
    return l > r;
  }
};

int main()
{
  // Input filenames
  std::cout << "Enter a filename for the input stream: ";
  std::string filename;
  std::cin >> filename;
  std::ifstream infile(filename);

  std::cout << "Enter a filename for the output stream: ";
  std::string output;
  std::cin >> output;
  std::ofstream outfile(output);

  // Input a value for k
  std::cout << "Enter a value for k: ";
  int k;
  std::cin >> k;
  std::cout << std::endl;

  // Declare priority queue and map
  int elements = 0;
  int replacements = 0;
  int value;
  std::string id;
  std::priority_queue<int, std::vector<int>, compare> heap;
  std::map<int, std::vector<std::string>> ids;

  // Begin read/sort timer
  std::cout << "Beginning read and sort ..." << std::endl;
  auto readsortstart = std::chrono::high_resolution_clock::now();

  // Begin read and sort
  while (infile >> id >> value){
    elements++;
    if (heap.size() < k){
      ids[value].push_back(id);
      heap.push(value);
    } else if (heap.top() < value) {
      ids[value].push_back(id);
      heap.pop();
      heap.push(value);
      replacements++;
    }
  }

  // End timer
  auto readsortstop = std::chrono::high_resolution_clock::now();
  auto readduration = std::chrono::duration_cast<std::chrono::milliseconds>(readsortstop-readsortstart).count();
  std::cout << "Read and sort completed." << std::endl << std::endl;

  // Ensure that k is not larger than the total number of lines
  k = std::min(k,elements);

  // Begin write timer
  std::cout << "Beginning write ..." << std::endl;
  auto writestart = std::chrono::high_resolution_clock::now();

  // Pop k entries off of the sorted heap to retrieve the k largest results
  for (int i = 0; i < k; i++) {
    int key = heap.top();
    outfile << ids[key].back() << " " << heap.top() << std::endl;
    ids[key].pop_back();
    heap.pop();
  }

  // End write timer
  auto writestop = std::chrono::high_resolution_clock::now();
  auto writeduration = std::chrono::duration_cast<std::chrono::milliseconds>(writestop-writestart).count();
  std::cout << "Write completed." << std::endl << std::endl;

  std::cout << "----------------------- Statistics ------------------------" << std::endl
            << "  Total number of replacements: " << replacements << std::endl
            << "  Total number of elements:     " << elements << std::endl
            << "  Read/sort time elapsed:       " << readduration << "ms" << std::endl
            << "  Write time elapsed:           " << writeduration << "ms" << std::endl;
}


texts:
I'm working on a little project and although it all works, I think I might be doing it in an incorrect way. The front end consists of a simple form that gathers input data (make and color) and once submitted, it sends the input data to a POST endpoint in express via AJAX and gets filtered to return the items I need in a JSON file. Once the data posts, I use another AJAX call to get the filtered data back to my front end to display. Again this all works, but I'm posting and getting from the same route in express. Is this all good or can I accomplish this in a better manner?

Front end:

var carList = [];

form.addEventListener('submit', function(e) {
  e.preventDefault();

  var make  = document.querySelector('.make').value.toLowerCase(),
      color = document.querySelector('.color').value.toLowerCase();

  $.ajax({
    method: 'POST',
    url: '/cars',
    data: {
      make: make,
      color: color
    },
    success: function(data) {}
  });

  $.ajax({
    method: 'GET',
    url: '/cars',
    success: function(data) {
      carList = data;
      populateList();
    }
  });
});

ExpressJS:

function readJSONFile(filename, callback) {
  fs.readFile(filename, (err, data) => {
    if(err) {
      callback(err);
      return;
    }
    try {
      callback(null, JSON.parse(data));
    } catch(exception) {
      callback(exception);
    }
  });
}

let make  = '',
    color = '';

app.get('/cars', (req, res) => {
  let newList = [];

  readJSONFile('cars.json', (err, json) => {
    var items = json.cars.filter((item) => {
      if (item.type.toLowerCase() == make || item.color.toLowerCase() == color) {
        newList.push(item);
      }
    });
    if (err) throw err;
    res.send(newList);
  });
});

app.post('/cars', (req, res) => {
  make = req.body.make;
  color = req.body.color;
});


texts: More efficient way of counting the number of values within an interval?

texts:
Suppose I have a text file which contains 10,000 random values between 0 and 1, and I want to count the number of values within a specific interval.  An example may explain it more clearly.

Suppose my Datefile.txt contains data like:

0.0102244
0.028072
0.0144578
0.064578
0.08148
0.012749
0.12749.....and 10,000 more values

And I want to count the number of values within the interval 0.05 (i.e. it searches for the values within the range 0.0 to 0.05, then 0.05 to 0.1 and so on). For the example above, the output will be:

In range 0 to 0.05, total values 4
In range 0.05 to 0.1, total values 2
In range 0.1 to 0.15, total values 1...etc.

Here is my code:

int main(){

double area;
double a=0,b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;

ifstream theFile ("Datafile.txt");

  while(theFile >>area){

    if (area<=0.05){
        a++;
    }

    else if (area<=0.1){
        b++;
    }
    else if (area<=0.15){
        c++;
    }
    else if (area<=0.2){
        d++;
    }
    else if (area<=0.25){
        e++;
    }
    else if (area<=0.3){
        f++;
    }
    else if (area<=0.35){
        g++;
    }
    else if (area<=0.4){
        h++;
    }
    else if (area<=0.45){
        i++;
    }
    else if (area<=0.5){
        k++;
    }

    else if (area<=0.55){
        l++;
    }
    else if (area<=0.6){
        m++;
    }
    else if (area<=0.65){
        n++;
    }
    else if (area<=0.7){
        o++;
    }
    else if (area<=0.75){
        p++;
    }
    else if (area<=0.8){
        q++;
    }
    else if (area<=0.85){
        r++;
    }
    else if (area<=0.9){
        s++;
    }
    else if (area<=0.95){
        t++;
    }
    else if (area<=1.0){
        u++;
    }

}

Though my code is working fine, it might not be the most efficient way. So I put my code here for review. Can anyone suggest a better way of doing this?

Updated (based on the answer of ChrisWue)

#include <iostream>
#include <cmath>
#include <vector>
#include <fstream>

using namespace std;

int main(){

const double bucket_size = 0.05;
double area=0;
int number_of_buckets = (int)ceil(1 / bucket_size);
std::vector<int> histogram(number_of_buckets);
ifstream theFile("Datafile.txt");

while (theFile >> area) {
    int bucket = (int)floor(area / bucket_size);
    histogram[bucket] += 1;
}
for(auto loop = histogram.begin(); loop != histogram.end();++loop)
    {

cout<<bucket_size<<"\t"<<number_of_buckets<<endl;

}

return 0;
}

For the data-

0.0102244
0.028072
0.0144578
0.064578
0.08148
0.012749
0.12749.....

it gives the output like this-

0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20
0.05    20

What am I doing wrong?


texts:
I have this menu in jQuery that works perfectly, but I think it would be better if, instead of using class="btn-accordion" for each li, I just had a single class="accordion-menu".

Is that possible or is the code OK?

my html:

jquery

  $('.btn-accordion').on('click', function() {
        $(this).closest('li').toggleClass('is-active');
  });

scss:

.btn-accordion {
  color: red;
  background-color: blue;
  .fa {
    color: white;
  }
  &.is-active {
    color: blue;
    background-color: red;
    .fa {
      color: yellow;
    }
  }
}


texts: Extending prototype of given instance from factory method

texts:
I created a rubber ball by extending instance of b2Body prototype of Box2D.js. I get the instance from factory method b2World#CreateBody.

var ball = world.CreateBody(bodyDef);

I extended the instance in the constructor of my RubberBall prototype. In result, I made the constructor very long.

function RubberBall(position) {
  var ball = world.CreateBody(bodyDef);
  :
  :
  very long implementation to extend `ball` to make it a rubber ball
}

How can I extract the extending ball part and make the constructor simple?

http://jsfiddle.net/suzuki/XXmeR/


texts: Checking for a values existence: slice iteration vs map lookups in Go

texts:
Assuming I have the following slice:

mySlice := []string{"one", "two", "three"}

and I want to know whether or not it contains a given string, say "three".

I could iterate over each entry:

for i, v := range mySlice {
  if v == "three" {
    return i
  }
}

But I could also convert the slice to a map:

myMap := make(map[string]string)
for i, v := range mySlice {
  myMap[v] = i
}

if v, ok := myMap["three"]; ok {
  // three exists in original slice
}

I think that the first is faster than the second for a single lookup, but at what point does the second method become faster? Would converting to a map be more performant if I'm doing 2 or more lookups? Or does it depend on the size of the array?


texts:
Question 2 of Homework 11 from Berkeley's CS6 1A says:

  Implement permutations, a generator function that takes in a lst and outputs all permutations of lst, each as a list (see doctest for an example). The order in which you generate permutations is irrelevant.

This is my solution:

def permutations(lst):

    if not lst:
        yield []
        return
    "*** YOUR CODE HERE ***"
    if type(lst)==tuple:
        t=lst
        lst=[]
        for elem in t:
            lst+=[elem]
    if type(lst)==str:
        lst=list(lst)

    for elem in lst:
        if elem:
            l_temp=[lst[0]]
            lst=lst[1:]
            lst.extend(l_temp)
            temp=list(lst[1:])
            r_list=[]
            lst_of_lst=[]
            r_list+=[lst[0]]
            while len(lst_of_lst)!=len(lst)-1:
                holder=temp[1:]
                t_holder=[temp[0]]
                temp=[]
                temp.extend(holder)
                temp.extend(t_holder)
                if len(r_list)==1:
                    r_list.extend([e for e in temp])
                    lst_of_lst+=[r_list,]
                    r_list=[]
                    r_list+=[lst[0]]
            yield lst_of_lst

Test cases:

>>> sorted(permutations([1, 2, 3]))
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
>>> type(permutations([1, 2, 3]))
<class 'generator'>
>>> sorted(permutations((10, 20, 30)))
[[10, 20, 30], [10, 30, 20], [20, 10, 30], [20, 30, 10], [30, 10, 20], [30, 20, 10]]
>>> sorted(permutations("ab"))
[['a', 'b'], ['b', 'a']]

I need some suggestions in order to improve my code.


texts: Simple integer range for C++11 range-based for loops

texts:
I'm really tired of having to type

for (int iSomething = rangeBegin; iSomething < rangeEnd; ++iSomething)
{
   ...
}

whenever I want to iterate over an integer range (most IDEs help with the typing, but still it looks so verbose, naming the integer 3 times!)

I wanted something like this:

for (int iSomething : LoopRange(rangeBegin, rangeEnd))
{
   ...
}

Or if rangeBegin is 0 (the majority of the cases) then a simple

for (int iSomething : LoopRange(rangeEnd))
{
   ...
}

My very simple implementation:

class LoopRangeIterator
{
public:
    LoopRangeIterator(int value_)
        : value(value_){}

    bool operator!=(LoopRangeIterator const& other) const
    {
        return value != other.value;
    }

    int const& operator*() const
    {
        return value;
    }

    LoopRangeIterator& operator++()
    {
        ++value;
        return *this;
    }

private:
    int value;
};

class LoopRange
{
public:
    LoopRange(int from_, int to_)
        : from(from_), to(to_){}

    LoopRange(int to_)
        : from(0), to(to_){}

    LoopRangeIterator begin() const
    {
        return LoopRangeIterator(from);
    }

    LoopRangeIterator end() const
    {
        return LoopRangeIterator(to);
    }

private:
    int const from;
    int const to;
};

I named it LoopRange to make it clear that it's for loops and it isn't some general integer range class that you would use for intersecting or building union etc.

Of course this class could be generalized in many ways, but I think if you need more complex functionality (e.g. custom step sizes, double values), then you are doing something special and you are better off writing the explicit for loop.

What do you think about it?
If I use such a thing throughout my project, would it confuse and disturb/distract people too much compared to just using the classic and verbose for(...; ...; ...) style?


texts:
I've written some Python 3 code that computes the \$n\$-th prime. I implemented first a naive isprime function that looks for divisors of \$m\$ between \$2\$ and \$\lfloor \sqrt m \rfloor+1\$. Then a loop looks for primes and stops when the \$n\$th one is found.

from math import sqrt
def isprime(n):
    for i in range(2,int(sqrt(n))+1):
        if n%i==0:
            return False
    return True

def prime(n):
    m=3
    i=2
    ans=3
    while i<=n:
        if isprime(m):
            i=i+1

            ans=m
            m=m+2
        else:
            m=m+2
    return ans

It occured to me that prime performs a lot of unnecessary computations: for a given \$m\$, it checks if composite numbers (like 14,16) divide \$m\$. That is useless, and it would be more efficient to look only for prime divisors of \$m\$. This led me to some "storage" approach, where I maintain a list of all the primes I've found, and use them to test for divisors of the next numbers.

from math import sqrt
def prime(n):
    list=[2]
    i=1
    m=3
    while i<n:
        flag=0
        for p in list:
            if m%p==0:
                flag=1
                break
            else:
                continue
        if flag==0:

            list.append(m)
            m=m+2
            i=i+1
        else:
            m=m+2
    return list

The \$n\$th prime is given by prime(n)[-1]

I have an issue with the performance of the second code: it's really slow.
On my computer, according to the Unix command time python code.py, computing the \$6000\$-th prime with the first code takes \$0.231\$ seconds, and \$2.799\$ seconds with the other approach!

Why is the clever way slower than the naive one?


texts: Changing cuts to sed for parsing dates from apache log (common log file)

texts:
Would switching my cuts below to SED improve performance? I am trying to get a per date count of requests for the last two weeks from a server log. The script runs, but slowly (comes in around 14 minutes). The file is 8,867,820 lines long and around 1.9G. I would guess grep, SED (or AWK) would do this more efficiently but my initial attempts failed and I resorted to cuts.

Is my piping and redirection causing unnecessary delay? Is this simply an issue of a large file?

# Log is in common log format
# host ident authuser date request status bytes
# 127.0.0.1 user-identifier frank [10/Oct/2000:13:55:36 -0700] "GET /apache_pb.gif HTTP/1.0" 200 2326

#initialize check date and end date
ckdate=$(date --date='1 days ago' +%s)
#enddate=$(date --date='1 fortnight ago' +%s)
enddate=$(date --date='3 days ago' +%s) #test date for shorter term

#feed log in reverse into loop
# tac to print log backwards into loop (newest log entry at bottom of file)
# chkdate is seconds most recent date from line is
tac "/etc/httpd/logs/access_log" | \
 while read line && (( $ckdate >= $enddate ))
do
  #send line into output, cutting out the date-time (-f4),
  # and cleaning for date only (-d: f1)
  #echo $line | cut -d ' ' -f4 | tr -d '[' | cut -d: -f1

  echo $line | cut -d ' ' -f4 | tr -d '[' \
    | cut -d: -f1 | tr '/' '-' | xargs -i date -d '{}' +'%Y-%m-%d'

  #update the check date based on latest line, formatting as seconds since 1970
  ckdate=$( ( echo $line | cut -d ' ' -f4 | tr -d '[' \
    | cut -d: -f1 | tr '/' '-' | xargs -i date -d '{}' +'%s' ) )
done | sort | uniq -c | head -n -1 | head -n 2
#put output into sorted list, with uniq counts, and trim outer bounds


texts: ObservingCache - scheduled task executor that returns a result

texts:
I wrote a utility class called ObservingCache, which receives a task in the form of Supplier<T> and an interval, computes the task every [interval] millis and allows its result to be queried via the getItems() method.
I'm using for making sure that outside resources (such as configuration files or DB tables) are always in sync with the app and can be modified without having to restart the application.

The code is as follows:

public class ObservingCache<T> {
  private static final int DEFAULT_CACHE_REFRESH_INTERVAL = 10 * 60 * 1000; // 10 minutes
  private static final int DEFAULT_THREAD_POOL_SIZE = 10;

  private static volatile ScheduledExecutorService executor;

  protected T items;

  public ObservingCache(Supplier<? extends T> syncFunc) {
      this(syncFunc, DEFAULT_CACHE_REFRESH_INTERVAL, true);
  }

  public ObservingCache(Supplier<? extends T> syncFunc, boolean firstRunBlocking) {
      this(syncFunc, DEFAULT_CACHE_REFRESH_INTERVAL, firstRunBlocking);
  }

  public ObservingCache(Supplier<? extends T> syncFunc, int intervalMillis) {
      this(syncFunc, intervalMillis, true);
  }

  public ObservingCache(Supplier<? extends T> syncFunc, int intervalMillis, boolean firstRunBlocking) {
      initExecutor();
      Runnable task = () -> {
          T result = syncFunc.get();
          if (result != null) {
              items = result;
          }
      };
      if (firstRunBlocking) {
          task.run(); // First run is blocking (saves a lot of trouble later).
      }
      executor.scheduleAtFixedRate(task, firstRunBlocking ? intervalMillis : 0, intervalMillis, TimeUnit.MILLISECONDS);
  }

  private void initExecutor() {
      if (executor == null || executor.isShutdown()) {
          synchronized (this) {
              if (executor == null || executor.isShutdown()) {
                  executor = Executors.newScheduledThreadPool(DEFAULT_THREAD_POOL_SIZE);
              }
          }
      }
  }

  public T getItems() {
      return items;
  }
}

I'd really like to hear your opinion about this piece of code, especially regarding the subject of potential memory leaks caused by either a bug of mine or any known issue with Java 8's ScheduledExecutorService class.


texts:
My client needs their Google AdWords destination URL query parsed and the values spell checked to eliminate any typos ("use" instead of "us", etc).

I'm pulling the data using the AdWords API and putting it into a dateframe for manipulation. Everything works, but there are over 100,000 records every pull and sometimes the code takes hours and hours to run. Is there a way to optimize the following code blocks?

def parse_url(df):
    for index, row in df.iterrows():
        parsed = urlparse(str(row['Destination URL'])).query
        parsed = parse_qs(parsed)
        for k, v in parsed.iteritems():
            df.loc[index, k.strip()] = v[0].strip().lower()
    return df

def typo_correct(urlparams, df, dictionary):
    for index, row in df.iterrows():
         for w in urlparams:
            if df.loc[index,w] == None or len(df.loc[index,w])<2 or w == 'account':
                pass
            else:
                high = 0.0
                word = None
                for item in dictionary:
                    prob = lev.ratio(str(df.loc[index,w]), item)
                    if prob == 1.0:
                        high = prob
                        word = str(df.loc[index, w])
                        continue
                    elif prob > high:
                        high = prob
                        word = item+"*"
                    else:
                        pass
                if high != 1.0:
                    df.loc[index,w] = word
                    df.loc[index, 'Fix'] = "X"
    return df

Basically it parses out the query parameters, and puts them into a dictionary. The script takes the keys and creates headers in the dataframe, then the first function above iterates through and puts the values in the correct location.

The second one then goes through each value and checks if it's in a dictionary text file and uses the Levenshtein edit distance to find the right word in the case of a typo.

I'm not sure if this is something that can be done using map or apply as I haven't been working with Pandas long. Does anyone have any suggestions?


texts:
This is my first C program that is not "Hello World" level; I would welcome ideas to make it more efficient and readable.
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <stdbool.h>
#define FALSE 0
#define TRUE  1

bool incircle(double x, double y);

int main (int argc, char *argv[]) {
    unsigned long long loops, cpoints, i;
    double             approx, cpu_time_used;
    int                seed;
    clock_t start, end;
    cpoints  = 0;
    loops = atoll(argv[1]);
    seed = time(NULL);
    srand(seed);
    start = clock();
    for (i = 0; i < loops; ++i)
    {
        double x = (rand() + 1.0) / (RAND_MAX+2.0);
        double y = (rand() + 1.0) / (RAND_MAX+2.0);
        if ( incircle(x,y) !=FALSE )
            cpoints+=1;
    }
    end = clock();
    cpu_time_used = ((double) (end - start)) / CLOCKS_PER_SEC;
    approx=4*(cpoints/(double)i);
    printf ("%llu" "%s" "%llu"   "%s" "%0.9f" "%s" "%0.3f\n",
            i,     " ", cpoints, " ", approx, " ", cpu_time_used);
    return 0;
}

bool incircle(double x, double y) {
        return ( x * x + y * y <= 1 );
    }