texts: MySQL Schema for Tag System Works, But Can It Be Better?

texts:
I'm working on system that tags images. I'm going to use the xxHash (lz4) for hashing images. With hashes of size 64 bits, it looks like I won't have a 50% chance of a collision until ~4 billion images are added. At that point I think a collision would be the least of my worries.

The size of my VARCHARs in the images and tags table are not set in stone. The image path can be calculated from the file_hash (to base 36 number string) and the file_extension. file_name is just for preserving the file_name, as the file will be renamed to its base 36 hash. In the future I plan on normalizing the table further, having a table for all the file extensions and then storing the key in the images table. Might be excessive though, as file extensions don't change.

Here's my schema:

CREATE TABLE images (
  file_hash BIGINT PRIMARY KEY NOT NULL,
  file_extention VARCHAR(4) NOT NULL,
  file_name VARCHAR(64)
) Engine=InnoDB;

CREATE TABLE tags (
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
  tag_name VARCHAR(64) UNIQUE NOT NULL
) Engine=InnoDB;

CREATE TABLE tag_references (
  tag_id INT NOT NULL,
  file_hash BIGINT NOT NULL,
  CONSTRAINT img_hash_fk
    FOREIGN KEY (file_hash)
    REFERENCES images(file_hash)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
  CONSTRAINT tag_id_fk
    FOREIGN KEY (tag_id)
    REFERENCES tags(id)
    ON UPDATE CASCADE
    ON DELETE CASCADE,
  PRIMARY KEY(tag_id, file_hash)
) Engine=InnoDB;

I'm a little worried about using the BIGINT as the primary key. I was also thinking about using an INT (auto increment) as the primary key and having the hash as just another field marked as unique. I'm not sure how much complexity referring to images by a long will be on the code side either. I guess in some cases reading a long takes more than one cpu cycle, which might introduce complexities in a multi-threaded environment. I don't know if I'll even need to share "references" to images between threads though. I don't want to pre-maturely optimize.


texts: Extracting an integer command-line argument and printing a sum of numbers up to that limit

texts:
The below code works fine but I have the feeling that there must be something more idiomatic way to do this within the do-notation without having to resort to the two liftMs?

main = do
  n <- (liftM read (liftM head getArgs)) :: IO Int
  putStrLN . show $ sum [1..n]

If I do:

main = do
  args <- getArgs
  arg1 <- head args
  n <- read arg1 :: IO Int
  putStrLn . show $ sum [1..n]

I get:

Expected type: String
  Actual type: Char
In the first Argument of 'read', namely 'arg1'

which I do not understand. <- getArgs returns IO [String], so <- head args should return IO String, but it seems to return IO Char?! (as per error message).

So my two questions are:

what is the most idiomatic way do do this
what's wrong in the second version?


texts: Why does my implementation of the Sieve of Eratosthenes take so long?

texts:
def sieve_of_erastothenes(number):
    """Constructs all primes below the number"""
    big_list = [2] + range(3, number+1, 2)  # ignore even numbers except 2
    i = 1  # start at n=3, we've already done the even numbers
    while True:
        try:
            # use the next number that has not been removed already
            n = big_list[i]
        except IndexError:  # if we've reached the end of big_list we're done here
            return big_list
        # keep only numbers that are smaller than n or not multiples of n
        big_list = [m for m in big_list if m<=n or m%n != 0]
        i += 1

On my computer, this code takes about half a second to calculate all primes below 10,000, fifteen seconds to do 100,000, and a very long time to calculate primes up to one million. I'm pretty sure it's correct (the first few numbers in the returned sequence are right), so what can I do to optimise it?

I've tried a version that removes the relevant numbers in-place but that takes even longer (since it takes \$O(n)\$ to move all the remaining numbers down).


texts: Isolate a Database Change Within Django Transaction.Atomic

texts:
I have been typically adding the @transaction.atomic decorator to my endpoints and appreciate if a request fails at any point the data completely rolls back.  However, some of my endpoints will make an API call to another API service.  If my token for that API service is invalid, I refresh the token.  This is all well and good until an exception occurs after the API token has been refreshed.  The transaction is rolled back including the token information which then will be stale.  This includes the new refresh token information so I'm now unable to refresh the auth token.

I attempted to get around this situation by distributing the token refresh to a celery task and waiting for the result as a way of isolating that database change.   Even if the requests fails later on, the token information remains while the rest is rolled back.

Here is a simplified example

@transaction.atomic()
def post(request):
  response = api_call()
  db_operation(response['result']) #  Could potentially have an exception

def api_call(allow_refresh=True)
  response = requests.post(url, params)

  if response.status_code == 401:
    if allow_refresh:
     refresh_token_task.delay().get(timeout=10)
     response = api_call(allow_refresh=False)
    else:
      raise Exception('Invalid authorization') # In the case refreshing token doesn't resolve authorization issues, this prevents infinite loop.

  return response

Phew! I thought I was in the clear except... sometimes I distribute api calls.  It didn't occur to me but I realized calling celery tasks from celery tasks easily risks locking.   So now I've written out a solution that involves chaining.

def post(request):
  chain(api_call_task.s(), refresh_token_task.s(), api_call_task.s(), db_operation_task.s())()

@task
def api_call_task(initial_response=None)
  if initial_response and initial_response.status_code != 401:
    return response

  response = requests.post(url, params)

  return response

@task
def refresh_token_task(response):
  if response.status_code == 401:
    refresh_token()

  return response

@transaction.atomic()
@task
def db_operation_task(response):
  if response.status_code == 401:
    raise Exception('Invalid authorization')

  db_operation(response['result'])

I think this works to a degree but gosh what a confusing mess.  By chaining the functions, the response is continuously passed through which determines if the token needs to be refreshed and/or if the call needs to be made again and then finally to handle the db operation based upon the response to the api.

Is there a simpler way? Marginal improvement? Bad practice involved?  Would it better to just let go of transaction.atomic?  Let me know if my simplified pseudo code can use clarification.


texts: Bounded Queue with multiple consumers and multiple producers

texts:
It was an interview question:

Should implement a class - BlockingQueue with those constraints:

2 Methods - Adding an item and Take an item from the queue.
The class should support multiple consumers and multiple producers.
The class will getting a bounded size of queue and a maximum of producers and consumers at constructor:

public BlockingQueue(int boundedCapacity, int producers, int consumers)

At method Take - if the queue is empty - should to wait till have least one item in the queue.
At the method Insert - if the queue is full - should to wait till the queue was dequeued least one item.

I've written a queue class for supporting multiple producers and multiple consumers threads.

the class is getting bounded size and number of producers and consumers.

as following:

class BlockingQueue<T>
{
    readonly ConcurrentQueue<T> _queue = new ConcurrentQueue<T>();
    readonly int _boundedCapacity;

    readonly SemaphoreSlim _semaphoreSlimProducer;
    readonly SemaphoreSlim _semaphoreSlimConsumer;

    public BlockingQueue(int boundedCapacity, int producers, int consumers)
    {
        _boundedCapacity = boundedCapacity;
        _semaphoreSlimProducer = new SemaphoreSlim(0, producers);
        _semaphoreSlimConsumer = new SemaphoreSlim(consumers);
    }

    public void Insert(T item)
    {
        if(item == null) throw new ArgumentNullException("item");
        while(Count >= _boundedCapacity)
        {
            _semaphoreSlimProducer.Wait(1000);
            _semaphoreSlimConsumer.Release();
        }

        _semaphoreSlimProducer.Wait();
        _queue.Enqueue(item);
        _semaphoreSlimConsumer.Release();
    }

    public T Take()
    {
        while(Count == 0)
        {
            _semaphoreSlimConsumer.Wait(1000);
            _semaphoreSlimProducer.Release();
        }
        _semaphoreSlimConsumer.Wait();
        T retval = default(T);

        _queue.TryDequeue(out retval);

        _semaphoreSlimProducer.Release();
        return retval;
    }

    public int Count
    {
        get
        {
            return _queue.Count;
        }
    }
}

Testing:

private static void TestBlockingQueue()
{
    BlockingQueue<string> b = new BlockingQueue<string>(3, 3, 3);

    ConcurrentBag<Task> tasks = new ConcurrentBag<Task>();
    for(int i = 0; i < 10; i++)
    {
        var t = Task.Factory.StartNew(() => {
            string item = "Threadid:Thread.CurrentThread.ManagedThreadId_" + Thread.CurrentThread.ManagedThreadId + "_Count_";
            int count = 0;
            while(true)
            {
                item += count++;
                b.Insert(item);
                Console.WriteLine("insert item: " + item);
            }
        });
        tasks.Add(t);
    }

    for(int i = 0; i < 10; i++)
    {
        var t = Task.Factory.StartNew(() => {
            while(true)
            {
                var item = b.Take();
                Console.WriteLine("taked item: " + item);
            }
        });
        tasks.Add(t);
    }

    Task.WaitAll(tasks.ToArray());
}

I will be glad for getting a code review for this implementation.


texts: Vertically print a list of strings to STDOUT into 3 columns with column lengths as balanced as possible

texts:
This was a interview question I struggled with, I am posting my solution hoping to look for more elegant/efficient solutions.

Problem: Given a list of strings, print its element out to STDOUT one by one vertically into 3 columns, while making sure the 3 columns' length are as balanced as possible.

For example, given list = ['a','b','c','d','e','f','g','h','i','j']

The output could be either:

a e h
b f i
c g j
d

OR

a d g
b e h
c f i
    j

But not:

a e i
b f j
c g
d h

My approach in Python 3:

Basically I put each word into a "N by 3" 2D list horizontally and try to print them out vertically. If the length is not divisible by 3, I manually increase the length of the first 2 rows depending on the remainder. This creates quite a few edge cases for me to handle separately, such as when the length of the list is between 3 and 6 or when the length is less than or equal to 3.

def assign_words(grid, words):
    i = 0
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            grid[row][col] = words[i]
            i += 1
            if i == len(words):
                return

def print_words(words):
    word_count = len(words)
    rows = word_count // 3
    extra_columns = word_count % 3

    grid = [[''] * 3 for _ in range(rows)]

    # special case
    if word_count <= 3:
        grid.append(['']*3)
        assign_words(grid, words)
        for row in grid:
            print (' '.join(row))
        return

    if extra_columns == 1:
        if rows > 2:
            grid[0].append('')
        elif rows == 2:
            grid[1].pop()
            grid.append(['']*3)
    elif extra_columns == 2:
        if rows > 2:
            grid[0].append('')
            grid[1].append('')
        else:
            grid.append(['']*3)

    assign_words(grid, words)

    # special case
    if 3 < word_count < 6:
        print (grid[0][0]+ ' '+grid[0][2]+' '+grid[1][1])
        print (grid[0][1]+ ' '+grid[1][0]+' '+grid[1][2])
        return

    # print grid
    for col in range(len(grid[0])):
        for row in range(len(grid)):
            if col == len(grid[row]):
                break
            print (grid[row][col], end=' ')
        print ()
 print_words(['a','b','c','d','e','f','g'])


