texts:
This is pretty much an OOP version of this question, with the improvements:
import copy
import shelve

class GameOfLife(object):
    def __init__(self, board, generations = 10):
        self.__board = board
        for i in range(generations):
            print(self)
            self.__nextGeneration()

    def __str__(self):
        string = ""
        for row in self.__board:
            for cell in row:
                if cell:
                    string += "#"
                else:
                    string += "."
            string += "\n"
        return string

    def __isInRange(self, row, cell):
        return 0 <= row < len(self.__board) and \
               0 <= cell < len(self.__board[0])

    def __countSurrounding(self, row, cell):
        SURROUNDING = ((row - 1, cell - 1),
                       (row - 1, cell    ),
                       (row - 1, cell + 1),
                       (row    , cell - 1),
                       (row    , cell + 1),
                       (row + 1, cell - 1),
                       (row + 1, cell    ),
                       (row + 1, cell + 1))
        count = 0
        for surrRow, surrCell in SURROUNDING:
            if self.__isInRange(surrRow, surrCell) and \
               self.__board[surrRow][surrCell]:
                count += 1
        return count

    def __nextGeneration(self):
        nextBoard = copy.deepcopy(self.__board)
        for row in range(len(self.__board)):
            for cell in range(len(self.__board[0])):
                if self.__board[row][cell] and \
                   self.__countSurrounding(row, cell) not in (2, 3):
                    nextBoard[row][cell] = 0
                elif not self.__board[row][cell] and \
                     self.__countSurrounding(row, cell) == 3:
                    nextBoard[row][cell] = 1
        self.__board = nextBoard

def main():
    boardFile = shelve.open("boardFile.dat")
    board = boardFile["board"]
    game = GameOfLife(board)

if __name__ == "__main__":
    main()

Where boardFile.dat is just a shelved file containing a boolean array.
Can anyone provide an honest code review?
Thanks.


texts: Removing numbers from the middle of an array

texts:
I have an array like this (make sure you scroll to the right):

[0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]

Where it will always be the same length. And there will always be some number of 0's surrounding some number of 1's. I am trying to find a good/efficient/smart way to turn the middle of the array of into 0's when there is a padding of 4 1's on each side. The result would be something like:

[0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0]

Where you now have a padding of 4 1's on either side.

This is how I implemented it:

var a = [0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0];

var hitOne = false;
var oneCount = 0;
var oneStopPoint = a.lastIndexOf(1) - 3;
for(var n in a){
    if(n == oneStopPoint){
        break;
    }
    if(a[n] == 1 && !hitOne) {
        hitOne = true
        oneCount++;
    } else if(a[n] == 1 && hitOne) {
        oneCount++;
    }
    if(oneCount > 4){
        a[n] = 0;
    }
}
console.log(a);

http://jsfiddle.net/4gk9L9uv/1/


texts: Guess-the-number game by a Python beginner

texts:
For some background I'm pretty much a beginner and attempting to learn Python currently. So I decided after a few days of lessons I'd look for some beginner projects to test my knowledge. A website suggested I do a 'Guess the Number' game and basically suggested I follow this guideline.

Random function
Variables
Integers
Input/Output
Print
While loops
If/Else statements

In short I read the documentation on random and decided to give it a shot. Now for the actual question. Is this a good way of doing this or can I simplify it?

I've pretty much been working at this for longer than I would like to admit (approximately 90 minutes), because I'd get stumped and then rewrite what I was thinking.

# guess the number game
import random

print "Welcome to guess the number!"
print "You have 10 tries to guess the correct number!"
print "The range of numbers will be from 0-25"

# variables to store winning number, user guess and number of tries
number = random.randint(0, 25)
guess = raw_input("Please enter a number (0-25): ")
tries = 0

# check to see if the user guessed the right number
if int(guess) == number:
    print "Congratulations you\'ve won!"

# noticed that you could input invalid numbers and it counted as a guess so this is how i solved that
while int(guess) > 25 or int(guess) < 0:
    guess = raw_input("Please enter a VALID guess: ")
else:
    # my attempt at making the game loop
    while tries < 10 and int(guess) != number:
        guess = raw_input("Please guess again: ")
        tries = tries + 1
        # i noticed if i guessed the right answer out of the loop it would just exit so i duplicated here to prevent it
        if int(guess) == number:
            print "Congratulations you\'ve won!"
        # implemented the lose mechanic
        elif tries == 10:
            print "You've Lost!"
        # same with the correct answer issue i had so i put it in the loop as well
        elif int(guess) > 25 or int(guess) < 0:
            while int(guess) > 25 or int(guess) < 0:
                guess = raw_input("Please enter a VALID guess: ")
                # this is here because I didn't want to take tries away for invalid guesses
                tries = tries

So the game for me works as expected. You can win, lose, guess invalid numbers (I haven't tried letters but I won't get into that yet). Just not sure if this is the most efficient I can get. But if it's good enough for a beginner, I'll take it.


texts: Searching for the closest "stop" elements surrounding a start point

texts:
This code works but is there a simple / better way to do this?

It starts from a particular point (starthere) in the array, looks for first stop value to the left of start point, and the first stop to the right side.

Basically returns the closest values' positions to a start point both sides. (I'll make this a function.)

var arr = ['f','f','stop','stop','f','f','starthere','f','f','f','stop','stop','f','f','f','f'];

var i = arr.indexOf('starthere');
while (i--) {
    if (arr[i] == 'stop') {
        document.write(i + '
');
        break;
    }
}

for (var i = arr.indexOf('starthere'); i < arr.length; i++) {
    if (arr[i] == 'stop') {
        document.write(i);
        break;
    }

}

Returns 3
10


texts:
A practice interview question:

  Write an algorithm such that if an element in an MxN matrix is 0, its entire row and column is set to 0.

void SetZeroOnMatrix(int **matrix, int M, int N)
{
    bool *rowZeros = new bool[M];
    bool *colZeros = new bool[N];

    // Find the 0's
    for(int i=0; i<M; i++)
    {
        for(int j=0; j<N; j++)
        {
            if(matrix[i][j] == 0)
            {
                rowZeros[i] = false;
                colZeros[j] = false;
            }
        }
    }

    // Replace the values
    for(int i =0;i<M;i++)
    {
        for(int j=0;j<N;j++)
        {
            if(!rowZeros[i]||!colZeros[j])
                matrix[i][j]=0;
        }
    }

    delete[](rowZeros);
    delete[](colZeros);
}

If \$N = M\$, I'm assuming that this would have a time complexity of \$O(N^2)\$ and a space complexity of \$O(N)\$.


texts: Daily SQL job to delete records older than 24 hours

texts:
Below is a delete job to delete 1M+ records daily and takes 13 hours to complete and sometimes more than that. I need to optimize this.

  The table tblcalldatastore is being inserted 24*7 through a stored
  procedure and is supposed to have no records older than 24 hours.

Execution plan is below.

https://www.brentozar.com/pastetheplan/?id=ryYi2Sv7B

BEGIN

SET NOCOUNT ON;

DECLARE @DELETECOUNT int
DECLARE @DELETEATATIME int

DECLARE @CutOffDate datetime
DECLARE @HourRetained smallint
set @HourRetained = 24
begin Try

set @CutOffDate = getutcdate()

select  @DELETECOUNT = count(*) from [tblcalldatastore]
where  istestcase=0
and datediff(hour,receiveddate,@CutOffDate)>@HourRetained

SET @DELETEATATIME = 20000

WHILE @DELETECOUNT > 0

BEGIN

DELETE TOP(@DELETEATATIME) FROM tblcalldatastore WITH (ROWLOCK)  WHERE IsTestCase=0 and datediff(hour,receiveddate,@CutOffDate)>@HourRetained

SET @DELETECOUNT = @DELETECOUNT - @DELETEATATIME

END

end try

BEGIN CATCH

SELECT 'FAILED - ' + ERROR_MESSAGE() AS ErrorMessage

END CATCH

END


texts:
It's been pointed out (see the first comment) that my makefile rebuilds all source files regardless of changes made.

# Variables #

TARGETS := libAurora.a libAurora.so
    # The names of targets that can be built.
    # This is used in the list of valid targets when no target is specified, and when building all targets.

TARGET_DIRECTORY := ./Binaries
    # The place to put the finished binaries.

CXX := g++
    # The compiler to use to compile the source code into object files.

CXXFLAGS := -I. -Wall -Wextra -fPIC -g -O4
    # Options passed to the compiler when compiling source files into object files.

AR := ar
    # The archiver to use to consolidate the object files into one library.

ARFLAGS := -rcs
    # Options to be passed to the archiver.

SOURCE_FILES := $(shell find Source -type f -name *.cpp)
    # Because it's inconvenient to maintain an up-to-date list of all the source files
    # that should be compiled, we just search for all .cpp files in the project

OBJECT_FILES := $(SOURCE_FILES:.cpp=.o)

.PHONY: Default
    # The default target, which doesn't actually do anything except give the user instructions,
    # can be called even if nothing needs to be updated.

.INTERMEDIATE: %.o
    # Specifying the object files as intermediates deletes them automatically after the build process.

# Rules #

Default:
    @echo "Please specify a target, or use \"All\" to build all targets.  Valid targets:"
    @echo "$(TARGETS)"

All: $(TARGETS)

lib%.a: $(OBJECT_FILES)
    $(AR) $(ARFLAGS) $(TARGET_DIRECTORY)/$@ $(OBJECT_FILES)

lib%.so: $(OBJECT_FILES)
    $(AR) $(ARFLAGS) $(TARGET_DIRECTORY)/$@ $(OBJECT_FILES)

What can I do to improve it?


texts: Match the maximum consective count of `)` followed by a keyword

texts:
I am applying a regular expression to match and keyword that is followed by maximum number of closing parenthesis. Code is done in python using re module.
String provided for testing contains only one match()and(). But the solution I require shouldn't limit this.

Test String:

filters=(is_diabled = 1 and age gte 19) and (created_at = '1479487560' or updated_at = '1479487560')

Regular Expression:

re.compile(r'(\)+\s\s+\b(and|or)\b\s\s+\(+)', flags = re.I | re.X)

With this expression I get and preceded by any number of closing parenthesis.

After I get all matches I create an array of custom objects with these attributes:

node.create_node(range = match.span(),
            operator = match.group(2),
            matched_operator = match.group(),
            level = match.group().count(')'),
            query_string = query_string_dict)

self.filters.append(node)
self.filters.sort(key = lambda filter: filter.level, reverse = True)

Now can determine the parenthesis count from level field and highest match will be self.filters[0].

Is this a good approach to match )*and or are there some other more optimized way to achieve this?


texts: Checking if an xy position is within a rectangular bounds

texts:
This is pretty straightforward, but is there a better way to do this?

function isWithinBounds(obj, pos) {
    var oXmin, oXmax, oYmin, oYmax;
    if (obj.startPos.x < obj.endPos.x) {
        oXmin = obj.startPos.x;
        oXmax = obj.endPos.x;
    }
    else {
        oXmin = obj.endPos.x;
        oXmax = obj.startPos.x
    }

    if (obj.startPos.y < obj.endPos.y) {
        oYmin = obj.startPos.y;
        oYmax = obj.endPos.y;
    }
    else {
        oYmin = obj.endPos.y;
        oYmax = obj.startPos.y;
    }

    return (pos.x > oXmin && pos.x < oXmax && pos.y > oYmin && pos.y < oYmax);

}


texts: Method has same erasure: How should I go about refactoring?

texts:
Currently, in a utility class I have methods like so:

public static String getNextAvailableNumber(List<MyObject> currentObjects)
{
    int nextNumber = UtilClass.getNextAvailableNumberAsInteger(currentObjects, null);
    return UtilClass.formatNumber(nextNumber); //formats number as string
}

