texts:
- INTERRUPT HANDLER -

> READ FROM IN.1 THROUGH IN.4
> WRITE THE INPUT NUMBER WHEN
  THE VALUE GOES FROM 0 TO 1
> TWO INTERRUPTS WILL NEVER CHANGE
  IN THE SAME INPUT CYCLE

I was stuck on this one when I went to bed last night.  But of course, like any good programmer, sleeping is when I get most of my work done.

My primary goal here is fewer cycle counts.  If the above... erm, graph... is anything to go by, it looks like I could have quite a bit less cycle counts.  Secondary would be reducing the instruction count (but not at the expense of cycle counts).  I can imagine how to get it down to 7 nodes rather than 9, but I can't imagine that also makes the program more efficient (in terms of cycle counts).

So, how can I reduce the cycle counts here?

ROW 1, COLUMN 1 (IN.1)

MOV UP, ACC
START:
 MOV 0, DOWN
 JEZ CHECK
 JNZ CONTINUE
CHECK:
 MOV UP, ACC
 JEZ START
 MOV 1, DOWN
CONTINUE:
 MOV UP, ACC
 JMP START

ROW 1, COLUMN 2 (IN.2)

MOV UP, ACC
START:
 MOV 0, DOWN
 JEZ CHECK
 JNZ CONTINUE
CHECK:
 MOV UP, ACC
 JEZ START
 MOV 2, DOWN
CONTINUE:
 MOV UP, ACC
 JMP START

ROW 1, COLUMN 3 (IN.3)

MOV UP, ACC
START:
 MOV 0, DOWN
 JEZ CHECK
 JNZ CONTINUE
CHECK:
 MOV UP, ACC
 JEZ START
 MOV 3, DOWN
CONTINUE:
 MOV UP, ACC
 JMP START

ROW 1, COLUMN 4 (IN.4)

MOV UP, ACC
START:
 MOV 0, DOWN
 JEZ CHECK
 JNZ CONTINUE
CHECK:
 MOV UP, ACC
 JEZ START
 MOV 4, DOWN
CONTINUE:
 MOV UP, ACC
 JMP START

ROW 2, COLUMN 1

MOV UP, RIGHT

ROW 2, COLUMN 2

ADD LEFT
ADD UP
MOV ACC, RIGHT
MOV 0, ACC

ROW 2, COLUMN 3

ADD LEFT
ADD UP
ADD RIGHT
MOV ACC, DOWN
MOV 0, ACC

ROW 2, COLUMN 4

MOV UP, LEFT

ROW 3, COLUMN 3 (OUT)

MOV ANY, DOWN


texts: Null Object pattern with simple class hierarchy

texts:
I have a simple two-class hierarchy to represent U.S. ZIP (12345) and ZIP+4 (12345-1234) codes. To allow clients to allow both types for a field/parameter or restrict it to one type or the other, the specific types inherit from a common generic ZipCode interface.

Update: A ZIP code is five digits. A ZIP+4 code consists of the primary five-digit ZIP code plus a four-digit plus-4 (+4) code. You can create a ZIP+4 from a regular ZIP and get the primary ZIP from a ZIP+4. Thus, the interface which the two classes implement knows about the two classes, and they know about each other.

interface ZipCode
    boolean isPlusFour()
    ZipPlusFour plusFour(String code)
    Zip primary()
    boolean hasSamePrimary(ZipCode other)

class Zip implements ZipCode
    String code

class ZipPlusFour implements ZipCode
    Zip primary
    String plusFourCode

Introducing Null Object Pattern

To avoid duplicating code that checks for null values throughout the application, I would like to introduce the Null Object pattern. However, I'm afraid the only way to do so that supports the features above is to add three new classes instead of just one:

class NullZipCode implements ZipCode
class NullZip extends Zip
class NullZipPlusFour extends ZipPlusFour

Worse, since the last two extend concrete classes they will need to pass special values to their superclass that will pass validation but not block the possibility of using real values. For example, NullZip would call super("00000").

Here are my main questions, though please don't hesitate to throw out any suggestions you have.

Is there a way to solve this with just one new class to cover all bases?
Is it worth extracting interfaces from Zip and ZipPlusFour so that NullZip won't extend the concrete Zip implementation (same for ZipPlusFour)?

ZipCode
  Zip
    NullZip
    RealZip

Another option is to forego separate classes altogether and check for a special value in Zip and ZipPlusFour to signify a missing ZIP code.

class Zip
    boolean isNone() {
        return code.equals("00000");
    }

    boolean hasSamePrimary(ZipCode other) {
        if (isNone() || other.isNone())
            return false;
        else
            return code.equals(other.primary().code);
    }

At least the complicated checks are encapsulated in these classes which is the whole point of introducing the pattern. The downside is that this logic can be more fragile than inheritance. Is this a good trade-off?


texts: Group list of words by occurrence / inverse index of strings

texts:
I'm currently working through Coding the matrix, though I'm trying to work through it using Haskell rather than Python. One of the exercises has you write a function where you take a list of strings, and then transform them into an inverse index of the words contained in each string, along with the index of the originating string:

> makeInverseIndex ["hello world", "world test", "hello test"]
fromList [("hello",fromList [0,2]),("test",fromList [1,2]),("world",fromList [0,1])]

You then implement an orSearch and an andSearch, which returns the indexes of the strings that match the search:

> orSearch ["hello", "world"] $ makeInverseIndex ["hello world", "world test", "hello test"]
fromList [0,1,2]

> andSearch ["hello", "world"] $ makeInverseIndex ["hello world", "world test", "hello test"]
fromList [0]

Here is my attempt in Haskell:

import Data.List as L
import Data.Map.Strict as M
import Data.Set as S

makeInverseIndex :: [String] -> Map String (Set Int)
makeInverseIndex = L.foldr (unionWith S.union . uncurry group) M.empty . zipWithIndex . L.map words
  where
    zipWithIndex :: [a] -> [(Int, a)]
    zipWithIndex xs = zip [0..length xs] xs

    group :: Ord k => v -> [k] -> Map k (Set v)
    group n = M.fromList . L.map (\w -> (w, S.singleton n))

orSearch :: [String] -> Map String (Set Int) -> Set Int
orSearch words =
  M.foldr S.union S.empty . pick words

andSearch :: [String] -> Map String (Set Int) -> Set Int
andSearch words index =
  M.foldr S.intersection (S.fromList [0..length index-1]) . pick words $ index

pick :: Ord k => [k] -> Map k v -> Map k v
pick keys m =
  restrictKeys m $ S.fromList keys


texts: Converting polar coordinates to Cartesian coordinates