texts: Given a set of random strings, write a function that returns a set that groups all the anagrams together in objective-c

texts:
I would like to get feedback on the solution and a question regarding Big O.
I am first converting each character in the string into the array and that would be O(n) then i am sorting the array O(n log n) and then I join back the array.  Not sure if that is O(n).  After i get the sorted string I would retrieve the NSArray from NSDictionary if it is there and either add the word to the array or create a new array and then set it back into the NSDictionary.  I would those operations are O(1).  The total runtime complexity is O(N log N) because of sort. Is that the correct breakdown.

void printAllAnagrams(NSArray *words)
{
    NSMutableDictionary *anagramsDictionary = [[NSMutableDictionary alloc]init];
    NSMutableArray *wordArray = [[NSMutableArray alloc]init];

    for(NSString *word in words){

        //Loop through each word
        for(int i = 0;i < [word length]; i++){
            //create a character array
            [wordArray addObject:[NSString stringWithFormat:@"%c",[word characterAtIndex:i]]];
        }

        //sort character array
        [wordArray sortUsingSelector:@selector(localizedCompare:)];
        //convert character array back to string to use it as a key for in the dictionary
        NSString *sortedString = [wordArray componentsJoinedByString:@""];
        NSMutableArray *anagramStrings =[[anagramsDictionary objectForKey:sortedString] mutableCopy];

        if(anagramStrings){
            //if anagram(s) of the word is already in the dictionary then add this word to the array
            //and store it back into the dictionary
            [anagramStrings addObject:word];
            [anagramsDictionary setObject:anagramStrings forKey:sortedString];
        }else{
            //create an array with current word and store it in the dictionary
            //using the sorted characters string as the key
            [anagramsDictionary setObject:@[word] forKey:sortedString];
        }
        [wordArray removeAllObjects];
    }
    NSLog(@"%@",anagramsDictionary);
}


texts:
I am attempting to write a function that returns the records that a user has selected on a grid. In this example, I grab all of them and return their IDs.

Grid.prototype.getSelectedRecords = function () {
    var self = this;

     self.selectedRecords = this.grid.selModel.getSelection().map(function (record) {
         return record.internalId;
     });

     return self.selectedRecords;
}

Here I am placing them in a object property AND returning that property. This function, in effect is working as a setter and a getter. Would it confuse other programmers that might be looking for a setter? I don't know if I want to write a setter/getter each time...

With how quirky JavaScript does object-oriented, is this bad?


texts: Control of empty fields in a form via JavaScript

texts:
I would like to know if it is safe enough to create via JavaScript control of empty fields. Here is my example in detail:

    <script language='javascript'>
        function validate () {
            if(document.getElementById('title').value=="") {
                alert("Enter a Title!");
                return false;
            }
            if(document.getElementById('description').value=="") {
                alert("Enter a Description!");
                return false;
            }
            if(document.getElementById('image').value=="") {
                alert("Inser an Image!");
                return false;
            }
    alert("Success");
    return true;
}
</script>


texts: C: QuickSort following the book "Schaum's Outlines"

texts:
Please make some comment about this code of QuickSort.

My code is based on the example shown in this book.

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

#define SIZE 12

struct StackItem
{
    int StartIndex;
    int EndIndex;
};
struct StackItem myStack[SIZE * SIZE];
int stackPointer = 0;

int myArray[SIZE] = {11,44,33,55,77,90,40,60,99,22,88,66};

void Push(struct StackItem item)
{
    myStack[stackPointer] = item;
    stackPointer++;
}

struct StackItem Pop()
{
    stackPointer--;
    return myStack[stackPointer];
}

int StackHasItem()
{
    if(stackPointer>0)
    {
        return 1;
    }
    else
    {
        return 0;
    }
}

void ShowStack()
{
    int i =0;

    printf("\n");

    for(i=0; i<stackPointer ; i++)
    {
        printf("(%d, %d), ", myStack[i].StartIndex, myStack[i].EndIndex);
    }

    printf("\n");
}

void ShowArray()
{
    int i=0;

    printf("\n");

    for(i=0 ; i<SIZE ; i++)
    {
        printf("%d, ", myArray[i]);
    }

    printf("\n");
}

void Swap(int * a, int *b)
{
    int temp = *a;
    *a = *b;
    *b = temp;
}

int Scan(int *startIndex, int *endIndex)
{
    int partition = 0;
    int i = 0;

    if(*startIndex > *endIndex)
    {
        for(i=*startIndex ; i>=*endIndex ; i--)
        {
            if(myArray[i]<myArray[*endIndex])
            {
                Swap(&myArray[i], &myArray[*endIndex]);
                *startIndex = *endIndex;
                *endIndex = i;
                partition = i;
                break;
            }
            if(i==*endIndex)
            {
                *startIndex = *endIndex;
                *endIndex = i;
                partition = i;
            }
        }
    }
    else if(*startIndex < *endIndex)
    {
        for(i=*startIndex ; i<=*endIndex ; i++)
        {
            if(myArray[i]>myArray[*endIndex])
            {
                Swap(&myArray[i], &myArray[*endIndex]);
                *startIndex = *endIndex;
                *endIndex = i;
                partition = i;
                break;
            }
            if(i==*endIndex)
            {
                *startIndex = *endIndex;
                *endIndex = i;
                partition = i;
            }
        }
    }

    return partition;
}

int GetFinalPosition(struct StackItem item1)
{
    struct StackItem item = {0};
    int StartIndex = item1.StartIndex ;
    int EndIndex = item1.EndIndex;
    int PivotIndex = -99;

    while(StartIndex != EndIndex)
    {
        PivotIndex = Scan(&EndIndex, &StartIndex);

        printf("\n");
    }

    return PivotIndex;
}

void QuickSort()
{
    int splitPoint = 0;
    struct StackItem item;
    struct StackItem item1={0};
    struct StackItem item2={0};

    item.StartIndex = 0;
    item.EndIndex = SIZE-1;

    Push(item);

    while(StackHasItem())
    {
        item = Pop();

        splitPoint = GetFinalPosition(item);

        if(splitPoint>=0 && splitPoint<=(SIZE-1))
        {
            if(item.StartIndex <= (splitPoint-1))
            {
                item1.StartIndex = item.StartIndex;
                item1.EndIndex = splitPoint-1;
                Push(item1);
            }
            if((splitPoint+1) <= item.EndIndex)
            {
                item2.StartIndex = splitPoint+1;
                item2.EndIndex = item.EndIndex;
                Push(item2);
            }
        }
    }
}

main()
{
    ShowArray();
    QuickSort();
    ShowArray();
}


texts:
Is it possible to optimize this solution to the N-queens puzzle?

#include <iostream>
#include <cstdio>
#include <cstdlib>
#define N 10
using namespace std;

/* print solution */
void printSolution(int board[N][N])
{
    for (int i = 0; i < N; i++)
    {
        for (int j = 0; j < N; j++)
            cout<<board[i][j]<<"  ";
        cout<<endl;
    }
}

/* check if a queen can be placed on board[row][col]*/
bool isSafe(int board[N][N], int row, int col)
{
    int i, j;
    for (i = 0; i < col; i++)
    {
        if (board[row][i])
            return false;
    }
    for (i = row, j = col; i >= 0 && j >= 0; i--, j--)
    {
        if (board[i][j])
            return false;
    }

    for (i = row, j = col; j >= 0 && i < N; i++, j--)
    {
        if (board[i][j])
            return false;
    }

    return true;
}

/*solve N Queen problem */
bool solveNQUtil(int board[N][N], int col)
{
    if (col >= N)
        return true;
    for (int i = 0; i < N; i++)
    {
        if ( isSafe(board, i, col) )
        {
            board[i][col] = 1;
            if (solveNQUtil(board, col + 1) == true)
                return true;
            board[i][col] = 0;
        }
    }
    return false;
}

/* solves the N Queen problem using Backtracking.*/
bool solveNQ()
{
    int board[N][N] = {0};
    if (solveNQUtil(board, 0) == false)
    {
        cout<<"Solution does not exist"<<endl;
        return false;
    }
    printSolution(board);
    return true;
}

// Main
int main()
{
    solveNQ();
    return 0;
}


texts: Chess programming algorithm minimax to Alpha Beta

texts:
I have written some code for alpha beta for Chess programming and not sure completely if that is the correct way to do it. Can someone please tell me if I implemented the alpha_beta properly?

public class Minimax{
    private boolean side;
    public static int depth;

    public Minimax(boolean inputSide, int inputDepth) {
        side = inputSide;
        depth = inputDepth;
    }

    public int[] getMoves(Board board, boolean white, int inputDepth, boolean check) {
        ArrayList<int[]> values = new ArrayList<int[]>();
        int initScore = board.getScore();
        boolean multipleMoves = false;
        ArrayList<int[]> multiple = new ArrayList<int[]>();
        if (white) {
            values.add(new int[]{-2000, 0, 0, 0, 0});
        }
        else {
            values.add(new int[]{2000, 0, 0, 0, 0});
        }
        int position = 0;
        if (inputDepth == depth) {
            int[] ret = {board.getScore(), 0, 0, 0, 0};
            return ret;
        }
        for (Pieces[] subPiece : board.getArray()) {
            for (Pieces piece : subPiece) {
                if (piece != null && piece.white() == white) {
                    int[][] moves = piece.getMoves(board, false);
                    if (moves != null) {
                        for (int[] move : moves) {
                            Board newBoard = board.newBoard(move[0], move[1], move[2], move[3]);
                            if (newBoard != null) {
                                int score = getMoves(newBoard, !white, inputDepth + 1, newBoard.check(white))[0];
                                values.add(new int[]{score, move[0], move[1], move[2], move[3]});
                                if ((white && score > values.get(position)[0]) || (!white && score < values.get(position)[0])) {
                                    position = values.size() - 1;
                                    multipleMoves = false;
                                    multiple.clear();
                                }
                                else if (score == values.get(position)[0]) {
                                    multipleMoves = true;
                                    multiple.add(values.get(values.size() - 1));
                                    multiple.add(values.get(position));
                                }
                            }
                        }
                    }
                }
            }
        }
        if (values.size() == 1) {
            if (depth == 0) {
                return null;
            }
            else {
                if (white) {
                    return new int[]{-3000, 0, 0, 0, 0};
                }
                else {
                    return new int[]{3000, 0, 0, 0, 0};
                }
            }
        }
        if (multipleMoves && multiple != null) {
            position = (int)((multiple.size() - 1) * Math.random() + 1);
            return multiple.get(position);
        }

        return values.get(position);
    }

    public int getDepth() {
            System.out.println(depth);
            return depth;

    }
}


texts: Painting a lot of diagrams for a board game

texts:
I'm creating a chess application and I would like to show plenty of big chess diagrams in scrollview. At the moment I just create ImageView for every diagram, create bitmap into it, paint the diagram on a canvas and that's it.