public static int getNextAvailableNumberAsInteger(List<MyObject> currentObjects, List<String> otherUnavailableNumbers)
{
    //returns nextNumber as int.
}

I now find myself wanting to add another method...

public static String getNextAvailableNumber(List<String> unavailableNumbers)
{
    int nextNumber = UtilClass.getNextAvailableNumberAsInteger(null, unavailableNumbers);
    return UtilClass.formatNumber(nextNumber);
}

You may notice that I would end up with a List argument in both places, causing a method has same erasure compiler error.

I'm considering the following solution..

//replace old getNextAvailableNumber() with generic version
public static String getNextAvailableNumber(List<?> objects)
{
    List<MyObject> objectList = new ArrayList<MyObject>();
    List<String> stringList = new ArrayList<String>();

    if (objects.get(0) instanceof MyObject)
    {
        objectList = (List<MyObject>) objects;
    }
    else if (objects.get(0) instanceof String)
    {
        stringList = (List<String>) objects;
    }
    int nextNumber = UtilClass.getNextAvailableNumberAsInteger(objectList, stringList);
    return UtilClass.formatNumber(nextNumber);
}

From what I've read, using instanceof is generally a sign that something can be done in a better way. Is there a better way? How should I go about refactoring this?


texts:
I'm starting to learn Lua and in one part of the book I need to convert a "Maze Game" that uses goto to another one that doesn't use goto.

The maze is the simplest ever made, starting from room #1:

---------
| 1 | 2 |
---------
| 3 | 4 |
---------

This is the original version using goto from the book:

goto room1 -- initial room
::room1:: do
  local move = io.read()
  if move == "south" then goto room3
  elseif move == "east" then goto room2
  else
    print("invalid move")
    goto room1 -- stay in the same room
  end
end

::room2:: do
  local move = io.read()
  if move == "south" then goto room4
  elseif move == "west" then goto room1
  else
    print("invalid move")
    goto room2
  end
end

::room3:: do
  local move = io.read()
  if move == "north" then goto room1
  elseif move == "east" then goto room4
  else
    print("invalid move")
    goto room3
  end
end

::room4:: do
  print("Congratulations, you won!")
end

And this is my attempt:

local rooms = {}
rooms[1] = {
  south=3,
  east=2
}
rooms[2] = {
  south=4,
  west=1
}
rooms[3] = {
  north=1,
  east=4
}
currentRoom = 1
repeat
  local move = io.read()
  local room = rooms[currentRoom][move]
  if room == nil then
    room = currentRoom
    print("Invalid move")
  elseif room == 4 then
    print("Congratulations, you won!")
  end
  currentRoom = room or currentRoom
until currentRoom == 4

The above code is working but I was wondering if there is something I need to change to improve it somehow.


texts: Periodically synching data from an API to database is extremely slow

texts:
I have a scheduled task where I synch all the data from one table (via an API) to another. There are about 10,000 rows that are being updated and the new ones get created. This is what I came up with and for some reason, it is extremely slow.

def sync_data_from_hub():
    stats = tasks.sync_clients_from_hub()

    return stats

tasks.py

# 1. This method calls an external API to fetch all the rows.
def sync_clients_from_hub():
    url = resolve_hub_url('clients')

    response = requests.get(url, headers=headers)

    if response.status_code != 200:
        print('api response error: {}'.format(response))
        return

    try:
        response_payload = response.json()
    except ValueError:
        return

    # response from API
    clients_data = response_payload.get('data')

    for (key, value) in clients_data.items():
        # Check whether there are any actual changes in this row
        # by comparing the last updated date
        if services.should_update_data_from_hub(value, constants.SyncTypes.CLIENT):
            user, action = services.update_or_create_client_from_hub_data(value)

            if action == constants.SyncActions.CRT:
                result['new'] += 1
            if action == constants.SyncActions.UPD:
                result['update'] += 1

    # soft delete clients which are not present in payload but still available in database.
    if clients_data:
        discarded_clients = models.Client.objects.exclude(pk__in=list(map(int, clients_data.keys()))).filter(
            is_active=True)

        for client in discarded_clients:
            client.is_active = False
            client.save()

            result['deleted'] += 1

    return result

service.py

# logic to determine whether we should update the row or not
def should_update_data_from_hub(hub_data: dict, sync_type: str) -> bool:
    last_updated_date_from_api = hub_data.get('updatedAt', None)

    hub_data['id'] = int(hub_data.get('client', ''))

    # This line hits DB to fetch the row corresponding to the one in the API
    entity = get_client_by_pk(hub_data['id'])

    if not entity:
        return True

    last_updated_date_local = entity.last_updated_date

    if not last_updated_date_local:
        return True
    # The last updated dates have different timezones, so I have to adjust the timezone before comparison.
    last_updated_date_tz = last_updated_date.replace(tzinfo=timezone.utc).astimezone(tz=None)

    last_updated_date_local_formatted = last_updated_date_tz.strftime('%Y-%m-%d %H:%M:%S')

    return last_updated_date_formatted != last_updated_date_from_api

# Actual method to update the data
def update_or_create_client_from_hub_data(client_data: dict):
    client_data['id'] = int(client_data.get('client', None))

    # Set `is_active` based on the `archived` flag.
    if client_data.get('archive', None) == '1':
        client_data['is_active'] = False
    else:
        client_data['is_active'] = True
    ...

    # Set `last_updated_date`
    client_data['last_updated_date'] = client_data.get('updatedAt', datetime.datetime.now())

    serializer = serializers.ClientCreateSerializer(data=client_data)

    if not serializer.is_valid():
        print('client sync errors: {}'.format(serializer.errors))
        return None, None

    # This line hits DB to fetch the row corresponding to the one in the API
    client = get_client_by_pk(serializer.validated_data['id'])

    if client:
        action = constants.SyncActions.UPD

        for (key, value) in serializer.validated_data.items():
            setattr(client, key, value)

        client.save()
    else:
        action = constants.SyncActions.CRT

        client = models.Client.objects.create(**serializer.validated_data)

    return client, action

def get_client_by_pk(pk: int) -> Optional[models.Client]:
    return models.Client.objects.filter(pk=pk).first()

How can I optimize it to perform better? Should I load all the rows from DB in memory first rather than fetching them one by one and doing a comparison?


texts:
Project Euler problem 10 is to find the sum of all primes less than 2 million. I have written a program that does this, and it works, but it takes an excruciatingly long amount of time. What I'm asking is if there is any way I could optimize this to make it run much faster.

I wrote it in an app on my iPad called Pythonista.

def checkPrime(number):
    if number == 2:
        return True

    if number < 2:
        return False

    if number % 2 == 0:
        return False

    for i in range(3, (number**1/2)-1, 2):
        if number % i == 0:
            return False

    return True

primes = [i for i in range(10000) if checkPrime(i)]
print sum(primes)


texts: Synchronous loop with internal asynchronous calls

texts:
Below I've written a simple version of what I'm attempting to accomplish. I'm new to asynchronous functions, so it's difficult to wrap my head around this. My goal is to wait for the loop to finish all the callbacks before console.log() runs, but I want all the callbacks inside the loop to be asynchronous, so they don't wait for calls to complete one after another, taking way too much time to complete. How would I write this, the loop to be synchronous (wait for all internal calls to complete) but the internal calls to be asynchronous?

Much appreciated!

var addressList = [];

for (var i = 0; i < members.length; i++) {
  service.member.info({
    name: members[i],
    company: "Cerberus",
    // Callback function
    function(body) {
      addressList.push(body.address);
    }
  });
}

console.log(addressList);


texts:
I'm a beginner to intermediate in programming, and created a Tic-tac-toe game in python. I plan to add an AI player and a GUI using pygame.
Any improvements I could make to the code, especially with the logic, or just formatting in general?
my_board = [
    ["1", "2", "X"],
    ["4", "5", "6"],
    ["7", "8", "9"]
]

class Tictactoe():
  def __init__(self, board):
    self.board = board

  def print_board(self):
    print("|-------------|")
    print("| Tic Tac Toe |")
    print("|-------------|")
    print("|             |")
    print("|    " + self.board[0][0] + " " + self.board[0][1] + " " + self.board[0][2] + "    |")
    print("|    " + self.board[1][0] + " " + self.board[1][1] + " " + self.board[1][2] + "    |")
    print("|    " + self.board[2][0] + " " + self.board[2][1] + " " + self.board[2][2] + "    |")
    print("|             |")
    print("|-------------|")
    print()

  def available_moves(self):
    moves = []
    for row in self.board:
      for col in row:
        if col != "X" and col != "O":
          moves.append(int(col))
    return moves

  def select_space(self, move, turn):
    row = (move-1)//3
    col = (move-1)%3
    self.board[row][col] = "{}".format(turn)

  def has_won(self, player):
    for row in self.board:
        if row.count(player) == 3:
            return True
    for i in range(3):
        if self.board[0][i] == player and self.board[1][i] == player and self.board[2][i] == player:
            return True
    if self.board[0][0] == player and self.board[1][1] == player and self.board[2][2] == player:
        return True
    if self.board[0][2] == player and self.board[1][1] == player and board[2][0] == player:
        return True
    return False

  def game_over(self):
    self.available_moves()
    if self.has_won("X") or self.has_won("O") or len(self.available_moves()) ==0:
      return True
    else:
      return False

  def get_player_move(self, turn):
    move = int(input("Player {player} make your turn: ".format(player=turn)))
    self.available_moves()
    while move not in range (1,10) or move not in self.available_moves():
      move = int(input("Invalid move, try again: "))
    return move

def game(board):
  tictactoe = Tictactoe(my_board)
  while not tictactoe.game_over():
    tictactoe.print_board()
    x_move = tictactoe.get_player_move("X")
    tictactoe.select_space(x_move,"X")
    tictactoe.print_board()
    if tictactoe.game_over():
      break

    o_move = tictactoe.get_player_move("O")
    tictactoe.select_space(o_move,"O")
  if tictactoe.has_won("X"):
    print("X wins")
  elif tictactoe.has_won("O"):
    print("O wins")
  else:
    print("tie")

game(my_board)


texts:
The script is for rotating 5 different coloured gears (tandwiel) on my site.

I think the code can be improved and improved performance. 5x var paper isn't that smart for speed?

Getting the current code working faster in the normal state is the primary concern, but there are two smaller issues I know of that I would appreciate help with:

The code works most of the time, but when changing the browser size I have a problem with the rotating left and right: 1 gear will rotate the other direction, but starts to rotate very fast and finally slows down to normal speed. The longer you let it rotate at normal speed and then change browser, the longer the gear rotates too fast. It seems to me it rotates backwards all the missing angles til it will be normal again??
How to stop the JavaScript when the browser size is mobile. So it won't overload for mobile. The animation should start again when changing to bigger browser size.

Those two issues are not the primary concern.

var w = window.innerWidth;

if (w>=960) {window.direction = -1; }
else {window.direction = 1; }

window.onresize=function(){
var w = window.innerWidth;
if (w>=960) {window.direction = -1; }
else if (w<960 && w>=715){window.direction = 1; }
};

