texts:
I have the following functions:

 function getExample($id, $otherid) {
            global $db;
            $query = 'SELECT * FROM examples WHERE id = :id AND otherid= :otherid';
            try {
                $statement = $db->prepare($query);
                $statement->bindValue(':id', $id);
                $statement->bindValue(':otherid', $otherid);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                return $result;
            } catch (PDOException $e) {
                $error_message = $e->getMessage();
                display_db_error($error_message);
            }
        }

 function getSecExample($id) {
            global $db;
            $query = 'SELECT * FROM examples WHERE id= :id';
            try {
                $statement = $db->prepare($query);
                $statement->bindValue(':id', $id);
                $statement->execute();
                $result = $statement->fetchAll();
                $statement->closeCursor();
                return $result;
            } catch (PDOException $e) {
                $error_message = $e->getMessage();
                display_db_error($error_message);
            }
        }

Is there a way to make this one function instead of two? I want it to be secure and done with the best practices.


texts: Deque Container with an instant consumer for high speed object dumping

texts:
I currently have a container that has two features it allows adding objects to it and at the same time an independent thread continuously consumes items from it. It is a FIFO type deque. Which receives object at an extremely high rate. Following is the code for the container

std::deque<Some_object*> my_container;

void Container::Add_item(Some_object* obj)
        {
            try
            {
                {//Begin Lock
                    boost::lock_guard<boost::mutex> lock(mutex_lk);
                    my_container.push_back(obj);
                }
                condition_consumer_silo.notify_one();
            }
            catch (std::exception& e)
            {
                __debugbreak();
            }
        }

        //This method continuously consumes object in FIFO order
        void Container::Consume_Object()
        {
            while(true)
                {
                    Some_object* obj;
                    {//Lock
                        try
                        {
                            boost::unique_lock<boost::mutex> lock(mutex_lk);
                            while(my_container.empty()) { condition_consumer_silo.wait(lock); }//Block if empty - for spurious wakeup

                            if(!my_container.empty())
                            {
                                obj = my_container.front();
                                my_container.pop_front();
                            }
                        }
                        catch (std::exception& e)
                        {
                            __debugbreak();
                        }

                    }//Unlock
                    try
                    {
                            Consume_obj(obj);

                     } catch (std::exception& e)
                     {
                        __debugbreak();
                     }
                }//end while
        }

Could this container be improved ? Is there a library out there that would do a better job.


texts: Generate all possible permutations from a string with character repetitions

texts:
I want to know if my code is good, with reasonable efficiency, and if it is possible to improve my code and how. What would you suggest?

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class FindAllPermutationsWithRepetitions {

    public static void main(String[] args) {
        String str = "ferarri";
        Set<String> permutations = getPermutations(str);

        int i = 1;
        for(String s : permutations){
            System.out.println(i++ + ": " + s);
        }

        /* check correctness */
        System.out.println("\nThere must be " +  numOfArrangements(str) + " values");

    }

    public static Set<String> getPermutations(String remained){
        if(remained.length() <= 1){
            Set<String> set = new HashSet<String>();
            set.add(remained);
            return set;
        }

        char c = remained.charAt(0);
        Set<String> old_permutations = getPermutations(remained.substring(1));
        Set<String> new_permutations = new HashSet<String>();

        for(String old_s : old_permutations){
            for(int j = 0; j < old_s.length(); j++){
                new_permutations.add(old_s.substring(0, j) + c + old_s.substring(j));
            }
            new_permutations.add(old_s + c);
        }

        return new_permutations;
    }

    public static int factorial(int num){
        int result = 1;

        for (int i = 1; i <= num; i++) {
            result = result * i;
        }

        return result;
    }

    public static int numOfArrangements(String str){
        HashMap<Character, Integer> hm = new HashMap();

        for(char key : str.toCharArray()){
            if(hm.containsKey(key)) hm.put(key, hm.get(key) + 1);
            else hm.put(key, 1);
        }

        int divisor = 1;
        for(Integer value : hm.values()){
            divisor *= factorial(value);
        }

        return factorial(str.length()) / divisor;
    }
}


texts: Find the greatest common divisor of n numbers

texts:
Just had this as a practice test problem and I'm curious how to optimize for performance. Thanks!

The greatest common divisor (GCD), also called the highest common factor (HCF) of N numbers is the largest positive integer that divides all numbers without giving a remainder.

Write an algorithm to determin the GCD of N positive integers.

function generalizedGCD(num, arr)
{
    // find the factors of lowest member of arr and then check if every other number is divisible
    arr.sort( function( a, b ) { return a-b; });
    const lowest = arr[0];
    const factors = [];

    for ( let i = 1; i <= lowest; i++) {
        if ( lowest % i === 0 ) {
            factors.push(i);
        }
    }

    // now check to see if each member of the factors array divides into each member of the original numbers array. If not, remove it from the array.
    for ( let j = 1; j < num; j++) {
        for ( let k = 0;  k < factors.length; k++) {
            if ( arr[j]  % factors[k] != 0 ) {
                factors.splice( k, 1);
            }
        }
    }

    return factors[factors.length-1];
}


texts:
Here is my shot at Homework 8 of CIS-194 (from Spring '13). The problem is about a hierarchy of employees at a company (a tree), each node being of type Employee, each described by a label (empName :: String) and an integer value (empFun :: Integer). We need to choose a subset of employees so that no two chosen employees have a parent-child relationship within the tree and the sum of empFuns of the chosen employees is maximised.
Some of the outline and structure of this code is based on what was suggested by the document, but I am curious to know if the rest of it is consistent and idiomatic Haskell. I'm not sure what I'm expecting as feedback, but any is welcome.
module Party where

import Data.List ( sort )
import Data.Tree ( Tree(Node) )
import Employee ( Employee(empFun, empName), Fun, GuestList(..) )

instance Semigroup GuestList where
    (GL a b) <> (GL c d) = GL (a ++ c) (b + d)

instance Monoid GuestList where
    mempty = GL [] 0

glCons :: Employee -> GuestList -> GuestList
glCons emp (GL a b) = GL (a ++ [emp]) (empFun emp)

moreFun :: GuestList -> GuestList -> GuestList
moreFun = max

treeFold :: (a -> [b] -> b) -> Tree a -> b
treeFold f (Node label subtree) = f label (map (treeFold f) subtree)

nextLevel :: Employee -> [(GuestList, GuestList)] -> (GuestList, GuestList)
nextLevel emp subList = (glCons emp (foldMap snd subList), foldMap (uncurry max) subList)

maxFun :: Tree Employee -> GuestList
maxFun tree = uncurry moreFun $ treeFold nextLevel tree

getFormattedGL :: GuestList -> String
getFormattedGL gl = unlines (("Total fun " ++ show (fun gl)) : sort (map empName (emps gl)))
    where fun (GL _ fun) = fun
          emps (GL emps _) = emps

work :: [Char] -> String
work = getFormattedGL . maxFun . read

main :: IO ()
main = readFile "company.txt" >>= putStrLn . work


texts: Merge sort implementation and improvements

texts:
I would like your opinion on my Java implementation of the merge sort algorithm on an integer array, since I'm not really into algorithms I'd like to know from you if this is a correct implementation and if it can be improved somehow.

For example, it requires a lot of space for the sub arrays, but this should be normal for the merge sort as it is not space constant. I tested it and it seems to work.

private int[] mergeSort(int[] array) {

    if (array.length == 1) return array;

    int start = 0;
    int end = array.length;
    int middle = (end-start)/2;

    int[] left = Arrays.copyOfRange(array, start, middle);
    int[] right = Arrays.copyOfRange(array, middle, end);

    int[] sortedLeft = mergeSort(left);
    int[] sortedRight = mergeSort(right);

    return merge(sortedLeft, sortedRight);

}

private int[] merge(int[] first, int[] second) {

    int[] result = new int[first.length + second.length];

    int posFirst = 0;
    int posSecond = 0;
    int resultPos = 0;

    while (resultPos < result.length) {

        if (posFirst == first.length) {
            result[resultPos++] = second[posSecond++];
        }
        else if (posSecond == second.length) {
            result[resultPos++] = first[posFirst++];
        }
        else if (first[posFirst] > second[posSecond]) {
            result[resultPos++] = second[posSecond++];
        } else {
            result[resultPos++] = first[posFirst++];
        }

    }

    return result;

}


texts:
Could you please help me to review my first function (modified from an example) in terms of best practice, coding style suggestions and any obvious language mistake/improvements?

unsigned int edit_distance(const vector<string> &s1, const vector<string> &s2)
{
    const size_t len1 = s1.size(), len2 = s2.size();
    vector<vector<unsigned int>> d(len1 + 1, vector<unsigned int>(len2 + 1));

    d[0][0] = 0;
    for(unsigned int i = 1; i <= len1; ++i) d[i][0] = i;
    for(unsigned int i = 1; i <= len2; ++i) d[0][i] = i;

    for(unsigned int i = 1; i <= len1; ++i)
            for(unsigned int j = 1; j <= len2; ++j)
            {
                unsigned int a = d[i - 1][j] + 1;
                unsigned int b = d[i][j - 1] + 1;
                unsigned int c = d[i - 1][j - 1] + (s1[i - 1] == s2[j - 1] ? 0 : 1);
                        d[i][j] = std::min( std::min(a,b), c);
            }
    return d[len1][len2];
}


texts:
I've seen a few TTT related posts recently, and thought I might learn something or be reminded of certain techniques from attempting my own rendition. Here is that attempt! Hopefully any new coders can benefit from this as well. Any improvement suggestions are welcome, and numpy, scipy & bitwise operations are open to aid optimization.

ttt.py

import numpy as np
from random import randint

def print_board(board):
    print("""
  +---+---+---+
c | {}   {}   {} |
  +   +   +   +
b | {}   {}   {} |
  +   +   +   +
a | {}   {}   {} |
  +---+---+---+
    1   2   3
""".format(*list(x if x != '0' else ' ' for x in board)))

def check_for_win(board):
    def check_diagonal(dia):
        return '0' not in dia and len(set(dia)) == 1

    a = np.array(board).reshape(3, 3)

    # check lr diagonal
    if check_diagonal(a.diagonal()):
        return True

    # check rl diagonal
    if check_diagonal(np.fliplr(a).diagonal()):
        return True

    # check rows & cols
    for matr in [a, np.transpose(a)]:
        for row in matr:
            if '0' not in row and len(set(row)) == 1:
                return True

    return False

if __name__ == "__main__":
    board = ['0'] * 9
    codes = ('c1', 'c2', 'c3', 'b1', 'b2', 'b3', 'a1', 'a2', 'a3')
    turn, user = 1, 'X' if bool(randint(0, 1)) else 'O'
    print('Welcome! First to play is %s!' % user)
    print_board(board)

    while True:
        print('Player %s: ' % user)
        code = input().strip().lower()

        if code in codes:
            idx = codes.index(code)
            board[idx] = user
            print_board(board)

            if turn >= 5:
                if '0' not in board:
                    print("Aw, it's a draw!")
                    exit()
                elif check_for_win(board):
                    print('%s won in %d turns! Congratulations!' % (user, turn))
                    exit()

            user = 'X' if user == 'O' else 'O'
            turn = turn + 1
        else:
            print("Hmm, that's not a valid input.")


texts: Simplex number calculation (all dimensions) in python

texts:
How can I calculate simplex numbers in all dimensions?
Example:

dimension:     2|      3|      4|
simpl(1)       1|      1|      1|
simpl(2)       3|      4|      5|
simpl(3)       6|     10|     15|
simpl(4)      10|     20|     35|
simpl(5)      15|     35|     70|

First I considered about a recursive implementation (in python):

def simplex(n, dim):
    if dim == 1:
        return n
    else:
        i = 1
        ret = 0
        while i <= n:
            ret += simplex(i, dim-1)
            i+=1
        return ret

The algorithm works, but because of the recursion its really slow, especially if your dimension number is 5 or higher.


texts: Using Ramda in point-free way to transform data into new format

texts:
Recently I asked on SO about using point free methods to rearrange some data

The idea was to turn data in this format:

const data = [
  {
    timeline_map: {
      "2017-05-06": 770,
      "2017-05-07": 760,
      "2017-05-08": 1250,
    }
  }, {
    timeline_map: {
      "2017-05-06": 590,
      "2017-05-07": 210,
      "2017-05-08": 300,
    }
  }, {
    timeline_map: {
      "2017-05-06": 890,
      "2017-05-07": 2200,
      "2017-05-08": 1032,
    }
  }
]

Into this:

const hope = [
  ["2017-05-06", 770, 590, 890],
  ["2017-05-07", 760, 210, 2200],
  ["2017-05-08", 1250, 300, 1032],
]

The answers I got seemed kind of verbose in my opinion however (though I've no idea if they are better or worse than mine I haven't checked performance yet) so I spent more time studying Ramda and have come up with a solution of my own I like a little better. However I've only been doing this a little over a week so I'm sure it can be improved.

My code:

const datesValuesReducer = (accum, curr) => {
  if (accum.hasOwnProperty(curr[0])) {
    accum[curr[0]] = accum[curr[0]].concat(curr[1])
  } else {
    accum[curr[0]] = [curr[0], curr[1]]
  }
  return accum
}

const res = R.pipe(
  R.pluck('timeline_map'),
  R.map(R.toPairs),
  R.flatten,
  R.splitEvery(2),
  R.reduce(datesValuesReducer, {}),
  R.values
)

console.log(res(data))

Three points of possible concern:

1) Omitting R.flatten and R.splitEvery(2) get pretty close to what Is being output directly from R.map(R.toPairs) so maybe there is a way to deal with that data more directly and those methods can be omitted.