However, it goes crazy with memory necessary to work. On my quadHD display it uses hundreds of MB even on A4R4G4B4. As I need always to show only a chess board, pieces and arrows, it seems pretty unnecessary to store so much bitmap data as I'm only reusing the same images many times plus painting some polygons. Is there a way to make this more efficiently? Is there a way how to use ImageView without bitmap data, just painting to it when it's on the screen?

public void UpdateLecturePreviewPositionsCount(int newCount)
{
    //Function never removes extra views, but adds views if more then previously necessary
    while (lecturePreviewBoards.Count < newCount)
    {
        lecturePreviewBoards.Add(CreateBoard((xScreen - (NUM_DIAGRAMS_PER_PAGE * 2) * DIAGRAM_PADDING) / NUM_DIAGRAMS_PER_PAGE));
        lecturePreviewBoards[lecturePreviewBoards.Count - 1].imgv.SetPadding(DIAGRAM_PADDING, DIAGRAM_PADDING, DIAGRAM_PADDING, DIAGRAM_PADDING);
        layoutLecturePositionsPreview.AddView(lecturePreviewBoards[lecturePreviewBoards.Count - 1].imgv);
    }
    for (int i = 0; i < newCount; i++)
        lecturePreviewBoards[i].imgv.Visibility = ViewStates.Visible;
    for (int i = newCount; i < lecturePreviewBoards.Count; i++)
        lecturePreviewBoards[i].imgv.Visibility = ViewStates.Gone;

}

public c_image_painting CreateBoard(double dblSize = -1)
{
    if (dblSize < 0)
        dblSize = xScreen;
    int size = (int)dblSize;
    c_image_painting cbp = new c_image_painting();
    cbp.bmp = Bitmap.CreateBitmap(size, size, Bitmap.Config.Argb4444);
    cbp.cnv = new Canvas();
    cbp.imgv = new ImageView(context);
    cbp.cnv.SetBitmap(cbp.bmp);
    cbp.imgv.SetImageBitmap(cbp.bmp);
    return cbp;
}

public class c_image_painting
{
    public Canvas cnv;
    public Bitmap bmp;
    public ImageView imgv;
    private Bitmap.Config bmpFormat;
    public c_image_painting()
    {
        bmpFormat=Bitmap.Config.Argb4444;
    }
    public c_image_painting(Bitmap.Config bc)
    {
        bmpFormat = bc;
    }
}


texts:
I have a content management system for an iOS app built with Rails. Right now there are three different types of content. The first two are just strings uploaded into a textfield by the user. One is Twitter handles and hashtags, the other is URLs. The second type is photos.

The user can upload as many individual instances of these types content as he/she wants to given a feed which will is the then passed to the iOS app via an API call to display.

The current approach I am using is to have Feed, Picture, Twitter, and Webpage models. When the user creates a new Feed, they then associate the appropriate content with that feed via a one to many relationship between each Feed instance it's content instances.

When it comes time to display to content the user has uploaded, a GET request for a given stream is generated and the Feed model then does the following awful thing determine what type of content should be shown:

 def Feed.get_content_for_feed(feed_id)
    return self.map_type_to_class(feed_id).get_content_for_feed(feed_id)
  end

  private

  def Feed.map_type_to_class(feed_id)
    feed_type_id = Feed.find(feed_id).feed_type_id
    not_yet_implemented = nil
    case stream_type_id
      when 1
        return Webpages
      when 2
        return Pictures
      when 3
        return not_yet_implemented
      when 4
        return Twitter
      when 5
        return not_yet_implemented
      when 6
        return not_yet_implemented
      when 7
        return not_yet_implemented
      when 8
        return not_yet_implemented
      else
        return nil

    end
  end

Then each content class implements a get_content_for_feed method to return the content:

def Twitter.get_content_for_feed(feed_id)
    tweet_urls = self.where(:feed_id => feed_id.to_i)
    if tweet_urls.empty?
      return []
    else
      return tweet_urls
    end
  end

It just returns the appropriate class. This works, but I know that it is wrong, but I am not sure what I would be doing.


texts: Calculating total number of calories burned

texts:
The following question was taken from Absolute Java 5th ed. by Walter Savitch:

  One way to measure the amount of energy that is expended during
  exercise is to use metabolic equivalents (MET). Here are some METS for
  various activities:

  Running 6 MPH: 10 METS
  Basketball: 8 METS
  Sleeping: 1 MET

  The number of calories burned per minute may be estimated using the
  following formula: Calories/Minute= 0.0175 * MET* Weight in
  kilograms.

  Write a program that calculates and outputs the total number of calories burned for a 150-pound person who runs 6 MPH for 30
  minutes, plays basketball for 30 minutes, and then sleeps for 6
  hours. One kilogram is equal to 2.2 pounds.

This is the code that I have written:

public class Question1 {

    final static int RUNNING6MPH = 10;
    final static int BASKETBALL = 8;
    final static int SLEEPING = 1;

    private static double value = 0.0175;
    private static double totalCaloriesBurned = 0;

    public static void main(String[] args) {

        totalCaloriesBurned = caloriesPerMinute(RUNNING6MPH, 150, 30)
                + caloriesPerMinute(BASKETBALL, 150, 30)
                + caloriesPerMinute(SLEEPING, 150, hoursToMinutes(6));
        System.out.println(totalCaloriesBurned);
    }

    public static double caloriesPerMinute(int met, double weight, double time) {
        return value * met * poundToKilogram(weight) * time;
    }

    public static double poundToKilogram(double pound) {
        return pound / 2.2;
    }

    public static double hoursToMinutes(double hours) {
        return hours * 60;
    }
}


texts:
This program reads a filename from standard input and then prints its content. Please review:

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>

int main()

{
    char fileName[20];

    // Get the filename from the user:
    int fileNameLength = read(0,fileName,19);
    // We need to get rid of the new line character caused by terminal
    // Replace the new line character with \0
    fileName[fileNameLength-1] = fileName[fileNameLength];

    printf("You want to see the contents of: %s\n", fileName);

    // open the file:
    int fd = 0;
    fd = open(fileName,O_RDONLY);

    if(fd == -1) {
        // Something went wrong, perhaps no such file:
        perror(NULL);
        printf("%s\n", fileName);
    } else {
        // Read until the read method returns 0 bytes.
        char buf[20];
        int numBytesRead = read(fd,buf,20);
        while(numBytesRead) {
            write(1,buf,numBytesRead);
            numBytesRead = read(fd,buf,20);
        }
        close(fd);
    }
    puts("");
}

And in action:

Korays-MacBook-Pro:~ koraytugay$ gcc koray.c
Korays-MacBook-Pro:~ koraytugay$ ./a.out
k.txt
You want to see the contents of: k.txt
Hello Code Review!
This is the contents of k.txt.
Have a good day!
Korays-MacBook-Pro:~ koraytugay$


texts: HashTable - separate chaining collision in C++

texts:
I'm trying to implement a HashTable. In fact, I want a HashSet with Persons that have a name and a phoneNumber, both string. I understood the theory with collisions and everything but I don't know how to really implement something. This is what I've done so far:

#ifndef HASHSET_H_
#define HASHSET_H_

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

template <typename Element>
class HashSet{
private:
    class Node{
    private:
        Element info;
        Node* next;
    public:
        Node(){ //constructor
            this->next=NULL;
        }
        Node(Node* next, Element info){ //parameters constructor
            this->info=info;
            this->next=next;
        }
        Node(const Node& node){ //copy constructor
            this->info=node.info;
            this->next=node.next;
        }
        ~Node(){} //destructor
        Element getInfo(){
            return this->info;
        }
        Node* getNext(){
            return this->next;
        }
        void setInfo(Element newE){
            this->info=newE;
        }
        void setNext(Node* value){
            this->next=value;
        }
    };
    Node** head;
    int hashSize;
    int bucketSize; //holds the total elements of a cell
    int totElems; //total number of elements in the hashset
public:
    HashSet(){
    }
    bool IsEmptyAtGivenKey(int key);
    bool HashSetIsFull();
    int HashFunction(string e);
    int HashSetSize();
};

template<typename Element>
HashSet<Element>::HashSet(){
    this->hashSize=11;
    this->head=new Node*[hashSize];
    for(int i=0; i< hashSize; i++){
        this->head[i]=NULL;
    }
    this->totElems=0;
}

template<typename Element>
bool HashSet<Element>::IsEmptyAtGivenKey(int key){
    if(key>=0 and key < hashSize){
        return head[key]==NULL;
    }
    return true;
}

template<typename Element>
int HashSet<Element>::HashFunction(string e){
    int length = e.size();
    int sum;
    for(int i=0; i < length; i++){
        sum+=e[i];

    }
    int hashCode = sum % hashSize;
    return hashCode;
}

#endif /* HASHSET_H_ */

Is it any good? Any advice that will help me improve is welcome!


texts: Want to check if I am using PDO correctly

texts:
So today after few years of not programming in PHP I decided to go back, but to do so I needed to change all MySQL connections. So I want to check if I am using it good.

Earlier I used to write something like this:

$user = clean($_COOKIE["Logged"]);
$GameReg = mysql_fetch_array(mysql_query("SELECT * FROM DB.GameReg WHERE hash='$user'"));

But now it is like this:

$stmt = $dbh->prepare("SELECT * FROM DB.GameReg WHERE hash = :user");
$stmt->bindParam(':user', $user);
$user = $_COOKIE["Logged"];
$stmt->execute();
$GameReg = $stmt->fetch(PDO::FETCH_ASSOC);

So am I using it correctly? I used to do all kinds of filtering before inserting or updating SQL table, but I've read that prepared statements doesn't need that. Is this safe to use?

As I am knew to PDO I am trying to save up some code, so I kinda came up with this:

$stmt = $dbh->prepare("SELECT * FROM DB.GameStats WHERE hash = :user");
$stmt = $dbh->prepare("SELECT * FROM DB.GameReg WHERE hash = :user");

$stmt->bindParam(':user', $user);
$user = $_COOKIE["Logged"];

$stmt->execute();
$GameReg = $stmt->fetch(PDO::FETCH_ASSOC);

$stmt->execute();
$GameStats = $stmt->fetch(PDO::FETCH_ASSOC);

I checked this by trying to call some table members:

echo $GameReg["pass"];
echo "\n";
echo $GameStats["nick"];

It works, but I am not sure if this is the best way to do. Any comments?


texts:
I have the following method that will return VariantID for given VariantName ("Name" in db).
To avoid calling my db few thousand times I have dumped all records (~30) to the simple dictionary.

I'm almost certain that this is the correct way of implementing this method but I would like to hear some feedback and any possible tips.

TestManagementEntities is an EntityFramework DbContext

Calling Method