window.onload = function() {
var paper = new Raphael(document.getElementById('canvas_container'), 730, 750);

var paper = new Raphael(document.getElementById('tandwiel-1'), 240, 240);
var tandwiel1 = paper.image( "tandwiel-1.png",0,0,240,240);

var paper = new Raphael(document.getElementById('tandwiel-2'), 240, 240);
var tandwiel2 = paper.image( "tandwiel-2.png",0,0,240,240);

var paper = new Raphael(document.getElementById('tandwiel-3'), 240, 240);
var tandwiel3 = paper.image( "tandwiel-3.png",0,0,240,240);

var paper = new Raphael(document.getElementById('tandwiel-4'), 240, 240);
var tandwiel4 = paper.image( "tandwiel-4.png",0,0,240,240);

var paper = new Raphael(document.getElementById('tandwiel-5'), 240, 240);
var tandwiel5 = paper.image( "tandwiel-5.png",0,0,240,240);

var angle = 0;

setInterval( function() {
angle += 2;
tandwiel1.stop().animate( { "transform": "R" + angle }, 1000, "<>" );
}, 150 );

setInterval( function() {
angle += 2;
tandwiel2.stop().animate( { "transform": "R" + -angle }, 1000, "<>" );
}, 150 );

setInterval( function() {
angle += 2;
tandwiel3.stop().animate( { "transform": "R" + angle }, 1000, "<>" );
}, 150 );

setInterval( function() {
angle += 2;
tandwiel4.stop().animate( { "transform": "R" + -angle }, 1000, "<>" );
}, 150 );

setInterval( function() {
angle += 2;
tandwiel5.stop().animate( { "transform": "R" + direction*angle }, 1000, "<>" );
}, 150 );
}


texts:
For practice I tried implementing a bubble sort algorithm in Ruby. I'm especially interested in creating clean DRY and KISS code and keeping things readable, but efficient. Any hints to improve things would be very much appreciated. The code looks like this:

class Sorter
  def initialize
  end

  def sort(stack)
    if stack.length == 0
      return stack
    else
      checkArguments(stack)
      if stack.length == 1
        return stack
      else
        newstack = []
        stackIsSorted = false
        while !stackIsSorted
          newstack = iterateThroughStack(stack)
          if  newstack == stack
            stackIsSorted = true
          else
            stack = newstack
          end
        end
        return newstack
      end
    end
  end

  def checkArguments(stack)
    stack.each do
      |element|
      if element.class != Float && element.class != Fixnum
        raise ArgumentError, "element detected in stack that is not an integer or double"
      end
    end
  end

  def iterateThroughStack(stack)
    newstack = []
    currentElement = stack[0]
    for i in (1...stack.length)
      if  currentElement < stack[i]
        newstack.push(currentElement)
        currentElement = stack[i]
      else
    newstack.push(stack[i])
      end
    end
    newstack.push(currentElement)
  end
end

Then, after reading about Test Driven Development, I started using this practice and since then, I think code makes more sense with unit tests. So below are the unit test I wrote:

require 'test/unit'
require 'lib/Sorter'

class Test_Sorter < Test::Unit::TestCase
  def setup
    @sorter = Sorter.new
  end

  def test_emptyStack
    stack = []
    assert_equal(stack, @sorter.sort(stack), "sorting empty stack failed")
  end

  def test_StackWithOneElement
    stack = [1]
    assert_equal(stack, @sorter.sort(stack), "sorting stack with one element: 1 failed")
    stack = ["a"]
    assert_raise (ArgumentError) { @sorter.sort(stack) }
  end

  def test_StackWithTwoElements
    stack = [2, 1]
    sorted_stack = [1, 2]
    assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with two elements: 1, 2 failed")
    stack = [2, "a"]
    assert_raise (ArgumentError) { @sorter.sort(stack) }
  end

  def test_StackWithThreeElements
    stack = [2, 3, 1]
    sorted_stack = [1, 2, 3]
    assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with three elements: 1, 2, 3 failed")
  end

  def test_StackWithFourElements
    stack = [4, 2, 3, 1]
    sorted_stack = [1, 2, 3, 4]
    assert_equal(sorted_stack, @sorter.sort(stack), "sorting stack with four elements: 1, 2, 3, 4 failed")
  end

end


texts:
Background
I have a script that either takes a text file that contains a list of player_ids or not. If the user provides a player_id list i ensure that all the ids are part of the tranche date they provided and then run the process job for all the player ids in the list.
If the user has not provided a list of players to run the jobs on we run the process job on all the players that are part of the tranche date.
Code
import argparse
from nba import release_checks, s3, shell
from typing import List
from nba.process_jobs_off_sqs import batch
from nba.process_jobs_off_sqs.exceptions import BatchTimeoutException

def _get_all_player_id(tranche_date: str) -> List[str]:
    return s3.download_str_key(
        s3.S3Path(
            "player-datasets",
            f"ENVIRONMENTS/staging/{tranche_date}/all_player_ids_in_delivery.txt",
        )
    ).splitlines()

def _is_player_id_list_valid(
    provided_player_id_list: List[str], all_player_id_list: List[str]
) -> bool:
    for player_id in provided_player_id_list:
        if player_id not in all_player_id_list:
            raise Exception(
                f"The following player id: {player_id} in the text file is not part of the tranche you provided."
            )
    return True

def _launch_process_job(list_of_player_ids: List[str]) -> None:
    jobs = [
        {"player_id": player_id, "job_id": player_id}
        for player_id in list_of_player_ids
    ]
    try:
        batch.launch_and_await_batch("automated_player_selection", jobs)
    except BatchTimeoutException:
        print(f"Jobs are known to fail due data missingness.")

def _run_mentality_check(nba_folder_name: List[str]) -> None:
    try:
        release_checks.mentality_check(
            nba_folder_name
        )
    except Exception as e:
        print(e)

def parse_args():
    parser = argparse.ArgumentParser()
    parser.add_argument("--nba-folder-name", required=True)
    parser.add_argument("--tranche-date", required=True)
    parser.add_argument("--list-of-player-id-file-path")
    return parser.parse_args()

if __name__ == "__main__":
    args = parse_args()
    all_player_id_list = _get_all_player_id(args.tranche_date)
    if args.list_of_player_id_file_path:
        provided_player_id_list = shell.lines_from_file(
            args.list_of_player_id_file_path
        )
        if _is_player_id_list_valid(provided_player_id_list, all_player_id_list):
            _launch_process_job(provided_player_id_list)
    else:
        _launch_process_job(provided_player_id_list)
    _run_mentality_check(args.nba_folder_name)

I am mostly looking for a code review for better python usage as i am new to python. I gave a vague background as i am less concerned on getting code review on the actual algorithm but more so about my code and how to make it more pythonic and clean.


texts:
I want to use SOLID more and more but still learning, I'm improving a PPT generator and would like your help applying SOLID principles in it.

That generator should print two photos per slide, first one to the left, second to the right;
If the last photo is a left photo, it should be placed in center;
Each photo has a text right below it;
I'll use a third party PPT lib to do the low level stuff.

This is what I came up with, a little bit abstracted just to pass the idea, the sample is in PHP but I'll accept answers in any programming language:

class Controller
{
    $ppt = new Ppt(Ppt::DEFAULT_RESOLUTION, $background, $header, $footer);

    $ppt->writeSlides($photoCollection);

    $pptFile = $ppt->saveToFile();

    $ppt->deleteLocalTemporaryFiles();

    readfile($pptFile);
    unlink($pptFile);
}

class Ppt extends thirdPartyPptLib
{
    const DEFAULT_RESOLUTION = 'x';

    private $resolution;
    private $background;
    private $header;
    private $footer;

    public function __construct($resolution = null, $background = null, $header = null, $footer = null)
    {
        $this->resolution = $resolution;
        $this->background = $background;
        $this->header     = $header;
        $this->footer     = $footer;
    }

    public function writeSlides(\Traversable $photoCollection)
    {
        $i     = 0;
        $count = count($photoCollection);

        foreach ($photoCollection as $photoInfo) {
            $photoToLeft = $i % 2 == 0;
            $isLastPhoto = $i == ($count - 1);

            if ($isLastPhoto) {
                $slide = $this->newSlide();
                $slide->addCenterPhotoInfo($photoInfo);

            } else if ($photoToLeft) {
                $slide = $this->newSlide();
                $slide->addLeftPhotoInfo($photoInfo);

            } else {
                $slide->addRightPhotoInfo($photoInfo);
            }

            $i++;
        }
    }

    private function newSlide()
    {
        $slide = parent->newSlide();

        if ($this->hasBackground()) {
            $slide->setBackground();
        }

        if ($this->hasHeader()) {
            $slide->setHeader();
        }

        if ($this->hasFooter()) {
            $slide->setFooter();
        }

        return $slide;
    }
}

class Slide extends thirdPartyPptLibSlide
{
    public function addLeftPhotoInfo($photoInfo)
    {
        $this->addLeftPhoto($photoInfo->getPhoto());
        $this->addUnderlyingText($photoInfo->getText());
    }

    // functions addRightPhotoInfo and addCenterPhotoInfo very similar
}

Should I separate it more into different classes? Or methods? Should I create Interfaces?


texts: Determining the difference between odd and even numbers

texts:
I have code that converts each character of a String to an int and returns the difference between odd and even numbers. Can this code be simplified?

int compareSumOfDigits(String N) {
int e=0,o=0;
for (int i =0;i<N.length();i++){
    int t = Character.getNumericValue(N.charAt(i));
    if(t%2==0)
    e+=t;
else
    o+=t;

}
      return  o-e ;
}


texts:
I'm thinking of making a little strategic game using tkinter (player should interact with it using buttons). But my code is very repetitive.  This is a mock-up of my program:

import tkinter as tk
import random

def multi(*args):
    for func in args:
        func()

def show_hide():
    if not button["text"]:
        button.configure(text="Perform action #1", bd=2, bg="white", command=activate_deactivate)
        status_label["text"] = "Status: {}".format(status.get())
        button_2.configure(text="Perform action #2", bd=2, bg="white", command=activate_deactivate_2)
        status_label_2["text"] = "Status: {}".format(status_2.get())
    else:
        button.configure(text="", bd=0, bg="#F0F0F0", command=None)
        status_label["text"] = ""
        button_2.configure(text="", bd=0, bg="#F0F0F0", command=None)
        status_label_2["text"] = ""

def activate_deactivate():
    if status.get() == "Can be done":
        status.set("To be done")
        status_label.configure(text="Status: {}".format(status.get()), fg="blue")
    else:
        status.set("Can be done")
        status_label.configure(text="Status: {}".format(status.get()), fg="black")

def activate_deactivate_2():
    if status_2.get() == "Can be done":
        status_2.set("To be done")
        status_label_2.configure(text="Status: {}".format(status.get()), fg="blue")
    else:
        status_2.set("Can be done")
        status_label_2.configure(text="Status: {}".format(status.get()), fg="black")

def step_forward():
    if status.get() == "To be done":
        button.configure(text="", bd=0, bg="#F0F0F0", state="disabled")
        status_label["text"] = ""
        result = random.choice(["success", "failure"])
        if result == "success":
            status.set("Accomplished")
            status_label["fg"] = "green"
        else:
            status.set("Failed")
            status_label["fg"] = "red"
    else:
        button.configure(text="", bd=0, bg="#F0F0F0", command=None)
        status_label["text"] = ""

def step_forward_2():
    if status_2.get() == "To be done":
        button_2.configure(text="", bd=0, bg="#F0F0F0", state="disabled")
        status_label_2["text"] = ""
        result = random.choice(["success", "failure"])
        if result == "success":
            status_2.set("Accomplished")
            status_label_2["fg"] = "green"
        else:
            status_2.set("Failed")
            status_label_2["fg"] = "red"
    else:
        button_2.configure(text="", bd=0, bg="#F0F0F0", command=None)
        status_label_2["text"] = ""

root = tk.Tk()

status = tk.StringVar()
status.set("Can be done")

status_2 = tk.StringVar()
status_2.set("Can be done")

main = tk.Button(root, text="Show/Hide", bg="white", font="courier 30", command=show_hide)
main.pack()

frame = tk.Frame(root, pady=10)
frame.pack()

frame_1 = tk.Frame(frame, padx=10)
frame_1.pack(side="left")