2) datesValuesReducer is pretty complex, maybe it could be simplified. I'm not sure if having the accum and curr means this solution isn't entirely "point free". Thoughts?

3) Also, I use pipe in favor over compose; I just find it reads more naturally. Maybe someone has some opinions about that.

JSBIN


texts:
I wrote a fully working VBA macro that goes through inputed client ID's and returns the specified commission fee for that client.

The code 100% works, however I need to have it so that my boss is able to easily add new clients with their special commission %'s to the list, without having to go through the VBA code.

How can I make a simplified VBA macro or just type an Excel function to do exactly what my code below does, but make it versitile to the special klient table?

The main Excel table looks like this:

The table with the special klients, commission fees, currency, markets, looks like this:

Option Explicit

Sub komisijas_calc_Click()

'Declare the variables
Dim klienta_nr As Long
Dim ISIN As String
Dim Cena As Double
Dim Skaits As Double
Dim Komisija As Double
Dim vk As String
Dim Summa As Double
Dim kSheet As Worksheet

Dim lngFirstRow As Long: lngFirstRow = 2
Dim lngLastRow  As Long
Dim lngCol      As Long: lngCol = 2
Dim lngCounter  As Long
Dim lngKom As Long: lngKom = 11

Set kSheet = ThisWorkbook.Sheets("spec_klienti")

With Worksheets(1)
    lngLastRow = .Cells(.Rows.Count, lngCol).End(xlUp).Row

    For lngCounter = lngFirstRow To lngLastRow

    klienta_nr = Range("B" & lngCounter).Value
    ISIN = Range("E" & lngCounter).Value
    Cena = Range("H" & lngCounter).Value
    Skaits = Range("I" & lngCounter).Value
    vk = Range("D" & lngCounter).Value
    Summa = Cena * Skaits

Select Case klienta_nr

    Case 111111
                '(Vācija, Francija, Nīderlandes, Itālija, Īrija) - 30 EUR MIN
                If klienta_nr = 111111 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                    Komisija = Summa * 0.01
                    .Cells(lngCounter, lngKom) = Komisija
                        End If
                If klienta_nr = 111111 And Komisija <= 30 Then
                    .Cells(lngCounter, lngKom) = 30
                        End If

                If klienta_nr = 1111111 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
                    Komisija = Summa * 0.003
                    If Komisija >= 40 Then
                        .Cells(lngCounter, lngKom) = 40
                            End If
                        End If

    Case 2222222
                '(Vācija, Francija, Nīderlandes, Itālija, Īrija) - 30 EUR MIN
                If klienta_nr = 222222 And (Left(ISIN, 2) = "DE" Or Left(ISIN, 2) = "FR" Or Left(ISIN, 2) = "NL" Or Left(ISIN, 2) = "IT" Or Left(ISIN, 2) = "IE") Then
                    Komisija = Summa * 0.01
                    .Cells(lngCounter, lngKom) = Komisija
                        End If
                'Set 30 EUR Min
                If klienta_nr = 2222222 And Komisija <= 30 Then
                    .Cells(lngCounter, lngKom) = 30
                        End If

                If klienta_nr = 2 And (Left(ISIN, 2) <> "DE" Or Left(ISIN, 2) <> "FR" Or Left(ISIN, 2) <> "NL" Or Left(ISIN, 2) <> "IT" Or Left(ISIN, 2) <> "IE") Then
                    GoTo AllElseFails
                        End If

Case Else

AllElseFails:

              'IP2, 0.03% komisija, 40 EUR/USD Max
                If Right(vk, 1) = 1 Or Right(vk, 1) = 8 Then
                    Komisija = Summa * 0.003
                    .Cells(lngCounter, lngKom) = Komisija
                        End If
              'IP1, 0.1% komisija, 40 EUR/USD Max
                If Right(vk, 1) = 7 Then
                    Komisija = Summa * 0.01
                    .Cells(lngCounter, lngKom) = Komisija
                        End If
                'Komisija MAX is 40, so anything >=40 equals 40
                If Komisija >= 40 Then
                    .Cells(lngCounter, lngKom) = 40
                        End If
            'End If
     End Select
   Next lngCounter
  End With
End Sub


texts: Creating a script to automate implicit remoting

texts:
Goal:

I am attempting to create a script that would automatically establish a PSSession to a Windows server for implicit remoting.

Problem:

Export-PSSession : Proxy creation has been skipped for the '%' command, because Windows PowerShell could not verify the safety of the command name.
At Z:Somewhere\aScript.ps1:12 char:3
+   Export-PSSession -Session $ServerPS -OutputModule 'First Module' - ...
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Export-PSSession], InvalidOperationException
    + FullyQualifiedErrorId : ErrorSkippedUnsafeCommandName,Microsoft.PowerShell.Commands.ExportPSSessionCommand

Side notes:

A large number of users will use this script to establish PSSessions daily, I am trying to find the most efficient way to get all the users to access these modules - Amodule, Bmodule and Cmodule. Additionally, the script still works despite the above mentioned error.

Here is a sample of my script:

$Server = New-PSSession -ComputerName ServerPS -Authentication Kerberos
Set-Alias -Name go -Value Get-CustomMods -Description 'Gets the modules'
function Get-CustomMods
{
  # Import first module
  Write-Verbose -Message 'Importing First module'
  Invoke-command { import-module 'Amodule.ps1' } -session $ServerPS
  Export-PSSession -Session $Server -OutputModule 'Amodule' -Force -AllowClobber
  # Import second module
  Write-Verbose -Message 'Importing Second Module'
  Invoke-command { import-module 'Bmodule.ps1'} -session $ServerPS
  Export-PSSession -Session $Server -OutputModule 'Bmodule' -Force -AllowClobber
  # Import third module
  Write-Verbose -Message 'Importing Third Module'
  Invoke-command { import-module 'Cmodule.ps1' } -session $ServerPS
  Export-PSSession -Session $Server -OutputModule 'Cmodule' -Force -AllowClobber
}

Question:

Is there a more effective way to structure/write this script given my goal and problem?


texts: Pattern finding function for years between 1998 and 2017 with several test cases

texts:
Pattern matching for years, I need to be able to return all years from a string.

When there is a dash "-" I need to return all numbers between. For example, '2004-2006' should return an array of numbers [2004,2005,2006];
If the number at the beginning of the dash is larger than the number following it, nothing should be printed out. For example '2006-2005' should return [].
years between commas should simply be returned as long as they do not exceed the current year, and are not less than 1999. For example '1998,2020' should return an empty array [].
There should be no duplicates and the values should be ordered.

I believe my code could be written in a more elegant and consise way.

Here are my test cases:

assert.deepEqual(parseRange('2002-2005, 2002-2005, 2002 - 2005'), [2002, 2003, 2004, 2005]);
assert.deepEqual(parseRange('2017'), [2017]);
assert.deepEqual(parseRange('2017 - 2015'), []);
assert.deepEqual(parseRange('2015 - 2015'), [2015]);
assert.deepEqual(parseRange('1999 , 2000,    , 2008'), [1999, 2000, 2008]);
assert.deepEqual(parseRange('2015, 2014, 2010'), [2010, 2014, 2015]);
assert.deepEqual(parseRange('1999, 3000'), [1999]);
assert.deepEqual(parseRange('1998, 2020'), []);

Here is my working Code

function parseRange(string) {
  return [...new Set(string.split(',').map(range => range.includes('-') ? range.split('-').map(num => +num) : +range)
    .filter(set => Array.isArray(set) ? set[0] <= set[1] : set > 1998 && set <= new Date().getFullYear()).reduceRight((arr, val) =>
      arr.concat(Array.isArray(val) ? Array(val[1] - val[0] + 1).fill().map((_, num) => val[0] + num) : val), []))].sort();
}

console.log(parseRange('2002-2005, 2002-2005, 2002 - 2005'));
console.log(parseRange('2017'));
console.log(parseRange('2017 - 2015'));
console.log(parseRange('2015 - 2015'));
console.log(parseRange('1999 , 2000,    , 2008'));
console.log(parseRange('2015, 2014, 2010'));
console.log(parseRange('1999, 3000'));
console.log(parseRange('1998, 2020'));


texts:
I'm working on a class to download some data from an external server and feed it into my data model.  I'm new to both HttpClient and async methods in C#, so I'm not sure of a few things.

Is my placement of new SearchResultSet() reasonable?  It's a little contrived, true, but I'm trying to get an example of how async code can streamline execution.
Is splitting the GetStringAsync() and await myTask statements going to cause any problems?

The HttpClient class is being passed in via the constructor to aid in unit testing.

class MySearch
{
    private readonly HttpClient searchClient;
    private readonly Uri baseSearchUrl;

    public MySearch(HttpClient client, Uri baseUrl) {
        searchClient = client;
        baseSearchUrl = baseUrl;
    }