texts:
I have a functional script that converts polar coordinates to Cartesian coordinates and then matches a value in a separate array to the coordinates. It works well, but I find that it takes a long time to run due to the length of the matrices being processed. Each file has four columns and 2,880,000 rows which means that I have 11,520,000 total values being processed. The data looks like this-

   [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

The array rf.190301 is a three dimensional array that looks like this-

, , 1

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

, , 2

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

, , 3

     [,1] [,2] [,3]
[1,]    1    1    1
[2,]    2    2    2
[3,]    3    3    3

I'm fairly new to R and am just looking for a way to optimize what I'm trying to do in order to make it run a bit faster.

Polar2Cart <- function(x) {

Cart.x <- matrix(NA, nrow = 2880000, ncol = 4)

   for (i in 1:nrow(x)) {

      z[i]<- x[i,1]
      t[i]<- x[i,2]
      r[i]<- x[i,3]

        theta.polar[i] <- (x[i,2] * (pi/180))
        r.polar[i] <- (x[i,3] * 0.075)

            x.cart[i] <- r.polar[i]*cos(theta.polar[i])
            y.cart[i] <- r.polar[i]*sin(theta.polar[i])
            value[i] <- rf.190301[z[i], t[i], r[i]]

        Cart.x[i,] <- cbind(z[i], y.cart[i], x.cart[i], value[i])
     }
}


texts: Checking 160,000 records in a database for changes

texts:
I am checking over 160,000 records in my database every 24 hours to see if there were changes in the incoming data coming from API and my existing data in the database. If there were I am updating those, otherwise I'm doing nothing. Checking 189 days takes 10 seconds and 160,000 about 2.5 hours.

What can I improve in my code to speed this up?

$listings = Array('23169','23567','23114','5487'); //Rooms to check (189 days in each room)
$count_listings = count(listings); //count the rooms
$continue = TRUE;
$x = 0;

while ($continue == TRUE && $x < $count_listings) {
    foreach ($listings as $list) {
        //Generates a link from the looped @list
        $url = $this->generate_link($list);
        $results_page = $this->http_get_contents($url, $this->generate_proxy()); //JSON output
        $calendar_month = json_decode($results_page, true); //Into Array

        $data = Array();

        foreach ($calendar_month['calendar_months'] as $month) {
            foreach ($month['days'] as $day) {
                $data[] = $day; //Getting each day
            }
        }
        //Super_unique removes duplicate days
        foreach ($this->super_unique($data) as $day_info) {
            $data_listing = Array(
                'list_id'           => $list,
                'list_price'        => $day_info['price']['local_price'],
                'list_currency'     => $day_info['price']['local_currency'],
                'list_date'         => $day_info['date'],
                'list_available'    => $this->check_list_available((int)$day_info['available'])
            );
            //First get incoming result and search in the database
            $check = $this->db->select('list_price, list_available')
                ->from('airbnb_lists_price')
                ->where("(list_id = '{$data_listing['list_id']}' and list_date = '{$data_listing['list_date']}')")
                ->get();
            //If the record exists
            if ($check->num_rows() > 0) {
                foreach ($check->result() as $row) {
                    //If the record info was changed update
                    if ($row->list_price != $data_listing['list_price'] || $row->list_available != $data_listing['list_available']) {
                        $this->db->where("(list_id = '{$data_listing['list_id']}' and list_date = '{$data_listing['list_date']}')");
                        $this->db->update('airbnb_lists_price', $data_listing);
                    }
                    else {
                    //do nothing
                    }
                }
            }
        }
        $x++;
    }
    if ($x > $count_listings) {
        $continue = FALSE;
    }
}


texts: jQuery toggle sort order and save to variable

texts:
This works fine but I find it quite big and had hoped there was a cleaner/smaller "toggle" function or alike which I could use but it seems to be related to visibility only - and I want to set a variable (for later usage).

Can this be optimized, if I want a toggle function which should be used to sort a column (and get the value into a variable)?

jsFiddle

    Col 1
    Col 2
    Col 3

    A
    B
    C

    B
    C
    A

And the jQuery stuff:

var column;
var order;

$('thead th').click(function () {

  // Get the current column clicked
  var thisColumn = $(this).text();

  // Check if the column has changed
  if(thisColumn == column) {
    // column has not changed

    if(order == "ascending") {
      order = "descending";
    } else {
      order = "ascending";
    }
  } else {
    // column has changed

    column = thisColumn;
    order = "descending";
  }

  // Replace text in DIV
  $("div").text("column=["+column+"], order=["+order+"]");

  // future code will use the sort order to get database
  // stuff with Ajax

});


texts:
I'm working on an exercise that counts the number of even digits, odd digits, or zeros in a user-input integer (I made it a long so the user could put in more numbers). However I have a bunch of repetitive code when I'm building my output, especially about the pluralization of "[s]". Really, the entire thing feels redundant. How can I factor or simplify the code to be cleaner and most efficient? This isn't homework or anything, but I'm trying to do stuff out of the book to get more practice.

/**************************************************************************************************
 *  Program Name:     Programming Project 4.5: Digit Checks in a Number
 *  Author:           Terry Weiss
 *  Date Written:     September 26, 2015
 *  Program Description:
 *     Design and implement an application that determines and prints the number of odd, even
 *  and zero digits in an integer value read from the keyboard.
 **************************************************************************************************/

import java.util.Scanner;

public class PP4_5
{

    public static void main( String[] args )
    {
        long number;
        boolean validInput = false;
        String numStr;
        Scanner input = new Scanner(System.in);

        do
        {
            System.out.print("Please enter an integer:  ");
            numStr = input.next();

            try {
                number = Long.parseLong(numStr);
                validInput = true;
            } catch (NumberFormatException e) {
                System.out.print("That's not an integer. ");
                number = 0;
            }
        } while (!validInput);

        // Break each digit up by dividing by powers of 10.
        int evens = 0, odds = 0, zeros = 0;
        for (long temp = number; temp > 0; temp /= 10)
        {
            int digit = (int)(temp % 10);

            if (digit == 0)
            {
                zeros++;
                System.out.println(digit + " is a zero digit.");
            }
            else if (digit % 2 == 0)
            {
                evens++;
                System.out.println(digit + " is an even digit.");
            }
            else
            {
                odds++;
                System.out.println(digit + " is an odd digit.");
            }
        }

        String evenStr = " even " + ((evens == 1) ? "digit" : "digits");
        String oddStr = " odd " + ((odds == 1) ? "digit" : "digits");
        String zeroStr = (zeros == 1) ? " zero" : " zeros";

        System.out.println(number + " has " + evens + evenStr + ", " + odds + oddStr + ", and "
                + zeros + zeroStr + ".");
    }

}


texts: Formatting uptime as a human-friendly time interval

texts:
# extend Time class for readable method
class Time
  def readable
    case uptime
    when 0 then 'just now'
    when 1 then 'uptime second ago'
    when 2..59 then uptime.to_s + ' seconds ago'
    when 60..119 then 'uptime minute ago' # 120 = 2 minutes
    when 120..3540 then (uptime / 60).to_i.to_s + ' minutes ago'
    when 3541..7100 then 'an hour ago' # 3600 = 1 hour
    when 7101..82_800 then ((uptime + 99) / 3600).to_i.to_s + ' hours ago'
    when 82_801..172_000 then 'uptime day ago' # 86400 = 1 day
    else ((uptime + 800) / 86_400).to_i.to_s + ' days ago'
    end
  end

  private

  def uptime
    (Time.now - self).to_i
  end
end

Linter raises the following warnings. How can this be fixed?

TooManyStatements: Time#readable has approx 10 statements [https://github.com/troessner/reek/blob/master/docs/Too-Many-Statements.md]
Assignment Branch Condition size for readable is too high. [22.47/15]
Cyclomatic complexity for readable is too high. [9/6]
Method has too many lines. [11/10]


texts:
I wrote this program in Python 3.I would like to know if there is some more functionality that could be added/removed/is missing.Any comments would be helpful!

#Steps from user :
"""
Enter Input
P1 and P2
Each time for input will be preceded by a printed board.
The game will continue until an input matches a win combination.
"""
win_combinations = [
    [1,2,3],
    [4,5,6],
    [7,8,9],
    [1,4,7],
    [2,5,8],
    [3,6,9],
    [1,5,9],
    [3,5,7]]

tot_list = [1,2,3,4,5,6,7,8,9]

def board():
    print ("{}|{}|{}".format(tot_list[0],tot_list[1],tot_list[2]))
    print ("{}|{}|{}".format(tot_list[3],tot_list[4],tot_list[5]))
    print ("{}|{}|{}".format(tot_list[6],tot_list[7],tot_list[8]))

p1 = 0
p2 = 0

def player_input():
    global p1
    global p2
    while True:
        try:
            print("\n\n")
            board()
            print("\n")
            p1 = int(input("P1(X): Enter your Input:"))
            print("\n")
            p2 = int(input("P2(O): Enter your Input:"))
            if 0 < p1 < 10 and 0 < p2 < 10 :
                assign_values(p1,p2)
                break
            print("Re-enter valid input")
        except:
            print("Invalid input")
            continue

def assign_values(player1,player2):
    if type(tot_list[player1-1]) == str() or type(tot_list[player2-1]) == str():
        print("Re-enter valid input")
        player_input()
    if player1 in tot_list:
        tot_list[player1-1] = "X"
    if player2 in tot_list:
        tot_list[player2-1] = "O"

p1_win = False
p2_win = False
tie = False

def default_values():
    global tot_list
    global p1
    global p2
    global p1_win
    global p2_win
    global tie
    tot_list = [1,2,3,4,5,6,7,8,9]
    p1 = 0
    p2 = 0
    p1_win = False
    p2_win = False
    tie  = False

def play():
    global p1_win
    global p2_win
    global tie
    global tot_list
    while True:
        player_input()
        for i in win_combinations:
            if tot_list[i[0]-1] == "X" and tot_list[i[1]-1] == "X" and tot_list[i[2]-1] == "X":
                p1_win = True
                break
            elif tot_list[i[0]-1] == "O" and tot_list[i[1]-1] == "O" and tot_list[i[2]-1] == "O":
                p2_win = True
                break
        if all(isinstance(i,str) for i in tot_list) == True:
            tie == False
        if p1_win==True:
            print("P1 has won!")
            break
        elif p2_win==True:
            print("P2 has won!")
            break
        elif tie == True:
            print("Its a tie!")
            break

    play_again = input("Play Again?(y/n)")
    if play_again == "y":
        default_values()
        play()
    else:
        print("Ciao")
if __name__ == '__main__':
    play()


texts: Method to Retrieve Data from a MySQL Database

texts:
I have a method that retrieves information relating to a Contact that was made between two Companies. I am looking to improve my code in any way and am intrigued in hearing any recommendations you may have on how this method can be improved. I use it throughout my program but modify it according to the DataModel I am attempting to load.

string constr = ConfigurationManager.ConnectionStrings["sqlString"].ConnectionString;
using (var sqlCon = new MySqlConnection(constr))
{
    sqlCon.Open();
    using (var myQuery = sqlCon.CreateCommand())
    {
        myQuery.CommandText = @"SELECT DISTINCT contacts.contactID, contacts.companyID,
        companies.name, contacts.donestatus, contacts.telephone, employees.ID, employees.name,
        people.ID, people.firstname, people.lastname,
        contacts.contractID, contacts.date, contacts.time,
        presets.presettext, contacts.enteredby, contacts.description
        FROM contacts
        LEFT OUTER JOIN companies ON contacts.companyID = companies.ID
        LEFT OUTER JOIN employees ON contacts.employeeID = employees.ID
        LEFT OUTER JOIN people ON contacts.personID = people.ID
        JOIN presets ON contacts.type = presets.presetIDFoxPro
        WHERE presets.presetreferencefoxpro = 8
        AND contacts.date > @date
        ORDER BY contacts.date DESC";
        myQuery.Parameters.AddWithValue("@date", date);
        using (var myReader = myQuery.ExecuteReader())
        {
            var listOfContacts = new ObservableCollection<ContactModel>();
            while (myReader.Read())
            {
                var details = new ContactModel
                {
                    ID = Convert.ToInt32(myReader[0]),
                    CompanyID = DBNullCheck(myReader[1]),
                    CompanyName = myReader[2].ToString().Trim(),
                    DoneStatus = Convert.ToInt32(myReader[3]),
                    Telephone = myReader[4].ToString().Trim(),
                    EmployeeID = DBNullCheck(myReader[5]),
                    EmployeeName = myReader[6].ToString().Trim(),
                    PersonID = DBNullCheck(myReader[7]),
                    PersonName = myReader[8].ToString().Trim() + " " + myReader[9].ToString().Trim(),
                    ContractID = DBNullCheck(myReader[10]),
                    Date = Convert.ToDateTime(myReader[11]),
                    Time = Convert.ToDateTime(myReader[12]),
                    TypeOfContact = myReader[13].ToString().Trim(),
                    EnteredBy = myReader[14].ToString().Trim(),
                    Notes = myReader[15].ToString(),
                };
                listOfContacts.Add(details);
            }
            return listOfContacts;
        }
    }
}

I would be happy if you could recommend improvements to my C# code or my MySQL statement alike.


texts: Coding Challenge: Return The Smaller String

texts:
A coding challenge in which we are to write a function that compares two strings and returns the one that is smaller. The comparison is both lexicographical and numerical, depending on the content of the strings as explained below and in the comments of the code.

Both strings may contain any characters. Consecutive numbers in the string are considered a single number. If during the search the character of only one string is a number, then that string is returned as numbers are lexicographically smaller than letters.

If during the search the characters of both strings are numbers, then parseInt(strX.slice(i)) checks if there are more consecutive digits in each string and returns the string whose number is numerically smaller.

Examples:

input: "a", "b"
expected output: "a" since "a" comes before "b" alphabetically

input: "a1", "a2"
expected output: "a1" since 1 comes before 2

input: "a10", "a2"
expected output: "a2" since 2 comes before 10

Here is the code:

const smallestString = (str1, str2) => {
    // we only need to iterate through the shortest string
    const len = str1.length < str2.length ? str1.length : str2.length;
    for (let i = 0; i < len; i++) {
        // check if both letters are strings
        if (str1[i].toUpperCase() !== str1[i].toLowerCase() && str2[i].toUpperCase() !== str2[i].toLowerCase()) {
            if (str1[i] === str2[i]) { // if both letters are the same, continue
                continue;
            } else {
                return str1[i] < str2[i] ? str1 : str2; // otherwise return the string with the 'smaller' char at that index
            }
        } else if (!isNaN(str1[i] || !isNaN(str2[i]))) { // check if either char is a number
            if (!isNaN(str1[i]) && !isNaN(str2[i])) { // if both chars are numbers, return str with numerically smaller number
              return parseInt(str1.slice(i)) < parseInt(str2.slice(i)) ? str1 : str2;
            }
        } else {
            return str1[i] < str2[i] ? str1 : str1;
        }
    }
    return str1; // if we get here then both strings are equal and either can be returned
}

console.log(smallestString('a10', 'a2')); // returns 'a2'

I am seeking any and all feedback about cleaning up the code and possibly improving the algorithm's current time complexity of O(n).


texts:
What can I do to improve performance of this function? So far I've changed stuff as local as possible and made a break if all possible surrounding tiles have been found. Also I use a separate variable to track the length of a list instead of len().

The usage of this is to find surrounding tiles for all tiles.

def getsurroundings(tiles):
    for t in tiles:
        currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
        check = currentrect.colliderect
        surroundings = t.surroundings
        append = t.surroundings.append
        surroundingscount = t.surroundingscount
        for t2 in tiles:
            if check(t2.rect) and not t == t2 and not t2 in surroundings:
                append(t2)
                t2.surroundings.append(t)
                surroundingscount+=1
                t2.surroundingscount+=1
            if surroundingscount == 8:
                break
    return tiles

Here's the code without localisations which might be easier to read:

def getsurroundings(tiles):
    for t in tiles:
        currentrect = Rect(t.rect[0] - t.rect[2] / 2, t.rect[1] - t.rect[3] / 2, t.rect[2] * 2, t.rect[3] * 2)
        for t2 in tiles:
            if currentrect.colliderect(t2.rect) and not t == t2 and not t2 in t.surroundings:
                t.surroundings.append(t2)
                t2.surroundings.append(t)
                t.surroundingscount+=1
                t2.surroundingscount+=1
            if t.surroundingscount == 8:
                break
    return tiles


texts:
This is a simple "Choose a number between 0-9" Game. It works perfectly but I'd like to know if there's a way to make my code smaller with the exact same functionality.

package firstGame;

    import java.util.Scanner;

    public class Player {

        static Scanner p2Name = new Scanner(System.in);
        static Scanner p1Name = new Scanner(System.in);
        static Scanner p3Name = new Scanner(System.in);

        static Scanner p1Num = new Scanner(System.in);
        static Scanner p2Num = new Scanner(System.in);
        static Scanner p3Num = new Scanner(System.in);

        String name;
        int age;
        int size;

        public static void main(String[] args) {

            // Create a random number generator (0-9)
            int number = (int) (Math.random() * 10);

            // Get Player1's name
            System.out.print("Player 1, please enter your name : ");
            String p1 = p1Name.nextLine();
            System.out.println("Welcome " + p1 + "!");

            // Get Player1's chosen number
            System.out.println("Please enter a number between 0 and 9");
            int p1Choice = p1Num.nextInt();
            System.out.println("");

            // Get Player2's name
            System.out.print("Player 2, please enter your name : ");
            String p2 = p2Name.nextLine();
            System.out.println("Welcome " + p2 + "!");

            // Get Player2's chosen number
            System.out.println("Please enter a number between 0 and 9");
            int p2Choice = p2Num.nextInt();
            System.out.println("");

            // Get Player3's name
            System.out.print("Player 3, please enter your name : ");
            String p3 = p3Name.nextLine();
            System.out.println("Welcome " + p3 + "!");

            // Get Player3's chosen number
            System.out.println("Please enter a number between 0 and 9");
            int p3Choice = p3Num.nextInt();
            System.out.println("");

            //Output generated number
            System.out.println("The number I was thinking of was : " + number);

            //if 1 player wins, output this
            if (number == p1Choice || number == p2Choice || number == p3Choice) {
                System.out.println("We have a winner!");
            }

            //Player1 won or lost?
            if (number == p1Choice) {
                System.out.println(p1 + " won!");
            } else {
                System.out.println(p1 + ", you lose!");
            }

            //Player2 won or lost?
            if (number == p2Choice) {
                System.out.println(p2 + " won!");
            } else {
                System.out.println(p2 + ", you lose!");
            }

            //Player3 won or lost?
            if (number == p3Choice) {
                System.out.println(p3 + " won!");
            } else {
                System.out.println(p3 + ", you lose!");
            }

        }

    }


texts: Web page that calculates results of four arithmetic operations for two numbers

texts:
This is the code that I have written for a simple mathematical application using javascript. In accordance with the task, I broke the program into functions that perform the computations.
But I guess my code looks very large:

function addTwoN(a, b){
    return (a + b);
}
function subtractNumb(a,b){
    return (a - b);
}
function multiplNumb(a,b){
    return (a * b);
}
function divisNumb(a,b){
    return (a / b);
}
function myFunction(){
    const firstInput = document.getElementById("first-number").value;
    const secondInput = document.getElementById("second-number").value;
    const result = document.getElementById("result");
    var firstNumb = Number(firstInput);
    var secondNumb = Number(secondInput);
    var sum = addTwoN(firstNumb, secondNumb);
    var sbtr = subtractNumb(firstNumb, secondNumb);
    var multi = multiplNumb(firstNumb, secondNumb);
    var divis = divisNumb(firstNumb, secondNumb);
    var str =
    firstNumb + " + " + secondNumb + " = " + sum + "
" +
    firstNumb + " - " + secondNumb + " = " + sbtr + "
" +
    firstNumb + " * " + secondNumb + " = " + multi + "
" +
    firstNumb + " / " + secondNumb + " = " + divis;
    result.innerHTML = str;
}
<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,700" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">

<form class="ml-5 mb-5 mt-5">

     What is the first number?
     <input type="number" class="form-control" name="" id="first-number" oninput="validity.valid||(value=''); myFunction()" min="0" style="width: 90px">

     What is the second number?
     <input type="number" class="form-control" name="" oninput="validity.valid||(value=''); myFunction()" id="second-number" min="0" style="width: 90px">

</form>


texts:
I'm teaching myself Rust, and to do this I've written a toy register based virtual machine. I hope the code is easy to follow - I just want to know if there are any mistakes I am making with the language philosophy or if there are syntax tricks I could be using. For example, the program counter pc and the register fields reg_field are mutable. I feel like this is the right thing to do in this case as it better reflects processor architecture. But  of course, I might be wrong...

const NUMBER_OF_REGISTERS: usize = 3;

enum Instruction {
    Halt,
    Load { reg: usize, value: u16 },
    Swap { reg1: usize, reg2: usize, reg3: usize },
    Add { reg1: usize, reg2: usize, reg3: usize },
    Branch { offset: usize }
}

fn main() {
    let encoded_instructions = &[0x1110, 0x2100, 0x3010, 0x0];

    cpu(encoded_instructions);
}

fn cpu(encoded_instructions: &[u16]) {
    let mut pc = 0;
    let mut reg_field = [0; NUMBER_OF_REGISTERS];

    loop {
        let encoded_instruction = fetch(pc, encoded_instructions);
        let decoded_instruction = decode(encoded_instruction);

        match decoded_instruction {
            Some(Instruction::Load { reg, value })
                => load(reg, value, &mut reg_field, &mut pc),
            Some(Instruction::Swap { reg1, reg2, reg3 })
                => swap(reg1, reg2, reg3, &mut reg_field, &mut pc),
            Some(Instruction::Add { reg1, reg2, reg3 })
                => add(reg1, reg2, reg3, &mut reg_field, &mut pc),
            Some(Instruction::Branch { offset })
                => branch(offset, &mut pc),
            Some(Instruction::Halt)
                => { halt(&reg_field); break }
            None => break,
        }
    }
}

fn fetch(pc: usize, instructions: &[u16]) -> u16 {
    instructions[pc]
}

fn halt(register_field: &[u16]) {
    println!("{:?}", register_field[0]);
}

fn load(register: usize, value: u16, register_field: &mut [u16], pc: &mut usize) {
    register_field[register] = value;
    *pc += 1;
}

fn swap(reg1: usize, reg2: usize, reg3: usize, register_field: &mut [u16], pc: &mut usize) {
    register_field[reg3] = register_field[reg1];
    register_field[reg1] = register_field[reg2];
    register_field[reg2] = register_field[reg3];
    *pc += 1;
}

fn add(reg1: usize, reg2: usize, reg3: usize, register_field: &mut [u16], pc: &mut usize) {
    register_field[reg3] = register_field[reg1] + register_field[reg2];
    *pc += 1;
}

fn branch(offset: usize, pc: &mut usize) {
    *pc -= offset;
}

fn decode(encoded_instruction: u16) -> Option<Instruction> {
    let operator = encoded_instruction >> 12;
    let reg1 = ((encoded_instruction >> 8) & 0xF) as usize;
    let reg2 = ((encoded_instruction >> 4) & 0xF) as usize;
    let reg3 = (encoded_instruction & 0xF) as usize;
    let offset = (encoded_instruction & 0xFFF) as usize;
    let value = encoded_instruction & 0xFF;

    match operator {
        0 => Some(Instruction::Halt),
        1 => Some(Instruction::Load { reg: reg1, value: value }),
        2 => Some(Instruction::Swap { reg1: reg1, reg2: reg2, reg3: reg3 }),
        3 => Some(Instruction::Add { reg1: reg1, reg2: reg2, reg3: reg3 }),
        4 => Some(Instruction::Branch { offset: offset }),
        _ => None,
    }
}


texts: Copy first n lines of each file in a directory

texts:
In an attempt to learn Haskell, I've built this - it accepts a number n, a source directory, and a sink directory  (ending with /) copies n lines from each file in the source directory to the sink directory.  It is not recursive. Thoughts?

module Main where
import System.Directory
import Control.Monad
import System.IO
import System.IO.Error
import Data.List
import Control.Applicative
import Control.Exception.Base
import System.Environment
import Data.List

--requires / or \ at end.
listFilesInDir :: FilePath -> IO [FilePath]
listFilesInDir dir= (getDirectoryContents dir) >>= filterM (\x ->doesFileExist $ dir ++ x)

readAndWrite:: Handle -> Handle -> IO ()
readAndWrite inHandle outHandle = do
    myLn<-tryIOError(hGetLine inHandle)
    case myLn of
         Left e -> if isEOFError e
                   then return ()
                   else ioError e
         Right myLn -> do hPutStrLn outHandle myLn
                          return ()

writeFirstNLines :: Int-> FilePath->FilePath -> IO ()
writeFirstNLines n source sink =do
    inHandle <- openFile source ReadMode
    outHandle <- openFile sink WriteMode
    replicateM_ n (readAndWrite inHandle outHandle)

main :: IO ()
main = do
    args <- getArgs
    let n = read $ args!!0
    let source = args!!1
    let sink   = args!!2
    let fileList=listFilesInDir  source
    fileSources <-fmap (map (source ++)) $ fileList
    fileSinks <-fmap (map (sink ++)) $ fileList
    --putStrLn "Sources"
    --mapM_ putStrLn fileSources
    --putStrLn "Sinks"
    --mapM_ putStrLn fileSinks
    q<-zipWithM (writeFirstNLines n) fileSources fileSinks
    return()


texts:
I'm looking for a review of my macros. I have these in the project pre-compile header. I tent to copy them into all my new projects as well, unless its a very simple project.

#ifdef __APPLE__
    #import <TargetConditionals.h>
#endif

// turn on or off different types of logging. ALog() is always logged.
#define LOG_D       // Turn on standard debug messages  DLog();
#define LOG_N       // Turn on network debug messages   NLog();
#define LOG_DB      // Turn on database debug messages  DBLog();
#undef  LOG_V       // Turn off verose debug messages   VLog();
#undef  LOG_UI      // Turn off popup messages          UILog();

// -- You should not have to mess with anything below this line --

// Be safe, start with all things defined
#define DEBUGLOG(...) do {} while (0)
#define ALERTLOG(...) do {} while (0)
#define ALWAYSLOG(...) do {} while (0)

// Define three basic debug types, DEBUGLOG, ALERTLOG and ALWAYSLOG
// These macros generally should not be called directly
// DEBUGLOG - show a message only when compiled for debugging
// ALERTLOG - show a popup window message only when compile for debugging
// ALWAYSLOG - show a message debugging and release
#ifdef __APPLE__
#ifdef DEBUG
#undef DEBUGLOG
#define DEBUGLOG(type, fmt, ...) NSLog((@"%@: %s [Line %d] " fmt), type, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#undef ALERTLOG
#if TARGET_OS_MAC
#define ALERTLOG(fmt, ...) DEBUGLOG(@"I", fmt, ##__VA_ARGS__)
#else
#define ALERTLOG(fmt, ...)  { UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:@"%s\n [Line %d] ", __PRETTY_FUNCTION__, __LINE__] message:[NSString stringWithFormat:fmt, ##__VA_ARGS__]  delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; }
#endif
#endif
#undef ALWAYSLOG
#define ALWAYSLOG(type, fmt, ...) NSLog((@"%@: %s [Line %d] " fmt), type, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
#endif

// Create some standard logging macros
#ifdef LOG_D
#define DLog(fmt, ...) DEBUGLOG(@"D", fmt, ##__VA_ARGS__)
#else
#define DLog(...) do {} while (0)
#endif
#ifdef LOG_N
#define NLog(fmt, ...) DEBUGLOG(@"Net", fmt, ##__VA_ARGS__)
#else
#define NLog(...) do {} while (0)
#endif
#ifdef LOG_DB
#define DBLog(fmt, ...) DEBUGLOG(@"DB", fmt, ##__VA_ARGS__)
#else
#define DBLog(...) do {} while (0)
#endif
#ifdef LOG_V
#define VLog(fmt, ...) DEBUGLOG(@"V", fmt, ##__VA_ARGS__)
#else
#define VLog(...) do {} while (0)
#endif
#ifdef LOG_UI
#define UILog(fmt, ...) ALERTLOG(fmt, ##__VA_ARGS__)
#else
#define UILog(...) do {} while (0)
#endif
#define ALog(fmt, ...) ALWAYSLOG(@"V", fmt, ##__VA_ARGS__)


texts: Fast implementation of SQL Queries in Key-Value Store

texts:
I have an existing MySQL schema without rows and have already made a list of all SQL queries I need. Now I know that Redis is a key-value store, so you can only fetch data by key and save for example arrays as json-strings.

My videos table for example looks like the following:

 CREATE TABLE IF NOT EXISTS `videos` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(80) CHARACTER SET utf8 NOT NULL,
`weight` tinyint(4) NOT NULL DEFAULT '0',
`length` varchar(7) NOT NULL DEFAULT '0:00',
`script` text CHARACTER SET utf8 NOT NULL,
`node_id` int(11) NOT NULL,
`filename` varchar(255) CHARACTER SET utf8 NOT NULL,
`filetype` varchar(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `title` (`title`),
KEY `filename` (`filename`),
KEY `title_2` (`title`),
KEY `id` (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=159 ;

And I have for example the need to get all videos with a specific node_id, ordered by weight ascending. Now my approach was the following:

Storing queryable data by using tags in a hashed string like table_name + pos ('all|first|last') + condition_name + limit + order, e.g. hashing an imploded array, like this in php:

<?php
$key = md5(implode(", ", array('video', 'all', 'node_id = 5', 'weight asc')));

Now trying to replace the mysql database, I got the problem that when someone wants to write data into the database, I need to store the data in all needed queried conditions, so I need to hard code them in PHP, instead of just saving the data and querying it with SQL. I did it  in the example like this:

public function allVideosByNodeId($input) {
   $allVideosByNodeId_key = md5(implode(", ", array('video', 'all', 'node_id = '.$input['node_id'], 'weight asc')));
   $currentVideosByNodeId = $this->redis->get($allVideosByNodeId_key);
   if (!empty($currentVideosByNodeId)) {
      $allVideosByNodeId_value = json_decode($currentVideosByNodeId);
   }
   $allVideosByNodeId_value[] = $input; //append with input data array
   $this->redis->set($allVideosByNodeId_key, json_encode($this->sortByWeightAsc($allVideosByNodeId_value)));
}

This is a working approach, but it's my first trial with redis and I've no experience with it since I always used SQL Databases. If you have only one write to database it is still fast, but what happens if I i need to store twenty models like this writing new data becomes maybe slow. Does anyone have some tips for a better implementation of such queried results?


texts: Tensorflow implementation of the Thomson model

texts:
I've implemented the Thomson model in Tensorflow and it seems to work very well. I'm repeating some computation by computing the other half of the symmetric distance matrix. I think, for a GPU based approach (though I may be wrong), the savings from a vectorized computation is worth the doubling of my model size. Any comments or suggestions are welcome.

import tensorflow as tf
import numpy as np

def thompson_model(N):

    # Start with random coordinates from a normal dist
    r0 = np.random.normal(size=[N, 3])
    coord = tf.Variable(r0, name='coordinates')

    # Normalize the coordinates onto the unit sphere
    coord = coord/tf.reshape(tf.norm(coord, axis=1), (-1, 1))

    def squared_diff(A):
        r = tf.reduce_sum(A*A, 1)
        r = tf.reshape(r, [-1, 1])
        return r - 2*tf.matmul(A, tf.transpose(A)) + tf.transpose(r)

    RR = squared_diff(coord)

    # We don't need to compute the gradient over the symmetric distance
    # matrix, only the upper right half
    mask = np.triu(np.ones((N, N), dtype=np.bool_), 1)

    R = tf.sqrt(tf.boolean_mask(RR, mask))

    # Electostatic potential up to a constant, 1/r
    U = tf.reduce_sum(1/R)

    return U, coord


texts:
I am working on a sorted data file, so there does not need to be any sorting logic.  I find unique values, feed them into an array, then use the worksheetfunction.sum to get totals for a field.

Is this as efficient as I could be, or are there some things I'm not seeing and should?

The "Items" sheet is where a number of accounts are stored (in the thousands).  The user cuts and pastes the data from another spreadsheet  It is sorted by account, and each line all the columns are identical except for the totals, and the first coloumn which contains the account number.

I collect an array of account numbers, then cycle through the array to find the first instance, and continue down until I find the last instance.  Populate a second array with the contents of all cells in that row (up to the last column with a header, then get a sum of the totals, and overwrite that element of the array.

When completed, I drop the entire array made from the items sheet into the summary sheet.

Option Explicit

Sub makeSummary()

Dim inws As Worksheet
Dim outws As Worksheet

Dim fndRange As Range
Dim zell As Range

Dim firstRow As Integer
Dim lastRow As Integer
Dim colctr As Integer
Dim totalCol As Integer
Dim LastCol As Integer

Dim ctr As Long
Dim arrBound As Long

Dim distVals() As String
Dim newRows() As String

' Initialize variables
Set inws = Sheets("Items")
Set outws = Sheets("Summary_Sheet")
outws.Cells.Clear
Set fndRange = Range(GetLast(3, inws.Cells))
LastCol = fndRange.Column
lastRow = fndRange.Row
Set fndRange = Nothing

'populate the header columns in the output worksheet.
For ctr = 1 To LastCol
    outws.Cells(1, ctr) = inws.Cells(1, ctr).Value
Next ctr

' redim array, and populate with unique SFC values
ReDim distVals(1)
distVals(1) = inws.Cells(2, 1)
For ctr = 2 To lastRow
    If inws.Cells(ctr, 1).Value <> distVals(UBound(distVals)) Then
        ReDim Preserve distVals(UBound(distVals) + 1)
        distVals(UBound(distVals)) = inws.Cells(ctr, 1).Value
    End If
Next ctr

'Get upper bound of search array and use it to set max row value of newrows array
arrBound = UBound(distVals)
ReDim newRows(1 To arrBound, 1 To LastCol)

'build array,
For ctr = 1 To arrBound
    Set fndRange = inws.Cells.Find(distVals(ctr), lookat:=xlPart, LookIn:=xlFormulas)
    firstRow = fndRange.Row
    lastRow = fndRange.Row
    Do Until inws.Cells(lastRow + 1, 1) <> distVals(ctr)
        lastRow = lastRow + 1
    Loop
'fill row
    For colctr = 1 To LastCol
        newRows(ctr, colctr) = inws.Cells(firstRow, colctr)
    Next colctr
'Get total of totals in SFC
    newRows(ctr, 5) = WorksheetFunction.Sum(Range(inws.Cells(firstRow, 5), inws.Cells(lastRow, 5)))
Next ctr

'clean up of destination sheet
With outws
    .Columns("E").NumberFormat = "_($* #,##0.00_);_($* (#,##0.00);_($* ""-""??_);_(@_)"
    .Range(.Cells(2, 1).Address, .Cells(arrBound + 1, LastCol).Address) = newRows
    'excel doesn't recognize the numbers as numbers unless you multiply by 1 and drop the value back down.
    For Each zell In .Range(.Cells(2, 5).Address, .Cells(arrBound + 1, 5).Address)
        zell.Value = zell.Value * 1
    Next zell
    .Calculate
End With

End Sub

Function GetLast(choice As Long, rng As Range)
    ' 1 = GetLast row
    ' 2 = GetLast column
    ' 3 = GetLast cell

Dim ReturnRng As Range

Set ReturnRng = rng.Find(What:="*", After:=rng.Cells(1), lookat:=xlPart, LookIn:=xlFormulas, _
                SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False)

If Not ReturnRng Is Nothing Then
    With ReturnRng
        Select Case choice
            Case 1
                GetLast = .Row
            Case 2
                GetLast = .Column
            Case 3
                GetLast = .Address
            Case Else
        End Select
    End With
End If
End Function


texts: Efficient storage and calling of varying objects

texts:
This question deals with the ability to construct a structure that is able to be easily iterated through.

The problem:

I have four different "boxes":

Box A: Always has 1 apple and 1 pear
Box B: Always has 1 orange and 1 pear
Box C: Always has 1 peach
Box D: Can have varying amounts of apples and oranges (0 - 10+) but always has 1 pear

Each piece of fruit has a different taste value

I currently process this information by creating a queue of the different taste values and box types then process this information with a lots of if-elses in multiple functions.

Here is an example of one function that seeks to get a total sum of the taste values e.g.

void process_crate(vector<string> boxes, vector<double> taste_value, vector<vector<double> > amount){

    unsigned int count = 0; // holds index in taste_value
    double sum_taste = 0;  // holds taste value

    for(unsigned int i = 0; i < boxes.size(); i++){
        string active_box = boxes[i];

        if(active_box == "A"){ // An apple and a pear

            sum_taste += taste_box_A(taste_value[count],taste_value[count+1]); // user preference

            count += 2;
        }else if(active_box == "B"){ // An orange and a pear
            sum_taste += taste_box_B(taste_value[count], taste_value[count+1]); // user preference

            count += 2;
        }else if(active_box == "C"){ // A peach
            sum_taste += taste_box_C(taste_value[count], taste_value[count+1]); // user preference

            count += 1;
        }else{ // Box D varying apples and oranges, but always a pear

            unsigned int apples = amount[i][0];
            unsigned int oranges = amount[i][1];

            vector<double> apple_tastes(apples);
            vector<double> orange_tastes(oranges);

            double pear_taste = taste_value[count+apples + oranges];

            if(apples != 0){
                for(unsigned int j = 0; j<apples; j++){
                    apple_tastes[j] = taste_value[count+j];
                }
                count += apples;
            }

            if(oranges != 0){
                for(unsigned int j = 0; j<apples; j++){
                    orange_tastes[j] = taste_value[count+j];
                }
                count += oranges;
            }

            sum_taste += taste_box_D(apple_tastes, orange_tastes, pear_taste); // user preference
            count += 1;
        }

    }
}

I think use of IF-ELSE statements combined with lots of vectors to store the data could be greatly improved.

Any suggestions?


texts:
I am running a Markov Chain Monte Carlo algorithm for updating a density distribution. There is a specific section of my code which tries to fill a very large matrix thetha.mh (of dimension 5000x2x60). the following code snippet is trying to fill the first dimension of my matrix, but the specific operation in second line of the loop is taking too much time.

Does anybody know of a better way to improve the efficiency of this operation?

fhatt=kde(x=theta.mh[m1:m,s,t-1], h=hpi(theta.mh[m1:m,s,t-1]))
  p2=function(thetax)
  dkde(thetax, fhatt)

fhatd=kde(x=deltat.mh[m1:m,s,t-1], h=hpi(deltat.mh[m1:m,s,t-1]))
  p3=function(deltatx)
  dkde(deltatx, fhatd)
# P1 and P2 are two distribution updated from the previous values of tetha.mh through kernel density estimation
h1=function(thetax)
      log(p1(y[s,t],thetax)*p2(thetax))
# h1 is the the logarithm of the multiplication of p1 and p2 (laplace form estimate)
for(i1 in 2:5000)
      {
        thetas=rnorm(1,theta.mh[i1-1,s,t],stheta[i1,s,t])
        r1[i1,s,t]=exp(h1(thetas)-h1(theta.mh[i1-1,s,t]))
        if (r1[i1,s,t]>runif(1))
          theta.mh[i1,s,t]=thetas
        else {
          theta.mh[i1,s,t]=theta.mh[i1-1,s,t]
          }
      }


texts:
I am writing a gem for users to interact with a third party api. I want users to have easy and natural access to objects and properties delivered by the JSON payload.

The collection of entities delivered are called Entries so after making an http request I pass the json response to an Entries object like so:

  class Entries
    include Enumerable

    attr_reader :body, :entries

    def initialize(body)
      @body = body
      @entries = body.map { |entry| Entry.new(entry) }
    end

    def each(&block)
      entries.each(&block)
    end
  end

And for my single Entry object I have written:

  class Entry

    attr_reader :properties, :attributes

    def initialize(attributes)
      @attributes = attributes
      @properties = attributes.keys

      properties.each do |prop|
        define_singleton_method prop do
          @attributes[prop]
        end
      end
    end

    def to_s
      "#{attributes[:title]} created on #{attributes[:created_at]}"
    end

    def is_entry?
      true
    end
  end

I haven't tested this much but things seem to be working so far. Users of my gem can now do this:

entries = client.entries(content_type: 'shirts')
entries.each { |entry| puts entry.title }

But I am worried this is an inefficient way of doing things and that perhaps I am using too much memory in these loops.

Also I want to keep magical meta-programming to a minimal but still achieve this. Is this a reasonable way to do this in Ruby? Would love some feedback and advice.


texts: List of all prime factors of a number, including repeats

texts:
This code will return a list of the prime factors of n, and the prime factors are repeated so that the product of the list is equal to n.

import math

def product(iterable):
    """
    Returns product of all elements in iterable
    """
    p = 1
    for x in iterable:
        p *= x
    return p

def generate_primes(n):
    """
    Returns list of all primes less than or equal to n
    """
    l = []
    for i in range(1,n+1):
        prime = True # Assume i is prime
        for j in l:
            if j > math.sqrt(n):
                break
            if i % j == 0 and j != 1:
                prime = False # Number i has been shown to be composite
                break
        if prime:
            l.append(i)
    return l

def prime_factor_set(n):
    """
    Returns set of the prime factors of n
    """
    return {i for i in generate_primes(n) if n % i == 0 and i != 1}

def prime_factor_list(n):
    """
    Returns full list of the prime factors of n, such that the product of this
    list is equal to n
    """
    l = list(prime_factor_set(n))
    while product(l) != n:
        r = int(n/product(l)) # Remaining number to be factored into primes
        prime_factors = prime_factor_set(r)
        l.extend(prime_factors)
    return sorted(l)

Example:

prime_factor_list(2000)

[2, 2, 2, 2, 5, 5, 5]


texts:
I wrote the following script to run through several excel files and format them before saving as a CSV for upload to a Quickbase app I'm creating. Each excel file is roughly 100k lines and the code takes about 3-5 minutes per file. I'm currently using pandas to make my edits. If there is a more efficient way please let me know.

import pandas as pd
import os

# set working directories for files
starting_folder=('Purchasing/unformatted/')
save_folder = ('Purchasing/')

#create list of excel file names from folder
files = []
for file in os.listdir(starting_folder):
    filename = os.fsdecode(file)
    files.append(filename)

# create list for file names to be saved as csv
save_files = [w.replace('xlsx','csv') for w in files]

# create data frame of fiscal calendar
calendar = pd.read_excel('Purchasing/Fiscal Calendar 15-18.xlsx')
fiscal_calendar = pd.DataFrame([])
#create new data frame with only two columns
fiscal_calendar['InvoiceDate'] = calendar['Date']
fiscal_calendar['Week'] = calendar['Week.1']

#loop through csv files to format and save to new location
for i in range(len(files)):
    #reads unformatted excel file into dataframe
    df = pd.read_excel(starting_folder+files[i])
    #change dtype of dates in report to date time
    df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])
    #drop unwanted rows
    df = df.drop(df[df.Brand == 'NONPROD'].index)
    #add in fiscal week based on invoice date
    Sygma = pd.merge(df,fiscal_calendar, how = 'left', on = 'InvoiceDate')
    #save to csv for db loading
    Sygma.to_csv(save_folder+save_files[i],index = False)


texts: Comma Code - Automate the Boring Stuff with Python

texts:
Below is my code for the Comma Code problem from Chapter 4 of Automate the Boring Stuff with Python. Is there anything I can do to make it cleaner?

Comma Code
Say you have a list value like this:
spam = ['apples', 'bananas', 'tofu', 'cats']
Write a function that takes a list of values as an argument and returns a string with all the items separated by a comma and a space, with 'and' inserted before the last item. For example, passing the previous spam list to the function would return 'apples, bananas, tofu, and cats'. But your function should be able to work with any list passed to it.
The output of this program could look something like this:
apples, bananas, tofu, and cats

import sys

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

def print_list(list):
    for item in list:
        if len(list) == 1:
           print(list[0])
        elif item != list[-1]:
            print(item + ', ', end='')
        else:
            print('and ' + list[-1])

print_list(spam)


texts: Comma delimited string from list of items

texts:
Is there a simple way to create a comma delimited string from a list of items without adding an extra ", " to the end of the string?

I frequently need to take an ASP.NET CheckBoxList and format the selected values as a string for insertion into an e-mail. It's straightforward to loop over the selected checkboxes, get the values, and add them to a StringBuilder with a ", " separating them, but the Count property returns the number of items in the list total, not the number of items that are actually selected. So it's hard to know when you've reached the last item, and you end up with a stray ", " on the end.

I've played around with several different approaches to this problem. Lately I've been doing something like this:

private string ConcatenateCheckBoxListItems()
{
    StringBuilder sb = new StringBuilder();
    char[] characters = new char[] {" ", ","};
    String trimmedString;

    foreach (ListItem item in MyList)
    {
        sb.Append(item.Value + ", ");
    }

    trimmedString = sb.ToString().TrimEnd(characters);
    return trimmedString;
}

But it's definitely clunky. So do the various for loop approaches I've tried. Any suggestions for a cleaner implementation?


texts:
I had a problem where I needed to find the largest amount of passengers in multiple cars/vans etc, so I got the totals from each vehicle and added them to a list, I then created this method to sort the list...

static List<int> SortList(List<int> tobesorted)
{
    var j = 0;
    int JP = 0;

    int value1 = Convert.ToInt32(tobesorted[j]);
    int value2 = Convert.ToInt32(tobesorted[JP]);

    for (var i = 0; i < tobesorted.Count-1; i++)
    {
        for (j = 0; j < tobesorted.Count-1; j++)
        {
            JP = (j + 1);
            value1 = Convert.ToInt32(tobesorted[j]);
            value2 = Convert.ToInt32(tobesorted[JP]);

            if (value2 > value1)
            {
                tobesorted[j] = value2;
                tobesorted[JP] = value1;
            }
        }
        j = 0;
        JP = 0;
    }

    return tobesorted;
}

I don't understand is this is acceptable, and if not what methods are? It seems quick enough, I know of sorting algorithms, but haven't ever been forced to use any.


texts: Convert unsigned Integer to ASCII in x86 assembly

texts:
This is my best effort to code an x86 32 bits to get an unsigned int (4 bytes) and convert it into a string. My strategy was successively divide the number by ten and fulfill the remainder of the div according its position in the heap pre-allocated string. I am assuming the bigger value has 10 digits at most.

File i2a.s:

# convert integer to ASCII

.section .data

num:
    .long   123456789
str:
    #    0123456789A
    .string "          \n"
len:
    .long .-str

.section .text
    .globl _start

_start:
    # last index of str
    lea str+0xa, %edi
    # initialize eax
    mov num, %eax
loop:
    # divide
    xor %edx, %edx
    mov $0xa, %ecx
    div %ecx        # quocient: EAX / remainder: EDX

    # convert remainder to ASCII
    add $0x30, %edx
    # store it in str[i--]
    mov %dl, -1(%edi)
    dec %edi

    # if quocient is zero, we're done.
    cmp $0, %eax
    je  print

    # if i == 0, we're done.
    cmp     str, %edi
    je  print

    # repeat.
    jmp loop

print:
# print content of str
    mov $4, %eax
    mov $1, %ebx
    lea str, %ecx
# where the generated string starts?
#   str[%edi]
    sub $str, %edi
    add %edi, %ecx
# what is the final length of str?
#   len -= %edi
    mov len, %edx
    sub %edi, %edx
    int $0x80

exit:
    mov $1, %eax
    mov %edx, %ebx
    int $0x80

I know there are some criticism about div and its slow execution. Please, fell free to criticize it as well as to point out caveats, tips, and tricks.

Simple script I'm using to build it: (it will create bin directory in cwd)

#! /bin/bash

# binaries output directory (objects and executables are placed there)
OUTDIR=bin
[ -d $OUTDIR ] || mkdir $OUTDIR

as --32 $1.s -o $OUTDIR/$1.o \
    && ld -m elf_i386 $OUTDIR/$1.o -o $OUTDIR/$1 \
    && $OUTDIR/$1

Usase:

./build i2a


texts: Race car with falling objects that make the car go back to its initial position game

texts:
I saw a game made in Python and PyGame in a tutorial, so I thought I'd make a game like it in Allegro5 and C++. I think I made my style a little better than my style before since I stopped putting everything in the main function, and I also stopped using 'magic numbers'. I'd like to know of your opinions, and what else I can improve to make my code better.

#include <stdio.h>
#include <allegro5/allegro.h>
#include <allegro5/allegro_font.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_color.h>
#include <allegro5/allegro_ttf.h>
#include <iostream>
ALLEGRO_DISPLAY *display;
ALLEGRO_EVENT ev;
ALLEGRO_EVENT_QUEUE *eventqueue;
ALLEGRO_TIMER *timer;
ALLEGRO_BITMAP *car;
ALLEGRO_BITMAP *object;
float FPS = 60.0;
int width = 800;
int height = 600;
int objectX = 810;
int objectY = 610;
int objectYStep = 5;
int playerPosX = width / 2;
int playerPosY = 510;
int playerStep = 10;
bool isOpen = true;
void moveObject(){
objectY = objectY + objectYStep;
}
void movePlayerRight(){
playerPosX = playerPosX + playerStep;
    }
void movePlayerLeft(){
playerPosX = playerPosX - playerStep;
}
bool objectOutOfBounds(){
return objectX > width || objectY > height;
}
bool intersects(ALLEGRO_BITMAP *objecte, ALLEGRO_BITMAP *cars, int objecteX,    int objecteY, int carsX, int carsY){
int objecteW = al_get_bitmap_width(objecte);
int objecteH = al_get_bitmap_height(objecte);
int careW = al_get_bitmap_width(cars);
int careH = al_get_bitmap_height(cars);
return objecteX<careW + carsX && objecteX + objecteW>carsX && objecteY<careH + carsY && objecteX + objecteH>carsY;
}

int main(){

al_init();
if (!al_init()){
    std::cout << "Failed to initialize allegro5." << std::endl;
}
al_init_image_addon();
if (!al_init_image_addon()){
    std::cout << "Failed to initialize image." << std::endl;
}
display = al_create_display(width, height);
if (!display){
    std::cout << "Failed to create display." << std::endl;
}
al_install_keyboard();
if (!al_install_keyboard()){
    std::cout << "Failed to install keyboard." << std::endl;
}

eventqueue = al_create_event_queue();
timer = al_create_timer(1.0 / FPS);
car = al_load_bitmap("racecar.png");
object = al_load_bitmap("brickonn.jpg");

al_register_event_source(eventqueue, al_get_display_event_source(display));
al_register_event_source(eventqueue, al_get_keyboard_event_source());
al_register_event_source(eventqueue, al_get_timer_event_source(timer));

while (isOpen){
    al_clear_to_color(al_map_rgb(255, 255, 0));
    ALLEGRO_EVENT event;
    al_wait_for_event(eventqueue, &event);
    al_start_timer(timer);
    if (objectOutOfBounds()){
        objectX = rand() % width;
        objectY = 0;
        objectYStep = objectYStep + 1;
    }
    if (event.type == ALLEGRO_EVENT_TIMER){
        moveObject();
    }
    if (event.keyboard.keycode == ALLEGRO_KEY_LEFT){
        movePlayerLeft();
    }
    else if (event.keyboard.keycode == ALLEGRO_KEY_RIGHT){
        movePlayerRight();
    }
    if (intersects(object, car, objectX, objectY, playerPosX, playerPosY)){
        std::cout << "CRASH!" << std::endl;
        playerPosX = width / 2;
    }
    al_draw_bitmap(car, playerPosX, playerPosY, 0);
    al_draw_bitmap(object, objectX, objectY, 0);
    al_flip_display();
}

al_flip_display();
al_rest(10);
}


texts:
I just wrote this code to concatenate two wide characters strings. Could someone please comment if it looks OK? (seems to work at least).

SomeStringClass amount = Window->get_text();
wchar_t strAmount[100] = L"Amount: "; // I know I could remove 100 from here too
wchar_t *ptr = wcscat( strAmount, amount.c_str() );
SomeStringClass  final;
final.set(ptr, 10 /* 10 is roughly due to length of Amount line 2*/ + amount.length());

Now, final contains what I wanted (e.g. "Amount: 123").


texts: Check if an integer equals the sum of its digits to the fifth power

texts:
I can do this in one line in Python:

sum([i for i in range(9,9999999) if i == sum([int(x)**5 for x  in str(i)])])

Not very fast, but works nicely. I thought it might be quicker to do it in Haskell, a language I'm quite new to:

-- helper func
toDigits    :: Int -> [Int]
toDigits 0 = []
toDigits x = toDigits (x `div` 10) ++ [x `mod` 10]

isSumofFifth n = n == sum (map (^5) (toDigits n))
sum (filter isSumofFifth [9..9999999])

But it seems as slow, or even slower (I haven't done exact profiling).

I realise I could optimise it with a more refined upper bound, but aside from that, is there a better way to write this in Haskell?


texts: Generating multiple new arrays using numpy

texts:
Say I have the following two different states:
state1 = [0, 1, 0, 1, 1]
state2 = [1, 1, 0, 0, 1]

And I want to generate n number of new states by only changing the values at where these states differ; and I want to do so randomly. So I did the following:
state1 = np.array(state1)
differ = np.where(state1 != state2)[0]  # --> array([0, 3], dtype=int64)

rand = [random.choices([1, 0], k=len(differ)) for _ in range(4)]
states = [state1.copy() for _ in range(4)]

for i in range(len(states)):
    states[i][differ] = rand[i]  # Will replace the values at locations where they are mismatched only

Out:
[array([1, 1, 0, 0, 1]),
 array([1, 1, 0, 1, 1]),
 array([0, 1, 0, 1, 1]),
 array([0, 1, 0, 1, 1])]

This does the job but I was wondering if there is a better way (to avoid 2 for loops), but this was the best I could come up with. Any ideas on how to do the same thing but better/cleaner?


texts:
I have an array of 4 names, and was wondering what the best best way to reliably pick 1 name for a contest would be. I've read online that javascripts Math.Random is only pseudo random. Which makes me wonder, would this be a fair enough function to put a prize on the line?

The picking process won't be externally/customer facing, so I'm not worried about how it looks, more just about how fair it would be.

$(".randomize").click(function() {
  var contestents = [{
    person: "Kareem"
  }, {
    person: "Charlie"
  }, {
    person: "Hobie"
  }, {
    person: "Hoder"
  }];

  var winner = Math.floor(Math.random() * contestents.length)
  $('div').html(contestents[winner].person);
});

jsfiddle here

If not, how could I randomize this even more to be fair enough to put a prize on the line.


texts:
Background:
This began with James Colgan's Lisp-Dojo for Ruby.  My implementation can be found here. I then moved on to Write yourself a scheme in 48 hours.  This question has to do with one of the implementation decisions.

Code:

My implementation of eval

--# The eval function takes a scope and paresed Lisp value and
--# returns the resulting Lisp Value.
--# String, Number and Bool return themselves.
--# An Atom trys to find its self in the scope and retrun that value
--# A List is evaluated using the normal Lisp rules.
eval :: LispScope-> LispVal -> IOThrowsError LispVal
eval s val@(String _) = return val
eval s (Atom val) =  do
  (liftIO $ getValue s val) >>= maybe (throwError $ "Value not in scope: " ++ val) (return)
eval s val@(Number _) = return val
eval s val@(Bool _) = return val
eval scope (List (fn:lvs)) = do
    fun <- eval scope fn
    case fun of
      Syntax f _-> f scope lvs
      Function f _-> evalMap scope lvs >>= f
      val -> throwError $ (show val) ++ " is not a function"
eval scope (List []) = return $ List []
eval _ badForm = throwError $ "Unrecognized form: " ++ show badForm

Note two things: 1) I do not refer to any special forms, 2) the use of Syntax for hygenic forms.

This is a piece of code from Write yourself a scheme in 48 hours:

--# evaluate the "if" form
eval (List [Atom "if", pred, conseq, alt]) =
    do result <- eval pred
       case result of
         Bool False -> eval alt
         otherwise -> eval conseq

Note that in the tutorial the form is written directly into the eval function.  This pattern is followed for other syntaxes like define and lambda.

Question:
When I implemented my version I followed what I thought was a wise choice demonstrated in James Colgan's solution to the lisp-dojo to keep eval as simple as possible and instead to push the syntax implementations into the root scope.  eg:

ifSyntax :: LispScope -> [LispVal] -> IOThrowsError LispVal
ifSyntax s [pred, consequent, alternate] = do
  pred' <- eval s pred
  case pred' of
    Bool False -> eval s alternate
    otherwise -> eval s consequent
ifSyntax _ _ = throwError "if: Bad Syntax"

ifVal = (Syntax ifSyntax $ Left "syntax (if)")
--# this is then added to the initial scope

I would like to know why one choice might be better then the other, and what is typical in real-world implementations.

Reference:

My definition of the LispVal data type:

type LispScope = Scope LispVal

data Lambda = Lambda {params :: [String], body :: [LispVal]}

data LispVal = Atom String
             | List [LispVal]
             | Number Integer
             | Real Double
             | String String
             | Function ([LispVal] -> IOThrowsError LispVal) (Either String Lambda)
             | Syntax (LispScope -> [LispVal] -> IOThrowsError LispVal) (Either String Lambda)
             | Bool Bool
             | Port Handle


texts: Print Bitcoin price by getting JSON data using CoinDesk API

texts:
In this code in Python, I used an API called CoinDesk to get the Bitcoin price as JSON.
I'm trying to follow the best practices in coding, so, I've used logging and I'm using a code formatter in my editor.
Kindly, any enhancements on this code will be appreciated.

# Project Idea: Bitcoin price program using CoinDesk API with Python.

# Importing libraries
import requests as rq
from datetime import datetime
import logging
import objectpath  # Read the library doc: http://objectpath.org/

def get_api_data():

    LOG_FORMAT = '%(levelname)s : %(asctime)s - %(message)s'
    logging.basicConfig(level=logging.DEBUG,
                        format=LOG_FORMAT, filemode='w')  # , datefmt='%d-%b-%y %H:%M:%S'
    logger = logging.getLogger()

    try:
        API_LINK = 'https://api.coindesk.com/v1/bpi/currentprice.json'   # CoinDesk API Link
        API_Data = rq.get(API_LINK)
        logger.debug("Getting API data - Done")

        api_data = API_Data.json()
        logger.debug("Converting API data to JSON - Done")
        return api_data

    except Exception as e:
        print("Exception occurred: ", e)
        logger.debug("Exception occurred.")

def main():

    # Getting the data from API
    data = get_api_data()
    tree_data = objectpath.Tree(data)

    time = tuple(tree_data.execute('$..updated'))

    usd = list((tree_data.execute('$..USD')))
    price = dict(usd[0])
    price_usd = price["rate"]
    price_description = price["description"] + ' - USD'

    print(f"The price in {price_description}: {price_usd}")
    print(f"Time of the price: {time}")

if __name__ == '__main__':
    main()


texts:
As suggested in comments here I created a new topic for next version. I edited a bit original code, added exception processing and optimization, that first N = 1/core count tasks are processed on main thread.

public static void Foreach<T>(ICollection<T> source, Action<T> action)
{
    var toBeProcessedOnMainThread = (int) Math.Ceiling((double)source.Count / Environment.ProcessorCount);
    var countdown = new CountdownEvent(source.Count - toBeProcessedOnMainThread);
    ConcurrentBag<Exception> exceptionsBag = null;
    var onMainThread = source.Take(toBeProcessedOnMainThread);
    foreach (var item in source.Skip(toBeProcessedOnMainThread))
    {
        ThreadPool.QueueUserWorkItem(state =>
        {
            var closure = (T)state;
            try
            {
                action(closure);
            }
            catch (Exception ex)
            {
                HandleException(ref exceptionsBag, countdown, ex);
            }
            finally
            {
                countdown.Signal();
            }
        }, item);
    }
    foreach (T value in onMainThread)
    {
        try
        {
            action(value);
        }
        catch (Exception ex)
        {
            HandleException(ref exceptionsBag, countdown, ex);
        }
    }
    countdown.Wait();
    if (exceptionsBag != null)
        throw new AggregateException(exceptionsBag);
}

private static void HandleException(ref ConcurrentBag<Exception> exceptions, object syncRoot, Exception ex)
{
    if (exceptions == null)
        lock (syncRoot)
            if (exceptions == null)
                exceptions = new ConcurrentBag<Exception>();

    exceptions.Add(ex);
}

I do lock countdown because I do not want to introduce another local variable, and it locks only once and only if exception occurs. Normally it won't be called an thus won't be locked.


texts: First attempt: Python Rock Paper Scissors

texts:
I finished Python Principles and this is my first program I've done (mostly) from scratch since, having to get some outside help on the loop to repeat the program, and I saw a nifty thing about using modular math to figure out the results so I did that to save a bunch of lines.

I'm just looking for any comments, improvements, bad habits, any comments at all!

import random
options = ['rock', 'paper', 'scissors']

def pickRando(): #set random choice for CPU
        global randoPick
        randoPick = random.choice(options)

def game(): #start up the game
    global player
    print('Rock, Paper, Scissors:')
    player = input("Choose wisely: ") #get player input
    player = player.lower()
    if player in options:
        check = True
        print("Okay, you picked " + player + ' and I picked ' + randoPick + '!')
        return check
    else:
        print('You have not chosen a viable option! Try again')
        check = False
        return check

def convertible(swap): #changing the word into a number
    if swap == 'rock':
        swap = 0
    elif swap == 'paper':
        swap = 1
    else:
        swap = 2
    return swap

def combatCheck(a, b): #determine the results of the choices
    a = convertible(a)
    b = convertible(b)
    result = (a - b) % 3 #modmath
    return result

def finish(z): # report the results
    global wins
    global losses
    global ties
    if z == 0:
        print('A tie! You are a most worthy opponent! Go again?')
        ties = ties + 1
    if z == 1:
        print('You win! My honor demands a rematch!')
        wins = wins + 1
    if z == 2:
        print('Haha, I am victorious! Dare you challenge me again?')
        losses = losses + 1
    print('You have ' + str(wins) + ' wins, ' + str(losses) + ' losses and, ' + str(ties) + ' ties!')

wins = 0
losses = 0
ties = 0

while True :
    pickRando()
    check = False
    while check == False:
        check = game()
    finish(combatCheck(player, randoPick))
    while True: #looping
        global answer
        answer = input('Run again? (y/n): ')
        if answer in ('y', 'n'):
            break
            print('Invalid input.')
    if answer == 'y':
        continue
    else:
        print('You are weak!')
        break


texts: Prompt user to enter boat details and print them

texts:
My code works perfectly fine but I was wondering if there was any better ways I could write my code like tidy it up a bit or rewrite a part of it. I want to learn how I can write my code in a better way. The code prompts the user to type the details of 3 different boats and then prints them.

program BoatDetails;
uses TerminalUserInput;

type
Boat = record
    ID : integer;
    Manufacturer : string;
    Model : string;
    Registration : string;
end;

Boats = Array of Boat;

function ReadBoat(const prompt : string): Boat;
begin
    WriteLn(prompt);
    ReadBoat.ID := readInteger('Please enter the Boat ID: ');
    ReadBoat.Manufacturer := readString('Please enter the manufacturer of the Boat: ');
    ReadBoat.Model := readString('Please enter the model of the Boat: ');
    ReadBoat.Registration := readString('Please enter the registration number for the Boat: ');
end;

procedure WriteBoat(b: Boat);
begin
    WriteLn('ID - ', b.ID);
    WriteLn('Manufacturer - ', b.Manufacturer);
    WriteLn('Model - ', b.Model);
    WriteLn('Registration - ', b.Registration);
end;

function ReadAllBoats(count: integer): Boats;
var i : integer;
begin
     SetLength(result, count);
     for i := Low(result) to High(result) do
         result[i] := readBoat('Enter Boat details');
end;

procedure WriteAllBoats(BoatArray: Boats);
var i : integer;
begin
    for i := Low(BoatArray) to High(BoatArray) do
        WriteBoat(BoatArray[i]);
end;

procedure Main();
     var Boats: Array of Boat;
         index: integer;
begin
    Boats := ReadAllBoats(3);
    WriteAllBoats(Boats);
end;

begin
    Main();
end.


texts: Dollar value of coins and calculating interest compounded annually

texts:
I've made this program to do a few integer calculations.  Do the methods for converting the numbers look good?  Do you have any other basic tips?

/* Dollar Value of Coins, Investment Compounded Annually
 * B, Morris
 */

import java.util.*;
import java.lang.*;
import java.text.*;
public class HW3_DollarValuOfCoinsInvestmentCompoundedAnnually {
public static void main(String args[]) {
Scanner keyboard = new Scanner(System.in);
NumberFormat priceFormat = NumberFormat.getCurrencyInstance();

//Dollar value of coins

System.out.println("How many quarters do you have?");
double quarters = keyboard.nextDouble();

System.out.println("How many dimes do you have?");
double dimes = keyboard.nextDouble();

System.out.println("How many nickles do you have?");
double nickles = keyboard.nextDouble();

quarters = quarters * (0.25);
dimes = dimes * (0.10);
nickles = nickles * (0.05);
double total =(quarters + dimes + nickles);
System.out.println("You have: " + priceFormat.format(total));

//Investment Compounded Annually

System.out.println("What is the initial investment?");
double investment = keyboard.nextDouble();

System.out.println("At what intrest rate is the intrest compounded annually?");
double intrestRate = keyboard.nextDouble();

double futureValueFive = investment * (Math.pow((1 + intrestRate), (double) 5));
System.out.println("In five years the investment will be worth : " + priceFormat.format(futureValueFive));

double futureValueTen = investment * (Math.pow((1 + intrestRate), (double) 10));
System.out.println("In ten years the investment will be worth : " + priceFormat.format(futureValueTen));

double futureValueTwenty = investment * (Math.pow((1 + intrestRate), (double) 20));
System.out.println("In twenty years the investment will be worth : " + priceFormat.format(futureValueTwenty));

}
}


texts:
I have a file with an specific format. It's divided in stripes of 1058816 bytes:

4096 bytes with only a 64 bit unsigned integer.
An array of 512 64 bit unsigned integer.
An array of 512 32 bit unsigned integer.
An array of 512 elements with 2048 bytes each one.

I have to read the file, change some values and write it again.

This is what I'm doing to work with it:

struct Segment {
        char bytes[2048];
};

struct Metadata {
        uint64_t serial;
};

class Stripe {
        uint8_t ptr[STRIPE_SIZE];

        Metadata *metadata;
        uint64_t *hash_array;
        uint32_t *size_array;
        Segment *segment_array;

        do_something(fstream_obj)
        {
                fstream_obj.read(ptr, STRIPE_SIZE);

                metadata = new(ptr) COSSMetadata;
                hash_array = new(ptr + METADATA_BYTES) uint64_t[ARRAY_SIZE];
                size_array = new(ptr + METADATA_BYTES + HASH_ARRAY_BYTES) uint32_t[ARRAY_SIZE];
                segment_array = new(ptr + METADATA_BYTES + HASH_ARRAY_BYTES + SIZE_ARRAY_BYTES) Segment[ARRAY_SIZE];

                // .... code to change the the values.....

                fstream_obj.write(ptr, STRIPE_SIZE);

        }
};

I have more experience with C. I'm not sure if this is the best to do what I want. I think that is faster, because I'm not doing any conversion and the information in ptr already is in the format of the structures. I want to hear opinios of more experience C++ coderes.


texts: Is this code efficient for file parsing?

texts:
Is the below code efficient for parsing the file, or do I face performance issues?  If the latter, please offer suggestions.

#include <iostream>
#include <fstream>
#include <map>

using namespace std;
ofstream outfile;
void writedata(string data, string file)
{
    outfile.open(file.c_str(), ios::app);
    outfile << data;
    outfile.close();
}

int main()
{
    ifstream input("data.txt", ios::in);

    ofstream out;
    string line;
    string tmp;
    string data;
    string filename;
    string name;
    size_t found;
    map<string, string> MyFileMap;
    map<string, string>::iterator it;

    while (input >> line)
    {
        found = line.find_last_of("pmf");
        if (found != string::npos)
        {
            name = line.substr(found + 1, line.length());
            filename = line.substr(found + 1, line.length());
            cout << "filename without txt " << filename << endl;
            for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
            {
                if (name.compare(it->first) == 0)
                {
                    while (input >> tmp && tmp.compare("pme"))
                    {
                        data += tmp;
                    }
                    cout << "Data push " << data << " to " << it->second << endl;
                    writedata(data, it->second);
                    data.clear();
                    break;
                }
            }
            if (it == MyFileMap.end() || MyFileMap.empty())
            {
                cout << "No match in map" << endl;
                filename = filename + ".txt";
                cout << "Filename " << filename << endl;
                while (input >> tmp && tmp.compare("pme"))
                {
                    data += tmp;
                }
                cout << "Data push " << data << " to " << it->second << endl;
                out.open(filename.c_str());
                MyFileMap[name] = filename;
                for (it = MyFileMap.begin(); it != MyFileMap.end(); ++it)
                {
                    if (name.compare(it->first) == 0)
                    {
                        writedata(data, it->second);
                        data.clear();
                        break;
                    }
                }
            }
        }
    }
    system("pause");
}

sample file : data.txt

pmfwork1
data1
data1
pme
pmfwork2
data2
data2
pme
pmfwork3
data3
data3
pme
pmfwork4
data4
data4
pme

In the above code, I am trying to parse the sample file with pmf and pme as begin and end flags, work as the file name, and data as file contents.  Below is the sample file.

I would like to reduce the use of open call for multiple times.  It would be of great help if you provide any suggestions.

Above code is generating four different text files: work1, work2 and so on.


texts:
I am using Scroll Magic for the first time and I am in general very new to JavaScript/jQuery. I got it to work but it is very messy and repetitive code.

Here is the fiddle. This is the messy code (I just gave this as an example, in my project there is about 50 scenes after each other in this manner!):

var controller = new ScrollMagic.Controller();

var tween1 = TweenMax.to('#animation1', 0.7, {
    opacity: 0
  });
var scene1 = new ScrollMagic.Scene({
    offset: 200,
    reverse: true
})
.setTween(tween1)
.addTo(controller)
.addIndicators();

var tween2 = TweenMax.to('#animation2', 0.7, {
    opacity: 1
  });
var scene2 = new ScrollMagic.Scene({
    triggerHook: 'onEnter',
    offset: 500,
    reverse: true
})
.setTween(tween2)
.addTo(controller)
.addIndicators();

Is there any way I can make this code more DRY?


texts:
I have a question to find the N th number in the sequence.

         1
        11
        21
      1211
    111221
    312211
  13112221
1113213211

The next number is obtained by saying out loud the number of digits in the previous number.

  eg. inital number =1
  next number = One 1 = 11
  next number = Two 1 = 21
  next number = One 2 and One 1 = 1211

Here is my code for getting next number:

private static void nextSequence(int N){

        int i=1;

        StringBuffer current = new StringBuffer(); // to populate current number
        StringBuffer last = new StringBuffer();   // to populate next number

        System.out.println("1");

        // populate next number in sequence
        current.append(1);
        current.append(1);

        while(i<=N){

            int begin=1; // pointer to next index
            int start=0; // pointer to start index
            int count=1; // count the number of repeats
            int j=1;     // counts the length of characters counted
            while(j<current.length()){

                if(current.charAt(begin)==current.charAt(start)){
                    count++;     // count the repeats between start and begin
                }else{
                    last.append(count);
                    last.append(current.charAt(start));
                    start=begin;
                    count=1;
                }

                begin++;
                j++;
            }

            last.append(count);
            last.append(current.charAt(start));
            System.out.println(last);
            current=last;
            last = new StringBuffer(); // reset the next seq numbe
            i++;
        }
    }

Is this the correct approach? I am able to generate the said sequence, but I am not sure if this is the most efficient.  Could you please help me correct if my I made any mistakes?


texts:
Let me know if it seems right to you and if anything can be optimized.

/*
 * Doubly Linked List
 *
 * Each node of the list contain two references (or links) – one to the previous node and other to the next node.
 * The previous link of the first node and the next link of the last node points to NULL.
 * In comparison to singly-linked list, doubly-linked list requires handling of more pointers
 * but less information is required as one can use the previous links to observe the preceding element.
 */

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

typedef struct Node {
    int data;
    struct Node *next;
    struct Node *prev;
} Node;

void insert(Node *current, int data);
void delete(Node *current, int data);
void print(Node *current);
int find(Node *current, int data);

void insert(Node *current, int data) {

    // current is pointing to first element
    // we iterate until we find the end
    while(current->next != NULL) {
        current = current->next;
    }
    // create a new Node and insert the item
    current->next = (Node *)malloc(sizeof(Node));
    (current->next)->prev = current;
    current = current->next;
    current->data = data;
    current->next = NULL;
}

void delete(Node *current, int data){

    // Iterate until we find a pointer next to the one we need to delete
    while (current->next != NULL && (current->next)->data != data) {
        current = current->next;
    }

    // Item is not found
    if(current->next == NULL) {
        printf("\nElement %d is not present in the list\n", data);
        return;
    }

    // The element is found in the node next to the one that current points to
    // We removed the node which is next to the pointer (which is also temp)
    Node *tmp = current->next;
    // In special case that we are deleting last node
    if(tmp->next == NULL) {
        current->next = NULL;
    } else {
        current->next = tmp->next;
        (current->next)->prev = tmp->prev;
    }
    tmp->prev = current;

    // We got rid of the node, now time to dellocate the memory
    free(tmp);

    return;
}
void print(Node *current) {
    while(current != NULL) {
        printf("%d ", current->data);
        current = current->next;
    }
}

int find(Node *current, int data) {
    // First pointer is head aka dummy node with no data
    // so we go to next one
    current = current->next;

    // Iterate through the linked list
    while(current != NULL) {
        if(current->data == data) {
            return 1;
        }
        current = current->next;
    }
    return 0;
}

int main() {

    Node *head = (Node *)malloc(sizeof(Node));
    head->next = NULL;
    head->prev = NULL;

    int data = 0;
    int usr_input = 0;

    while(1){
        printf("0. Exit\n");
        printf("1. Insert\n");
        printf("2. Delete\n");
        printf("3. Print\n");
        printf("4. Find\n");

        scanf("%d", &usr_input);

        // can also use a switch instead
        if( usr_input == 0) {
            exit(0);

        } else if(usr_input == 1) {
            printf("\nEnter an element you want to insert: ");
            scanf("%d", &data);
            insert(head, data);

        } else if(usr_input == 2) {
            printf("\nEnter an element you want to delete: ");
            scanf("%d", &data);
            delete(head, data);

        } else if(usr_input == 3) {
            printf("The list is ");
            print(head->next);
            printf("\n\n");

        } else if(usr_input == 4) {
            printf("\nEnter an element you want to find: ");
            scanf("%d", &data);
            int is_found = find(head, data);
            if (is_found) {
                printf("\nElement is found\n\n");
            } else {
                printf("\nElement is NOT found\n\n");
            }
        }
    }
    return 0;
}


texts:
How can I simplify this in Delphi?

Procedure colori1
Begin

 if Temperatura<=15 then
 begin
  Form1.Label1.Font.Color:=clBlue;
  Form1.Label2.Font.Color:=clBlue;
  Form1.Label3.Font.Color:=clBlue;
  Form1.Label4.Font.Color:=clBlue;
  Form1.Label5.Font.Color:=clBlue;
 end;

 if (Temperatura>=16) and (Temperatura<=18) then
 begin
  Form1.Label1.Font.Color:=clAqua;
  Form1.Label2.Font.Color:=clAqua;
  Form1.Label3.Font.Color:=clAqua;
  Form1.Label4.Font.Color:=clAqua;
  Form1.Label5.Font.Color:=clAqua;
 end;

 if (Temperatura>=19) and (Temperatura<=22) then
 begin
  Form1.Label1.Font.Color:=clLime;
  Form1.Label2.Font.Color:=clLime;
  Form1.Label3.Font.Color:=clLime;
  Form1.Label4.Font.Color:=clLime;
  Form1.Label5.Font.Color:=clLime;
 end;

 if (Temperatura>=23) and (Temperatura<=26) then
 begin
  Form1.Label1.Font.Color:=clYellow;
  Form1.Label2.Font.Color:=clYellow;
  Form1.Label3.Font.Color:=clYellow;
  Form1.Label4.Font.Color:=clYellow;
  Form1.Label5.Font.Color:=clYellow;
 end;

 if (Temperatura>=27) and (Temperatura<=29) then
 begin
  Form1.Label1.Font.Color:=$000080FF;
  Form1.Label2.Font.Color:=$000080FF;
  Form1.Label3.Font.Color:=$000080FF;
  Form1.Label4.Font.Color:=$000080FF;
  Form1.Label5.Font.Color:=$000080FF;
 end;

 if Temperatura>=30 then
 begin
  Form1.Label1.Font.Color:=clRed;
  Form1.Label2.Font.Color:=clRed;
  Form1.Label3.Font.Color:=clRed;
  Form1.Label4.Font.Color:=clRed;
  Form1.Label5.Font.Color:=clRed;
 end;
end;

If I use "for cycle" like this:

For i:=0 to n do label[i].font.color:=clRed

I'll obviously get an error, because Delphi doesn't know what label[i] means. Any suggestions?


texts:
I was assigned a task to fix the SQL injection flaw reported by a code analysis tool. I am not the original author of the code. I am fairly knowledgeable with SQL.

 public int ExecuteNonQuery(string query, SqlParameter[] parameters)
 {
     using (SqlCommand command = CreateCommand(query, parameters))
     {
         int rowsAffected = command.ExecuteNonQuery();
         log.Debug("rows affected: {0}", rowsAffected);
         return rowsAffected;
     }
 }

and the tool has reported the injection flaw at the line number 3. The ExecuteNonQuery is being called from so many places.

Here is one such sample:

public void AddDataFrom(IWorkflowStepExecutionStorage storage, bool inverseSourceAndTargetSide)
{
    WorkflowStepExecutionStorage storageImpl = storage as WorkflowStepExecutionStorage;
    if (storageImpl == null)
    {
        throw new InvalidOperationException();
    }
    const string queryTemplate =
        @"insert into [$mappingDictionaryTable](sourceObjectId, sourceObject, targetObjectId, targetObject, linkedObjectTypesPairId)
          select sourceTable.objectId, sourceTable.systemEntry, targetTable.objectId, targetTable.systemEntry, @linkedObjectTypesPairId from
            [$mappingTable] mt
            inner join [$sourceImportStorageTable] sourceTable on mt.$sourceIdColumn = sourceTable.id
            inner join [$targetImportStorageTable] targetTable on mt.$targetIdColumn = targetTable.id
        ";
    QueryBuilder queryBuilder = new QueryBuilder(queryTemplate);
    queryBuilder.AddParameter("$mappingDictionaryTable", this.mappingDictionaryTable.TableName);
    queryBuilder.AddParameter("$mappingTable", storageImpl.MappedTable.TableName);
    queryBuilder.AddParameter("$sourceImportStorageTable", inverseSourceAndTargetSide ?
        (storageImpl.TargetImportStorage as ImportExecutionStorage).ImportTable.TableName :
        (storageImpl.SourceImportStorage as ImportExecutionStorage).ImportTable.TableName);
    queryBuilder.AddParameter("$targetImportStorageTable", inverseSourceAndTargetSide ?
        (storageImpl.SourceImportStorage as ImportExecutionStorage).ImportTable.TableName :
        (storageImpl.TargetImportStorage as ImportExecutionStorage).ImportTable.TableName);
    queryBuilder.AddParameter("$sourceIdColumn", inverseSourceAndTargetSide ? MappedTable.TargetIdColumn.Name : MappedTable.SourceIdColumn.Name);
    queryBuilder.AddParameter("$targetIdColumn", inverseSourceAndTargetSide ? MappedTable.SourceIdColumn.Name : MappedTable.TargetIdColumn.Name);

    string query = queryBuilder.GetParametrizedQuery();
    SqlParameter[] sqlParams = new[] { new SqlParameter("@linkedObjectTypesPairId", storageImpl.RunConfiguration.LinkedTypesPairConfiguration.Id) };

    using (IQcDbConnection dbConnection = this.connectionProvider.CreateDbConnection())
    {
        dbConnection.ExecuteNonQuery(query, sqlParams);
    }
}

Here is the CreateCommand code:

private SqlCommand CreateCommand(string commandText, SqlParameter[] parameters)
 {
     SqlCommand retVal = this.connection.CreateCommand();
     retVal.CommandText = commandText;
     retVal.CommandTimeout = this.commandsTimeout;
     retVal.Parameters.AddRange(parameters);
     return retVal;
}

Is there any injection risk in this code? If yes, how do I recognize it?


texts: I created a sorting algorithm, called Grid Sort

texts:
Index & Sorting

Index

• Counting: when the index, or the position, is dependent on the item. Count from one. (Zero-based index is mathematically wrong.)

• Grid: when the index, or the position, is independent on the item. (e.g. JavaScript array)

Counting arrays are used in bubble sort, merge sort, quick sort, etc. Because of the nature of the index, sorting techniques using counting arrays require comparing the items and moving the items around.

Grid arrays are better suited for sorting.

Grid Sort

• Assigning the number (or other value associated with the number, such as name) to the corresponding index’s item

• Filtering out the undefined for print, iterate, length, etc.

• Assigning is sorting

• No comparing. No swapping. No moving around items.

• No need for indexOf()

• Stable

• Limitations : whole numbers only, size of an array

• An example using JavaScript

• https://code.sololearn.com/WWuuXR9rO45U/?ref=app

var test = [57, 285, 0, 854, 0, 27, 5, 5, 2885, 497, 57, 16, 803, 653, 62, 905, 975, 367, 147, 99, 58, 207643, 73, 83, 95, 24, 3, 1986, 47, 954, 1, 99, 954, 36, 67, 2, 753, 97, 3689, 79864, 5788, 479, 9865, 8900, 73, 753, 588, 19537, 489964, 30674, 578, 55, 99999, 578, 1000000, 58, 279, 3, 75, 975, 46, 785, 6789, 164, 5538, 744, 85, 2, 579, 753, 5538, 975, 158, 689, 379, 965, 57, 803, 84, 653, 85, 73, 864, 8643, 9047, 864, 783, 7, 4, 932, 5, 80, 97, 79, 849, 7, 3, 5, 10, 0];

document.write(test+”
”);
document.write(“Count: “+test.length+”
”);
document.write(“
”);

var test_original = [];
var x = 0;
while (x < test.length){
    if (test_original[test[x]] === undefined){
        test_original[test[x]] = [];
        test_original[test[x]][0] = test[x];
    }
    else{
        test_original[test[x]].push(test[x]);
    }
    x = x + 1;
}

var test_defined = [];
var defined_from = 0;
var defined_to = test_original.length;
var x = defined_from;
while (x < defined_to){
    if (test_original[x] !== undefined){
        test_defined.push(x);
    }
    x = x + 1;
}

var definedIndex = 0;
while (definedIndex < test_defined.length){
    document.write(definedIndex + 1);
    document.write(“. “);
    document.write(test_defined[definedIndex]);
    document.write(“: “);
    document.write(test_original[test_defined[definedIndex]]);
    document.write(“
”);

    definedIndex = definedIndex + 1;
}


texts:
I'm reading Professional Node.js: Building Javascript Based Scalable Software by Pedro Teixeira and created a web page responding with www.google.de. Could you take a look at my code and let me know if the implementation is not good?

var request = require('request');
var url = 'http://www.google.de'; // input your url here

// use a timeout value of 10 seconds
var timeoutInMilliseconds = 10 * 10000;
var opts = {
    url : url,
    timeout : timeoutInMilliseconds
};

require('http').createServer(function(req, res) {

    res.writeHead(200, {
        'Content-Type' : 'text/html'
    });

    request(opts, function(err, webRes, body) {
        if (err) {
            console.dir(err);
            return;
        }
        var statusCode = webRes.statusCode;
        console.log('status code: ' + statusCode);
        res.write(body);
    });
}).listen(4000);


texts: Simple Bespoke WordPress Integration Plugin

texts:
I am in the process of setting up WordPress with WooCommerce, one of the requirements is a bit of integration that takes a person from another website directly to a specific product. I have set the external product references in tags on the products.

An example incoming query would be:

http://localhost/TestSite/search?q=9404

I have written a short plugin that does this.

I am an average programmer, but very new to PHP, WordPress and WooCommerce. Can you see any potential errors, inefficencies or, security issues?

Any insight would be gladly recieved.

    //Tag on Test Product: 98614
    //example URL:
    //http://localhost/TestSite/search?q=98614

    function TagLinker(){

        if (isset($_GET['q']))
        {
            $TagNumber = $_GET['q'];
            $params=array(
            'post_type' => 'product',
            'post_status' => 'publish',
            'tax_query' => array( array(
                                'taxonomy' => 'product_tag',
                                'field' => 'slug',
                                'terms' => $TagNumber
                            )
            ));
            $wc_query = new WP_Query($params);

            if ($wc_query -> have_posts() ) {
                $wc_query -> the_post();

                $product_id = get_the_ID($wc_query->ID);

                $url = get_permalink( $product_id );

                wp_reset_postdata();
                if ( wp_redirect( $url ) ) {exit;}
            };
        }
    }

add_action( 'init', 'TagLinker' );
?>


texts:
Is this an efficient way to compute the value of Pi, where the limit of j \$\propto\$ accuracy?

PI = 0;

for (var j = 1; j < 100; j+=2) PI += (4/j)*((j+1)%4?1:-1);

The formula I used to write this is:

$$\pi \equiv \frac{4}{1}-\frac{4}{3}+\frac{4}{5}-\frac{4}{7}+\cdots$$


texts:
I am looking to speed up the search for black and white images. I have about 150,000 images that I need to check but this is taking so long. How can I speed up the code?

Private Sub BlackOrWhite()
    Dim iPath As String = txtFile1.Text
    Dim allFiles() As String = IO.Directory.GetFiles(iPath, "*.*", IO.SearchOption.TopDirectoryOnly)
    For Each eachPic In allFiles
        Dim myImage As Bitmap = New Bitmap(eachPic, True)
        Dim myColor As Color = CalculateColorKey(myImage)
        myImage.Dispose()

        If GetRgbDelta(myColor) = 0 Then
            IO.File.Move(eachPic, iPath & "Delete\" & IO.Path.GetFileName(eachPic))
        End If
    Next
End Sub

Public Shared Function CalculateColorKey(bmp As Bitmap) As Color
    Try
        Dim keyColor As Color = Color.Empty
        Dim highestRgbDelta As Integer = 0

        For x As Integer = 0 To CInt((bmp.Width / 2))
            For y As Integer = 0 To CInt(bmp.Height / 2)
                If GetRgbDelta(bmp.GetPixel(x, y)) <= highestRgbDelta Then
                    Continue For
                End If

                highestRgbDelta = GetRgbDelta(bmp.GetPixel(x, y))
                keyColor = bmp.GetPixel(x, y)
            Next
        Next

        Return keyColor
    Catch ex As Exception
        Debug.Print("CalculateColorKey: " & ex.Message)
    End Try
End Function

Private Shared Function GetRgbDelta(color As Color) As Integer
    GetRgbDelta = 100
    Try
        Dim aaa As Integer = Math.Abs(CInt(color.R) - CInt(color.G))
        Dim bbb As Integer = Math.Abs(CInt(color.G) - CInt(color.B))
        Dim ccc As Integer = Math.Abs(CInt(color.B) - CInt(color.R))
        Return aaa + bbb + ccc
    Catch ex As Exception
        Debug.Print("GetRgbDelta: " & ex.Message)
    End Try
End Function