private void UpdateVariants(WorkItem workItem, string variantValue, TestManagementEntities db)
    {

        string[] variants = variantValue.Split(',').Where(x => !String.IsNullOrEmpty(x)).ToArray();

        int[] variantIds = new int[variants.Count()];

        Dictionary<string, int> variantDictionary =
            db.Variants.ToDictionary(x => x.Name, y => y.VariantID);
        Object lockObject = new Object();

        System.Threading.Tasks.Parallel.For(0, variants.Count(), i =>
        {
            variants[i] = variants[i].Trim();
            //Method in question call
            variantIds[i] = GetVariantId(variants[i], variantDictionary, db, lockObject);
        });

        //Some not relevant to question code here
    }

private int GetVariantId(string variantName, Dictionary<string, int> variantDictionary, TestManagementEntities db, Object lockObject)
    {
        if (variantDictionary.ContainsKey(variantName))
        {
            return variantDictionary[variantName];
        }
        else
        {
            lock (lockObject)
            {
                if (variantDictionary.ContainsKey(variantName))
                {
                    return variantDictionary[variantName];
                }
                else
                {
                    Variant newVariant = new Variant();
                    newVariant.Name = variantName;
                    db.Variants.Add(newVariant);
                    db.SaveChanges();
                    variantDictionary.Add(variantName, newVariant.VariantID);
                    return newVariant.VariantID;
                }
            }
        }
    }


texts:
I have a variable List. Its declaration is like :

List<HashMap<String, Object>>

Sample data in it:

  [{total-expense=228, company=HiHard, year=2009}, {total-expense=2936, company=POTENT, year=2009}, {total-expense=1362412.65, company=HiHard, year=2010}, {total-expense=9007.96, company=POTENT, year=2010}, {total-expense=240427.43, company=HiHard, year=2011}, {total-expense=1956.11, company=POTENT, year=2011}]

I have written a program to fetch the below result:

  {"HiHard":[[228,1362412.65,240427.43]],"POTENT":[[2936,9007.96,1956.11]]}

i.e. to fetch company-wise total expense incurred for financial years 2009, 2010, 2011.

Current program logic:

1) getDistinctCompanies from the list

2) Iterate through the distinct companies[from step 1] and get the expense incurred by passing in company and list.

Complete program:

public class JSONConstruction {
    public static void main(String[] args) {
        List<HashMap<String, Object>> list = new ArrayList<HashMap<String, Object>>();

        ... ASSUME list has the SAMPLE data as described before.

        List<String> companyList = getDistinctCompanies(list);

        Iterator<String> iterCompany = companyList.iterator();
        String company;
        JSONObject obj = new JSONObject();
        while(iterCompany.hasNext()){
            company = iterCompany.next();
            JSONArray jsonList = new JSONArray();
            jsonList.add(getExpenseList(list, company));
            obj.put(company, jsonList);
        }

        System.out.print(obj);
    }

    private static List<String> getDistinctCompanies(List<HashMap<String, Object>> list) {
        Iterator<HashMap<String, Object>> iterList = list.iterator();
        String company;
        List<String> companyList = new ArrayList<String>();
        while (iterList.hasNext()) {
            HashMap<String, Object> map = iterList.next();
            company = (String) map.get("company");
            if(companyList==null || (!companyList.contains(company))) {
                companyList.add(company);
            }
        }
        return companyList;
    }

    private static List<Object> getExpenseList(List<HashMap<String, Object>> list, String company) {
        Iterator<HashMap<String, Object>> iterList = list.iterator();
        List<Object> expenseList = new ArrayList<Object>();
        String companyMatch;
        while (iterList.hasNext()) {
            HashMap<String, Object> map = iterList.next();
            companyMatch = (String) map.get("company");
            if(companyMatch.equals(company)) {
                Object obj = map.get("total-expense");
                expenseList.add(obj);
            }
        }
        return expenseList;
    }

Though the data is fetched correctly, I am eager to know a better way of coding this program.


texts: Password-generation function using custom seed

texts:
After reading an article on Skull Security mentioning the potential weakness of php's mt_rand function because of weak auto-seeding (http://ow.ly/4nrne), I decided to see what -- if any -- entropy I could find available from within php. The idea is to have enough (weak) sources that even if one or two are manipulated, lost or recovered, there's enough left to thwart brute force against the resulting passwords later.

Hopefully the result is both readable and usable, although I don't expect it to be production-quality.

<?php
  /**
   * Return a random password.
   *
       * v1.01
   * Jumps through many hoops to attempt to overcome autoseed weakness of php's mt_rand function
   *
   */
  function myRandomPassword() {
        // Change this for each installation
        $localsecret = 'qTgppE9T2c';
    // Determine length of generated password
    $pwlength = 10;
    // Character set for password
    $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz0123456789';
    $l = strlen( $pwchars ) - 1;
    // Get a little bit of entropy from sources that should be inaccessible to outsiders and non-static
    $dat = getrusage(); // gather some information from the running system
    $datline = md5(implode($dat)); // wash using md5 -- it's fast and there's not enough entropy to warrant longer hash
    $hardToGuess = $datline;
    $self = __FILE__; // a file the script should have read access to (itself)
    $stat = stat($self); // information about file such as inode, accessed time, uid, guid
    $statline = md5(implode($stat)); // wash
    $hardToGuess .= $statline;
    $preseed = md5(microtime()) . getmypid() . $hardToGuess . memory_get_usage() . disk_free_space('.') . $localsecret;
    $seed = sha1( $preseed ); // final wash, longer hash
    // Seed the mt_rand() function with a better seed than the standard one
    mt_srand ($seed);
    // Pick characters from the lineup, using the seeded mt_rand function
    $pw = '';
    for ( $i = 0; $i < $pwlength; $i++ ) {
      $pw .= $pwchars{ mt_rand( 0, $l ) };
    }
    // Return the result
    return $pw;
  }

echo myRandomPassword();
?>

Revision 1.01 adds a local secret.


texts:
Intro

I've been having fun with natas a wargame, from overthewire.

To pass a certain stage I had to do some xor'ing, in combination with base64 encoding/decoding. So I wrote a little python utility to help me pass that stage.

Any feedback on the code I've written is helpfull, but I'm especially interested in the repeated_substring() function. I don't think my function is the most optimised way of handling that.

When I run the code it should output the newly generated cookie value:

b'ClVLIh4ASCsCBE8lAxMacFMOXTlTWxooFhRXJh4FGnBTVF4sFxFeLFMK'

Code

import base64

def xor_break_cookie(cookie):
    """Breaking the key"""
    json = b'{"showpassword":"no","bgcolor":"#ffffff"}'
    return ''.join([chr(cookie[i] ^ json[i % len(json)]) for i in range(len(cookie))])

def decode_base64(data):
    """Decoding with the missing padding"""
    missing = len(data) % 4
    if missing != 0:
        data += b'=' * (4 - missing)
    return base64.decodestring(data)

def xor_gen_cookie(key):
    """Getting the new cookie value"""
    json = b'{"showpassword":"yes","bgcolor":"#ffffff"}'
    return ''.join([chr(json[i] ^ key[i % len(key)]) for i in range(len(json))])

def repeated_substring(text):
    """Gets the longest repeated xor key from text"""
    length = x = y = m = 0
    for y in range(len(text)):
        for x in range(len(text)):
            substring = text[y:x]
            if len(substring) > length and text.count(substring) >= m and len(substring) > 1:
                m, length, match = text.count(substring), len(substring), substring
    return match

if __name__ == '__main__':
    cookie = decode_base64(b'ClVLIh4ASCsCBE8lAxMacFMZV2hdVVotEhhUJQNVAmhSEV4sFxFeaAw')
    password = repeated_substring(xor_break_cookie(cookie))
    new_cookie = xor_gen_cookie(bytes(str.encode(password)))
    print(base64.encodestring(bytes(str.encode(new_cookie))).rstrip())


texts: Function to match the case of a text as per another text

texts:
I am translating a text into another language using Google APIs.

Sometimes the translated text returned from the API does not match the case of the text  provided - e.g. when translating the text "Now Activated" to German, I get the translated text response as "jetzt aktiviert" instead of "Jetzt Aktiviert".

I wrote a function which can change the case of translated text to match the input text:

public string MaintainCase(string text, string translatedText)
    {
        // Split the inputs provided into string arrays
        var textStrArray = text.Split(' ');
        var translatedTextStrArray = translatedText.Split(' ');

        // Count the no of words of both the texts provided
        var noOfWordsInText = textStrArray.Length;
        var noOfWordsInTranslatedText = translatedTextStrArray.Length;

        // Check if the word count matches
        bool wordCountMatches =
                        noOfWordsInText == noOfWordsInTranslatedText
                        ? true
                        : false;

        // Start changing the case of translated text as per text
        for (int i = 0; i < noOfWordsInText; i++)
        {
            // Take the word no i of text and translated text
            var textWord = textStrArray[i];
            var translatedTextWord = translatedTextStrArray[i];

            // Using string builder to modify the first character of translated text
            // based on the case identified of the first character of text
            var strBuilder = new StringBuilder(translatedTextWord);
            var changedChar =
                    char.IsUpper(textWord[0])
                    ? char.ToUpper(translatedTextWord[0])
                    : char.ToLower(translatedTextWord[0]);

            strBuilder[0] = changedChar;
            translatedTextStrArray[i] = strBuilder.ToString();

            // If the word count does not match, after changing the case of only first word, break the loop
            if (!wordCountMatches)
            {
                break;
            }
        }

        // Return the modified translated text
        return string.Join(" ", translatedTextStrArray);
    }

Kindly suggest if this can be made more efficient (usage of string builders etc) and if I need to add some additional checks which I may have missed.


texts:
How can I vectorize this code snippet and eliminate this double loop? Even with "only" 1001 elements in a this takes almost 30s.

a = np.linspace(-.5, .5, 1001)
S = np.zeros((a.size, a.size))

# east, north and tp are np.arrays of equal length
for l, sy in enumerate(a):
    for k, sx in enumerate(a):
            S[l,k] = np.sum((east*sx + north*sy - tp)**2)


texts: Decorator to pass instance and class to method

texts:
In some of my peewee-based ORM models, I need to access the instance as well as the respective class.
Since I caught myself always repeating the line cls = self.__class__ at the top of each such methods, I wrote a decorator for that:

def with_class(function):
    """Adds the instance's class as second
    parameter to the wrapped function.
    """

    @wraps(function)
    def wrapper(self, *args, **kwargs):
        """Wraps the given function."""
        return function(self, self.__class__, *args, **kwargs)

    return wrapper

Example use case:

class Location(_TerminalModel):
    """Location of a terminal."""

    address = CascadingFKField(Address, column_name='address')
    annotation = CharField(255, null=True)

    …

    @with_class
    def save_unique(self, cls, *args, **kwargs):
        """Saves the location if it is new or
        returns the appropriate existing record.
        """
        if self.annotation is None:
            annotation_selector = cls.annotation >> None
        else:
            annotation_selector = cls.annotation == self.annotation