    public async Task<SearchResultSet> SearchAsync(string term)
    {
        var query = "?gws_rd=ssl#q=" + term;
        var searchUrl = new Uri(baseSearchUrl, query);

        try {
            var myTask = searchClient.GetStringAsync(searchUrl);
            var result = new SearchResultSet()
            {
                SearchPageUrl = searchUrl
            };

            var searchData = await myTask;

            result.Fill(searchData); //parsing HTML is off-topic for this class!

            return result;
        }
        catch (AggregateException ex)
        {
            throw ex;
        }
        catch (WebException ex)
        {
            throw ex;
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}


texts: Array splitting in sub-arrays of consecutive elements

texts:
I want to split an array in sub-arrays of consecutive elements. For example, for the array:

a=[1 2 3 6 7 9 10 15]

I want an output 1 2 3, 6 7, 9 10, 15.

I think that the natural choice is to use a struct for this:

[v,x] = find(diff(a)>1) %find "jumps"

xx=[0 x length(a)]

for ii=1:length(xx)-1
   cs{ii}=a(xx(ii)+1:xx(ii+1)); %output struct array
end

  v =

 1     1     1

  x =

 3     5     7

  xx =

 0     3     5     7     8

The code works correctly but I was wondering if there are smarter ways to do this.


texts: Filter properties and format values if they are currency

texts:
The function I've written in Typescript works great, but I'm not convinced that it's the cleanest and most efficient function.

The function takes an object, omits properties found in an array, and does a check to see if any of the objects properties is in an array called currencyFields. It then returns both a map of the properties, and sorted array of objects, where each object is both a key and value.

This formatted and filtered data then gets displayed in an angular5 template, where I iterate over the array, and use the map to display a quick profile of the person. Because angular's *ngFor doesn't have a nice way of iterating over an object without writing some custom functionality, I decided to just return both an object and array that I could use.

Questions:

I like using lodash's functional programming approach, but I'm having a hard time factoring-out the if statement from the reduce function. It'd be cool to writing something like _.chain(properties).omit().reduce()..... Is that possible? Maybe I'm getting too hung-up on the "look" of the code.

For the properties argument, it is currently an object type, but was an Interface. I removed the interface because any number of properties based on if they are in the showPropertiesOnlyIfDataExists array, could be removed and I didn't want to make each interface property optional, so instead, I went with a default object type. Am I thinking about this correctly?

export interface IPropDetails {
    showNo1: string;
    showNo2: string;
    name: string;
    address: string;
    city: string;
    state: string;
    country: string;
    salary: string;
    bonus: string;
    manager: boolean;
}

// using a config file where these are defined so just stubbing these here for now
const showPropertiesOnlyIfDataExists: string[] = ['showNo1', 'showNo2'];
const currencyFields: string[] = ['salary', 'bonus'];

const formatValuesAndFilterProperties = (properties: object): {map: object, list: object[]} => {

    const filteredProps: {} = _.omit(properties, showPropertiesOnlyIfDataExists);

    const filteredPropsAndFormatCurrencyValues: {} = _.reduce(filteredProps, (acc, value, key) => {
        if (currencyFields.includes(key) && _.isNumber(value)) {
            value = this.convertPropertyValueToCurrency(value);
        }

        acc[key] = value;
        return acc;
    }, {});

    return {
        map: filteredPropsAndFormatCurrencyValues,
        list: _.sortBy(_.map(filteredPropsAndFormatCurrencyValues, (value, key) => ({key: key, value: value})), o => o.key)
    };

}

const exampleData: object = {
    showNo1: '',
    showNo2: 'show no 2',
    name: 'Jim Smit',
    address: '123 elm',
    city: 'portland',
    state: 'OR',
    country: 'USA',
    salary: '100000',
    bonus: '40000',
    manager: true
};

formatValuesAndFilterProperties(exampleData);


texts: Java loop extracting month and year between two dates

texts:
I have a ContratMercan with 2 Timestamps containing start and end dates.
I have to create a new entity SeguimientoSeccion for each month between this 2 dates.

I have 2 questions:

There is a way to improve it?
After this I will need to manipulate the List<SeguimientoSeccion> secciones to see which one matches other entity... I though about making a Map but there can be 2 or more sections in each month and year

private List<SeguimientoSeccion> createSectionsPerMonth(ContratMercan contrato)
{
    List<SeguimientoSeccion> secciones = new ArrayList<SeguimientoSeccion>();

    Calendar start = Calendar.getInstance();
    start.setTime(contrato.getPeriodoEntregaIni());
    start.set(Calendar.DAY_OF_MONTH, 1);

    Calendar end = Calendar.getInstance();
    end.setTime(contrato.getPeriodoEntregaFin());
    end.set(Calendar.DAY_OF_MONTH, 2);  // for loop comparison

    for (int month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR); start.before(end); month = start.get(Calendar.MONTH), year = start.get(Calendar.YEAR)) {
        SeguimientoSeccion seccion = new SeguimientoSeccion();
        seccion.setMonth(month + 1);  // natural month number
        seccion.setYear(year);

        start.add(Calendar.MONTH, 1);

        secciones.add(seccion);
    }

    return secciones;
}


texts: Finding the name of a given constant using reflection

texts:
The code below comes from the Arm_const class of my Android disassembler project:

// ARM condition code

public static final int ARM_CC_INVALID = 0;
public static final int ARM_CC_EQ = 1;
public static final int ARM_CC_NE = 2;
public static final int ARM_CC_HS = 3;
public static final int ARM_CC_LO = 4;
public static final int ARM_CC_MI = 5;
public static final int ARM_CC_PL = 6;
public static final int ARM_CC_VS = 7;
public static final int ARM_CC_VC = 8;
public static final int ARM_CC_HI = 9;
public static final int ARM_CC_LS = 10;
public static final int ARM_CC_GE = 11;
public static final int ARM_CC_LT = 12;
public static final int ARM_CC_GT = 13;
public static final int ARM_CC_LE = 14;
public static final int ARM_CC_AL = 15;

public static String getCCName(int cc)
{
    Class clazz=Arm_const.class;
    Field[] fields=clazz.getFields();
    for(Field f:fields)
    {
        String s=f.getName();
        if(s.contains("ARM_CC_"))
        try
        {
            if (((int)f.get(null))==cc)
            {
                return s.replace("ARM_CC_","");
            }
        }
        catch (IllegalAccessException e)
        {
            Log.e("arm","",e);
        }
        catch (IllegalArgumentException e)
        {}
    }
    return "";
}

The method getCCName returns the name of a constant from the declared public static final ints.

Examples:

3 → "HS"
12 → "LT"

Any suggestions to improve its performance (speed) are appreciated!


texts: Damerau Levenshtein Implementation in Kotlin

texts:
This is an implementation of the Damerau-Levenshtein distance in Kotlin which I created as an exercise, but might be also useful, if it proves to be correct.

The implementation is based on this Wikipedia article, even though it does not 100% follow the suggested pseudo-code.

fun damerauLevenshteinCount(a: CharSequence, b: CharSequence): Int {
    return damerauLevenshtein(a, b).first
}

/**
 * According to Wikipedia:
 * <cite>Damerau–Levenshtein distance between two words is the minimum number of operations (consisting of insertions,
 * deletions or substitutions of a single character, or transposition of two adjacent characters) required to change one word into the other</cite>
 */
fun damerauLevenshtein(a: CharSequence, b: CharSequence): Pair<Int, Array<IntArray>> {
    requireNotNull(a) { "First string should not be null. Make sure you specify the first string." }
    requireNotNull(b) { "Second string should not be null. Make sure you specify the second string." }
    val aLength = a.length
    val bLength = b.length
    val d = Array(aLength + 1, { IntArray(bLength + 1) })
    val daMap = hashMapOf<Char, Int>()
    val maxdist = a.length + b.length
    for (i in 0..aLength) {
        d[i][0] = i
    }
    for (j in 0..bLength) {
        d[0][j] = j
    }
    for (i in 1..aLength) {
        var db = 0
        for (j in 1..bLength) {
            val k = daMap.getOrDefault(b[j - 1], 0)
            val l = db
            var cost = 0
            if (a[i - 1] == b[j - 1]) {
                db = j
            } else {
                cost = 1
            }
            val substitution = d[i - 1][j - 1] + cost
            val insertion = d[i][j - 1] + 1
            val deletion = d[i - 1][j] + 1
            val transposition = if (k == 0 || l == 0) maxdist else d[k - 1][l - 1] + (i - k - 1) + 1 + (j - l - 1)
            d[i][j] = intArrayOf(substitution, insertion, deletion, transposition).min() as Int
        }
        daMap[a[i - 1]] = i
    }
    return Pair(d[aLength][bLength], d)
}

Here is a unit test which shows the behaviour of this implementation:

@Test
fun damerauLevenshteinDistanceCount() {
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("h1", "h1")).isEqualTo(0)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("gil", "gil")).isEqualTo(0)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("gil", "gill")).isEqualTo(1)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("ca", "abc")).isEqualTo(2) // Differs from optimal string alignment distance distance
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("waht", "what")).isEqualTo(1)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("thaw", "what")).isEqualTo(2)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("waht", "wait")).isEqualTo(1)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("Damerau", "uameraD")).isEqualTo(2)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("Damerau", "Daremau")).isEqualTo(2)
    Assertions.assertThat(wagnerDamerau.damerauLevenshteinCount("Damerau", "Damreau")).isEqualTo(1)
    Assertions.assertThat(wagnerDamerau.osaDistanceCount("waht", "whit")).isEqualTo(2)
    Assertions.assertThat(wagnerDamerau.osaDistanceCount("what", "wtah")).isEqualTo(2)
}

I want to check for its correctness as well if I am using Kotlin in the best possible idiomatic manner.


texts:
This code controls whether the user has checked at least one checkbox field before saving the record. If the user has failed to do so the code throws an error message and cancels the operation.

Is there a better/more efficient way to write it?

function BusComp_PreWriteRecord ()
{
    try
    {
        var sSMS =          this.GetFieldValue("R SMS");
        var sEmail =        this.GetFieldValue("R Email");
        var sChannel1 =     this.GetFieldValue("R Channel 1");
        var sChannel2 =     this.GetFieldValue("R Channel 2");
        var sChannel3 =     this.GetFieldValue("R Channel 3");

        //R 17.12.14 ES: Added to make channel choice fields required if none are filled in
        if ((sSMS != "Y") && (sEmail != "Y") && (sChannel1 != "Y") && (sChannel2 != "Y") && (sChannel3 != "Y"))
        {
            TheApplication().RaiseErrorText("Please check at least one box");
        }
    }
    catch(e)
    {
        throw e;
    }
}


texts:
I have the following two vectors in C++11:

vector<unsigned char> left = { 1, 2, 3, 4, 5, 6 }; // it is meant to represent the number: 123456
vector<unsigned char> right = { 1, 2, 3, 4 }; // meant to be number: 1234

After a function processes them, they become:

left = { 6, 5, 4, 3, 2, 1 };
right = { 4, 3, 2, 1 };

Now, I need to complete the shorter one with zeros at the end until they are equal in size(). I have thefollowing method:

void bigint::process_operands( vector<unsigned char> & left, vector<unsigned char> & right )
{
    size_t left_size = left.size();
    size_t right_size = right.size();

    if( left_size < right_size )
    {
        size_t size_diff = right_size - left_size;

        for( size_t i = 0; i != size_diff; ++i )
            left.push_back( '0' );
    } else if( right_size < left_size )
    {
        size_t size_diff = left_size - right_size;

        for( size_t i = 0; i != size_diff; ++i )
            right.push_back( '0' );
    }
}

Is there any better implementation?


texts: Function to send email, refactored based on SOLID principles

texts:
I have the below method that is responsible for generating and sending a MailMessage using a SmtpClient object:

public static void SendEmail(
    string subject,
    string body,
    bool isBodyHtml,
    List<string> emails,
    List<string> ccs = null)
{
    if (emails == null)
    {
        throw new ArgumentNullException("emails");
    }
    MailMessage message = new MailMessage
    {
        Subject = subject,
        Body = body,
        IsBodyHtml = isBodyHtml
    };
    foreach (string email in emails)
    {
        message.To.Add(email);
    }
    if (ccs != null)
    {
        foreach (string cc in ccs)
        {
            message.CC.Add(cc);
        }
    }
    SmtpClient client = new SmtpClient
    {
        EnableSsl = true,
        DeliveryMethod = SmtpDeliveryMethod.Network
    };
    client.Send(message);
}