frame_2 = tk.Frame(frame, padx=10)
frame_2.pack(side="left")

button = tk.Button(frame_1, text="", font="courier 20", bd=0)
button.grid(row=0, column=0)

status_label = tk.Label(frame_1, text="", font="courier 14")
status_label.grid(row=1, column=0)

button_2 = tk.Button(frame_2, text="", font="courier 20", bd=0)
button_2.grid(row=0, column=1)

status_label_2 = tk.Label(frame_2, text="", font="courier 14")
status_label_2.grid(row=1, column=1)

next_day = tk.Button(root, text="Next day", bg="white", font="courier 30",
                     command=lambda: multi(step_forward, step_forward_2))
next_day.pack()

root.mainloop()

This definitely looks terrible. With blank lines, it takes 100+ lines of code just to make 2 buttons (well, it's not only "2 buttons"), but I want to have many of these (a few groups each one containing around 4+ buttons which is a lot). If you know how "this" can be changed, I'd love to hear any suggestions (although this code is bad, it perfectly represents functionality and look of the interactive part of the UI, so these should remain the same).


texts: Cleanly passing in a large number of mutable parameters through a python class

texts:
I want to create two classes, one for attributes and one for functional behaviors. The point of the attributes class was to hold all of the attributes along with property methods (setters/getters), and I wanted to split the classes up this way so that everything related to the attributes would not fill up the entire other class.
Due to the way python handles mutable default arguments, I have to handle the attributes using None for default arguments, but I have a very large number of parameters. This has caused the code to become unnecessarily long when passing arguments around on the initialization:
class Attributes:
    def __init__(self,
            arg1,
            arg2,
            arg3,
            arg4,
            arg5):

        self.arg1 = default_arg1 if arg1 is None else arg1
        self.arg2 = default_arg2 if arg2 is None else arg2
        self.arg3 = default_arg3 if arg3 is None else arg3
        self.arg4 = default_arg4 if arg4 is None else arg4
        self.arg5 = default_arg5 if arg5 is None else arg5

    # attribute methods like getters and setters

class Functionality(Attributes):
    def __init__(self,
            arg1 = None,
            arg2 = None,
            arg3 = None,
            arg4 = None,
            arg5 = None):

        super(Functionality, self).__init__(
            arg1,
            arg2,
            arg3,
            arg4,
            arg5
        )

    # Methods that give functionality to the class

I want to be able to use this class as follows:
example_obj = Functionality(
    arg1 = example_arg1,
    arg4 = example_arg4
)

Is there any cleaner way to do this? I want to add more attributes (more than 20 attributes instead of 5), but the above code involves writing basically the same thing way too many times.


texts: Write an anonymous function validating email address

texts:
Problem statement

  Write an anonymous function which take email address as parameter and returns true/false after validating the input parameter.

  Objective

  This assignment will help you to master the following concepts:

  function
  closures

Solution

<!DOCTYPE html>
<html>
    <head>
        <title>Anomymous function</title>
        <meta charset="UTF-8">
        <script type="text/javascript">
            var result = (function(email_id){
                            var regpat = /^[a-zA-Z_\.\-]+@[a-zA-Z_\-\.]+?\.[a-zA-Z]{2,4}$/;
                            return regpat.test(email_id);
                        })('xyz@gmail.com');
            document.write(result);
        </script>
    </head>
    <body>

    </body>
</html>

1) Is this the corresponding solution?

2) Why document.body.innerHTML = result; does not work?


texts: Checkbox binding to change the ListView's items source

texts:
I am using a checkbox to filter some components on my ListView by changing the variable's content which is bound to this ListView:

C#

#region Constructor

void CreateAllParts()
{
    // GetParts() returns List<Part>. Now we can pour it's results
    // using the following select in List<EditPartViewModel> on the
    // fly.
    // allpvms: All Part View Models.
    allpvms = _partRepository.GetParts().Select(p => new EditPartViewModel(p)).ToList();

    foreach (EditPartViewModel cvm in allpvms)
    {
        cvm.PropertyChanged += this.OnPartViewModelPropertyChanged;
    }

    this.AllParts = new ObservableCollection<EditPartViewModel>(allpvms);
    this.AllParts.CollectionChanged += this.OnCollectionChanged;
}

void LoadErrorParts()
{
    if (_errorParts)
    {
        this.AllParts = new ObservableCollection<EditPartViewModel>(allpvms.Where(p => p.Price == null));
        this.AllParts.CollectionChanged += this.OnCollectionChanged;
    }
    else
    {
        this.AllParts = new ObservableCollection<EditPartViewModel>(allpvms);
        this.AllParts.CollectionChanged += this.OnCollectionChanged;
    }
}

#endregion // Constructor

#region Public Interface

/// <summary>
/// Returns a collection of all the EditPartViewModel objects.
/// </summary>
public ObservableCollection<EditPartViewModel> AllParts
{
    get
    {
        return _allParts;
    }
    set
    {
        _allParts = value;
        OnPropertyChanged("AllParts");
    }
}

public bool ErrorParts
{
    get
    {
        return _errorParts;
    }
    set
    {
        _errorParts = value;
        OnPropertyChanged("ErrorParts");
        LoadErrorParts();
    }
}

#endregion // Public Interface

XAML

<CheckBox DockPanel.Dock="Top"
          IsChecked="{Binding ErrorParts, Mode=TwoWay}"
          HorizontalAlignment="Right"
          Content="Parts with Error"
          />

<ListView
  AlternationCount="2"
  d:DataContext="{d:DesignInstance Type=vm:MockViewModel, IsDesignTimeCreatable=True}"
  ItemsSource="{Binding AllParts}"
  >
  <ListView.ItemContainerStyle>
    <Style TargetType="{x:Type ListViewItem}">
      <EventSetter Event="MouseDoubleClick" Handler="ListViewItem_MouseDoubleClick" />
      <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
    </Style>
  </ListView.ItemContainerStyle>
</ListView>

ListViews content get collected by a DataTemplate in the Resources.

Is the way I use the binding concept look okay? Any corrections or "good practice" methods I should consider when doing similar procedures?


texts: Given set of cubes can we get a given word?

texts:
Given some cubes, can cubes be arranged such that an input word can be formed from the top view of the cubes?

For example: assume an imaginary cube with only 3 surfaces where cube1: {a, b, c} and cube2 {m, n, o}, then word an can be formed but word ap cannot be formed.

Please look into the two following issues:

A couple of questions nested inside the codes regarding premature optimization.
Verifying complexity to be O(n!), where n is the number of alphabets in the word.

public final class CubeFind {
    private CubeFind() {}

    public static boolean checkWord(char[][] cubeMatrix, String word) {

        /*
         * Premature optimization: read that they were bad practices. they look good in my code, should i keep them ?
         *
         * 1. If not checked now, then NPE would result after hashMap is computed. on line 46
         * if (cubeMatrix == null) { throw new NullPointerException("The input cube matrix should not be null");
         *
         * 2. if (word == null {throw new NullPointerException("The input word should not be null"); }
         *
         * 3. if (cubeMatrix.length != word.length()) return false;
         */

        char[] chWords = word.toCharArray();
        final Map<Character, Integer> charFreq = new HashMap<Character, Integer>();

        for (char ch : chWords) {
            if (charFreq.containsKey(ch)) {
                charFreq.put(ch, charFreq.get(ch) + 1);
            } else {
                charFreq.put(ch,  1);
            }
        }

        return findWordExists(cubeMatrix, charFreq, 0);
    }

    private static boolean findWordExists (char[][] cubeMatrix, Map<Character, Integer> charFreq, int cubeNumber) {
        assert charFreq != null;

        if (cubeNumber == cubeMatrix.length) {
            for (Integer frequency : charFreq.values()) {
                if (frequency > 0) return false;
            }
            return true;
        }

        for (int i = 0; i <  cubeMatrix[cubeNumber].length; i++) {
            if (charFreq.containsKey(cubeMatrix[cubeNumber][i])) {
                int frequency = charFreq.get(cubeMatrix[cubeNumber][i]);
                // this check is needed to get a false result when input chars are less than number of cubes
                // eg: 'hel' should return false.
                if (frequency > 0) {
                    charFreq.put(cubeMatrix[cubeNumber][i], frequency - 1);
                    if (findWordExists(cubeMatrix, charFreq, cubeNumber + 1)) {
                        return true;
                    }
                    charFreq.put(cubeMatrix[cubeNumber][i], frequency);
                }
            }
        }

        return false;
    }

    public static void main(String[] args) {
        char[][] m = {{'e', 'a', 'l'} , {'x', 'h' , 'y'},  {'p' , 'q', 'l'}, {'l', 'h', 'e'}};
        System.out.println("Expected true,  Actual: " + CubeFind.checkWord(m, "hell"));
        System.out.println("Expected true,  Actual: " + CubeFind.checkWord(m, "help"));
        System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hplp"));
        System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hplp"));
        System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "helll"));
        System.out.println("Expected false, Actual: " + CubeFind.checkWord(m, "hel"));
    }
}


texts:
http://en.wikipedia.org/wiki/Monotone_cubic_interpolation

We have implemented it using the formula from Wikipedia :

public class MonotoneCubicSplineInterpolation
    {
        public static double[] Calc(double[] xs, double[] ys, double[] x_interp)
        {
            var length = xs.Length;

            // Deal with length issues
            if (length != ys.Length)
            {
                IPDevLoggerWrapper.Error("Need an equal count of xs and ys");
                throw new Exception("Need an equal count of xs and ys");
            }
            if (length == 0)
            {
                return null;
            }
            if (length == 1)
            {
                return new double[] {ys[0]};
            }

           // Get consecutive differences and slopes
            var delta = new double[length - 1];
            var m = new double[length];

            for (int i = 0; i < length - 1; i++)
            {
                delta[i] = (ys[i + 1] - ys[i]) / (xs[i + 1] - xs[i]);
                if (i > 0)
                {
                    m[i] = (delta[i - 1] + delta[i]) / 2;
                }
            }
            var toFix = new List<int>();
            for (int i = 1; i < length - 1; i++)
            {
                if ((delta[i] > 0 && delta[i - 1] < 0) || (delta[i] < 0 && delta[i - 1] > 0))
                {
                    toFix.Add(i);
                }
            }
            foreach (var val in toFix)
            {
                m[val] = 0;
            }

            m[0] = delta[0];
            m[length - 1] = delta[length - 2];

            toFix.Clear();
            for (int i = 0; i < length - 1; i++)
            {
                if (delta[i] == 0)
                {
                    toFix.Add(i);
                }
            }
            foreach (var val in toFix)
            {
                m[val] = 0;
                m[val + 1] = 0;
            }

            var alpha = new double[length - 1];
            var beta = new double[length - 1];
            var dist = new double[length - 1];
            var tau = new double[length - 1];
            for (int i = 0; i < length - 1; i++)
            {
                alpha[i] = m[i] / delta[i];
                beta[i] = m[i + 1] / delta[i];
                dist[i] = Math.Pow(alpha[i], 2) + Math.Pow(beta[i], 2);
                tau[i] = 3/Math.Sqrt(dist[i]);
            }

            toFix.Clear();
            for (int i = 0; i < length - 1; i++)
            {
                if (dist[i] > 9)
                {
                    toFix.Add(i);
                }
            }

            foreach (var val in toFix)
            {
                m[val] = tau[val] * alpha[val] * delta[val];
                m[val + 1] = tau[val] * beta[val] * delta[val];
            }

            var y_interp = new double[x_interp.Length];
            int ind = 0;

            foreach (var x in x_interp)
            {
                int i;
                for (i = xs.Length - 2; i >= 0; --i)
                {
                    if (xs[i] <= x)
                    {
                        break;
                    }
                }
                var h = xs[i + 1] - xs[i];
                var t = (x - xs[i])/h;
                var t2 = Math.Pow(t, 2);
                var t3 = Math.Pow(t, 3);
                var h00 = 2*t3 - 3*t2 + 1;
                var h10 = t3 - 2*t2 + t;
                var h01 = -2*t3 + 3*t2;
                var h11 = t3 - t2;
                y_interp[ind++] = h00*ys[i] + h10*h*m[i] + h01*ys[i + 1] + h11*h*m[i + 1];

                continue;
            }

            return y_interp;
        }
    }