        try:
            return cls.get((cls.address == self.address) & annotation_selector)
        except cls.DoesNotExist:
            self.save(*args, **kwargs)
            return self

I'd like to have critique on this solution and am open to alternatives.


texts:
The task is to make a program that prints out how many possible paths a driver can use to visit three cities so that he visits each city exactly n times. The program must be executed within 1 minute and print the solution for n = 10. The program works correctly but for n above 7 it doesn't execute in time. Is there a way to get it to execute n=10 in time? These are some of the solutions: n = 1, the solution is 6, n = 2, the solution is 30, n = 3, the solution is 174 and n = 4, the solution is 1092.

#include<iostream>
#include <algorithm>
using namespace std;
double paths (long long unsigned int path[],int n,double s,int e){
    int r=0;
    do{
        for(int i=0;i<e-1;i++){
            if(path[i]!=path[i+1]){
                r++;
            }
        }
            if(r==e-1){
                s++;

            }
            r=0;

        }while(next_permutation(path, (path+e)));

        return s;
    }
int main(){
    double s=0;
    int y=0;
    int buff=0;
    int n;
    cin>>n;
    int e=(n*3);
    long long unsigned int path[e];
    while(y!=e){
       for(int t=1;t<=3;t++){
           path[y]=t;
           y++;
       }
    };
    bool test=false;
    for(int z=0;z<e;z++){
        for (int j =0; j<e; j++){
            if (path[j+1] < path[j]){
                buff=path[j];
                path[j]=path[j+1];
                path[j+1]=buff;
                test=true;
            }
        }
        if(!test){
            break;
        }else{
            test=false;
        }
    }
    cout<<"Number of posibilities: "<<paths(path,n,s,e)<<endl;

}


texts:
As a sample of dialects and teaching myself parse with block! values, I wrote the following dice dialect with the following grammar:

[
    word!
|
    integer! word!
]

Where the word!s are defined as integers (d10: 10) so an expression of this dialect would look like:

dice: [d2 20 d100 d10 5 d6]

This would sum the totals of one 2-sided die roll, 20 hundred-sided dice, one 10-sided die and five 6-sided dice.   I wrapped this in the function below

Rebol [
    Title: "Dice Rolling Dialect"
]
random/seed now/precise

d2: 2
d4: 4
d6: 6
d8: 8
d10: 10
d12: 12
d20: 20
d100: 100

calculate: function [b] [
    dice-rule: [
        (total: 0)
        some [
            copy die word!
            (total: total + roll 1 get die/1)
        |
            copy n integer!
            copy die word!
            (total: total + roll n/1 get die/1)
        ]
    ]

    roll: func [times [integer!] die [integer!]] [
        result: 0
        repeat i times [result: result + random die]
        result
    ]

    parse b dice-rule
    total
]

repeat i 400 [
    print calculate [d100 10 d10 d2 4 d6]
]

I was looking for improvements in the handling of the variables in parsing to make it more elegant than requiring the get die/1 notation.


texts: Explicitely passing a parameter by reference in C++03

texts:
In C#, passing a parameter by reference can't be ignored:

// C#
void foo(ref int p_value) ; // passing an int by reference

void bar()
{
   int i = 0 ;
   foo(ref i) ;
}

In C++ (and as far as I am concerned, it is a good thing), the passing by reference is only marked in the function prototype, so the code above becomes:

// C++
void foo(int & p_value) ; // passing an int by reference

void bar()
{
   int i = 0 ;
   foo(i) ;     // at call site, there is no "ref" marker.
}

The thing is, for a few special functions, to ease code reviewing, we would want to use a C#-like solution to read at call site if a variable is expected to be modified or not.

I devised a solution wrapping the value with a struct, something like:

template<typename T>
struct Ref
{
   T & m_value ;
   explicit Ref(T & p_value) : m_value(p_value) {}

   operator T & () { return this->m_value ; }
   operator const T & () const { return this->m_value ; }
} ;

template <typename T>   // wrapping T with Ref
Ref<T> byRef(T & p_value)
{
   return Ref<T>(p_value) ;
}

template <typename T>   // idempotent-enabling overload (no need for Ref<Ref<T>>)
Ref<T> & byRef(Ref<T> & p_value)
{
   return p_value ;
}

I expect this trivial code to be inlined away in optimized code.

This enables me to write the code:

void foo(Ref<int> p_int)
{
   p_int *= 10 ;
}

void bar()
{
   int i = 0 ;
   foo(byRef(i)) ;
}

Which is exactly what I want:

no use of foo(& i) C-style notation, with pointers, needing to handle NULL, etc.
in the cases we care, we can see in the code what is passed by non-const reference

Did I miss some unexpected problem/hidden cost that will come back to bite me in a few weeks/months/years?

Could this code be written better?

Will the code be confusing when seen through some un*x debuggers?

P.S.: Of course, Ref and byRef will be properly namespaced. I'm still not sure about making Ref::m_value public or private.


texts:
Github Link To Code

Pastebin Link

I am well aware of how terrible the SettingsMenu class is, it's still a work in progress and is the way it is so it can actually work.
Can't paste it directly in the post because it would be mostly code.

I feel like this function needs work, but I've been over it a couple times and can't find anything meaningful to do.

def title_screen():
    background = assets_base_path + 'title_screen.png'
    font_size = 0
    frames = 0
    enter_game = False
    while not enter_game:
        for event_ in pygame.event.get():
            if event_.type == pygame.QUIT:
                quit()
            elif event_.type == pygame.KEYDOWN:
                if event_.key == pygame.K_KP_ENTER or pygame.K_SPACE:
                    enter_game = True
            # print(event_)

        game_display.blit(pygame.image.load(background), (0, 0))
        font = pygame.font.Font(fonts_path + 'Futura.ttf', font_size)
        game_display.blit(font.render(str('An RPG'), True, Color.Black), (500, 111))
        # game_display.blit(font.render(str(frames), True, Color.Goldenrod), (0, 0))

        if font_size < 65: font_size += 1
        if font_size == 65:
            game_display.blit(font.render(str('Press Enter To Play'), True, Color.Black), (345, 400))