But recently I've been reading more on S.O.L.I.D and principles of OOP design, so I thought to refactor this method, and compartmentalize it more.

Am I on the right track with my refactor? Are there ways to make my code more modular/testable?

Here's my refactored code:

private static MailMessage CreateMailMessage(
    string subject,
    string body,
    bool isBodyHtml,
    List<string> emails,
    List<string> ccs = null)
{
    if (emails == null)
    {
        throw new ArgumentNullException("emails");
    }
    MailMessage message = new MailMessage
    {
        Subject = subject,
        Body = body,
        IsBodyHtml = isBodyHtml
    };
    foreach (string email in emails)
    {
        message.To.Add(email);
    }
    if (ccs != null)
    {
        foreach (string cc in ccs)
        {
            message.CC.Add(cc);
        }
    }
    return message;
}

private static SmtpClient CreateSmtpClient(
    bool enableSsl,
    SmtpDeliveryMethod deliveryMethod)
{
    SmtpClient client = new SmtpClient
    {
        EnableSsl = enableSsl,
        DeliveryMethod = deliveryMethod
    };
    return client;
}

And here's the method responsible for calling the above two and sending the email:

public static void SendEmail(string subject, string body, List<string> emails, List<string> ccs = null)
{
    using (MailMessage message = CreateMailMessage(subject, body, true, emails, ccs))
    {
        using (SmtpClient client = CreateSmtpClient(true, SmtpDeliveryMethod.Network))
        {
            client.Send(message);
        }
    }
}


texts: What parts of my Python code are adopting a poor style and why?

texts:
Here I have some simple code that worries me, look at the second to last line of code, I have to return spam in order to change spam in the global space. Also is it bad to be writing code in this space and I should create a function or class to call from that space which contains most my code?

I found out very recently that I never even understood the differences between Python's identifiers compared to C or C++'s variables. This helps put into perspective why I always have so many errors in Python.

I do not want to continue writing code and get into a bad habit and this is why I want your opinion.

I also have a tendency to do things like spam = fun() because I do not know how to correctly make Python call a function which changes a variable in the scope of where the function was called. Instead I simply return things from the functions never learning how to correctly write code, I want to change that as soon as possible.

import random
MAX = 20

def randomize_list(the_list, x=MAX):
    for i in range(len(the_list)):
        the_list[i] = random.randint(1, x)

def lengthen_list(the_list, desired_length, x=MAX):
    if len(the_list) >= desired_length:
        print "erroneous call to lengthen_list(), desired_length is too small"
        return the_list
    while(len(the_list) < desired_length):
        the_list.append(random.randint(1, x))
        # organize the_set
        the_list = set(the_list)
        the_list = list(the_list)
    return the_list

spam = list(range(10))
randomize_list(spam, MAX)

print "the original list:"
print spam, '\n'

spam = set(spam)
spam = list(spam)

print "the set spam:"
print spam

print "the set spam with length 10"
spam = lengthen_list(spam, 10, MAX)
print spam

Please help me adopt a style which correctly fixes, in particular, the second to last line of code so that I do not need the function to do return things in order to work, if this is even possible.


texts:
This is a very simple ball game in which we have to avoid projectiles falling from the sky. This is my second project and first game. Please review and tell where I can improve.

import time
import random
import pygame
pygame.init()

#colors
black=(0,0,0)
white=(255,255,255)
red=(255,0,0)
green=(0,255,0)
blue=(0,0,255)
darkViolet=(148,0,211)

#display
displayWidth=1024
displayHeight=600
display=pygame.display.set_mode((displayWidth, displayHeight))
pygame.display.set_caption('PHY')
heart=pygame.image.load('heart.png')
myfont=pygame.font.SysFont('Terminal', 18)
clock=pygame.time.Clock()
endTime=time.time()

#physics
x,y=displayWidth/2,displayHeight/2
ux, uy, ax, ay= 0, 0, 0, 0 # u means velocity, a  means acceleration
yp1, up1, ap = 0, 50, 50 #p for projectile
xp1,yp1,up1,ap1=[],0,50,50 #projectile variables. xp1 list coz multiple projectiles
uc, ac = 20, 5 # c stands for the amount of change on key press
score, lives=0,3
touching=False
running=True

#misc
projectile=pygame.Surface((10,20))
projectile.fill(darkViolet)

#adding random locations for projectiles to spawn in
for _ in range(20):
    xp1.append(random.randint(0,displayWidth))

while running:
    #taking dt to be a small value which will depend on the processing power
    startTime=time.time()
    t=startTime-endTime

    #changing the postions and velocities with time
    ux+=ax*t
    uy+=ay*t
    x+=ux*t
    y+=uy*t
    up1+=ap*t
    yp1+=up1*t

    endTime=time.time()

    #checking for collision of ball with boundaries
    if x<0:
        x=0
        ux=-ux/3
    if x>displayWidth:
        x=displayWidth
        ux=-ux/3
    if y<0:
        y=0
        uy=-uy/3
    if y>displayHeight:
        y=displayHeight
        uy=-uy/3

    for ev in pygame.event.get():
        if ev.type == pygame.QUIT:
            running=False
        elif ev.type == pygame.KEYDOWN: #acts on pressing and not on holding key
            if ev.key == pygame.K_UP:
                ay-=ac
                uy-=uc
            if ev.key == pygame.K_DOWN:
                ay+=ac
                uy+=uc
            if ev.key == pygame.K_LEFT:
                ax-=ac
                ux-=uc
            if ev.key == pygame.K_RIGHT:
                ax+=ac
                ux+=uc
        elif ev.type == pygame.KEYUP:
            if ev.key == pygame.K_UP:
                ay=0
            if ev.key == pygame.K_DOWN:
                ay=0
            if ev.key == pygame.K_LEFT:
                ax=0
            if ev.key == pygame.K_RIGHT:
                ax=0

    #condition for when the projectile crosses the screen
    if yp1>displayHeight:
        yp1=0
        up1=3*up1/5
        ap+=5
        xp1=[]
        score+=1
        for _ in range(20):
            xp1.append(random.randint(0,displayWidth))

    #checking for collision between ball and projectile
    for g in range(20):
        if x>xp1[g]-10 and x<10+xp1[g] and y>yp1-15 and y<yp1+15:
            touching=True
            xp1[g]=1050
    if touching:
        if lives>1:
            lives-=1
            touching=False
        else:
            running=False

    #displaying
    display.fill(black)
    for g in range(lives): #displaying the lives as hearts
        display.blit(heart, (950+g*25,25))
    for g in range(20): #displaying the same projectile at 20 places
        display.blit(projectile, (xp1[g], yp1))
    textDisp=myfont.render('SCORE: %s'%(score),False,white)
    pygame.draw.circle(display, red, (int(x),int(y)), 10, 0) #displaying the ball
    display.blit(textDisp,(950,50)) #displaying the score
    pygame.display.update()
    clock.tick(60)

pygame.quit()
quit()


texts:
I created the following HtmlHelper extension method for my Asp.Net MVC Razor views because the ternary syntax sucks when you need to use it intermixed with markup.

Is there a better way to write this and are there any potential type safety issues with it?

public static string GetValueTernary(this HtmlHelper htmlHelper, object a, object b, object valueIfEqual, object valueIfNotEqual)
{
    return a.Equals(b) ? valueIfEqual.ToString() : valueIfNotEqual.ToString();
}

and its usage in a Razor view is like this:

...


texts:
From Coderbyte:

  Have the function StringReduction(str) take the str parameter being
  passed and return the smallest number you can get through the
  following reduction method. The method is: Only the letters a, b, and
  c will be given in str and you must take two different adjacent
  characters and replace it with the third. For example "ac" can be
  replaced with "b" but "aa" cannot be replaced with anything. This
  method is done repeatedly until the string cannot be further reduced,
  and the length of the resulting string is to be outputted. For
  example: if str is "cab", "ca" can be reduced to "b" and you get "bb"
  (you can also reduce it to "cc"). The reduction is done so the output
  should be 2. If str is "bcab", "bc" reduces to "a", so you have "aab",
  then "ab" reduces to "c", and the final string "ac" is reduced to "b"
  so the output should be 1.

Source ( passed all validations ):

var replacements =
{
  "ab" : "c",
  "ac" : "b",
  "bc" : "a",
  "ba" : "c",
  "ca" : "b",
  "cb" : "a"
};

function StringReduction(s)
{
  var original, key;
  while( s != original )
  {
   original = s;
   for( key in replacements )
      s = s.replace( key , replacements[key] );
  }
  return s.length;
}

// keep this function call here
// to see how to enter arguments in JavaScript scroll down
StringReduction(readline());

The funny part of this challenge is that you write against time, so the first version was a terrible, recursive approach. Since then I rewrote it a few times before posting to CR, thinking each time mistakenly that it was perfect, at this point I would like to get your feedback on it.


texts:
This is codechef beginner problem.
How I can make it efficient, It is taking 2.09 sec while time limit is 2.0764 secs.
Problem is:
For a given positive integer K of not more than 1000000 digits, write the value of the smallest palindrome larger than K to output. Numbers are always displayed without leading zeros.
https://www.codechef.com/problems/PALIN
#include<iostream>
using namespace std;

long int reverse_num(long int n){
  long int reversenumber=0,remainder1;
    while(n != 0){
    remainder1 = n%10;
    reversenumber = (reversenumber*10)+remainder1;
    n /= 10;
}
return reversenumber;
}

int main(){

int T;
cin>>T;

while(T--){

long int n,reversenum;
bool chek;
cin>>n;
n = n+1;
bool flag = false;
while(!flag){

    reversenum = reverse_num(n);
    (n == reversenum) ? flag = true : flag = false;
    n++;
}
cout<<reversenum;
}
return 0;
}


texts:
I wrote this code to automate in Word from Visual Fox Pro. I put between the escapes <|< and >|> some VFP code (like take some values from tables and so on). At the press of a button, the code scans all of the document and, when finding these escapes, evaluates the instructions between. The last two FOR loops eliminate the escape strings.

The code works, but I ask. Is there a better way to do what I look for?

LOCAL oWord, oDocument, oRange, Lc_start, Lc_expr, Lc_ris, Ln_count, Lc_val
DIMENSION Lc_funct[1]

Lc_expr = ""
Ln_count = 1

oWord = CREATEOBJECT("Word.Application")
oWord.Visible = .T.
cFile = GETFILE()

oDoc = oWord.Documents.Add(m.cFile)

oRange = oWord.ActiveDocument.Range()
    nWordCount = oRange.Words.Count
    oRange.Collapse(1)
    FOR nWord = 1 TO m.nWordCount-1
    oRange.Expand(2)
    cWord = oRange.Text
    DO CASE

    CASE m.cWord = "<|<"
        Lc_start = .T.
        Lc_Expr = ""

    CASE m.cWord = ">|>"
        Lc_start = .F.
        Lc_funct[Ln_count] = Lc_Expr
        Ln_count = Ln_count + 1
        DIMENSION Lc_funct[Ln_count]

    CASE m.Lc_start
        Lc_expr = Lc_expr + m.cWord

    OTHERWISE
        *do anything

    ENDCASE

    oRange.Collapse(0)
    ENDFOR

    FOR i = 1 TO Ln_count-1
    oRange = oWord.ActiveDocument.Range()
        oRange.Find.Text = Lc_funct[i]
        oRange.Find.Replacement.Text = EVALUATE(Lc_funct[i])
        lFound = oRange.Find.Execute( , , , , , , , , , , 2 )
    ENDFOR

    FOR i = 1 TO Ln_count-1
    oRange = oWord.ActiveDocument.Range()
        oRange.Find.Text = "<|<"
        oRange.Find.Replacement.Text = ""
        lFound = oRange.Find.Execute( , , , , , , , , , , 2 )
    ENDFOR

    FOR i = 1 TO Ln_count-1
        oRange = oWord.ActiveDocument.Range()
        oRange.Find.Text = ">|>"
        oRange.Find.Replacement.Text = ""
        lFound = oRange.Find.Execute( , , , , , , , , , , 2 )
    ENDFOR