Please comment about style, correctness and complexity.


texts:
I am working on a plugin for a Minecraft server. In it, I have a function that returns a ChatColor depending on what permission level you are.

Whenever I need reference the user with proper colors, I always get a color from the below function.

/**
 * ChatColor
 *
 * @param Player
 * @return ChatColor
 */
public ChatColor getColor(Player p) {
    // By default the color is Guest. The color will stay at guest otherwise.
    ChatColor color = ChatColor.GRAY;
    if (p.hasPermission("level.owner")) {
        // Owner
        color = ChatColor.RED;
    } else if (p.hasPermission("level.staff")) {
        // Admin / Mod
        color = ChatColor.AQUA;
    } else if (p.hasPermission("level.builder")) {
        // Builder
        color = ChatColor.DARK_AQUA;
    } else if (p.hasPermission("level.member")) {
        // Member
        color = ChatColor.GOLD;
    } else if (p.hasPermission("level.guest")) {
        // Guest
        // We don't need to change the color, since the color defaults to gray.
    }
    return color;
}

One might call this function as below:

p.sendMessage("Welcome back, " + getColor(p) + p.getName() + gold + "!");

And it would send a message to the player like "Welcome back, (playerName)!" with playerName the level's color.

What I have found is that if you have the first permission level (level.owner) it can take a much longer time. After putting in some debugging (e.g getting a NanoTime, running my function, and subtracting the difference) I've found the following:

With level.owner it takes about 4580ns to run
With level.staff it takes about 6340ns to run
With level.builder it takes about 8000ns to run
With level.member it takes about 7630ns (sometimes going as high as 10240ns) to run
With level.guest it takes about 10000ns+ to run

Is there any way to improve my function run at nearly the same speed for all of my checks?

(I am a beginner at Java, but know many other languages, so this is somewhat new to me.)


texts: String tokenization and replacing a numbered field

texts:
I created various functions for string manipulation in Lua, where the strings are composed of tokens separated by an ASCII character (which may be the point, comma, semicolon etc.). One of these is the function puttok()

local function tokenize(C, strng)
    local sInput = strng or ""
    local sChar = string.format('%c', C)
    local tReturn = {}
    for sWord in string.gmatch(sInput, "[^"..sChar.."]+") do
        table.insert(tReturn, tonumber(sWord) or sWord)
    end
    return tReturn
end

local function puttok(text,token,N,C)
    local char = string.format("%c", C)
    local n
    local result
    local tokens = tokenize(C, text)
    if (N == 0) or (N > #tokens) then
        result = text
    end
    if (N) then
        n = (N > 0) and N or #tokens + N + 1
        table.remove(tokens,n)
        table.insert(tokens,n,token)
        result = table.concat(tokens,char)
    end
    return result
end

Where

text = string to manipulate
token = token (string) we want insert
N = position in which will be added to the token
C = ASCII code of the token separator

This function is to replace a token with another. Here's an example

local text = "Violets.are.white"
text = puttok(text,"blue",3,46)
print(text)
—› Violets.are.blue

The token "blue" was inserted in position 3 in place of "white," and "Violets" and "are" are respectively in position 1 and 2. The tokens are separated by a dot (.) with ASCII code 46.

Is there a way to improve this code?
Would metatables be usefull in this case?


texts: Wrap glium_text so that parameters aren't passed redundantly

texts:
I was annoyed by the API of glium_text, so I decided to make a wrapper that cleans up the API instead of coding my own text rendering. (I might do that later.)

The wrapping turned out to be rather nontrivial. I was mystified by the amount of generics that were involved in glium_text. Surely there is some way to make this wrapping in an easier way.

extern crate glium;
extern crate glium_text;
extern crate cgmath;

use std::ops;

pub trait SizedFacade: glium::backend::Facade + Sized {}
impl<T> SizedFacade for T where T: glium::backend::Facade + Sized {}

pub struct System<'a, F: SizedFacade + 'a> {
    system: glium_text::TextSystem,
    display: & 'a F
}

impl<'a, F: SizedFacade + 'a> System<'a, F> {
    pub fn new(display: & 'a F) -> System<'a, F> {
        System{
            system: glium_text::TextSystem::new(display),
            display: display
        }
    }

    pub fn new_font(&self, bytes: &[u8], size:u32) -> Font<F> {

        Font {
            system: self,
            texture: glium_text::FontTexture::new(self.display, bytes, size).unwrap()
        }
    }
}

pub struct Font<'a, T: SizedFacade + 'a> {
    system: & 'a System<'a, T>,
    texture: glium_text::FontTexture,
}

impl<'a, T: SizedFacade + 'a> Font<'a, T> {
    pub fn new_text(&self, s: &str) -> Text<&glium_text::FontTexture, T> {
        Text {
            text: glium_text::TextDisplay::new(&self.system.system, &(self.texture), s),
            system: self.system,
        }
    }
}

pub struct Text<'a, T: ops::Deref<Target=glium_text::FontTexture>, F: SizedFacade + 'a> {
    text: glium_text::TextDisplay<T>,
    system: & 'a System<'a, F>,
}

impl<'a, T: ops::Deref<Target=glium_text::FontTexture>, F: SizedFacade + 'a> Text<'a, T, F> {
    pub fn draw(&self, frame: &mut glium::Frame, matrix: [[f32; 4]; 4], color: (f32, f32, f32, f32)){
        glium_text::draw(&self.text, &self.system.system, frame, matrix, color);
    }
}


texts:
I wrote a productivity app for Android. It lets you switch system settings, like Bluetooth, wife, screen brightness, volumes, ringtones, mobile data, airplane mode, etc. Unfortunately I have discovered that device manufacturers modify the OS in every possible way, disabling functionality, requesting additional permissions, or making it available only to system apps. I.e. switching WiFi on stock Android requires android.permission.CHANGE_WIFI_STATE permission, but most Samsung devices also require android.permission.ACCESS_WIFI_STATE. Switching mobile data is simply disabled on many devices.

This makes it impossible to predict how my code will work on a particular device, or on a future version of OS. But at the same time, I definitely don't want my app to crash, because there's really nothing worse that an app can do. So in order to be safe, I've been using what is sometimes called a "Pokemon exception handling" (Gotta catch 'em all!):

try {
    //Do stuff
} catch (Exception e) {
    //Log an error, send crash report, etc.
}
//Keep calm and carry on

I know that this is generally considered a bad practice, but I just can't find a better way to handle this situation. I simply can't predict all possibilities of what could go wrong. Most of my methods for executing actions look something like this:

private boolean switchWiFi(boolean state) {
    try {
        WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);
        wm.setWifiEnabled(state);
        return true; //Executed successfully
    }
    catch (Exception e){
        //Give user a notification about an error, rather than crash
        showErrorNotification("Couldn't switch WiFi.");
        if(BuildConfig.DEBUG){Log.getStackTraceString(e);}//Log exception stack trace
        return false; //Execution failed
    }
}

Is there a better way to handle exceptions?


texts: For each pair of strings, eliminate the characters they have in common

texts:
In the below code there are 3 inputs.
First line of input is the number of testcases for which the program will run where (1<=testcases<=10) and i is an int.
For each testcase
Second and third input will be a String where (1<=Stringlength<=10^5)
Output
Now for the output we need to compare both the strings and remove similar characters from both them. The output will be based on which string encounters 0 length first. if none of them is 0 after completion then it will be a draw.
Time of execution is 1.0 sec for each input but my time for 10^5 strings is 2.0. Is there a way to increase its efficiency based on the time.

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

public class MyProg{
public static void main(String[] args) throws IOException
{
    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the number of testcases");
    String ts=br.readLine();
    int testcase=Integer.parseInt(ts);
    for(int i=0;i<testcase;i++)
    {
        System.out.println("Enter the 2 strings");
        String sa=br.readLine().replaceAll("\\s+", "");
        String sb=br.readLine().replaceAll("\\s+", "");
        List<Character> s1 = new ArrayList<Character>();
        List<Character> s2 = new ArrayList<Character>();
        for(char c : sa.toCharArray())
            s1.add(c);
        for(char c : sb.toCharArray())
            s2.add(c);
        for(char c:s2)
        {
                s1.remove((Character)c);

        }

        for(char c:sa.toCharArray())
        {
                s2.remove((Character)c);
        }
        if(s1.size()==0 && s2.size()>0)
            System.out.println("You lose some.");
        else if(s1.size()>0 && s2.size()==0)
            System.out.println("You win some.");
        else
            System.out.println("You draw some.");
    }
}}


texts: Is there a better way how to force file download than using this simple PHP script?

texts:
I've written this simple script to force download some files (jpg, mp3, usually those which are loaded in browser by default).
I was wondering whether there's any way this could be improved upon, which means:

making it more secure
making it use less cpu (filesize(), fopen(), fpassthru() are the usual suspects here)
making it simpler maybe

Here it goes:

<?php

if (!isset($_GET['file'])){
   die('no file requested');
}

else{

   if (substr($_GET['file'], 0, 1) == '.'){
      die('trying to leave this directory? :)');
   }

   $path = './'.$_GET['file'];
   if (file_exists($path) && is_readable($path)){
    $size = filesize($path);
    header('Content-Type: application/octet-stream');
    header('Content-Length: '.$size);
    header('Content-Disposition: attachment; filename='.$_GET['file']);
    header('Content-Transfer-Encoding: binary');
    $file = fopen($path, 'rb');
    fpassthru($file);
    exit;
   }

}

?>

Usage: /?file=sample.jpg


texts: Building a flexible upsert statement for SQL

texts:
This is a single function in C#. It works fine. My concern is that although I've made the code as short and as multi-functional as I can, what it's doing seems very unclear. It looks like the sort of thing I'm going to come back to in six months and hate myself for writing.

Its purpose is to build and execute generic "upsert" sql statements for a variety of scenarios. Each record that it comes across has a name, an address and a flag to say whether the operation on that record is a delete and whether that record represents someone who's gone away. The former tells us whether we're setting a bit value to true or false, while the latter determines the column name.

How can I make this code clearer without turning it into a mess of flow control?

private void Sprail(FileRow fr, string columnName)
{
    List<Suppression> addressMatches = GetMatchingRecordsFromDb(SanitiseForMySql(fr.CleanedAddress), SanitiseForMySql(fr.CleanedName));

    using (MySqlConnection con = new MySqlConnection(_connectionString))
    {
        string sqlTargetFlag = columnName;
        string sqlTargetValue = "1";
        string sql = "";

        if (fr.IsDeleted)
        {
            sqlTargetValue = "0";
        }

        if (fr.IsGoneaway)
        {
            sqlTargetFlag = sqlTargetFlag + "Goneaway";
        }

        if (string.IsNullOrWhiteSpace(fr.CleanedAddress))
        {
            sql = BuildInsertSql(sqlTargetFlag, fr, sqlTargetValue);
        }

        foreach (Suppression s in addressMatches)
        {
            if (fr.CleanedName.ToString().ToLower() == s.NameKey.ToLower())
            {
                sql = string.Format("UPDATE MyTable set {0} = {1} where SuppressionId = {2}", sqlTargetFlag, sqlTargetValue, s.SuppressionId);
                break;
            }
        }

        if(sql != "")
        {
            con.Open();
            MySqlCommand cmd = new MySqlCommand(sql, con);
            cmd.ExecuteNonQuery();
        }
    }
}