        pygame.display.update()
        frames += 1
        sleep(0.013)

I also feel like there's room to improve in this section. Seems like there should be a better way to do it, but I'm not sure what it would be.

rect_ = copy(player)
    if active_keys['w']: rect_.y -= config.player_movespeed_vertical
    if active_keys['s']: rect_.y += config.player_movespeed_vertical
    if active_keys['a']: rect_.x -= config.player_movespeed_horizontal
    if active_keys['d']: rect_.x += config.player_movespeed_horizontal
    rect_.refresh_rect()
    pillar_player_collisions_list = pygame.sprite.spritecollide(rect_, active_pillars, False)
    wall_player_collisions_list   = pygame.sprite.spritecollide(rect_, active_walls, False)
    if len(pillar_player_collisions_list + wall_player_collisions_list) != 0:
        # print('Collisions With Pillars')
        pass
    else:
        # print('No Collisions With Pillars')
        if active_keys['w']: player.y -= config.player_movespeed_vertical
        if active_keys['s']: player.y += config.player_movespeed_vertical
        if active_keys['a']: player.x -= config.player_movespeed_horizontal
        if active_keys['d']: player.x += config.player_movespeed_horizontal
        player.refresh_rect()

Thanks!


texts: I'm just starting out with tasks. I need to know if there's a better way to do TAP for socket handling (serving a request)

texts:
I've got this quick and dirty little console app in C# to serve an HTTP/HTML page.
static void Main()
{
    // create a socket
    var socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
    // bind to localhost:8080
    socket.Bind(new IPEndPoint(IPAddress.Loopback, 8080));
    socket.Listen(16); // listen
    // begin our accept task
    var t = socket.AcceptTaskAsync();
    // when we're done accepting process the request
    t.ContinueWith((task) =>
    {
        _ProcessRequest(socket, t);
    });
    // show a prompt and wait for a keypress to exit
    Console.WriteLine("Press any key to exit...");
    Console.ReadKey();

}
static void _ProcessRequest(Socket socket,Task<Socket> t)
{
    Console.Write("Awaiting request...");

    t.ContinueWith((task1) =>
    {
        var s = t.Result;
        var rt = s.ReceiveHttpRequestAsync();

        rt.ContinueWith((task2) =>
        {
            Console.Write("Done: ");
            var req = rt.Result;
            Console.WriteLine(req.Method + " " + req.Url);

            // our html to send
            var html = "<title>Hello</title>
Hello World!
";
            var headers = "HTTP/1.1 200 OK\nDate: "
                + DateTime.Now.ToUniversalTime().ToString("r")
                + "\nContent-Type: text/html\nContent-Length: "
                + html.Length.ToString()
                + "\nConnection: Closed\n";
            s.SendAsync(headers + "\n" + html, Encoding.UTF8)
                .ContinueWith((task3) =>
                {
                    s.DisconnectAsync(false);
                    t = socket.AcceptTaskAsync();
                    t.ContinueWith((task4) =>
                    {
                        _ProcessRequest(socket, t);
                    });
                }).Wait();
            s.Close();
        });
    });
}

I'm calling async TAP methods on a socket because I use an EAP->TAP adapter class that I built up from this code:
https://blogs.msdn.microsoft.com/pfxteam/2011/12/15/awaiting-socket-operations/
It appears to work, and it has little to do with my question, which has to do with handling incoming requests using TAP. I've also got HttpReceiveRequestAsync which I've used for a year and isn't important here.
Basically what I'm trying to do is accept on a socket and then asynchronously serve the request, and then accept on a socket again to keep it going. The code works, but I don't think it works right. For one thing, my _ProcessRequest() routine is getting called 3 times every time I refresh the browser (i'm using chrome) - i know chrome will sometimes initiate multiple requests but i think it will only do two. Edit: I figured out why this is, and it's fine
Also this seems dodgy. I don't know why but there's code smell, and not just because I threw it together. I don't trust it. Can anyone take a look and see if there isn't a better way to do this? I'm pretty new at this.
Edit: I fixed it up and I trust it more now, but I just wanted to see if it could be improved, or if there is some better pattern for this. I don't care about using async/await keywords unless it significantly eases things. Sometimes it does. Here I didn't find much use.


texts:
I have read some articles regarding the factory pattern and decided to write some code as an exercise. This is my first attempt and am not 100% if I did it right. I've omitted some implementations for the sake of focusing on the concept at hand.

class NumbersFactory {
    public static function makeNumber( $type, $number ) {
        $numObject = null;
        $number = null;

        switch( $type ) {
            case 'float':
                $numObject = new Float( $number );
                break;
            case 'integer':
                $numObject = new Integer( $number );
                break;
            case 'short':
                $numObject = new Short( $number );
                break;
            case 'double':
                $numObject = new Double( $number );
                break;
            case 'long':
                $numObject = new Long( $number );
                break;
            default:
                $numObject = new Integer( $number );
                break;
        }

        return $numObject;
    }
}

/* Numbers interface */
abstract class Number {
    protected $number;

    public function __construct( $number ) {
        $this->number = $number;
    }

    abstract public function add();
    abstract public function subtract();
    abstract public function multiply();
    abstract public function divide();
}
/* Float Implementation */
class Float extends Number {
    public function add() {
        // implementation goes here
    }

    public function subtract() {
        // implementation goes here
    }

    public function multiply() {
        // implementation goes here
    }

    public function divide() {
        // implementation goes here
    }
}
/* Integer Implementation */
class Integer extends Number {
    public function add() {
        // implementation goes here
    }

    public function subtract() {
        // implementation goes here
    }

    public function multiply() {
        // implementation goes here
    }

    public function divide() {
        // implementation goes here
    }
}
/* Short Implementation */
class Short extends Number {
    public function add() {
        // implementation goes here
    }

    public function subtract() {
        // implementation goes here
    }

    public function multiply() {
        // implementation goes here
    }

    public function divide() {
        // implementation goes here
    }
}
/* Double Implementation */
class Double extends Number {
    public function add() {
        // implementation goes here
    }

    public function subtract() {
        // implementation goes here
    }

    public function multiply() {
        // implementation goes here
    }

    public function divide() {
        // implementation goes here
    }
}
/* Long Implementation */
class Long extends Number {
    public function add() {
        // implementation goes here
    }

    public function subtract() {
        // implementation goes here
    }

    public function multiply() {
        // implementation goes here
    }

    public function divide() {
        // implementation goes here
    }
}

$number = NumbersFactory::makeNumber( 'float', 12.5 );


texts: Calculating work using dot product in C++

texts:
Write a C++ program fulfilling the following task: The user should enter the 3 dimensional force vector F and a 3 dimensional length vector s. The force is assumed to be constant. The program then calculates the work W = F (dot) s and prints the result on the screen.

#include <iostream>

using namespace std;

int main()
{
    //I decided to try and declare my variables locally to make it easier for readers.
    double F[3];
    int i;

    cout << "Enter in components of the force vector F:\n";

    for(i=0; i<3; i++)
    {
        cout << "Component " << i+1 << ": ";
        cin >> F[i];

    }

    double s[3];

    cout << "Enter in the components of the length vector s:\n";

    for(i=0; i<3; i++)
    {
        cout << "Component " << i+1 << ": ";
        cin >> s[i];
    }

    double W = 0.0;

    for(i=0; i<3; i++)
    {
       W = W + (F[i] * s[i]);
    }

    cout << "The work done is: " << W << " J";

    return 0;
}

Does "The force is assumed to be constant" change anything about the code. I don't see how that makes a difference? Is it included for completeness?


texts: Function to check whether two strings are similar at given %

texts:
Since the previous question I posted here was not found as interesting as I expected, I decided to post a new one. I made a function solely for the purpose of having fun. That is, a function that checks if two strings are similar with a given %.

int case_insensitive_chrcmp (int ch1, int ch2)
{
    return ch1 == ch2 || ch1 + ' ' == ch2 || ch1 - ' ' == ch2;
}

int strpcmp (char* str1, char* str2, unsigned setting)
{
    int szStr1 = strlen(str1);
    int szStr2 = strlen(str2);
    int szMax  = max(szStr1, szStr2);
    int szMin  = 0;
    int chars  = 0;

    if(setting > 100)
        setting = 100;

    if(szStr1 == szMax)
        szMin = szStr2;
    else szMin = szStr1;

    chars = szMax * setting / 100;

    int cur = 0;
    for(int i = 0; i < szMin; i++)
    {
        if(case_insensitive_chrcmp(str1[i], str2[i]))
            cur++;
        else cur = 0;

        if(cur >= chars)
            return 1;
    }

    return 0;
}

(you may need to provide your own definition for min and max since I think they are not supported by all compilers)

Example usage:

char* str1 = "Hello";
char* str2 = "Hey";
int percentage = 50%101; // or just 50 or w/e
printf("%s %i%% %s - %s\n", str1, percentage, str2, strpcmp(str1, str2, percentage) ? "true" : "false");

Output:

  Hello 50% Hey - true

More info on what the function is supposed to do:

It calculates how many characters must match consecutively based on percentage in order to return true. The comparison between characters is also done in case insensitive manner.

More info on how the function is required to work:

Regarding safety, this function can do much more, check
against null pointers, re-entrancy guarding, MT-safety and that shouldn't really damage the performance level.
Speaking of performance, I am a performancecholic and the first thing I can see that is bothering me here is the two strlens - the size of the two strings can be obtained within a single loop. Otherwise there are redundant iterations.


texts:
I've made a small program that calculates the cost of flooring for a given area based on the price per sqft and total sqft. I have only been programming for a few days now so I am sure that there are some things I could be doing better.

from decimal import *
import time

print("This program will help you find the cost of floor covering\n")

def program():
    exit_program = ["q", "Q"]

    global move_on
    move_on = ["y", "Y"]

    global more_info
    more_info = ["n", "N"]

    cost_of_tile = Decimal(input("What is the cost of the tile per square foot?"))

    global answer
    answer = input("Do you know how big the room is in sqft? Y/N")

    if answer in move_on:
        global sqft
        sqft = Decimal(input("Please enter the room's size in SQUARE FEET"))
        print("The cost to cover your floor will be $%s" % (sqft * round(cost_of_tile, 2)))
        labor()
        answer = input("Would you like to run the calculator again for another room? Y/N")
        should_i_stay()
    elif answer in more_info:
        answer = input("Do you know the length and the width of the room? Y/N")

        if answer in move_on:
            width = Decimal(input("What is the width of the room?"))
            length = Decimal(input("What is the length of the room?"))
            sqft = width * length
            print("Your room is %s sqft" % sqft)
            print("The cost to cover your room will be $%s" % (sqft * round(cost_of_tile, 2)))
            labor()
        elif answer in more_info:
            print("Sorry we need more information ")

            answer = input("Would you like to run the calculator again? Y/N")
            should_i_stay()
    elif answer in exit_program:
        print("Exiting")
        exit()

def should_i_stay():
    if answer in move_on:
        program()
    else:
        print("Good Bye")
        time.sleep(1)
        exit()

def labor():
    rate = 86
    total_labor = (sqft / 20) * rate
    hours_of_labor = sqft / 20
    if hours_of_labor <= 1:

        hours_of_labor = 1
        total_labor = rate
        print("The labor will be approximately $%s at a rate $%s per "
              "hour for a total of %s hours of labor" % (round(total_labor, 2), rate, hours_of_labor))
    else:
        print("The labor will be approximately $%s at a rate $%s per "
              "hour for a total of %s hours of labor" % (round(total_labor, 2), rate, hours_of_labor))

program()


texts: C string library inspired by Python string functions

texts:
I'm working on a C library which attempts to bring some of the Python string functions over to C.

This is where my full source is located, but the majority of what I have so far is here.

Are there any places where code efficiency can be improved?

#ifndef OCTO_H
#define OCTO_H

#include <stdlib.h>
#include <string.h>

int len(char* string){

    int i = 0;
    while(*string != '\0'){
        i++;
        *string++;
    }

    return i;

}

char* lstrip(char* string){

    if(!string)
        return;

    /* Trim off leading whitespace */
    while(*string == ' '){
        string++;
    }

    return string;

}

char* rstrip(char* string){

    /* Trim off trailing whitespace */
    char* end = string + len(string) - 1;
        while (end >= string && *end == ' ')
                end--;
        *(end + 1) = '\0';

    return string;

}

char* strip(char* string){

    /* Trim off both leading and trailing whitespace */
    char* lstring = lstrip(string);
    char* finalString = rstrip(lstring);

    return finalString;

}

char* slice(char* s, int start, int end){

    /* Create a new identical buffer */
    char* buff = (char*) malloc((end - start) + 2);
    strncpy(buff, s + start, (end - start) + 1);
    *(buff + (end - start) + 1) = '\0';
    return buff;
}

char* toUpperCase(char* s){

}

char* toLowerCase(char* s){

}

#endif /* OCTO_H */


texts:
For an interview question I made a roman to integer converter:

def romanToInt(self, s):
        """
        :type s: str
        :rtype: int
        """
        mapping = {"I": 1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
        numeral_list = list(s)

        num_list = [[mapping[i], -1] for i in numeral_list]
        count = 0
        i = 0
        while(i < len(num_list) - 1):
            if num_list[i] < num_list[i + 1]:
                count += num_list[i + 1][0] - num_list[i][0]
                num_list[i+1][1] = 1
                num_list[i][1] = 1
                i += 2
            else:
                count += num_list[i][0]
                num_list[i][1] = 1
                i += 1
        if num_list[-1][1] == -1:
            count += num_list[-1][0]
        return count

As you can see I sometimes miss the last digit because I didn't want to get an index error. To avoid that I added an extra attribute that would check if the last element was checked or not (in cases where s[len(s)-2] < s[len(s)-1], s[len(s)-1] is checked, but if s[len(s)-2] > s[len(s)-1] then s[len(s)-1] is not checked.

Having an extra check and using extra space just for one element is highly erroneous. Where am I going wrong in my logic?


texts:
I'm a beginner in JEE development.  I have just finished a web application that I'm going to deploy in a server.

It's a new level for me; it's not just a simple application that I can run for 10 min, etc.

My question is for the quality of code.  Of course we all know that a piece of code that works does not mean it's correct.  In my managed beans, I use @postConstruct, for example:

@PostConstruct
public void post() {
    listChaletss = chaletService.getAllChalet();

    for (Chalet it : listChaletss) {

        if (it.getType().equals("permanent")) {

            listChaletp.add(it);
        }
    }
    allPeriodes = periodeService.getAllPeriodes();
    // System.out.println("size periode" + allPeriodes.size());
    for (Chalet order : listChaletss) {
        order.setEditable(false);
    }
}

I'm wondering if someone can determine if we can face any memory problems using this application.  Some piece of code and any help from some Java experts will be welcomed.


texts: Best practice for Constant Class in Java

texts:
I create a constant class by looking at some of the best practices described here in stackoverflow. Many of those have a single Constant class with variables. Some of the answers suggested creating separate Contant Classes. The way I create a constant class is by naming it Parameters and creating classes i.e. Variables and Constants. Then these classes further have child classes e.g. URL, Columns etc. This time I created a constant class with same structure and a separate class named ReportTemplate. This is my first time creating a Constant class of Objects that don't have a primitive datatype.

public final class ReportTemplate {

    public final static class ColumnIds {
        public static final String TITLE_COLUMN_ID = "title";
        public static final String TYPE_COLUMN_ID = "type";
        public static final String LIFECYCLESTATUS_COLUMN_ID = "lifecyclestatus";
        public static final String INSERTIONTIMESTAMP_COLUMN_ID = "insertionTimestamp";
    }

    public final static class Columns {
        public static final TextColumnBuilder<String> TITLE = col.column(
                "Title", ColumnIds.TITLE, type.stringType());

        public static final TextColumnBuilder<String> LIFECYCLESTATUS = col.column(
                "Lifecycle Status", ColumnIds.LIFECYCLESTATUS,
                type.stringType());

        public static final TextColumnBuilder<String> TYPE = col.column("Type",
                ColumnIds.TYPE, type.stringType());

        public static final TextColumnBuilder<String> INSERTIONTIMESTAMP = col
                .column("Insertion Timestamp",
                        ColumnIds.INSERTIONTIMESTAMP,
                        type.stringType());
    }

    public final static class Styles {
        public static final StyleBuilder HEADING1 = stl.style()
                .setName("heading1").bold().setFontSize(15);

        public static final StyleBuilder HEADING2 = stl.style().setName("heading2")
                .bold().setFontSize(12);

        public static final StyleBuilder HEADING3 = stl.style().setName("heading3")
                .bold().setFontSize(10);
    }

}

I want to know if my

Naming Scheme is correct
Constant class structure is among best practices.
Should I create separate constant classes or having them encapsulated in a parent Constant class is fine?

Edit: April 19, 2016

I have accpeted an answer but i would like more suggestions anytime.

Thank you.


texts:
For a project I'm working on I have the following requirements:

We have two student types: Domestic and International

public enum StudentType {
    Domestic,International
}

Students of both types must have a ID number, First/Last name but only international students require documentation (Passports, drivers licence, etc).

I've decided to create the Student class as immutable, and came up with the following implementation:

public final class Student {

    private final String id;
    private final String firstname;
    private final String lastname;
    private final Collection<String> documents;;
    private final StudentType typeofStudent;

    private Student(String id, String firstname, String lastname, List<String> documents, StudentType typeofStudent)
    {
        this.id = id;
        this.firstname = firstname;
        this.lastname = lastname;
        this.documents = Collections.unmodifiableList(new ArrayList<String>(documents));
        this.typeofStudent = typeofStudent;
    }

    public static Student createDomestic(String id, String firstname, String lastname)
    {
        return new Student(id, firstname, lastname, Collections.emptyList(), StudentType.Domestic);
    }

    public static Student createInternational(String id, String firstname, String lastname, List<String> documents)
    {
        return new Student(id, firstname, lastname, documents, StudentType.International);
    }
}

I left out constructor validation to keep my code short and concise.

Advantages of the static method approach:

If the constructor was public, I would need to write a private helper method that checks if the student is domestic, the client didn't pass a list of documents. I would throw an exception to notify the client if this happened.
My code is shorter because I prohibit the client from passing a List<String> documents if the student was domestic. I simply ask for the ID, and first/last name. The Collections.unmodifiableList(); and StudentType are set when domestic students are created. In other words, no need for a private helper method.
The client knows exactly what type of student is being created without calling a getter/internal method to verify the student type.

Problem:

I came across this SESE page that was talking about the disadvantages of static. I became confused and wanted someone to review my code and tell me if my use of static methods are okay given what was said on that page?

The code and answer on this page provide what I need.


texts:
I've been trying to learn java recently and I finally finish my first code. Any suggestions on where I can improve? Also, is it possible to send an argument to a class using something like an init function in python and are there any good and bad habits that I should keep in mind?
class LIFO {

    //Create an empty list with the lenght of the given size
    //Initialize our top value as 0
    int my_list[] = new int[5];
    int top = 0;

    //Adds a value to the list
    //Add one to our top
    public void push(int data)
    {
        my_list[top] = data;
        top++;
    }

    //Removes the top value from the list
    //Substract one from our top
    public int pop()
    {
        int data;
        top--;
        data = my_list[top];
        my_list[top] = 0;
        return data;

    }

    //Prints our list
    public void show()
    {
        for(int n : my_list)
        {
            System.out.print(n + " ");
        }
    }
}

//Driver Class
class Main {
    public static void main(String args[])
    {
        LIFO s = new LIFO();
        s.push(1);
        s.push(2);
        s.push(3);
        s.show();
        System.out.println("\n" + s.pop() + " Popped from stack");
        s.show();

    }
}


texts: Web page downloader that supports redirects

texts:
I wrote a class that downloads the HTML of a page from the internet. This class also manages redirects. This works well but I'm not very satisfied about time management for slower servers. In fact, if the website is slow, the method GetHtml will return an empty string, so  how can I optimize this class, to prevent such a situation from happening?

CODE

using System;
using System.IO;
using System.Net;
using System.Net.Http;

namespace SWP.Helpers
{
    /// <summary>
    /// Download html from an Internet page.
    /// </summary>
    public class NetworkHelper
    {
        /// <summary>
        /// Store the previous url used in the request.
        /// </summary>
        private Uri _storedUrl = null;

        /// <summary>
        /// Store the previous html downloaded.
        /// </summary>
        private string _storedData = "";

        /// <summary>
        /// Get the html structure of a site.
        /// </summary>
        /// <param name="url">Represents the URL of the page where to download the data.</param>
        /// <returns>Return a string that contains the html of the site.</returns>
        public string GetHtml(Uri url)
        {
            //If the current url is the same of the older, then will returned the previous html structure, in this way will not be wasted any time to perform another connection.
            if (url == _storedUrl)
                return _storedData;
            else
                _storedUrl = url;

            //Web request handler.
            HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(url);

            try
            {
                //Configure the client manager for perform a page compression.
                HttpClientHandler handler = new HttpClientHandler();
                handler.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

                //Handle the client to manage possible redirect.
                HttpClient httpClient = new HttpClient(handler);

                //Set the web request.
                HttpRequestMessage request = new HttpRequestMessage
                {
                    RequestUri = url,
                    Method = HttpMethod.Get
                };

                //Get the response.
                HttpResponseMessage response = httpClient.SendAsync(request).Result;

                //Return the code of the web request.
                int statusCode = (int)response.StatusCode;

                //If the code is within this range, then the server has executed a redirect.
                if (statusCode >= 300 && statusCode <= 399)
                {
                    //Get the new url.
                    Uri redirectUri = response.Headers.Location;

                    //Sanitize the url.
                    if (!redirectUri.IsAbsoluteUri)
                    {
                        redirectUri = new Uri(request.RequestUri.GetLeftPart(UriPartial.Authority) + redirectUri);
                    }

                    //Call again this method with the correct url.
                    return GetHtml(redirectUri);
                }

                _storedData = response.Content.ReadAsStringAsync().Result;
                return _storedData;
            }
            catch (WebException)
            {
                throw;
            }
        }
    }
}

as you can see, the logic is really simple, and the method is well commented. Are there any problems I haven't taken into account?


texts:
I was facing an issue where I want to retrieve existing/active ViewModels from the Prism runtime.

Here's the code I've done to achieve it:

public class ViewModelFinder
{
  readonly IRegionManager _RegionManager;
  readonly IContainer _Container;
  public ViewModelFinder(IContainer container, IRegionManager regionManager)
  {
    _RegionManager = regionManager;
    _Container = container;
  }

  public TViewModel FindOrResolve<TViewModel>()
    where TViewModel : class =>
    Find<TViewModel>() ?? _Container.Resolve<TViewModel>();

  /// <summary>
  /// Locates an existing VM in the entire region manager.
  /// </summary>
  public TViewModel Find<TViewModel>() => (TViewModel)Find(typeof(TViewModel));
  public object Find(Type viewModelType)
  {
    var shellContext = Application.Current.MainWindow.DataContext;
    if (shellContext != null && viewModelType.IsAssignableFrom(shellContext.GetType()))
      return shellContext;

    foreach (var region in _RegionManager.Regions)
    {
      var viewModel = Find(region, viewModelType);
      if (viewModel != null)
        return viewModel;
    }
    return null;
  }

  /// <summary>
  /// Locates an existing VM in the specified region.
  /// </summary>
  public TViewModel Find<TViewModel>(IRegion region) =>
  (TViewModel)Find(region, typeof(TViewModel));
  public object Find(IRegion region, Type viewModelType)
  {
    foreach (var view in region.Views.OfType<FrameworkElement>())
      if (view.DataContext != null &&
      viewModelType.IsAssignableFrom(view.DataContext.GetType()))
        return view.DataContext;
    return null;
  }
}

It's intended to be used from any VM, by adding a ViewModelFinder to its constructor to be resolved by the IoC (in my case DryIoc).

When requesting for a VM, it will check for the Shell, then iterate over all views in all regions until it finds the desired VM.

Would love to hear about any better ways to achieve this.


texts: Implementation of FastICA in multithreading approach

texts:
I am to implement a parallel version of FastICA, so I implemented the serial version of FastICA.

Now this is the architectural diagram of how it is going to parallelize. I just coded a basic thread model of this. But I need to know what I did was correct or wrong regarding inter threads synchronization.

#include <condition_variable>
#include <mutex>
#include <vector>
#include <iostream>
#include <thread>

int numberOfThreads=10;
std::vector<int> checkedEvent(numberOfThreads);
std::vector<double> data(numberOfThreads);
std::mutex lock;
int IsPrepare=0;

std::condition_variable data_prepare;

class MainProcess
{
private:
    int rank;
    double input;
public:
    MainProcess(int rank_, double dataPr){
        rank=rank_;
        input=dataPr;
    }
    MainProcess(){

    }
    void fastICA_processing()
    {
        while(true){
            std::unique_lock<std::mutex> lk(lock);
            data_prepare.wait(lk,[this]{return checkedEvent[rank]!=1;});
            data[rank]=input;
            checkedEvent[rank]=1;
            IsPrepare=IsPrepare+1;
            std::cerr <<IsPrepare<<" thread is processing"<<std::endl;
            lk.unlock();
        }

    }

    void controller()
    {
        while(true)
        {

            while(IsPrepare==numberOfThreads)
            {
                std::lock_guard<std::mutex> lk(lock);
                std::cerr<<"Now controller is checking fastICA is converged or not "<<std::endl;
                std::fill(checkedEvent.begin(), checkedEvent.end(), 0);
                IsPrepare=0;
                data_prepare.notify_all();
            }
        }

    }
    };

int main()
{
    std::vector<std::thread> thredArray;
    MainProcess p3(0,0);
    std::thread process_thread(&MainProcess::controller,&p3);
    for(int i=0;i<numberOfThreads;i++){
        MainProcess* p1= new MainProcess(i,i);
        thredArray.push_back(std::thread (&MainProcess::fastICA_processing,p1));
    }
    for(auto &t:thredArray)
    {
        t.join();
    }
    process_thread.join();

    return 0;
}

Note: Here "data" stands for input data. First fastICA_processing threads do some mathematical calculations and then the controller thread gets all that data and processes it. This will happen again and again. I didn't add threads detaching part here.


texts:
Can someone help me optimize speed for my code? I tested it via stopwatch in milliseconds. I've implemented my own ArrayList and I would like to improve its speed without using C# built-in structures.

Mylist.cs

using System;
using System.Collections;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ManualArrayList {
class MyList : IList {
private object[] _items;

public MyList() {
    _items = new object[0];
}

public void PrintElement() {
    for(int i = 0; i < _items.Length; i++) {
        Console.WriteLine(_items[i]);
    }
}

public int Add(object value) {
    object[] tmp = new object[_items.Length + 1];
    for(int i = 0; i < _items.Length; i++) {
        tmp[i] = _items[i];
    }
    tmp[tmp.Length - 1] = value;
    _items = tmp;
    return tmp.Length - 1;
}

public bool Contains(object value) {
    return IndexOf(value) != -1;
}

public int IndexOf(object value) {
    return IndexOf(value, 0);
}

public int IndexOf(object value, int startIndex) {
    for(int i = startIndex; i < _items.Length; i++) {
        if(_items[i].Equals(value)) {
            return i;
        }
    }
    return -1;
}

public void Remove(object value) {
    if(!Contains(value)) {
        return;
    }
    object[] tmp = new object[_items.Length - 1];
    bool deleted = false;
    for(int i = 0, j = 0; i < tmp.Length; i++, j++) {
        if(_items[i].Equals(value) && !deleted) {
            j++;
            deleted = true;
        }
        tmp[i] = _items[j];
    }
    _items = tmp;
}

public void Insert(int index, object value) {
    object[] tmp = new object[_items.Length + 1];
    if(index - 1 >= _items.Length + 1 || index < 0) {
        Console.WriteLine("This type of index was not found in array");
        return;
    }
    for(int i = 0, j = 0; i < tmp.Length && j < _items.Length; i++, j++) {
        if(j == index - 1) {
            tmp[j] = value;
            i++;
        }

        tmp[tmp.Length - 1] = value;
        tmp[i] = _items[j];
    }

    _items = tmp;

}
public void RemoveAt(int index) {
    if(index >= _items.Length || index < 0) {
        Console.WriteLine("This type of index was not found in array");
        return;
    }
    object[] tmp = new object[_items.Length - 1];
    for(int i = 0, j = 0; i < tmp.Length; i++, j++) {
        if(i == index) {
            j++;
        }
        tmp[i] = _items[j];
    }
    _items = tmp;
}

public void Clear() {
    _items = new object[0];
}

public int Count {
    get {
        return _items.Length;
    }
}

// es avxsnat ertad mere...
public object this[int index] {
    get {
        throw new NotImplementedException();
    }
    set {
        throw new NotImplementedException();
    }
}

//es ertad gavaketot
public void CopyTo(Array array, int index) {
    throw new NotImplementedException();
}

//es ertad gavaketot
public IEnumerator GetEnumerator() {
    throw new NotImplementedException();
}

#region We Dont Touch This
public bool IsFixedSize {
    get {
        return false;
    }
}

public bool IsReadOnly {
    get {
        return false;
    }
}

public bool IsSynchronized {
    get {
        return true;
    }
}

public object SyncRoot {
    get {
        return this;
    }
}
#endregion

}
}


texts:
I am writing an API which gets results from a DynamoDB table and puts the JSON back into the browser.

The code below works and returns the desired results.  However, after reading about async and callbacks, it's becoming important for me to know if I should be writing this in another way.  Does the following scale well with hundreds of concurrent API callers?

This code does not seem to be using callbacks.  Is it asynchronous?

var restify = require('restify');
var AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-1'});
var db = new AWS.DynamoDB();

function myFunction(req, res, next) {
  var params = {
    TableName : 'myTable',
    KeyConditions :
      {
        "number" :
          {
            "AttributeValueList" : [
              {
                "S" : req.params.simethingid
              }
            ],
            "ComparisonOperator" : "EQ"
          }
      }
  }

  db.query(params, function(err, data) {
    if (err) {
      console.log(err);
      }
    else {
      res.statusCode = 200;
      res.setHeader('Content-Type', 'text/plain; charset=UTF-8');
      res.send(JSON.stringify(data, undefined, 2));
      console.log(JSON.stringify(data, undefined, 2))
      res.end();
      }
  });
  return next();
 }

server.get('/searchme/:somethingid', myFunction);


texts: Whether or not to name Boolean parameters in Scala

texts:
def execute(parameterName : scala.Boolean = { /* compiled code */ })

When calling this method, you can go with

someobject.execute(true)

or

someobject.execute(parameterName = true)

If you use the former, IntelliJ pops up a recommendation stating that Boolean arguments should be named. But doesn't this introduce an unnecessary dependency on the name of the parameter? Essentially the name of the parameter becomes part of the interface.

If I then change the name of parameterName in execute() to something else, I potentially break a lot of code that is using the execute method.

I understand that it improves readability a bit (you can look at the code and see which Boolean is being set to true without having to look at the called method). But is it enough of an advantage?


texts:
Edit: A follow up question can be found here.

My first try at mergesort, without resorting to any references:

#include <iostream>
#include <vector>

std::vector<int> Merge(std::vector<int>, std::vector<int>);
std::vector<int> MergeSort(std::vector<int>);

int main()
{
    // No need to review this, it was just for testing purposes
    std::vector<int> a;
    for (int i = 0; i < 100; i++) {
        a.push_back(6000.0 * rand() / RAND_MAX);
    }
    for (int i = 0; i < a.size(); i++) {
        std::cout << a[i] << " ";
    }
    std::cout << "\n";
    a = MergeSort(a);
    for (int i = 0; i < a.size(); i++) {
        std::cout << a[i] << " ";
    }
    std::cout << "\n";
    return 0;
}

std::vector<int> Merge(std::vector<int> arr1, std::vector<int> arr2) {
    int size1 = arr1.size();
    int size2 = arr2.size();
    std::vector<int> res(size1 + size2, 0);
    int i1 = 0;
    int i2 = 0;
    while (i1 < size1 && i2 < size2) {
        if (arr1[i1] < arr2[i2]) {
            res[i1 + i2] = arr1[i1];
            i1++;
        }
        else {
            res[i1 + i2] = arr2[i2];
            i2++;
        }
    }
    while (i1 < size1) {
        res[i1 + i2] = arr1[i1];
        i1++;
    }
    while (i2 < size2) {
        res[i1 + i2] = arr2[i2];
        i2++;
    }
    return res;
}

std::vector<int> MergeSort(std::vector<int> arr) {
    if (arr.size() < 2) {
        return arr;
    }
    else if (arr.size() == 2) {
        // If array is of size 2, return it sorted
        if (arr[0] > arr[1]) {
            arr[1] += arr[0];
            arr[0] = arr[1] - arr[0];
            arr[1] -= arr[0];
        }
        return arr;
    }
    else {
        // Recursively split in halves until all vectors are size 1 or 2, then merge
        return Merge(
            MergeSort(std::vector<int>(arr.begin(), arr.begin() + arr.size() / 2)),
            MergeSort(std::vector<int>(arr.begin() + arr.size() / 2, arr.end()))
        );
    }
}

A few questions:

Have I implemented a merge sort correctly? Or is it some other sort?
How can I make it work for multiple data types rather than just int?
I imagine it's not very efficient (I don't know much about std::vector<T>.begin or std::vector<T>.end), how could I make it more efficient?


texts: Iterating and updating 35000 dictionaries

texts:
I'd like the function below reviewed. I'm especially interested in improvement ideas to process the API responses faster.

products_list is the API response in the form of list of dictionaries which returns all products for one supermarket only (out of many).

def encode_products_response_list(products_list, rows_list):
    """
    Convert unicode values to utf-8
    Convert all other values (e.g. Int, Float) to str
    Return list of unique rows

    :param products_list:  list of dictionaries
    :param rows_list:          empty list
    """
    for item in products_list:
        # extract name from list
        item['product_name'] = item['product_name'][0]

        for key, value in item.iteritems():
            if isinstance(value, unicode):
                item[key] = value.encode('utf-8')
            else:
                item[key] = str(value)

        if item not in rows_list:
            rows_list.append(item)

    return rows_list

if __name__ == '__main__':
    # all work in same product
    rows_list = []
    # the api products_list response is a list of dicts like the one below
    products_list = [
        {
            u'product_name': [u'Super Bleach 5'],
            u'product_description': 'Cleans like nothing you have ever seen',
            u'cost': 2.55,
        },
        {
            u'product_name': [u'Magic Breakfast'],
            u'product_description': 'Start your day with proper breakfast!',
            u'cost': 5,
        }
    ]
    products_list = products_list * 354342

    encode_products_response_list(products_list, rows_list)

The metrics below is just regarding one of many supermarkets (using line_profiler):

Timer unit: 1e-06 s

Total time: 108.972 s
File: example_1.py
Function: encode_products_response_list at line 2

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
 1                                           @profile
 2                                           def encode_products_response_list(products_list, rows_list):
 3    354343       362103      1.0      0.3      for row in response:
 4    354342       539821      1.5      0.5          item['product_name'] = item['product_name'][0]
 5
 6   2480394      1392104      0.6      1.3          for key, value in item.iteritems():
 7   2126052      1460806      0.7      1.3              if isinstance(value, unicode):
 8    354342       661158      1.9      0.6                  item[key] = value.encode('utf-8')
 9                                                       else:
10   1771710      1728154      1.0      1.6                  item[key] = str(value)
11
12   354342    102436117    289.1     94.0          if item not in rows_list:
13     13634        28912      2.1      0.0              rows_list.append(item)
14
15         1            1      1.0      0.0      return rows_list


texts:
I am pretty new to JavaScript and learning the intricacies of this language. I wanted a unique collection which will overwrite while adding if an item already exists else add. Rest of the behavior should be just like any other collection. I had written the type and its as below. Instead of using an array internally, I have used JavaScript's notion of storing an object as key-value pair to store the items.

My question is, is this implementation valid? Are there any disadvantage with this implementation over using an array internally to hold the collection items instead of an object?

Why I chose objects to store items over array is:

To avoid iterating through the array while adding an item, so that I don't have to check  if objects exists(instead of adding a duplicate).
To avoid iterating while retrieving or deleting an item.

function isValid(obj) {
    return (obj != undefined && obj != null && typeof (obj) != 'undefined');
}

function uniqueCollection() {
    var collection = {};
    var length = 0;
    return {
        removeItem: function (item) {
            if (isValid(collection[item])) {
                delete collection[item];
                --length;
            }
        },
        addItem: function (item) {
            if (!isValid(collection[item])) {
                collection[item] = item;
                ++length;
            }
        },
        getLength: function () {
            return length;
        },
        clear: function () {
            collection = {};
            length = 0;
        },
        exists: function (item) {
            if (isValid(collection[item])) {
                return true;
            }
            return false;
        },
        getItems: function () {
            var items = [];
            var i = 0;
            for (var o in collection) {
                if (collection.hasOwnProperty(o)) {
                    items[i] = o.toString();
                    i++;
                }
            }

            if (i !== length) {
                alert("Error occurred while returning items");
            }

            return items;
        }

    };//end of object literal

};//end of function