MESSAGEBOX("DONE")


texts: How to make Project Euler 32 in Python faster?

texts:
We shall say that an n-digit number is pandigital if it makes use of
  all the digits 1 to n exactly once; for example, the 5-digit number,
  15234, is 1 through 5 pandigital.

  The product 7254 is unusual, as the identity, 39 × 186 = 7254,
  containing multiplicand, multiplier, and product is 1 through 9
  pandigital.

  Find the sum of all products whose multiplicand/multiplier/product
  identity can be written as a 1 through 9 pandigital.

  HINT: Some products can be obtained in more than one way so be sure to
  only include it once in your sum.

I need help on making this code faster. Right now I'm using double nested for-loops; is there a way I can change that?

from timeit import default_timer as timer

start = timer()
products = set()
for a in range(12, 100):
    for b in range(102, 1000): # to get 9-digit: 2-digit * 3-digit
        product = a * b
        digits = list(str(a) + str(b) + str(product))
        digits = [int(x) for x in digits]
        if sorted(digits, key = int) == range(1, 10):
            products.add(product)

for a in range(1, 10):
    for b in range(1023, 10000): # other option is 1-digit * 4-digit
        product = a * b
        digits = list(str(a) + str(b) + str(product))
        digits = [int(x) for x in digits]
        if sorted(digits, key = int) == range(1, 10):
            products.add(product)

ans = sum(list(products))
elapsed_time = (timer() - start) * 1000 # s --> ms

print "Found %d in %r ms." % (ans, elapsed_time)


texts: Determining whether or not a number is prime

texts:
I wrote this code in Java without using any methods, just by using simple for loop and if statements.

When we input a number, it checks whether it's a prime or not. If it's a prime, then it prints "It's a prime". And if it's not a prime number, it says "It's not a prime" and prints the first number which divides it.

For example, if we input 1457, it will output "1457 is not a prime 1457 Divide by 31".

I want to know whether or not I can make this coding shorter.

import java.util.*;
public class PrimeNum{
public static void main(String args[]){
       Scanner x=new Scanner(System.in);
       System.out.println("Enter the number :  ");
       long y=x.nextLong();
       long i;
       for( i=2;i<y;i++){
       long z=y%i;
           if(z==0){
           System.out.println(y+" is not a prime");
           System.out.println(y+" Divide by "+i);
           i=y;
                         }

           }if(i==y) System.out.println("Number is prime");
            if(y==1) System.out.println("Number 1 is not a prime");
     }
}


texts:
I made a Python function that takes an XML file as a parameter and returns a JSON.
My goal is to convert some XML get from an old API to convert into Restful API.

This function works, but it is really ugly. I try to clean everything, without success.

Here are my tests:

    def test_one_node_with_more_than_two_children(self):
        xml = ''
        expected_output = {
            "a": {
                "@id": "0",
                "@name": "foo",
                "b": [
                    {
                        "@id": "00",
                        "@name": "moo"
                    },
                    {
                        "@id": "01",
                        "@name": "goo"
                    },
                    {
                        "@id": "02",
                        "@name": "too"
                    }
                ]
            }
        }
        self.assertEqual(expected_output, self.parser.convertxml2json(xml))

And my function:

from xml.dom.minidom import parseString, Node

class Parser(object):

    def get_attributes_from_node(self, node):
        attributes = {}
        for attrName, attrValue in node.attributes.items():
            attributes["@" + attrName] = attrValue
        return attributes

    def convertxml2json(self, xml):
        parsedXml = parseString(xml)
        return self.recursing_xml_to_json(parsedXml)

    def recursing_xml_to_json(self, parsedXml):
        output_json = {}
        for node in parsedXml.childNodes:
            attributes = ""
            if node.nodeType == Node.ELEMENT_NODE:
                if node.hasAttributes():
                    attributes = self.get_attributes_from_node(node)

                if node.hasChildNodes():
                    attributes[node.firstChild.nodeName] = self.recursing_xml_to_json(node)[node.firstChild.nodeName]

                if node.nodeName in output_json:
                    if type(output_json[node.nodeName]) == dict:
                        output_json[node.nodeName] = [output_json[node.nodeName]] + [attributes]
                    else:
                        output_json[node.nodeName] = [x for x in output_json[node.nodeName]] + [attributes]
                else:
                    output_json[node.nodeName] = attributes
        return output_json

Can someone give me some tips to improve this code?
def recursing_xml_to_json(self, parsedXml) is really bad.
I am ashamed to produce it :)


texts: Is this algorithm efficient for the 01Knapsack?

texts:
This code uses recursion to solve the 01Knapsack problem. It evaluates all the item permutations that can be added to the knapsack and checks if it gives the maximum profit. What else could have been used to get a faster solution?

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Scanner;
import java.util.Set;

class Item {

    static int id = 0;
    int weight;
    int cost;
    double ratio;
    int itemNo = ++id;

    boolean taken = false;

    public Item(int weight, int cost) {
        this.weight = weight;
        this.cost = cost;
        this.ratio = (double) cost / weight;
    }

    public String toString() {
        return itemNo + "";
    }
}

class Store {

    List<Item> store = new ArrayList<>();

    public Store() {
        takeInput();
    }

    Item getNextHighestRatioItem() {
        int i = -1;
        double highestRatio = Double.MIN_VALUE;
        for (int j = 0; j < store.size(); ++j) {
            double thisRatio = store.get(j).ratio;
            if (thisRatio > highestRatio) {
                i = j;
                highestRatio = thisRatio;
            }
        }
        return store.get(i);
    }

    public void takeInput() {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the number of items: ");
        int nItems = scan.nextInt();

        int weight, cost, ratio;
        for (int i = 0; i < nItems; ++i) {
            System.out.println("Enter item " + (i + 1) + "'s weight and cost: ");
            weight = scan.nextInt();
            cost = scan.nextInt();

            Item item = new Item(weight, cost);
            store.add(item);
        }
    }

    public int getSize() {
        return store.size();
    }
}

class Knapsack {

    Set<Item> knapsack = new HashSet<>();
    int maxWeight = 50;
    int weight;

    public boolean addItem(Item item) {
        if (weight + item.weight > maxWeight) {
            return false;
        }
        knapsack.add(item);
        weight += item.weight;
        return true;
    }

    public void removeItem(Item item) {
        knapsack.remove(item);
        weight = weight - item.weight;
    }

    public boolean isFull() {
        return weight == maxWeight;
    }

    public int calculateTotalWorth() {
        int sum = 0;
        for (Item item : knapsack) {
            sum += item.cost;
        }
        return sum;
    }

}

public class KnapsackProblem01 {

    Store store = new Store();
    Knapsack knapsack = new Knapsack();

    int worth = 0;

    public void fillKnapsack() {

        int thisWorth = knapsack.calculateTotalWorth();
        if (thisWorth > worth) {
            worth = thisWorth;
            System.out.println("Found a better solution " + worth);
            System.out.println("Knapsack has items: ");
            for (Item i : knapsack.knapsack) {
                System.out.print(i + " ");
            }
        }

        if (knapsack.isFull()) {
            return;
        }

        for (Item i : store.store) {
            if (i.taken) {
                continue;
            }
            if (knapsack.addItem(i)) {
//                System.out.println("Added item "+i+" to the knapsack");
                i.taken = true;
                fillKnapsack();
                knapsack.removeItem(i);
//                System.out.println("Removed item "+i+" from the knapsack");
                i.taken = false;
            }
        }
    }

    public static void main(String[] args) {
        KnapsackProblem01 kp = new KnapsackProblem01();
        kp.fillKnapsack();
    }
}


texts: Remove pixel patch in image which is stored as array

texts:
I have an array I which stores N images of size P (number of pixels). Every image is of size P = q*q.

Now I want to delete patches of size ps around a selected index IDX (set all values to zero).

My approach was to reshape every single image using reshape(q,q) and delete the pixels around IDX. I also have to check if the index is not outside the image.

Here is an example:

BEFORE:

AFTER:

My code is a real bottleneck and I would like to know if there is a way to improve the performance of my approach.

import numpy as np
import matplotlib.pyplot as plt
import time

def myplot(I):
    imgs = 5
    for i in range(imgs**2):
        plt.subplot(imgs,imgs,(i+1))
        plt.imshow(I[i].reshape(q,q), cmap="viridis", interpolation="none")
        plt.axis("off")
    plt.show()

N = 10000
q = 28
P = q*q
I = np.ones((N,P))
myplot(I)

ps = 5
IDX = np.random.randint(0,P,(N,1))
x0, y0 = np.unravel_index(IDX,(q,q))

t0 = time.time()

# HOW TO IMPROVE THIS PART ? #
for i in range(N):
    img = I[i].reshape(q,q)
    for x in range(ps):
        for y in range(ps):
            if (x0[i]+x < q) and (y0[i]+y < q):
                img[x0[i]+x,y0[i]+y] = 0.0
    I[i] = img.reshape(1,q*q)

print(time.time()-t0)
myplot(I)

I call this code (without the plotting procedure) about one million times from another code. Every call takes about 1 second on my system. This makes the code so far quite useless.

Any advice?


texts:
My code compiles and executes.  I would like to hear any comments or suggestions pertaining to my use of C++.

#include <iostream>
#include <math.h>

bool error_check(){
    if(!std::cin){
        std::cin.clear();
        std::cin.ignore(256,'\n');
        return true;
    }
    else
        return false;
};

int main(){

//This line outputs directions for the user to follow.
std::cout << "\nEnter real numbers for side lengths.\n" <<
                 "\nEnter zero for an unknown side length.\n" <<
                 "\nTo exit enter zero for all side lengths.\n" << std::endl;

while(true){

    //This line prompts the user to enter a side length.
    std::cout << "side a: ";
    //This line initializes and stores user input into a variable for calculation.
    float sidea = 1; std::cin >> sidea;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This line prompts the user to enter another side length.
    std::cout << "side b: ";
    //This line initializes and stores user input into a variable for calculation.
    float sideb = 1; std::cin >> sideb;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This line prompts the user to enter a final side length.
    std::cout << "side c: ";
    //This line initializes and stores user input into a variable for calculation.
    float sidec = 1; std::cin >> sidec;
    //This condtional branch handles bad user input which is in this case anything but real numbers.
    if(error_check()){
        std::cout << "\nYou must enter a real number.\n" << std::endl;
        continue;
    }

    //This conditional branch calculates and outputs the unknown side length.
    if(sidea == 0){
        sidea = sqrt(pow(sidec,2) - pow(sideb,2));
        std::cout << "side a= " << sidea << "\n" << std::endl;
    }
    else if(sideb == 0){
        sideb = sqrt(pow(sidec,2) - pow(sidea,2));
        std::cout << "side b= " << sideb << "\n" << std::endl;
    }
    else if(sidec == 0){
        sidec = sqrt(pow(sidea,2) + pow(sideb,2));
        std::cout << "side c= " << sidec << "\n" << std::endl;
    }
    else{
        std::cout << "\nYou must enter zero for an unknown side length.\n" << std::endl;
        continue;
    }

    //This conditional branch checks to see if the user wants to exit.
    if(sidea == 0 and sideb == 0 and sidec == 0)
        break;
    else
        continue;

}
return 0;
};