private string BuildInsertSql(string sqlTargetFlag, FileRow fr, string sqlTargetValue)
{
    return string.Format(@"INSERT INTO MyTable (`AddressKey`, `NameKey`, `{0}`) VALUES ('{1}', '{2}', '{3}')",
                                sqlTargetFlag, SanitiseForMySql(fr.CleanedAddress), SanitiseForMySql(fr.CleanedName), sqlTargetValue);
}


texts:
We have just learned about classes. Please help me improve this program. I created a class called Box with members that represent its dimensions.  Then I calculate the volume and surface area and print it.

#include <iostream>

using std::cout;
using std::endl;

class Box
{
public:
    Box(){};
    double m_Length;
    double m_Width;
    double m_Height;
private:
};

int main()
{
    Box box1;
    Box box2;

    double boxVolume(0.0);
    double surfaceArea(0.0);

    box1.m_Height = 18.0;
    box1.m_Length = 78.0;
    box1.m_Width = 24.0;

    boxVolume = box1.m_Height * box1.m_Length * box1.m_Width;
    surfaceArea = 2.0 * ((box1.m_Height * box1.m_Width) + (box1.m_Length * box1.m_Height) + (box1.m_Length * box1.m_Width));

    cout << "Volume of box1 = " << boxVolume << endl;
    cout << "Surface Area of box1 = " << surfaceArea << endl;
}


texts:
I'm new to Python/Programming and wrote this simple "Day of the week/Holiday finder" script. Ideally I'd use something so I can have a little widget on my desktop, but right now I'm looking for any and all suggestions to improve my code?

I'm importing this holiday module

import datetime
import holidays

today = datetime.date.today()
today = today.strftime("%m/%d/%Y")
today = datetime.datetime.strptime(today, "%m/%d/%Y")

def days_between(d1):
    d2 = today
    return (d2 - d1).days

def find_dt(input_dt):
    print(input_dt)
    dt1 = datetime.datetime.strptime(input_dt, "%m/%d/%Y")
    dt2 = dt1.strftime('%A')

    if days_between(dt1) == 0:
        print("Today IS {d}.".format(d=dt2))
    elif days_between(dt1) <= 1:
        print("It'll be a {d}.".format(d=dt2))
    else:
        print("It was a {d}.".format(d=dt2))

    us_holidays = holidays.UnitedStates()
    us_h = us_holidays.get(input_dt)

    if us_h is None and days_between(dt1) == 0:
        print("Today is not a holiday.")
    elif us_h is None and days_between(dt1) <= 1:
        print("It won't be a holiday.")
    elif us_h is None and days_between(dt1) >= 1:
        print("It wasn't a holiday.")
    elif days_between(dt1) == 0:
        print("Today is {h}.".format(h=us_h))
    elif days_between(dt1) <= 1:
        print("It'll be {h}.".format(h=us_h))
    else:
        print("It was {h}.".format(h=us_h))

def main():
    d = input('Type a date using MM/DD/YYYY: ')
    # d = '12/25/2015'
    find_dt(d)

main()


texts: Approach to string split by character in Haskell

texts:
I'm trying to learn Haskell and the mindset of programming functionally. I have started off by trying to understand the basics by writing code without any Monads in it.

So far, I think I'm getting used to the type system and how the basics works.

I thought to myself, why not try to get some feedback on what I have written to learn even more. So hopefully I will get some valuable information!

I have written a function which iterates a String and splits it into [String] by using given Char as a delimiter. Similar to what PHP's explode and Python's split does.

Here's what I have got so far:

main :: IO()
main = do
    print $ groupBy "/hejsan/asdas" '/' []
    print $ groupBy "/hejsan/asdas/hoho" '/' []
    print $ groupBy "/hejsan/asdas/hahsdhashdas" '/' []
    print $ groupBy "/hejsan/99/hahsdhashdas" '/' []
    print $ groupBy "/123/asdas/hahsdhashdas///" '/' []
    print $ groupBy "/123/asdas/hahsdhashdas//20////hej" '/' []

groupBy :: String -> Char -> [String] -> [String]
groupBy "" _ [] = []
groupBy (x:xs) c []
    | x == c = groupBy xs c []
    | otherwise = groupBy xs c [[x]]
groupBy "" _ (r:rs) = reverse result
    where result = if r == "" then rs else [r] ++ rs
groupBy (x:xs) c (r:rs)
    | x == c = groupBy xs c $ nextGroup ++ rs
    | otherwise = groupBy xs c $ [r ++ [x]] ++ rs
    where nextGroup = if r == "" then [r] else [""] ++ [r]

With output:

["hejsan","asdas"]
["hejsan","asdas","hoho"]
["hejsan","asdas","hahsdhashdas"]
["hejsan","99","hahsdhashdas"]
["123","asdas","hahsdhashdas"]
["123","asdas","hahsdhashdas","20","hej"]

So the main idea is to only show groups which have values in them. I bet there is:

Some library function which can simplify the functions internals
Some way to eliminate the 3rd argument so that it will be transparent to the user (Currying?)

I welcome all types of feedback except for feedback like "there is a library function which does all that for you". I'd like feedback on the internals and this particular problem is just an example


texts: Motorcycle rental station with flyweight pattern

texts:
The definition of flyweight pattern:

  Flyweight design pattern uses sharing to support large numbers of objects that have part of their internal state common and other parts of state can vary.

Please let me know whether I implemented this pattern correctly. I also want to know whether the map structure is always needed when implement this pattern. Anything related to the pattern is also welcomed.

Bike: Define the interface for clients to ride the bike at the speed they want.
Motorcycle: Implementation of Bike. Has internal state BikeType, which is decided when created.
BikeType: Two types of bikes

Scooter
Sports bike

FlyweightFactory: The bike rental store. I chose this name to make it clear of the role it plays in the flyweight pattern.

Factory is a singleton, only one factory.
Choose the BikeType and get the bike.

Bike.java

public interface Bike
{
    // speed is external state.
    public void rideBike(int speed);
}

Motorcycle.java

public class Motorcycle implements Bike
{
    // BikeType is internal state.
    private BikeType bikeType;

    public Motorcycle(BikeType bikeType) {
        this.bikeType = bikeType;
    }

    @Override
    public void rideBike(int speed) {
        System.out.format("Riding %s at speed %d mps%n",
            getBikeType().getTypeName(),
            speed);
    }

    //
    private BikeType getBikeType() {
        return this.bikeType;
    }
}

BikeType.java

public enum BikeType
{
    SPORTS("Sports Bike"), SCOOTER("Scooter");

    private String typeName;

    private BikeType(String typeName) {
        this.typeName = typeName;
    }

    public String getTypeName() {
        return this.typeName;
    }
}

FlyweightFactory.java

I implemented the flyweight rental store with singleton pattern:

public class FlyweightFactory
{
    // static fields & methods
    private static volatile FlyweightFactory factory;

    public static FlyweightFactory getFactory() {
        if (factory == null) {
            synchronized (FlyweightFactory.class) {
                if (factory == null) {
                    factory = new FlyweightFactory();
                }
            }
        }

        return factory;
    }

    // Instance fields & methods
    private Map<BikeType, Bike> bikes;

    private FlyweightFactory() {
        this.bikes = new HashMap<>();
    }

    public Bike getBike(BikeType bikeType) {
        Bike bikeReturn = getBikes().get(bikeType);

        if (bikeReturn == null) {
            bikeReturn = new Motorcycle(bikeType);
            getBikes().put(bikeType, bikeReturn);
        }

        return bikeReturn;
    }

    // setters & getters
    private Map<BikeType, Bike> getBikes() {
        return this.bikes;
    }
}

App.java

Example program to test the flyweight factory works well:

public class App
{
    public static void main(String[] args) {

        FlyweightFactory ff = FlyweightFactory.getFactory();

        Bike sportBike = ff.getBike(BikeType.SPORTS);
        System.out.println(sportBike);
        System.out.println(ff.getBike(BikeType.SPORTS));
        sportBike.rideBike(20);

        System.out.println(" --- ");

        Bike scooter = ff.getBike(BikeType.SCOOTER);
        System.out.println(scooter);
        scooter.rideBike(30);
    }
}

Output:

Motorcycle@7c17831
Motorcycle@7c17831
Riding Sports Bike at speed 20 mps
 ---
Motorcycle@26cf402f
Riding Scooter at speed 30 mps


texts:
It is my first time trying to create smooth animations using rAF and I would like some insight from more experienced developers. Basically I have 16 elements with x,y coordinates and on mousemove over their parent container, all elements move a set amount in the opposite direction. When I do tests on lower-end machines there is some stutter. Is there any technique I am not aware of that can boost my animation performance?

(function ($) {
$(document).ready(() => {
const animCont = document.querySelector('.shop-header-container');
const animContWidth = animCont.offsetWidth;
const animContHeight = animCont.offsetHeight;
const leftOffset = animCont.getBoundingClientRect().left;
const topOffset = document.querySelector('#primary').offsetTop;
const animImgs = animCont.querySelectorAll('.elem');
let mouseX = 0;
let mouseY = 0;
let mouseOver = false;
let positions = [
  {
    id: 82,
    start: {
      x: 0.596,
      y: 0.654,
    },
    range: 0.4,
  }
...
]
positions.forEach(el => {
  el.target = {};
  el.current = {};
})
function updateElements(){
  mouseTargetX = (mouseX - leftOffset) / animContWidth;
  mouseTargetY = (mouseY + topOffset) / animContHeight;
  positions.forEach((el,i) => {
    if (mouseOver) {
      el.target.x = ((mouseTargetX - el.start.x) * -el.range + el.start.x ) * animContWidth;
      el.target.y = ((mouseTargetY - el.start.y) * -el.range + el.start.y ) * animContHeight;
    } else {
      el.target.x = el.start.x * animContWidth;
      el.target.y = el.start.y * animContHeight;
    }

    if(!el.current.x) {
      el.current.x = el.target.x;
      el.current.y = el.target.y;
    } else {
      el.current.x = el.current.x + (el.target.x - el.current.x)*0.1;
      el.current.y = el.current.y + (el.target.y - el.current.y)*0.1;
    }

    animImgs[i].style.transform = 'translate3d('+el.current.x+'px,'+el.current.y+'px,0)';
  })
  requestAnimationFrame(updateElements);
}
updateElements();
function animContMouseEnter(e){
  mouseOver = true;
}
function animContMouseLeave(){
  mouseOver = false;
}
function animContMouseOver(e){
  mouseX = e.clientX;
  mouseY = e.clientY;
}
animCont.addEventListener("mousemove",animContMouseOver,false);
animCont.addEventListener("mouseenter",animContMouseEnter,false);
animCont.addEventListener("mouseleave",animContMouseLeave,false);
});
}(jQuery));


texts: Determining if a genetic sequence is palindromic

texts:
Adding another level to my previous question on 'normal' palindrome identification, in this one I'm interested in identifying genetic palindromes. Here's my attempt:

#include <iterator>
#include <algorithm>
#include <array>

namespace detail
{
    static constexpr std::array<char, 128> complement_table
    {
        4, 4,  4, 4,  4,  4,  4, 4,  4, 4, 4, 4,  4, 4, 4,  4,
        4, 4,  4, 4,  4,  4,  4, 4,  4, 4, 4, 4,  4, 4, 4,  4,
        4, 4,  4, 4,  4,  4,  4, 4,  4, 4, 4, 4,  4, 4, 4,  4,
        4, 4,  4, 4,  4,  4,  4, 4,  4, 4, 4, 4,  4, 4, 4,  4,
        4, 84, 4, 71, 4,  4,  4, 67, 4, 4, 4, 4,  4, 4, 78, 4,
        4, 4,  4, 4,  65, 65, 4, 4,  4, 4, 4, 4,  4, 4, 4,  4,
        4, 84, 4, 71, 4,  4,  4, 67, 4, 4, 4, 4,  4, 4, 4,  4,
        4, 4,  4, 4,  65, 65, 4, 4,  4, 4, 4, 4,  4, 4, 4,  4
    };
} // namespace detail