texts:
I have the following method that will take the car parts I searched for and match them to my car object in array. Then it tells me the percent match.

Example:

Car.h has NSSet toCarParts. toCarParts has may car parts.

My array contains 5,000 or so matches.

I will go through each one and match my parts to the car parts and calculate a percent match.  If I search for wheel, tire, rim, and Car X has wheel, tire, rim, seat, my % should be 75%.

The method does this, but take about 30 seconds on an iPhone 5 (double or triple on iPhone 4)

How can I optimize it?

I think what slows it down is that I need to open each car object, fire the faults, access the toCarParts set, for each part compare if it matches a part in my search array.

I also think it is slow when doing division (counter/[carPartsArrayFaulted count]=%).

-(NSMutableArray*)calculatePercentagePerFind:(NSMutableArray*)CarArray:(NSMutableArray*)partsArray{
    NSArray*defaultParts =[NSArray arrayWithArray:[[[HelperMethods alloc]init]getObjectUserDefault:@"AvailableDefaultParts"]];

    int lowestPercentMatchInt=[[[HelperMethods alloc]init]getIntegerUserDefault:@"lowestPercentageMatch"];

    NSMutableArray*partsFromCarArray=[[NSMutableArray alloc]init];

    NSMutableArray*returnArray=[[NSMutableArray alloc]init];

    NSMutableArray *partsWithDefaultParts =[NSMutableArray arrayWithArray:partsArray];
    [partsWithDefaultParts addObjectsFromArray:defaultParts];

    for (int i=0; i<[CarArray count]; i++) {
        double matchCount=0;
        Car *CarResult =(Car*)[CarArray objectAtIndex:i];

                //Check if it will at least be 30% match
        double number1 = [partsWithDefaultParts count];
            number1 =(number1/[CarResult.numberOfParts doubleValue])*100;
            if (number1>lowestPercentMatchInt) {
                partsFromCarArray =[NSMutableArray arrayWithArray:[[CarResult toParts]allObjects]];
                NSMutableArray *faultedParts=[[NSMutableArray alloc]init];
                for (int i =0; i<[partsFromCarArray count]; i++) {
                    CarPart*part = (CarPart*)[partsFromCarArray objectAtIndex:i];
                        [faultedParts addObject:part.name];
                }
            // for each part in the Car
            for (NSString *partInCar in partsWithDefaultParts){
                //if the search parts contain that part, add one to count
                if ([faultedParts containsObject:partInCar]) {
                    matchCount++;
                }
            }
            //Calculate percent match
            double percentMatch = matchCount;

            percentMatch =(percentMatch/[CarResult.numberOfParts doubleValue])*100;

            //if at least 30%(user default) then add the percent match to Car result
            if (percentMatch >lowestPercentMatchInt) {
                if (percentMatch>100) {
                    CarResult.percentMatch = [NSNumber numberWithDouble:100.00];
                }else{
                    CarResult.percentMatch = [NSNumber numberWithDouble:percentMatch];
                }
                [returnArray addObject:CarResult];
            }
    }
    }
    NSLog(@"Percent Matched Cars = %i",[returnArray count]);
    return [self arrangeByHighestPercentMatch:returnArray];
}


texts: Better Alternative For Storing Multiple Booleans?

texts:
I have a class, which stores an enum to track if my object is modified, newly created, or no change. If the object is modified, I have additional booleans for each field that is modified.

For instance,

public enum status
{
    NoChange,
    Created,
    Modified
}

private bool? name;
private bool? address;
...
private bool? numberOfDonkeysPurchased;

So the idea is that if the status is modified, then the nullable bools will be either true or false, depending on if these fields are changed.

If the status is not modified, then the nullable bools will be null.

The problem with this is that I have a couple of these fields that I want to check (say 10). Is it valid to create a nullable bool for each field that I am checking, knowing that I maybe be storing a lot of nulls? Or is that not a concern?

Is there a better way to store this?

Thanks!


texts: numpy performance of norm calculation using variable dimension

texts:
I am looking for advice to see if the following code performance could be further improved. This is and example using a 4x3 numpy 2d array:

import numpy as np

x = np.arange(12).reshape((4,3))
n, m = x.shape
y = np.zeros((n, m))

for j in range(m):
    x_j = x[:, :j+1]
    y[:,j] = np.linalg.norm(x_j, axis=1)

print x
print y

Which is printing

[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
[[  0.           1.           2.23606798]
 [  3.           5.           7.07106781]
 [  6.           9.21954446  12.20655562]
 [  9.          13.45362405  17.3781472 ]]

As you can see the code is computing the norms of the vectors considering increasing number of columns, so that y[i,j] represent the norm of the vector x[i,:j+1]. I couldn't find if this operation has a name and if it is possible to vectorize further the process and get rid of the for loop.

I only found in this post that using np.sqrt(np.einsum('ij,ij->i', x_j, x_j)) is a bit faster than using np.linalg.norm(x_j, axis=1).


texts: Would my implementation of this enum pass?

texts:
I have a feature with feature flagging enabled, basis the condition I want to load different pages in my screen, to achieve this I have the following enum:

enum class ImageHolderEnum(
    val titleId: Int,
    val qFragment: BaseFragment,
    val fragment: BaseFragment
) : IPageHolder {
    PAGE1(R.string.tab_shop_baby, BabyTwoFragment(), BabyThreeFragment()) {
        override fun getTitle(): Int = titleId
        override fun getFragmentToAdd(): BaseFragment =
            if (isFeatureAllowed()) qFragment else fragment
    },
    PAGE2(R.string.tab_shop_mom, MomThreeFragment(), MomTwoFragment()) {
        override fun getTitle(): Int = titleId
        override fun getFragmentToAdd(): BaseFragment =
            if (isFeatureAllowed()) qFragment else fragment
    },
    PAGE3(R.string.tab_shop_dad, DadTwoFragment(), DadThreeFragment()) {
        override fun getTitle(): Int = titleId
        override fun getFragmentToAdd(): BaseFragment =
            if (isFeatureAllowed()) qFragment else fragment
    };

    fun isFeatureAllowed(): Boolean  {
        val qSlideConfig: QSlideConfig by remoteFeatureFlag() // Kind of dependency injection here
        return qSlideConfig.isQSlideEnabled()
    }
}

The interface is as follows:

interface IPageHolder {
    fun getTitle(): Int
    fun getFragmentToAdd(): BaseFragment
}

I am concerned if I am using the dependency injection inside the enum and breaking some principles.


texts:
I've already done quite a bit of cleaning up. For example, the strings dryCheck and blueCheck no longer exist, instead they're replaced with "else". But I think this could be done 10x better, so if you know how (no advanced C++ lingo etc), that would be great!

  A red seed will grow into a flower when planted in soil temperatures
  above 75 degrees, otherwise it will grow into a mushroom. Assuming the
  temperature meets the conditions for growing a flower, planting a red
  seed in wet soil will produce a sunflower and planting a red seed in
  dry soil will produce dandelion. A blue seed will grow into a flower
  when planted in soil temperatures ranging from 60 to 70 degrees,
  otherwise it will grow into a mushroom. Assuming the temperature meets
  the conditions for growing a flower, planting a blue seed in wet soil
  will produce a dandelion and planting the blue seed in dry soil will
  produce a sunflower. Write a program that will ask the user to input
  the seed color, the soil temperature and whether the soil is wet or dry
  and then output the plant that will grow.

#include <iostream>
#include <string>
using namespace std;

int main()
{
    string seedColor, soilMoist, redCheck, wetCheck;
    int soilTemp;

    redCheck = "Red";
    wetCheck = "Wet";
    cout << "Enter the seed type (Blue/Red): ";
        getline(cin, seedColor);

    cout << "Enter the soil temperature: ";
        cin >> soilTemp;

    cout << "Is the soil dry or wet? ";
        cin >> soilMoist; // I tried another "getline(cin, soilMoist), but that conflicts with the cin >> soilTemp; (line 30)

    if (seedColor == redCheck)
    {
        if (soilTemp > 75)
            {
            if (soilMoist == wetCheck)
                cout << "It's a sunflower!";
            else
                cout << "It's a dandelion!";
            }
        else
            cout << "It's a mushroom!";
    }

    else
    {
        if (60 < soilTemp && soilTemp < 70)
            {
            if (soilMoist == wetCheck)
                cout << "It's a dandelion!";
            else
                cout << "It's a sunflower!";
            }
        else cout << "It's a mushroom!";
    }
}


texts: Changing the id field to an _id field for the lowest tweet id

texts:
I am collecting tweets using a Python script and I want to store them in a MongoDB database.

I want to find out the lowest tweet id and for each tweet, I want to change the id field to an _id field.

Is it possible not having to iterate over all the tweets with a for loop in order to do these 2 things.

search_result = #search result from Twitter API

min_id = float('inf')

result = []
for tweet in search_result:
    if tweet['id'] < min_id:
        min_id = tweet['id']
    tweet['_id'] = tweet.pop('id')
    result.append(tweet)


texts: Passing some redundant parameters to an interface vs creating a new request object every time for the interface

texts:
I am writing a proxy class, that will fetch a certain property (say propertyA) by calling an underlying service.

Currently we use Service A to get propertyA, but there is a chance that in the near future, we might migrate to service B to get propertyA instead.

Approach 1:
I wanted to make ServiceAProxy and ServiceBProxy both extend a common interface say PropertyAProxy that looks something like this

public interface PropertyAProxy{
    PropertyA getPropertyA(param1,param2, param3);
}

with the child classes as

public class ServiceAProxy implements PropertyAProxy{
    PropertyA getPropertyA(param1,param2,param3){
        return serviceA.getPropertyA(param1,param2); //param 3 is not needed for service A
    }
}

and

public class ServiceBProxy implements PropertyAProxy{
    PropertyA getPropertyA(param1,param2,param3){
        return serviceB.getPropertyA(param1,param2,param3);
    }
}

Approach 2:
or should I go for a really generic Provider interface

public interface Provider<I,O>{
    O get(I input);
}

with child classes being
public class ServiceAProxy implements

 Provider<PropertyARequestForServiceA,PropertyA>{
            PropertyA getPropertyA(PropertARequestForServiceA input){
                return serviceA.getPropertyA(input.getParam1, input.getParam2);
            }
        }

and

public class ServiceBProxy implements Provider<PropertyARequest2,PropertyA>{
    get(param1,param2,param3){
        return serviceB.getPropertyA(input.getParam1, input.getParam2,input.getParam3);
    }
}

My concerns with approach 1 are:

I am passing param3 to ServiceAProxy even though its not needed.
With the visibility I CURRENTLY have, we wont need anything else besides param1, param2 and param3. But in the future there might be a ServiceC which needs param4 and not param 1.

My concerns with approach 2:

For every input object i will have to define a new pojo to act as a request object, and that seems a bit excessive to have so many request classes (especially since the code base im working on is already getting quite large)

Additional Context:
I will be using serviceA to get paramA for now, but there is a VERY high chance that some point in the future we will migrate to serviceB to get paramA.
To avoid pains in the future, I wanted to make the callers of the proxy to call an interface instead, so that I could switch the underlying proxy implementation without having to rewrite the calling logic.

Approach 1, is simpler to implement, but i may end up passing parameters that are never used.
Approach 2, is more generic, but involves me making request objects for each implementation, which I personally feel is overkill.

I have no STRONG inclination over either approach, and hence reaching out to the wider community.


texts:
I'm working alone on my code, trying to learn Ruby as I go.

Class Robot is supposed to be instantiated with the position on a map, and whether it is facing toward a side of the map. It has a couple of moves: left or right, where the face of the robot changes direction, and a move action, one step forward.

class Robot

  def initialize(pos_X, pos_Y, facing)
    @pos_X, @pos_Y, @facing = pos_X, pos_Y, facing
  end

  def move
    world_switch(Proc.new { @pos_X += 1}, Proc.new { @pos_X -= 1},
                 Proc.new { @pos_Y += 1}, Proc.new { @pos_Y -= 1})
  end

  def left
    world_switch(Proc.new {@facing = 'WEST'}, Proc.new {@facing = 'EAST'},
                Proc.new {@facing = 'NORTH'}, Proc.new {@facing = 'SOUTH'})
  end

  def right
    world_switch(Proc.new {@facing = 'EAST'}, Proc.new {@facing = 'WEST'},
                Proc.new {@facing = 'SOUTH'}, Proc.new {@facing = 'NORTH'})
  end

  def report
    puts "Output: " <<  @pos_X.to_s << ',' << @pos_Y.to_s << ',' << @facing
  end

  def world_switch(do_on_north, do_on_south, do_on_east, do_on_west)
    case @facing
    when 'NORTH'
      do_on_north.call
    when 'SOUTH'
      do_on_south.call
    when 'EAST'
      do_on_east.call
    when 'WEST'
      do_on_west.call
    end
  end
end


texts:
The following is my implementation of a command-line Tic-Tac-Toe game, written in Ruby. This was my first attempt at practicing object-oriented design principles.

require 'colored'

module TicTacToe
  class Player
    attr_accessor :symbol
    def initialize(symbol)
      @symbol = symbol
    end
  end

  class Board
    attr_reader :spaces
    def initialize
      @spaces = Array.new(9)
    end

    def to_s
      output = ""
      0.upto(8) do |position|
        output << "#{spaces[position] || position}"
        case position % 3
        when 0, 1 then output << " | "
        when 2 then output << "\n-----------\n" unless position == 8
        end
      end
      output
    end

    def check_space(cell, sym)
      if spaces[cell].nil?
        place_symbol(cell, sym)
        @current_turn += 1
      else
        puts "Space unavailable! Please select another cell"
      end
    end

    def place_symbol(cell, sym)
      spaces[cell] = sym
    end

    WINNING_COMBOS = [
      [0, 1, 2], [3, 4, 5], [6, 7, 8],
      [0, 3, 6], [1, 4, 7], [2, 5, 8],
      [0, 4, 8], [2, 4, 6]
    ]

    def winning_scenarios
      WINNING_COMBOS.each do |set|
        if spaces[set[0]] == spaces[set[1]] && spaces[set[1]] == spaces[set[2]]
          return true unless spaces[set[0]].nil?
        end
      end
      false
    end

    def tie
      if !spaces.include?(nil) && !winning_scenarios
        return true
      end
    end
  end

  class Game < Board
    attr_reader :player1, :player2, :symbol
    def initialize
      super
      play_game
    end

    def play_game
      @player1 = Player.new("X")
      @player2 = Player.new("O")
      puts Board.new
      @current_turn = 1
      turn
      win_message
      tie_message
      play_again
    end

    def move(player)
      while !winning_scenarios && !tie
        puts "Where would you like to move 'player #{player.symbol}'?".red
        choice = gets.chomp.to_i
        check_space(choice, player.symbol)
        puts "Player #{player.symbol}'s move:".green
        puts self
        turn
      end
    end

    def tie_message
      puts "It's a Draw!".cyan if tie
    end

    def win_message
      puts "Game over!".cyan if winning_scenarios
    end

    def turn
      @current_turn.even? ? move(@player2) : move(@player1)
    end

    def play_again
      puts "Play again? (yes or no)".yellow
      answer = gets.chomp.downcase
      if answer == "yes"
        TicTacToe::Game.new
      else
        puts "Goodbye".cyan.bold
      end
    end
  end
end

TicTacToe::Game.new


texts:
I recently started learning Haskell and had to program a 4 Bit Ripple Carry Adder that worked with tuples of the form

type Nibble = (Bool, Bool, Bool, Bool)

Beforehand I wrote the functions

-- XOR operator
xor :: Bool -> Bool -> Bool
xor a b = (not (a && b) ) && (a || b)

-- Fulladder for 1-Bit binary numbers
-- Returns Tuple in the Form (add Carry, Sum)
fulladder :: Bool -> Bool -> Bool -> (Bool, Bool)
fulladder a b ci = ( (a && b) || ( (xor a b) && ci ), xor ci (xor a b) )

-- Second Element of (Bool, Bool)
saccess :: (Bool, Bool) -> Bool
saccess (f, a) = a

-- First Element of (Bool, Bool)
faccess :: (Bool, Bool) -> Bool
faccess (a, f) = a

-- 4-Bit Adder that does Nibble + Nibble = Nibble
rippleCarryAdder :: Nibble -> Nibble -> Nibble
rippleCarryAdder (a0, a1, a2, a3) (b0, b1, b2, b3) = (saccess (fulladder a0 b0 (faccess (fulladder a1 b1 (faccess (fulladder a2 b2 (faccess (fulladder a3 b3 False))))))), saccess (fulladder a1 b1 (faccess (fulladder a2 b2 (faccess (fulladder a3 b3 False))))), saccess (fulladder a2 b2 (faccess (fulladder a3 b3 False ))), saccess (fulladder a3 b3 False) )

I have the constraint that I can't change the types in the definitions of the functions fulladder and rippleCarryAdder. So one has to work with Nibble.
I would like to know if there is a more elegant way to work with the tuples returned by fulladder without defining a lot of other functions.


texts: Code that lists and inserts data to database: Make methods more reusable in superclass

texts:
I'm trying to make some methods more reusable and have now three classes that work together: AbstractDao (the superclass), MemberDao (extends AbstractDao) and ProjectTaskDao (extendsAbstractDao). The method insert is very similar in both subclasses with some minor differences:
insert method in MemberDao:
public void insert(Member member) throws SQLException {
try (Connection connection = dataSource.getConnection()){
    try(PreparedStatement statement = connection.prepareStatement(
            "INSERT INTO members (member_name, email) values (?, ?)",
            Statement.RETURN_GENERATED_KEYS
    )){
        statement.setString(1, member.getName());
        statement.setString(2, member.getEmail());
        statement.executeUpdate();

        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            generatedKeys.next();
            member.setId(generatedKeys.getLong("id"));
        }
    }
}

}
insert method in ProjectTaskDao:
public void insert(ProjectTask task) throws SQLException {
try (Connection connection = dataSource.getConnection()){
    try(PreparedStatement statement = connection.prepareStatement(
            "INSERT INTO project_tasks (task_name) values (?)",
            Statement.RETURN_GENERATED_KEYS
    )){
        statement.setString(1, task.getName());
        statement.executeUpdate();

        try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
            generatedKeys.next();
            task.setId(generatedKeys.getLong("id"));
        }
    }
}

}
Thesee methods do the same with some minor differences with the "statement.setSomething()". I`m not that advanced in Java yet so I'm kind of stuck on this. I would also like to pull these methods in as well:
list method in MemberDao:
public List<Member> list() throws SQLException {
List<Member>  members = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) {
    try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM members")) {
        try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                Member member = new Member();
                member.setName(rs.getString("member_name"));
                members.add(mapRow(rs));
            }
        }
    }
}
return members;

}
list method in ProjectTaskDao:
public List<ProjectTask> list() throws SQLException {
List<ProjectTask>  tasks = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) {
    try (PreparedStatement statement = connection.prepareStatement("SELECT * FROM project_tasks")) {
        try (ResultSet rs = statement.executeQuery()) {
            while (rs.next()) {
                //ProjectTask projectTask = new ProjectTask();
                //projectTask.setName(rs.getString(""));
                tasks.add(mapRow(rs));
            }
        }
    }
}
return tasks;

}
And here is the whole superclass as it stands currently:
public abstract class AbstractDao<T> {
protected final DataSource dataSource;

public AbstractDao(DataSource dataSource) {
    this.dataSource = dataSource;
}

protected T retrieve(Long id, String sql) throws SQLException {
    try (Connection connection = dataSource.getConnection()) {
        try (PreparedStatement statement = connection.prepareStatement(sql)) {
            statement.setLong(1, id);
            try (ResultSet rs = statement.executeQuery()) {
                if (rs.next()) {
                    return mapRow(rs);
                } else {
                    return null;
                }

            }
        }
    }
}

protected abstract T mapRow(ResultSet rs) throws SQLException;

}
Let me know if you need more information to help! Thanks :D


texts: Splitting a Multi-FASTA file into individual files

texts:
I have written a program to split a Multi-FASTA file into individual fasta files.

use strict;
use autodie;

open( my $IN, '<', $ARGV[0] );

my ( $id, $seq_obj );

sub dump_seq {

    my $sid = shift;
    my $seq = shift;

    my @parts = split( /\h+/, $sid );
    my $f_name = $parts[0];

    $f_name =~ s/\|/_/g;
    $f_name =~ s/^>//;
    $f_name =~ m/\_$/
        ? ( $f_name =~ s/.$/\.fasta/ )
        : ( $f_name .= ".fasta" );  # Controlling extension
    my @lines = $seq =~ m/.{1,60}/g; # controlling line length

    open( my $out, '>', $f_name );

    print {$out} "$sid\n";
    print {$out} "$_\n" for (@lines);

    return 0;

}

while (<$IN>) {

    chomp;

    if (/^>/) {

        if ( $. > 1 ) { # Else there would be no-output for first fasta
            dump_seq( $id, $seq_obj );
        }

        $id = $_;
        next;
    }

    $seq_obj = $seq_obj . $_;

    dump_seq( $id, $seq_obj ) if (eof); # For last fasta only
}

In this code I made calls to dump_seq() two times, I want to minimize it to one and place the call appropriately.

I can also do it by storing all the $id and $seq_obj in a hash and call the function once, which takes up lot of memory, which I don't want.

Sample Input:

>gi|129367|sp|P13481.1|P53_CHLAE RecName: Full=Cellular tumor antigen p53; AltName: Full=Tumor suppressor p53 [Chlorocebus aethiops]
MEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEAAPHMAPTPAAP
KPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPAGSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSD
>gi|635087583|ref|XP_008008385.1| PREDICTED: cellular tumor antigen p53 isoform X2 [Chlorocebus sabaeus]
MEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEAAPPMAPTPAAP
SCMGGMNRRPILTIITLEDSSGNLLGRNSFEVRVCACPGRDRRTEEENFRKKGEPCHELPPGSTKRALPNNTSSSPQPKK
KPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPAGSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSD
>gi|402898625|ref|XP_003912321.1| PREDICTED: cellular tumor antigen p53 [Papio anubis]
MEEPQSDPSIEPPLSQETFSDLWKLLPENNVLSPLPSQAVDDLMLSPDDLAQWLTEDPGPDEAPRMSEATPPMAPTPAAP
KPLDGEYFTLQIRGRERFEMFRELNEALELKDAQAGKEPAGSRAHSSHLKSKKGQSTSRHKKFMFKTEGPDSD


texts:
Is this a good/correct way to write a robust C program?

//File1 => Module1.c

static int Fun(int);

struct{
int (*pFn)(int)
}Interface;

static int Fun(int){
//do something
}

Interface* Init(void)
{
  Interface *pInterface = malloc(sizeof(Interface));
  pInterface->pFn = Fun;
  return pInterface;
}

//File 2
main()
{
  Interface *pInterface1 = Init();
  pInterface1->pFn(5);
}

My intention is to make each module expose an interface.  Give your thoughts.


texts: Handle Java Process outputs without extra-threads

texts:
Usually, people would create two extra-threads in order to read the standard output and error respectively. However, the following code would allow to handle a Process outputs without those threads (it is arguably a little bit more difficult to decode the characters if you are using something else than a single-byte encoding and if you can't buffer the output in memory).

Although the following code seems to work, it is different enough from the "standard" solution, that I'm wondering if anyone can find am issue with it.

public static void main(String[] args) throws IOException, InterruptedException {
  ProcessBuilder processBuilder = new ProcessBuilder(args);
  Process process = processBuilder.start();

  InputStream outputStream = null, errorStream = null;
  ByteArrayOutputStream outputBuffer = new ByteArrayOutputStream();
  ByteArrayOutputStream errorBuffer = new ByteArrayOutputStream();
  try {
    outputStream = process.getInputStream();
    errorStream = process.getErrorStream();

    byte[] tmp = new byte[1024];

    while (true) {
      int outputBytes = readAvailablOnce(outputStream, outputBuffer, tmp);
      int errorBytes = readAvailablOnce(errorStream, errorBuffer, tmp);
      if (outputBytes == 0 && errorBytes == 0) {
        try {
          process.exitValue();
          break;
        } catch (IllegalThreadStateException e) {
          // keep on looping
        }
      }
    }
    readAvailableAll(outputStream, outputBuffer, tmp);
    readAvailableAll(errorStream, errorBuffer, tmp);

  } finally {
    closeQuietly(outputStream);
    closeQuietly(errorStream);
  }

  System.out.println(outputBuffer.toString("ASCII"));
  System.err.println(errorBuffer.toString("ASCII"));
  System.err.println("exit code: " + process.exitValue());
}

private static void closeQuietly(InputStream in) {
  if (in != null) {
    try {
      in.close();
    } catch (IOException e) {
      // ignored
    }
  }
}

private static int readAvailablOnce(
  InputStream inputStream, OutputStream outputStream, byte[] buffer)
throws IOException {
  int bytesRead = 0;
  if (inputStream.available() > 0) {
    bytesRead = inputStream.read(buffer);
    outputStream.write(buffer, 0, bytesRead);
  }
  return bytesRead;
}

private static void readAvailableAll(
  InputStream inputStream, OutputStream outputStream, byte[] buffer)
throws IOException {
  if (inputStream.available() > 0) {
    int bytesRead = 0;
    while ((bytesRead = inputStream.read(buffer)) >= 0) {
      outputStream.write(buffer, 0, bytesRead);
    }
  }
}


texts:
Checking whether an item exist in a collection isn't straightforward in VBA, it requires error checking and during error handling we need to clear the error and also resume code to be able to correctly manage the next error.

In my codes I generally use this structure, is it a good practice?

    With MyWorkBook
        On Error GoTo NoItem
        With .Sheets(SheetName)
            ' do stuff here if sheet exists
        End With
NoItem:
        If False Then
            Err.Clear
            ' code to do if sheet doesn't exist (e.g. add a new one)
            Resume NoItem
        End If
        On Error GoTo 0 ' (or specify another label for error handling)
        ' continue macro ...
    End With


texts:
I have the following code:

function TSliverHelper.SlowNorth: TSlice;
var
  i: integer;
begin
  // Add pixels 0,1,2
  // This means expanding every bit into a byte
  // Or rather every byte into an int64;
  for i:= 0 to 7 do begin
    Result.Data8[i]:= TSuperSlice.Lookup012[Self.bytes[i]];
  end;
end;

This uses a straight forward lookup table, but obviously LUT's are slow and clobber the cache. This takes about 2860 millisecs for 100.000.000 items.

The following approach is a bit faster (1797 MS, or 37% faster):

function TSliverHelper.North: TSlice;
const
  SliverToSliceMask: array[0..7] of byte = ($01,$02,$04,$08,$10,$20,$40,$80);
asm
  //RCX = @Self    (a pointer to an Int64)
  //RDX = @Result  (a pointer to an array[0..63] of byte)
  movq xmm0,[rcx]                       //Get the sliver
  mov r9,$8040201008040201
  movq xmm15,r9 //[rip+SliverToSliceMask] //Get the mask
  movlhps xmm15,xmm15                   //extend it
  mov r8,$0101010101010101              //Shuffle mask
  movq xmm14,r8                         //00 00 00 00 00 00 00 00 01 01 01 01 01 01 01 01
  pslldq xmm14,8                        //01 01 01 01 01 01 01 01 00 00 00 00 00 00 00 00
  movdqa xmm1,xmm0                      //make a copy of the sliver
  //bytes 0,1
  pshufb xmm1,xmm14                     //copy the first two bytes across
  pand xmm1,xmm15                       //Mask off the relevant bits
  pcmpeqb xmm1,xmm15                    //Expand a bit into a byte
  movdqu [rdx],xmm1
  //bytes 2,3
  psrldq xmm0,2                         //shift in the next two bytes
  movdqa xmm2,xmm0
  pshufb xmm2,xmm14                     //copy the next two bytes across
  pand xmm2,xmm15                       //Mask off the relevant bits
  pcmpeqb xmm2,xmm15                    //Expand a bit into a byte
  movdqu [rdx+16],xmm2
  //bytes 4,5
  psrldq xmm0,2                         //shift in the next two bytes
  movdqa xmm3,xmm0
  pshufb xmm3,xmm14                     //copy the next two bytes across
  pand xmm3,xmm15                       //Mask off the relevant bits
  pcmpeqb xmm3,xmm15                    //Expand a bit into a byte
  movdqu [rdx+32],xmm3
  //bytes 6,7
  psrldq xmm0,2                         //shift in the next two bytes
  movdqa xmm4,xmm0
  pshufb xmm4,xmm14                     //copy the final two bytes across
  pand xmm4,xmm15                       //Mask off the relevant bits
  pcmpeqb xmm4,xmm15                    //Expand a bit into a byte
  //Store the data
  movdqu [rdx+48],xmm4
end;

However, that is a lot of code. I'm hoping there's a way to do with less processing that's going to work faster.
The way the code works (in prose) is simple.
First we clone the input byte 8 times. Next the bit is masked off using the 01,02,04... mask and an AND operation. Finally this randomish bit is expanded into a byte using the compare-equal-to-mask (pcmpeqb).

The opposite operation is a simple PMSKMOVB.

I can use AVX1 code, but not AVX2.


texts: Command manipulation functions for a toy shell program

texts:
I am writing a small program that is supposed to act as a shell of some sorts. It operates off of a few basic structures, one of them being a command, a command_list, and a command_history.

typedef struct command command;

typedef struct
{
    char** list;
    int len;
} command_history;

typedef struct
{
    command** list;
    int len;
    command_history* history;
} command_list;

typedef struct command
{
    char* alias;
    void (*function)(command_list*);
} command;

I have written functions to add new commands, add new history, find aliases in a list and return its index, among other things, but I have a feeling that the command for adding commands, addcommand is leaking memory. I am not very experienced with C and this is just an experiment to acquaint me with pointers. I would appreciate some feedback on the code I have written and how I can improve it.

Command manipulation functions:

void addcommand(char* str, void* fun, command_list* srclist)
{
    printdebug("Adding command \"%s\" pointing to function at %p in command list located at %p... ", str, fun, srclist);
    srclist -> list = realloc(srclist -> list, sizeof(command*) * (srclist -> len + 1));
    srclist -> list[srclist -> len] = malloc(sizeof(command));
    srclist -> list[srclist -> len] -> alias = malloc(sizeof(char) * (strlen(str) + 1));
    srclist -> list[srclist -> len] -> function = malloc(sizeof(void*)); // problems here and |
    memcpy(srclist -> list[srclist -> len] -> alias, str, sizeof(char) * (strlen(str) + 1)); //       |
    srclist -> list[srclist -> len] -> function = fun; //                                    <|
    srclist -> len++;
    printdebug("Command added.\n");
}

void addhistory(char* str, command_list* srclist)
{
    printdebug("Adding \"%s\" to history list located at %p...", str, srclist -> history);
    srclist -> history -> list = realloc(srclist -> history -> list, sizeof(char*) * (srclist -> history -> len + 1));
    srclist -> history -> list[srclist -> history -> len] = malloc((strlen(str) + 1) * sizeof(char));
    memcpy(srclist -> history -> list[srclist -> history -> len], str, (strlen(str) + 1) * sizeof(char));
    srclist -> history -> len++;
    printdebug(" String added to history.\n");
}

void renamecommand(char* str, command* srccom, command_list* srclist)
{
    if(!srccom -> alias || !srccom -> function)
        return;
    printdebug("Renaming \"%s\" to \"%s\" in command list located at %p... ", srccom -> alias, str, srclist);
    free(srccom -> alias);
    srccom -> alias = malloc((strlen(str) + 1) * sizeof(char));
    memcpy(srccom -> alias, str, (strlen(str) + 1) * sizeof(char));
    printdebug("Renamed command.\n");
}

void deletecommand(command* srccom)
{
    printdebug("Deleting command \"%s\" pointing to function %p located at %p... ", srccom -> alias, srccom -> function, srccom);
    srccom -> alias = "[REMOVED]";
    srccom -> function = NULL;
    printdebug("Command deleted.\n");
}

command_list* newcommandlist()
{
    printdebug("Making new command list... ");
    command_list* new_list = malloc(sizeof(command_list));
    new_list -> list = NULL;
    new_list -> len = 0;
    new_list -> history = malloc(sizeof(command_history));
    new_list -> history -> list = NULL;
    new_list -> history -> len = 0;
    printdebug(" Made new command list located at %p.\n", new_list);
    return new_list;
}


texts: String appending function (location-independent)

texts:
Very useful operation that hasn't been merged into a function.. until now.
This is supposed to insert a substring into a previously d.allocated source string.

void strapp (char *source_offset, int position, char *appendage)
{
    size_t appendage_size = strlen(appendage) + 1;

    char copy[strlen(source_offset)];
    strcpy(copy, source_offset);

    source_offset = realloc(source_offset, strlen(source_offset) + appendage_size);
    memcpy(&source_offset[position], appendage, strlen(appendage));
    sprintf(source_offset + (position + strlen(appendage)), &copy[position]);
}

USAGE:

int main(void)
{
    char *str1 = malloc(11 + 1);

    sprintf(str1, "Hello World");

    strapp(str1, 5, " Horrible");

    printf(str1);
    free(str1);

    return 0;
}

Produces the output:

Hello Horrible World


texts:
For practice I wrote a function to generate a list of numbers from a start to an end by a step. I couldn't make it- like the built-in range- default start to 0, because all optional parameters must come after required ones, so def range(start=0, end, step=1) won't work.

Here's my script:

def Range(start, end, step=1):
    """Returns a list of numbers beginning from start and
       incremented by step to end (with end excluded).

      start: an integer specifies the start of the range.

      end: an integer specifies the end of the range.

      step: an integer specifies the number to increment by.
      """

    num = start
    result = []

    while num < end:
        result.append(num)
        num += step

    return result

How can it be refactored and optimized ?

Notes:

I'm a hobbyist and beginner (in Python in particular, and programming in general).