inline constexpr char complement(const char base)
{
    return detail::complement_table[base];
}

namespace detail
{
    template <typename RandomIt>
    bool is_palindromic(RandomIt first, RandomIt last, std::random_access_iterator_tag)
    {
        if (first == last) return true;

        const auto size = std::distance(first, last);

        if (size % 2 != 0) return false;

        return std::equal(first, std::next(first, size / 2), std::make_reverse_iterator(last),
                          [] (const char lhs, const char rhs) {
                              return lhs == complement(rhs);
                          });
    }

    template <typename BidirIt>
    bool is_palindromic(BidirIt first, BidirIt last, std::bidirectional_iterator_tag)
    {
        if (first == last)   return true;
        if (first == --last) return false;

        for (; first != last; ++first, --last) {
            if (*first != complement(*last)) return false;
            if (std::next(first) == last) return true;
        }

        return false;
    }
} // namespace detail

template <typename BidirIt>
bool is_palindromic(BidirIt first, BidirIt last)
{
    return detail::is_palindromic(first, last, typename std::iterator_traits<BidirIt>::iterator_category {});
}

template <typename SequenceType>
bool is_palindromic(const SequenceType& sequence)
{
    return is_palindromic(std::cbegin(sequence), std::cend(sequence));
}

Used as such:

#include <iostream>
#include <string>
#include <list>

int main()
{
    std::cout << std::boolalpha;
    std::string str {"ACCTAGGT"};
    std::cout << is_palindromic(str) << std::endl;
    std::list<char> lst {str.cbegin(), str.cend()};
    std::cout << is_palindromic(lst) << std::endl;
    return 0;
}

Performance is my primary concern here. Comments and suggested improvements are welcome!


texts:
I wanted to create a loan calculator, but the code I could think of was using 3 functions, and calling them and getting result. But I felt it was easy but bad code because I thought this can be written in fewer lines and with more quality. I wanted to ask what are some things to keep in my mind while trying to write better code instead of going in flow and creating many functions.

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

float loanAmount,interestRate,Discount,i,loanPayment; //global variables

int years;

void loanDetails(void); //input from user regarding the loan
float annualRate(void);// interest rate
float discount(void); //discount to be added

int main() //main
{

    loanDetails(); //called three functions
    annualRate();
    discount();

    loanPayment = (loanAmount)/(Discount); //formula for monthly payments

    printf("\nthe monthly loan payment is %f",loanPayment);

    return EXIT_SUCCESS;
}

void loanDetails(void) //taking input from user
{
    printf("please enter Total Loan Amount: ");
    scanf("%f",&loanAmount);
    printf("please enter the number of years: ");
    scanf("%d",&years);
    printf("please enter the annualrate to be applied: ");
    scanf("%f",&interestRate);
}

float annualRate(void) //calculated annual rate
{
    float *ann;
    ann = &interestRate;
    i = ((*ann)/(100))/12;
    printf("the value for %d years is %f",years,i);
    return i;
}

float discount(void) //calculated dicount
{
    float *x,y;
    x = &i;
    y = 1 + *x;
    int n = years*12;

    float topD = (pow((y),n)-1);
    float botD = (y-1)*pow((y),n);
    Discount = topD/botD;
    printf("\nthe value of discount is : %f",Discount);
    return Discount;
}


texts: Finding b and e such that b to the power of e is closest to a given number

texts:
The question is to find a number with absolute minimum difference from a number of the form be. I came up with the below code which takes 4 seconds to solve each test case on an average however it has to be solved within 2 seconds.

Sample Input:

  11
  25

Sample Output:

  20

Explanation:

11 is the nearest to 32. Thus 11 - 9 = 2

25 is 52 thus there is no difference.

My code:

public static void main(String[] args) {
    Scanner in = new Scanner(System.in);
    int T = in.nextInt();    //Number of testcases

    for(int i = 0; i < T; i++){

            int number = in.nextInt();

            int sqrtNumber = (int)Math.sqrt(number);
            int powerNumber;

            int minDiff = Integer.MAX_VALUE;
            for (int b = 2; b <= sqrtNumber; b++) {
                for (int e = 1; (powerNumber = (int) Math.pow(b, e)) <= number; e++) {
                    if (number - powerNumber < minDiff)
                        minDiff = number - powerNumber;
                }
            }
            System.out.println(minDiff);

    }
}


texts: Efficiently sample a single row of an array at random

texts:
I have the following C++ code snippet that randomly samples a single row in an array called pop with num_specs columns and perms rows. In addition, K = 1. The triply-nested for loop uses a pointer for referencing.

Some of the below syntax (such as IntegerVector) is from Rcpp, an R package to integrate C++ code with R code.

// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::depends(RcppProgress)]]
#define ARMA_DONT_PRINT_OPENMP_WARNING
#include <RcppArmadillo.h>
#include <RcppArmadilloExtensions/sample.h>
#include <set>
using namespace Rcpp;

int sample_one(int n) {
  return n * unif_rand();
}

int sample_n_distinct(const IntegerVector& x,
                      int k,
                      const int * pop_ptr) {

IntegerVector ind_index = RcppArmadillo::sample(x, k, false);
std::set<int> distinct_container;

for (int i = 0; i < k; i++) {
    distinct_container.insert(pop_ptr[ind_index[i]]);
}

return distinct_container.size();
}

// [[Rcpp::export]]
arma::Cube<int> accumulate(const arma::Cube<int>& pop,
                     const IntegerVector& specs,
                     int perms,
                     int K) {

int num_specs = specs.size();
arma::Cube<int> res(perms, num_specs, K);

IntegerVector specs_C = specs - 1;
const int * pop_ptr;
int i, j, k;

for (i = 0; i < K; i++) {
    for (k = 0; k < num_specs; k++) {
        for (j = 0; j < perms; j++) {
            pop_ptr = &(pop(sample_one(perms), 0, sample_one(K)));
            res(j, k, i) = sample_n_distinct(specs_C, k + 1, pop_ptr);
        }
    }
}
return res;
}

While loops in compiled languages aren't bad, it is possible to write slow code.

I'm not a native C++ programmer, so I don't know all the tricks of the trade.

Is there a way to reduce the number of levels in the triply-nested for loop above, possibly by employing modular arithmetic in order to see a gain in speed for large input values?

The R code is below:

## Set up container to hold the identity of each individual from each permutation ##
num.specs <- N

## Create an ID for each tag ##
tags <- 1:h

## Assign individuals (N) ##
specs <- 1:num.specs

## Generate permutations. Assume each permutation has N individuals, and sample those
# individuals' tags from the probabilities ##
  gen.perms <- function() {
      sample(tags, size = num.specs, replace = TRUE, prob = probs)
  }

  pop <- array(dim = c(perms, num.specs, K))

  for (i in 1:K) {
    pop[,, i] <- replicate(perms, gen.perms())
  }

## Perform accumulation ##
HAC.mat <- accumulate(pop, specs, perms, K)

## Example
K <- 1
N <- 100
h <- 5
probs <- rep(1/h, h)
perms <- 100


texts:
Intersection of two sorted vectors in C++ - can this be written any better?

vector<int> intersection(vector<int>& nums1, vector<int>& nums2) {
        vector<int> result;
        int l = 0, r = 0;
        while(l < nums1.size() && r < nums2.size()){
            int left = nums1[l], right = nums2[r];
            if(left == right){
                result.push_back(right);
                while(l < nums1.size() && nums1[l] == left )l++;
                while(r < nums2.size() && nums2[r] == right )r++;
                continue;
            }
            if(left < right){
            while(l < nums1.size() && nums1[l] == left )l++;
            }else while( r < nums2.size()  && nums2[r] == right )r++;
        }
            return result;
    }


texts: Extract equally from X queues to one queue with Y elements

texts:
I need to implement a system of queueing that extracts elements equally from x queues to one single queue with y positions.

Let's say I have 5 queues, each with a number of elements and I need to extract elements from each of the 5 queues to build a new queue containing the extracted elements until the new queue is full.

For example:

5 queues to a queue with 100 positions. I need to extract 20 elements from each queue. Ok, but if some of the 5 input queues have less than 20 elements, the resulting queue will have some empty elements.
51 queues to a queue with 100 positions. I need to extract 1 element from each queue. The input queues have for sure at least 1 element. But the resulting queue will have 49 empty positions. So I'll need to iterate the input queues to extract 1 element from each one, until I reach the max 100 positions of the resulting queue.

I need this to implement a system of sending queues to send massive SMSs form web for our customers. In those example, the 51 queues are 51 different SMS, inside each of these queues there are all the mobile numbers to send the sms to.

I can send only $this->QueueMax sms every 2 minutes, so I have a script that takes a number of mobile phones from all sms to send and send all sms in parallel.

I've implemented this PHP script to manage the final queue: at the end, $smsToSend will tell me how many mobile numbers to extract for each SMS in the 'limit' field.

Is that alright? Will the script work fine?

But most of all, is there a less-complex method of doing this?

    $query = 'SELECT sms_id, COUNT(DISTINCT mobile) AS tot_mobile ';
    $query.= 'FROM sms_queue ';
    $query.= 'GROUP BY sms_id ';
    $this->Dbh->query($query);

    $smsToSend = array();
    while($this->Dbh->next()) {
        $smsToSend[$this->Dbh->Record['sms_id']] = array(
            'tot' => $this->Dbh->Record['tot_mobile'],
            'limit' => 0,
        );
    }

    /* The queue to send is empty */
    if( empty($smsToSend) ) {
        $this->IsSending = false;
        return false;
    }

    /* Total phone numbers to take from each sms queue */
            $totSmsToSend = count($smsToSend);

    /* There are more sms to send than empty positions in the send queue; send only the firsts "QueueMax" sms */
    if( $totSmsToSend > $this->QueueMax ) {
        $smsToSend = array_slice($smsToSend, 0, $this->QueueMax, true);
        $totSmsToSend = $this->QueueMax;
    }

    $totMobilesFromEachSms = (int)floor($this->QueueMax / $totSmsToSend);
    foreach( $smsToSend as $smsID => $info ) {
        $smsToSend[$smsID]['limit'] = ($totMobilesFromEachSms >= $info['tot']) ? $info['tot'] : $totMobilesFromEachSms;
    }

           /* If there are some empty positions, iterate $smsToSend and take 1 mobile number foreach sms 'till covering all empty positions */
    if( ($totMobilesFromEachSms * $totSmsToSend) < $this->QueueMax ) {
        $i = $totSmsToSend + 1;
        while(true) {
            $check = false;

            foreach($smsToSend as $smsID => $info) {
                if( $info['limit'] >= $info['tot'] ) {
                    continue;
                }

                $check = true;

                $smsToSend[$smsID]['limit']++;
                $i++;

                if( $i >= $this->QueueMax ) {
                    break 2;
                }
            }

            /* Each sms has all its phone numbers correctly placed inside the send queue*/
                            if( !$check ) {
                break;
            }
        }
    }


texts: Thread-Safe and Lock-Free - Queue Implementation

texts:
I was trying to create a lock-free queue implementation in Java, mainly for personal learning. The queue should be a general one, allowing any number of readers and/or writers concurrently.

Would you please review it, and suggest any improvements/issues you find?

(Cross-post from StackOverflow)

import java.util.concurrent.atomic.AtomicReference;

public class LockFreeQueue<T> {
    private static class Node<E> {
        final E value;
        volatile Node<E> next;

        Node(E value) {
            this.value = value;
        }
    }

    private AtomicReference<Node<T>> head, tail;

    public LockFreeQueue() {
        // have both head and tail point to a dummy node
        Node<T> dummyNode = new Node<T>(null);
        head = new AtomicReference<Node<T>>(dummyNode);
        tail = new AtomicReference<Node<T>>(dummyNode);
    }

    /**
     * Puts an object at the end of the queue.
     */
    public void putObject(T value) {
        Node<T> newNode = new Node<T>(value);
        Node<T> prevTailNode = tail.getAndSet(newNode);
        prevTailNode.next = newNode;
    }

    /**
     * Gets an object from the beginning of the queue. The object is removed
     * from the queue. If there are no objects in the queue, returns null.
     */
    public T getObject() {
        Node<T> headNode, valueNode;

        // move head node to the next node using atomic semantics
        // as long as next node is not null
        do {
            headNode = head.get();
            valueNode = headNode.next;
            // try until the whole loop executes pseudo-atomically
            // (i.e. unaffected by modifications done by other threads)
        } while (valueNode != null && !head.compareAndSet(headNode, valueNode));

        T value = (valueNode != null ? valueNode.value : null);

        // release the value pointed to by head, keeping the head node dummy
        if (valueNode != null)
            valueNode.value = null;

        return value;
    }
}


texts: Throwing exceptions in a database wrapper

texts:
I hope the extension methods ThrowArgumentNullExceptionIfNullOrEmpty and ThrowNullReferenceExceptionIfNullOrEmpty are straightforward.

I have a property in my class called ConnectionString. I can set this property through a method called SetConnectionString.

public static void SetConnectionString(string connectionString)
{
        _connectionString = connectionString.ThrowArgumentNullExceptionIfNullOrEmpty("connectionString", Localizer.GetString("0x000000004"));
}

My reason why I don't have

public static string ConnectionString { get; set; }

but

public static string ConnectionString { get { return _connectionString; } }

is because I want the property to be read-only and throw an ArgumentNullException if the argument in SetConnectionString is null or empty.

Since the class is static, it's possible for ConnectionString to be null (or an empty string if I do this: return _connectionString ?? "").

Part 1

In the code below I check the arguments for null or an empty string but to prevent an exception occurring when calling OpenConnection (see Part 2 for more on this method) I also check if the _connectionString (private variable of the ConnectionString property) is not null or empty (empty is for the internal connection string of the OleDbConnection object). Here I decided the exception should be a NullReferenceException because it's not directly an argument of the method.

Is this the correct approach to handle this situation? Consider that the code in between the checks might and might not have an impact on the application if the using fails.

public static int GetHighestID(string table, string column)
{
    _connectionString.ThrowNullReferenceExceptionIfNullOrEmpty(Localizer.GetString("0x000000000"));

    table.ThrowArgumentNullExceptionIfNullOrEmpty("table", Localizer.GetString("0x000000001"));

    column.ThrowArgumentNullExceptionIfNullOrEmpty("column", Localizer.GetString("0x000000002"));

    // Some other things are happening here ...

    using (var connection = new OleDbConnection(_connectionString))
    using (var command = new OleDbCommand(string.Format("SELECT MAX({0}) FROM {1}", column, table), connection))
    {
        OpenConnection(connection);

        return (int)command.ExecuteScalar();
    }
}

Part 2

The OpenConnection method as mentioned before is included below.

public static void OpenConnection(OleDbConnection connection)
{
    connection.ThrowArgumentNullExceptionIfNull("connection", Localizer.GetString("0x00000000C"));
    connection.ConnectionString.ThrowArgumentNullExceptionIfNullOrEmpty("connection.ConnectionString", Localizer.GetString("0x00000000F"));

    if (connection.State != ConnectionState.Open)
        connection.Open();
}

I also here check if the OleDbConnection object is not null and that the internal connection string is not null or an empty string. My intention is to always use this method when opening the connection with the database.

Again, is this the correct approach to handle this situation?


texts:
In my code's package, I have a flag such as:

public static final boolean LOGS_VERBOSE = false;

And in worker classes (multi threaded Runnable jobs), I have code like:

if(XYConstants.LOGS_VERBOSE){
    logger.debug("some state info var 1:" + var1 + ", var 2:" + var2);

Is this a good idea? Is there any performance gain? Developers say it avoids code going to the log4j level completely, and there is hardly any overhead to check the value of the constant.

We do plan to do performance testing, but that is a month away, and I need to show code to the client (who is a developer of 14 years) this Friday. I'm wondering if this should stay or not?

We have some debugs without the boolean check too, and those are wanted in all runs as long as log4j is configured in debug level.

This code is using log4j 1.2.16.


texts: Given a list of words, find the most common initial character and other statistics

texts:
20 different words are inputted using a string array.

A C++ program to display the alphabet which has occurred the maximum number of times as starting letter of a word in the list,and how many times it has occurred.

In this program i have also displayed a few other things too,like the longest length,shortest length,average length,maximum number of vowels,letter ending with s.

I would like to know how this program can be written more 'intelligently'.

#include<iostream.h>
#include<string.h>
int main()
{
int i,n,len=0,sum=0,j,max,min,c=0,c2=0,k=0;
int maxo=0,len1,maxi=0,c1=0,len2,counter=0,maxo1=0,len3;
 float avg;
char list[100][100] = { 0 };
char vow[] = "AEIOUaeiou";
char letter;
for(i=0;i<2;i++)
{
cout<<"Enter word:  ";
gets(list[i]);

len=strlen(list[i]);
sum=sum+len;
cout<<"Length of word:  "<<len<<endl;
if(list[i][len-1]=='s')
{cout<<"The Word "<<list[i]<<" ends with s"<<endl;
 c2++;
 }

}
//Word input by user.Prints word along with length.
min=strlen(list[0]);
max=strlen(list[0]);
//Initialising max and min.
for(i=0;i<2;i++)
 {
   if(strlen(list[i])<min)
   {min=strlen(list[i]);}
    if(strlen(list[i])>max)
    {max=strlen(list[i]);}

     }
  for(i=0;i<2;i++)
  {
  if(max==strlen(list[i]))
  cout<<"The max value of the lengths stored:"<<list[i]<<endl<<"Word count:"
  <<max<<endl;
  if(min==strlen(list[i]))
  cout<<"The min value of the lengths stored:"<<list[i]<<endl<<"Word count:"
  <<min<<endl;
  }
//Max and Min value of string lengths are printed.
 avg=sum/2;
 cout<<"Avg length:"<<avg<<endl;
 //Average value printed.
 cout<<"The number of words with s:"<<c2<<endl;
//Word ending with s.

 for (i = 0; i <2; i++)

 {len1 = strlen(list[i]);
 for (k = 0; k < len1; k++)
 {
    for (j = 0; j < strlen(vow); j++)
        //if (list[j][k] == vow[j])
        if (list[i][k] == vow[j])
            c++;
}
cout << "Number of vowels in line " << i << ": " << c << '\n';
if (c>maxo) maxo = c;
c = 0;
cout << "Maximum Vowel count so far:" << maxo << "\n\n";

 cout << "Maximum Vowel count:" << maxo << endl;
   }

 //Vowel maximum count

 for(i = 0 ;i < 2 ;i++)
 { len3 = strlen(list[i]);
    letter = list[i][0];
 {for(j=0;j<len3;j++)
  if(list[i][j]==letter)
   counter++;

 }
 cout << "Number of identical letters as  first letter in line " << i << ": " << counter << '\n';
if (c>maxo1) maxo1 = counter;
counter = 0;
cout << "Maximum letter count so far:" << maxo1 << "\n\n";

 cout << "Maximum letter count:" << maxo1 << endl;
   }

fflush(stdin);
getchar();
return 0;
}


texts: Numerical Python code to generate artificial data from a time series process

texts:
I'm writing code to generate artificial data from a bivariate time series process, i.e. a vector autoregression. This is my first foray into numerical Python, and it seemed like a good place to start.

The specification is of this form:

\begin{align}
\begin{bmatrix}
y_{1,t} \\
y_{2,t}
\end{bmatrix}
&=
\begin{bmatrix}
0.02 \\
0.03
\end{bmatrix}
+
\begin{bmatrix}
0.5 & 0.1 \\
0.4 & 0.5
\end{bmatrix}
\begin{bmatrix}
y_{1,t-1} \\
y_{2,t-1}
\end{bmatrix}
+
\begin{bmatrix}
0 & 0 \\
0.25 & 0
\end{bmatrix}
\begin{bmatrix}
y_{1,t-2} \\
y_{2,t-2}
\end{bmatrix}
+
\begin{bmatrix}
u_{1,t} \\
u_{2,t}
\end{bmatrix}
\end{align}

where \$u\$ has a multivariate normal distribution, i.e.
\begin{align}
\begin{bmatrix}
u_{1,t} \\
u_{2,t}
\end{bmatrix}
\sim N \left( \begin{bmatrix} \mu_1 \\ \mu_2 \end{bmatrix}, \Sigma \right)
\end{align}

My basic algorithm generates enough observations to get past the effects of the (arbitrary) initial conditions, and only returns the number of observations asked for. In this case, it generates ten times the number of observations asked for and discards the first 90%.

import scipy

def generate_data(y0, A0, A1, A2, mu, sigma, T):
    """ Generate sample data from VAR(2) process with multivariate
        normal errors

    :param y0: Vector of initial conditions
    :param A0: Vector of constant terms
    :param A1: Array of coefficients on first lags
    :param A2: Array of coefficients on second lags
    :param mu: Vector of means for error terms
    :param sigma: Covariance matrix for error terms
    :param T: Number of observations to generate
    """

    if y0.ndim != 1:
        raise ValueError("Vector of initial conditions must be 1 dimensional")

    K = y0.size

    if A0.ndim != 1 or A0.shape != (K,):
        raise ValueError("Vector of constant coefficients must be 1 dimensional and comformable")

    if A1.shape != (K, K) or A2.shape != (K, K):
        raise ValueError("Coefficient matrices must be conformable")

    if mu.shape != (K,):
        raise ValueError("Means of error distribution must be conformable")

    if sigma.shape != (K, K):
        raise ValueError("Covariance matrix of error distribution must be conformable")

    if T < 3:
        raise ValueError("Cannot generate less than 3 observations")

    N = 10*T

    errors = scipy.random.multivariate_normal(mu, sigma, size = N-1)
    data = scipy.zeros((N, 2))
    data[0, :] = y0
    data[1, :] = y0
    for i in range(2, N):
        data[i, :] = A0 + scipy.dot(A1, data[i-1, :]) + scipy.dot(A2, data[i-1, :]) + errors[i-1,:]
    return(data[-T:, :])

def main():
    y0 = scipy.array([0, 0])
    A0 = scipy.array([0.2, 0.3])
    A1 = scipy.array([[0.5, 0.1], [0.4, 0.5]])
    A2 = scipy.array([[0, 0], [0.25, 0]])
    mu = scipy.array([0, 0])
    sigma = scipy.array([[0.09, 0], [0, 0.04]])
    T = 30

    data = generate_data(y0, A0, A1, A2, mu, sigma, T)
    print(data)

if __name__ == "__main__":
    main()

As I said, this code is very simple, but since it's my first attempt at a numerical Python project, I'm looking for any feedback before I slowly start building a larger code project that incorporates this. Does any of my code (base Python, SciPy, etc.) need improvement?

This specific model comes from:

  Brüggemann, Ralf, and Helmut Lütkepohl. "Lag Selection in Subset VAR Models with an Application to a US Monetary System." (2000).