texts:
I have a function that takes a Dictionary<String, Object> as an argument.  It uses this Dictionary to create parameters for a query string.

private static TableAdapters dataSource = new TableAdapters();
private void findScriptsQueryButton_Click(object sender, EventArgs e)
{
  string fillBy = findByComboBox.SelectedItem.ToString();
  string server = serverComboBox.SelectedItem.ToString();
  Dictionary<String, Object> parameters = new Dictionary<String, Object>()
  {
    {"findBy", findByTextBox.Text}
  };
  dataGridView.DataSource = dataSource.GetDataSource(fillBy, server, parameters).Tables[0];
}

public class TableAdapters
{
  public DataSet GetDataSource(string fillBy, string server, Dictionary<String, Object> parameters)
  {
    string query = GetQuery[fillBy];
    SqlConnection connection = new SqlConnection();
    connection.ConnectionString = GetSqlConnection[server];
    SqlDataAdapter adapter = new SqlDataAdapter(query, connection);
    foreach (KeyValuePair<String, Object> p in parameters)
    {
      adapter.SelectCommand.Parameters.AddWithValue("@" + p.Key, (p.Value.ToString().Length == 0) ? DBNull.Value : p.Value);
    }
    DataSet dataSet = new DataSet();
    dataSet.Tables.Add(new DataTable());
    adapter.Fill(dataSet.Tables[0]);
    return dataSet;
  }
}

My primary problem with my code is:

I have to create a new dictionary of parameters every time before I call the function.
The parameter names are hard coded into both the dictionaries and the query strings.

The number of parameters for a query string in this particular program can be 1-11. Is there a better way for me to pass parameters to this function where I don't have to hard code the names?  Mind you I don't want to go off parameter number either, because then I've become dependent on ensuring I pass the parameters to the function in the right order.

For brevity here is an example of one of the queries from the query dictionary that this particular instance of the function calls:

private static readonly Dictionary<String, String> GetQuery = new Dictionary<String, String>()
{
  {"Target VDN",
   "SELECT * FROM table_name WHERE column_name = ISNULL(@findBy, column_name) "
  },
  // ...
}

In this case I am only dealing with one parameter but as I mentioned some of these queries in the dictionary can take up to 11 parameters.


texts: Reading arbitrarily long lines from a file that is redirected as input

texts:
So I have a file with a list of dates that are to be redirected as input to stdin and what the program does is it searches for valid dates, appends them to the output file and then appends all the dates in the input file to the output file. In other words, at the end of the program there would be a list of all the valid dates in the output file and list of all the dates that were in the input file. An important command line argument is the number of entries to search for. 0 here is the default case where we look through the entire input file. Any value greater than 0 represent the number of entries we have to look at. If we find one that is invalid, we skip it.

Command Example: ./program < input.txt 0 > output.txt

Here are all the relevant functions.

getDates Function

char ** getDates(char **lines, size_t *numOfLines, size_t *lineMax, int numOfEntries)
{
    char *strDate = NULL;
    int allEntries = FALSE, errorStatus = FALSE; // errorStatus is so I can report memory failures.

    if(numOfEntries == 0)
    {
        allEntries = TRUE; // A flag for the default case zero.
    }

    while((strDate = readLine(stdin, &errorStatus)) != NULL)
    {
        if(numOfEntries >= 0 || allEntries)
        {
            if(checkDate(strDate))
            {
                fputs(strDate, stdout);
            }

            numOfEntries--;
        }

        /*
       Keep a record of how many lines we have process.
       We will need this variable when we decide to print
       everything that we have in the variable lines.
        */
        lines[*numOfLines] = strDate;
        (*numOfLines)++;

        if((*numOfLines) == (*lineMax))
        {
            errorStatus = expand(lines, lineMax); // try to expand.

            if(errorStatus == MEMFAILURE)
            {
                fprintf (stderr,"Error, couldn't allocate any more memory.");
                return NULL;
            }
        }
    }

    if(errorStatus == MEMFAILURE)
    {
        fprintf (stderr,"Error, couldn't allocate any more memory.");
        return NULL;
    }

    if(ferror(stdin))
    {
        fprintf(stderr,"Error, couldn't completely process the entire file.\n");
        return NULL;
    }

    if(strDate != NULL)
    {
        free(strDate);
    }

    return lines;
}

readLine Function

char *readLine(FILE *stream, int *errorStatus)
{
    size_t size = 0;
    char *buffer = NULL;
    char *newLineFound = NULL;

    do
    {
        char *temp = realloc(buffer, size + BUFSIZ); // BUFSIZE is a define constant in the stdio library.

        if(!temp)
        {
            free(buffer);
            *errorStatus = MEMFAILURE; // an enum constant to record our error.
            return NULL;
        }

        buffer = temp;

        // One small problem. If there is no new line at the end of the file. it won't add whatever contents is there.
        if(!fgets(buffer + size, BUFSIZ, stream))
        {
            free(buffer);
            return NULL;
        }

        newLineFound = strchr(buffer + size, '\n');

    }
    while(!newLineFound && (size += BUFSIZ - 1)); // this is to simply update size at the same time that we don't find a newline.

    return buffer;
}

expand Function

int expand(char **lines, size_t *lineMax)
{
    char **tmp = realloc (lines, (*lineMax) * 2 * sizeof(*lines));

    if(!tmp)
    {
        return MEMFAILURE;
    }

    lines = tmp;
    (*lineMax) *= 2; // Update the size

    return SUCCESS;
}

What can I do to reduce my code as I feel that it is getting too bloated.
What did I forget to do, what didn't I do right and what did I do that was unnecessary.
Performance tips are welcome.


texts: Removing duplicate code from basic collision detection implementation

texts:
The code is part of a very basic 2D platformer based on code from the book Killer Game Programming in Java.

The methods are part of a TileMapManager class which is handling basic collision detection.

The first method returns the greatest distance that an entity can travel in the y axis (up to deltaY) without colliding with a tile:

public int getMaxDeltaY(Point initialPoint, int deltaY){

    //validate params
    if(deltaY>=tileMap.getTileHeight()) throw new IllegalArgumentException("Cannot validate if deltaY is larger than brickHeight");
    if(deltaY==0) return deltaY;

    int x = initialPoint.x;
    int testY = initialPoint.y + deltaY;

    if(isInsideTile(x, testY)){

        //get which row we are colliding with
        int mapRow = testY/tileMap.getTileHeight();
        //the distance between our position and
        //the top of the tile we are colliding with
        int topOffset = testY - (mapRow * tileMap.getTileHeight());
        //get the amount we should move to place
        //ourselves just next to the tile (top or bottom)
        int maxDeltaY = 0;

        //moving up case
        if(deltaY <0){
            maxDeltaY = deltaY + (tileMap.getTileHeight()-topOffset);
        }
        //moving down case
        else if(deltaY >0){
            maxDeltaY = deltaY - topOffset;
        }
        return maxDeltaY;
    }
    //we won't collide so it's okay to move deltaY
    return deltaY;
}

The second method does the same thing in the x axis:

public int getMaxDeltaX(Point initialPoint, int deltaX){
    //validate params
    if(deltaX>=tileMap.getTileWidth()) throw new IllegalArgumentException("Cannot validate if moveStep is larger than brickWidth");
    if(deltaX==0) return deltaX;

    int testX = (initialPoint.x + deltaX);
    int y = initialPoint.y;

    //if we collide
    if(isInsideTile(testX, y)){

        //get which column we are colliding with
        int mapCol = testX/tileMap.getTileWidth();
        //the distance between our position and
        //the left side of the tile we are colliding with
        int leftOffset = testX - (mapCol * tileMap.getTileWidth());
        //get the amount we should move to place
        //ourselves just next to the tile (left or right)
        int maxDeltaX = 0;

        //moving left
        if(deltaX < 0){
            maxDeltaX = deltaX + (tileMap.getTileWidth() - leftOffset);
        }
        //moving right
        else if(deltaX > 0){
            maxDeltaX = deltaX - leftOffset;
        }

        return maxDeltaX;
    }
    //we won't collide so it's okay to move deltaX
    return deltaX;
}

The algorithm (from the book) is essentially the same so I wanted to remove the duplication.

The code differs in only a few places:

use getTileWidth() or getTileHeight()
use x or y to create test point
use x or y to create offset
use mapRow or mapCol

So a basic way could be:

pass tile width/height as argument tileDimension
create test point before calling method (turn initialPoint into testPoint)
pass test x/y as argument testCoordinate
pass row/col as argument?  Can't think of good name (mapIndex?)

But now I have loads of confusing arguments and duplicate information (testCoordinate is contained in testPoint). I read that this is also a big no no, and even a beginner like me can see that this would be ugly.

Another way might be to pass the basic information and a flag for the axis, x or y. But this would still involve a bunch of arguments and then confusing switching in the body.

So I'm hoping there's a simple pattern that is used in these situations and will magically get rid of all duplication and leave a short method that's easy to read and use...

What is the best way to refactor these methods?


texts:
I have written a safe read function for haskell (for education!). I think this is fairly idiomatic haskell code, but I'd like to know for sure. If you see anything else that could be improved, please let me know in your answer.

module ReadNum (readNum) where

main = print $ readNum "87k7"

readNum :: String -> Maybe Int
readNum xs = readNum' $ reverse xs

readNum' :: String -> Maybe Int
readNum' (x:xs) = (\y z -> y + 10 * z) <$> readChr x <*> readNum' xs
readNum' [] = Just 0

chrToNum :: [(Char, Int)]
chrToNum = [('0', 0), ('1', 1),
            ('2', 2), ('3', 3),
            ('4', 4), ('5', 5),
            ('6', 6), ('7', 7),
            ('8', 8), ('9', 9)]

readChr :: Char -> Maybe Int
readChr c = lookup c chrToNum


texts:
The following Bash script takes a single parameter (the PAN) and exits with 1 if the PAN does not satisfy a  LUHN check.

#!/bin/bash

pan=$1
panlen=${#pan}

for i in $(seq $((panlen - 1)) -1 0); do
  digit=${pan:$i:1}
  if [ $(((panlen-i) % 2)) -eq 0 ]; then
     #even
     ((digit*=2))
     [ ${#digit} -eq 2 ] && digit=$((${digit:0:1}+${digit:1:1}))
  fi
  ((sum+=digit))
done

[ $((sum % 10)) -eq 0 ] || exit 1

For example, when placed in a file called isLUHNValid.sh it can be run with a valid PAN like:

./isLUHNValid.sh 4388576018410707 && echo 'Valid PAN' || echo 'Invalid PAN'

which will echo 'Valid PAN'.

And with an invalid PAN:

./isLUHNValid.sh 4388576018410708 && echo 'Valid PAN' || echo 'Invalid PAN'

it will echo 'Invalid PAN'.

I'm interested to know:

if I've followed best practices; and/or
if there's an opportunity for optimisation

I've been using Bash for a couple of years - but I'm constantly learning new things from examples on the Internet (like from here) and from man bash. Unfortunately in my position I don't have anyone to look over my shoulder and review by Bash code so I thought I'd take advantage of this community.


texts:
#include <iostream>
#include <string>
#include <algorithm>
#include <time.h>
int faults = 0;
int hangman();
int i = hangman();
int main(){

srand(time(NULL));
while (i == 1){
    std::string words[7]{"Alpha", "Cornwall", "Crepuscular", "Blind", "Steroid", "Plunder", "Talisman"};
    std::string word = words[rand() % 7];
    int n;

    n = rand() % word.length();
    char underscore = '_';
    char checkAnswer = word.at(n);
    word.at(n) = underscore;

    std::cout << word;
    char answer;
    std::cin >> answer;

    if (answer == checkAnswer){
        std::cout << "Correct!";
    }
    else{
        faults++;
        hangman();
    }
}

}
      int hangman(){
       if (faults == 0){
        std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|" << std::endl;
        std::cout << "|" << std::endl;
    std::cout << "|" << std::endl;
    return 1;
}
else if (faults == 1){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|" << std::endl;
    std::cout<<"|" << std::endl;
    return 1;
}
else if (faults == 2){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |"<<std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|" << std::endl;
        ;
    return 1;
}

else if (faults == 3){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                     /" << std::endl;
        ;
    return 1;
}
else if (faults == 4){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      X" << std::endl;
    return 1;
}
else if (faults == 5){
    std::cout << "|----------------------" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      O" << std::endl;
        std::cout << "|                      |" << std::endl;
        std::cout << "|                      X" << std::endl;
        std::cout << "                       -" << std::endl;
    return 1;
}
else if (faults == 6){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      X" << std::endl;
    std::cout << "                      - -" << std::endl;
    return 1;
}
else if (faults == 7){
    std::cout << "|----------------------" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      O" << std::endl;
    std::cout << "|                      |" << std::endl;
    std::cout << "|                      X" << std::endl;
    std::cout << "                      - -" << std::endl;
    std::cout << "Dead.Dead.The hangman is dead!You lose!" << std::endl;
    return 0;
}
}


texts: Random permutation with defined order of last occurrences

texts:
This Python function takes two arguments:

chr_list which is a mutable sequence of characters c
chr_counts which maps to each character c the number of occurrences n

For each character c in chr_list, it inserts this character into the list before its last occurrence n-1 times, where n equals chr_counts[c]. The resulting list contains chr_counts[c] occurrences of each character c, and the order of last occurrences is preserved.

def insert_repetitions_before(chr_list, chr_counts):

  for c, num_occurences in chr_counts.items():
    num_repeats = num_occurences - 1
    orig_pos_last = chr_list.index(c)

    for curr_pos_last in range(orig_pos_last, orig_pos_last+num_repeats):
      random_pos_before_last = random.randint(0, curr_pos_last)
      chr_list.insert(random_pos_before_last, c)

Example output:

chr_list = ['c','o','d','e']
chr_counts = {'c': 3, 'o': 1, 'd': 2, 'e': 2}
>>> insert_repetitions_before(chr_list, chr_counts)
>>> chr_list
['c', 'd', 'c', 'c', 'e', 'o', 'd', 'e']

I want to make it more efficient. Currently its time complexity is O(n*m), n being the number of distinct characters and m the average number repetitions. Perhaps something like random.shuffle on a list containing all characters with repetitions, followed by some reordering?

(I'm not sure whether this is the right site to ask, since this question isn't quite specific to Python. Maybe I'll move it to CS.)


texts: I want to most efficiently use array values and variables in a WordPress template while abiding by PHP/WordPress best practices and standards

texts:
Is it better to validate and put an array value into a variable at the top of a file or to check the array value directly right before output in the file?
I work at a WordPress shop and we have a function that some devs commonly use to check the value of indexes in an array of custom field values:
//Check if an array has a key and return its value if so
function pkav($arr,$key){
    return isset($arr[$key]) ? $arr[$key] : false;
}

This leads to the following code in a template:
<?php
    $options = get_fields('options');
    $footer_text = pkav($options, 'footer_text');
    $footer_button = pkav($options, 'footer_button');
?>

<?php if ( $footer_text || $footer_button ) : ?>

        <?php if( $footer_text ) : ?>

<?php echo esc_html( $footer_text ); ?>

        <?php endif; ?>
        <?php if( $footer_button ) : ?>
            <?php pk_output_button( $footer_button ); ?>
        <?php endif; ?>

<?php endif; ?>

Some devs think this is more readable and a better way to code and check values/variables. It also allows us to neatly declare all variables at the top of a file so we immediately know what variables are used in a given template/template part. We have other devs who think pkav is unnecessary and an incorrect way to use variables. They'd rather see code like this:
<?php
    $options = get_fields('options');
?>

<?php if ( ! empty( $options['footer_text'] ) || ! empty( $options['footer_button'] ) ) : ?>

        <?php if( ! empty( $options['footer_text'] ) ) : ?>

<?php echo esc_html( $options['footer_text'] ); ?>

        <?php endif; ?>
        <?php if( ! empty( $options['footer_button'] ) ) : ?>
            <?php pk_output_button( $options['footer_button'] ); ?>
        <?php endif; ?>

<?php endif; ?>

Is there a right answer on what should be used in terms of php/wordpress/programming best practices/standards? The pkav functions seems to create more readable code by eliminating duplicate empty() checks and shortening each line but using only empty() checks seems to prevent creating extra variables.


texts: Function to ensure that at least one choice is selected

texts:
First here is my settings object below. insight, spike and momentum are binded to 3 checkboxes in the markup. The objective here is to prevent the user from deselecting all choices, 1 choice must remain selected.

var settings = {
    user_id            : 0,
    insight            : true,
    spike              : true,
    momentum           : true,
    all_tickers        : true,
    errorMsg           : false,
    port_tickers       : [],
    fav_tags           : [],
    sensitivity        : 'medium',
    email_notification : true
};

So what I'm doing below is I create an Array with just the 3 keys from the settings object I want. Next I filter that array down to only the keys that are set to true. Next if the checkbox model is the same as the last item in the trueFilters Array I can then send back errorMsg = true.

function updateFilters(type) {
    settings[type] = !settings[type];

    // Create Array of filters that are true
    var filterKeys = _.map(settings, function(filter, key) {
        if (key === 'insight' || key === 'spike' || key === 'momentum') {
            if (filter) {
                return key;
            } else {
                return null;
            }
        } else {
            return null;
        }
    });

    // Remove any filters that are null/false
    var trueFilters = _.remove(filterKeys, function(n) {
        return n != null;
    });

    // If this filter is the last, prevent user from unselecting
    if (trueFilters.length === 0) {
        settings[type] = !settings[type];
        settings.errorMsg = true;
    }
}


texts: Detecting the attachment of a DataContext

texts:
In our application the views and the viewmodels are created in parallel to increase the performance and when the viewmodel is created it is attached to the datacontext.

While there is no datacontext the view shows an indefinite progressbar. To hide it we use the following code:

    <!-- Loading background. It gets removed when the datacontext is attached -->
    <Border Visibility="{Binding IsDataContextLoaded, Converter={StaticResource NegatedBooleanToVisibilityConverter}, Mode=OneWay, FallbackValue=Visible}" >
        <views1:CircularProgressBar Visibility="Visible" />
    </Border>

And the viewmodel has the following code:

    /// <summary>
    /// Gets a value indicating whether the datacontex has been loaded or not
    /// </summary>
    /// <remarks>If the view can reach this property it means that the datacontext
    /// has been loaded.</remarks>
    public bool IsDataContextLoaded
    {
        get
        {
            return true;
        }
    }

The solution looks a bit weird to me, any ideas that are more elegant?


texts: Best practice for lining up PHP syntax in HTML page

texts:
I'm using Codeigniter but this goes for any project in PHP. Let's say I have the following code in my view. I've been struggling, trying to figure out how best to indent and display PHP code within standard HTML code.

...
...

    <?php
        if ($this->session->flashdata('message')) {
            ...
            ...
    ?>

            ...
            ...

    <?php
        }
    ?>

So notice how I nested HTML within the PHP code by escaping w/ the PHP syntax. This can get out of hand if you have lines and lines of code. I'm using Komodo and I've enabled "Indentation Guidelines" but even with that, most of my code doesn't line up. So my question is, how best to handle this?

I've actually resorted to keeping the PHP marker <?php ?> to the far left and not indenting them. Seems to work so far ...


texts: Performance: getting first value from comma delimited string

texts:
I've got a string that has values that are delimited by comma's, like so:

$var = '1,23,45,123,145,200';

I'd like to get just the first value, so what I do is create an array from it and get the first element:

$first = current(explode(',', $var));

Fine enough. But this string can sometimes contain perhaps hundreds of values. Exploding it into an array and only using the first one seems kind of a waste. Is there a smarter alternative which is also more performant/less wasteful? I'm thinking some sort of regex or trimming, but I'm guessing that could be actually slower...


texts: Rails configuration variants for production / development environments

texts:
How can duplication be removed from this?

class Authentication
  PROVIDERS = if Rails.env.production?
                %w(weibo open_wechat wechat)
              else
                %w(weibo open_wechat wechat developer)
              end.freeze
end


texts: Data validation for preventing blank entries

texts:
I want to create a validation wherein blank entries will not be accepted. So if I call this code:

entry[i].setName(JOptionPane.showInputDialog("Enter Name: "));
if the entry is blank, it will not be accepted and an error will prompt:

it cannot accept blank entries. Of course it could easily remedied with this code:

String name = JOptionPane.showInputDialog("Enter Name: ");
 while (name.equals("")){
       JOptionPane.showMessageDialog(null, "Cannot accept blank entries!");
       name = JOptionPane.showInputDialog("Enter Name: ");
 }

but if I want to validate 100 fields that I don't want to have a blank entry, then my code will be messy and long.

How could I do it better? I've read about using getters and setters or the try-catch methods to do the validation but I don't know if this kind of validation is applicable. And I don't know how I can do it. And if it is applicable, would I be violating the Model-View-Controller concept if I included a JOption message dialog box on my getter and setter methods? What code does programmers usually use in doing blank entries validation?


texts: Send an inbound Enquiry to a Users registered Twitter Account to notify them of its arrival

texts:
This follows on from an earlier CR Question. - The reasoning behind which suggestions were taken on / which were not taken on board are no longer relevant as this is supposed to be, from my understanding, a distinct question that is capable of standing alone should anyone come across it.

Background

An enquiry is posted from a "Contact Me widget" on a registered user's 3rd party domain to a processing queue, this is one of the jobs that is triggered via an event handler that batch processes the queue and spawns events containing any new Enquiry Identifiers since the last time the queue was processed.

<?php

namespace App\Listeners\Enquiry;

use App\Events\NewEnquiryEvent;
use App\Models\Stores\Enquiry;

class TweetNewEnquiry
{
    /**
     * On enquiry event send tweet notifying the Enquiry target,
     * if applicable.
     *
     * @param NewEnquiryEvent
     *   The new enquiry event object.
     */
    public function handle(NewEnquiryEvent $event) : void
    {
        $enquiry_ids = (array) $event->body->id;

        $enquiries_to_tweet = Enquiry::find($enquiry_ids)->filter(function($enquiry) {
            return $enquiry->canTweet() && $enquiry->shouldTweet();
        });

        $enquiries_to_tweet->each->tweet();
    }
}


texts:
I am fairly new to C++ and programmed a maze game as an exercise. However, looking at it I can see it can be improved a lot. These are my requests if you don't mind:

I do not want to use the library <conio.h>.
I want to use another method instead of system("CLS").
This code is old; I think it has many unsafe codes in it and I cannot get used to C++11, C++17 etc. If you can help me update this game to the newer variants of C++, I would be more than happy.
In main function I just want to use function calling, so an Update() method would be nice.
OOP is highly appreciated.
Please do not hesitate to use advanced C++ like Lambda Expressions, auto type declarations etc. (see number 3). I don't know them yet, but I will try to understand.
Criticize like there is no tomorrow!

//maze game in console

#include <iostream>
#include <conio.h>
#include <stdlib.h>

#define KEY_UP 72
#define KEY_DOWN 80
#define KEY_LEFT 75
#define KEY_RIGHT 77

// S: Start
// #: Wall
// .: Space
// F: Finish
// P: Player

const char maze[5][5]={{'#','S','#','#','#'},
                       {'#','.','.','#','#'},
                       {'#','#','.','#','#'},
                       {'#','.','.','.','#'},
                       {'#','#','#','F','#'}};

void Clear(){
    system("CLS");//clear console
}
void InputHandle(int move, int &pX, int &pY){
    switch(move=getch()){
            case KEY_UP:
            if( pY-1 >= 0 ){
                if(maze[pY-1][pX] != '#'){//if it is not the limit or it is not the wall(#) move player
                pY--;
            }
        }
        break;

        case KEY_DOWN:
        if( pY+1 <= 4 ){
            if(maze[pY+1][pX] != '#'){
                pY++;
            }
        }
        break;

        case KEY_RIGHT:
        if( pX+1 <= 4 ){
            if(maze[pY][pX+1] != '#'){
                pX++;
            }
        }
        break;

        case KEY_LEFT:
            if( pX-1 >= 0 ){
            if(maze[pY][pX-1] != '#'){
                pX--;
            }
        }
}
}
void Display(int &pX, int &pY){
for(int i=0;i<5;i++){
    for(int j=0;j<5;j++){
        if(j==pX && i==pY){//instead of the maze char, put player's 'P'
            std::cout<<"P ";
            continue;
        }
        std::cout<<maze[i][j]<<" ";
    }
    std::cout<<"\n";
}
}
bool CheckWinCondition(int &pX, int &pY){
if(pX==3 && pY ==4){
    return true;
}
return false;
}

int main(){

//movement
int playerPosX=1;
int playerPosY=0;
int movement;

while(!CheckWinCondition(playerPosX,playerPosY)){//if player is not in the finish, loop
    Display(playerPosX, playerPosY);//Show current maze
    InputHandle(movement, playerPosX, playerPosY);//take input
    Clear();//Clear the screen
}
std::cout<<"Congrats, you finished the maze!";

}


texts: In Java: convert an array of floats to bytes and vice versa

texts:
I'm just returning to Java after a multi-decade hiatus -- there are some nice new packages, such as java.nio.
I need to convert an array of floats into bytes and vice versa.  The floatToBytes() function feels okay, but I'm pretty certain that bytesToFloats() could be implemented better.  Thoughts?
(P.S.: ignore the public, protected etc -- this code is wrapped inside a class...)
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

    protected static final int BYTES_PER_FLOAT = Float.SIZE / 8;

    public static byte[] floatsToBytes(float[] floats){
        ByteBuffer buffer =
                ByteBuffer.allocate(BYTES_PER_FLOAT * floats.length).
                order(ByteOrder.BIG_ENDIAN);
        for (float f : floats) {
            buffer.putFloat(f);
        }
        return buffer.array();
    }

    protected static float[] bytesToFloats(byte[] bytes) {
        if (bytes.length % BYTES_PER_FLOAT != 0) {
            throw new RuntimeException("Illegal length");
        }
        ByteBuffer buffer = ByteBuffer.wrap(bytes).order(ByteOrder.BIG_ENDIAN);
        int n_floats = bytes.length / BYTES_PER_FLOAT;
        float[] floats = new float[n_floats];
        for (int i=0; i<n_floats; i++) {
            floats[i] =  buffer.getFloat(i * BYTES_PER_FLOAT);
        }
        return floats;
    }

I also note that there's a FloatBuffer class -- would that be appropriate here?


texts:
I'm starting to play with F# to do some data parsing and I was able to create a function to group an array of string into sub groups. The code looks like this:

let breakBy lines pattern =
    let rec breakByRec lines pattern acc =
        match lines with
        | [] -> acc
        | head::tail ->
            match pattern head with
            | true ->
                let newGroup = [head]
                let newList = newGroup :: acc
                breakByRec tail pattern newList
            | false ->
                let lastGroup = List.head acc
                let newGroup = head :: lastGroup;
                let newList = newGroup :: List.tail acc
                breakByRec tail pattern newList
    breakByRec lines pattern [[]]

However, I feel that it could be improved specially regarding the way I handle intermediate values when concatenating the lists and the data structure used to return the grouped data.

The goal, at the end, is to insert each of these "groups" as single entities in the database. Is there a more suitable data structure that I should take a look?

Below is a sample ready to be used and an example output.

let data = [
    "Name=John"; "Age=29"; "City=San Francisco";
    "Name=Jane"; "Age=28"; "City=New York";
    "Name=Mike"; "Age=35"; "City=Miami"
]

let matchName line = Regex.IsMatch(line, "^Name=")
let people = breakBy data matchName

printfn "%A" people

/*
The output looks like this:

val people : string list list = [
   ["City=Miami"; "Age=35"; "Name=Mike"];
   ["City=New York"; "Age=28"; "Name=Jane"];
   ["City=San Francisco"; "Age=29"; "Name=John"];
   []
]
*/

Any suggestions are appreciated.


texts: Improving Makefile and general C++ project structure

texts:
I am a single developer on a numerics project. As it is growing, I would like to improve

the Makefile
the general organisation of the project
structuring of the files
workflow

As it stands now I have a few classes (where a few depend on each other) and a main.cc. In total maybe 20 files. From that the executable is build via make and ./projectName creates data files, which are later processed with gnuplot script files. This whole process can also be compressed in a shell script run.sh.

I am working under Linux using gnu make and g++ compiler.

What bothers me is:

As I add new classes make takes more and more time.
Everything is build from scratch each time make runs, even if  only one class file is changed.
Related to that I have seen others using a build/ directory where object files files are stored. I haven't used .obj files so far. Does that solve the problem of (2.) and if yes how do I create them using make?
A debug and release build would be nice too, but I have seen questions on that on Stack Overflow, so I'll get to that.

What I have is the following:

Dir Tree

ProjectName
|+data/     <-- data files generated by program
|+scripts/  <-- scripts that handle data processing
|~includes/
| |-headerClass1.h
| |-headerClass2.h
| |-...
| |-main.h
| |-parameters.h
|~src/
| |-main.cc
| |-class1.cc
| |-class2.cc
| |...
|-Makefile
|-tags
|-projectname <--executable

Makefile

workdir:=$(shell pwd)

SRCS =  $(workdir)/src/main.cc   \
          $(workdir)/src/class1.cc \
          $(workdir)/src/class2.cc \
                ...

INCLUDE = -I$(workdir)/include/\
                    -I$(workdir)/src/

CTALL = $(workdir)/include/*\
                $(workdir)/src/*

CTAGS = ctags

DEL = /bin/rm -f

RESULT = projectname
CC = g++
LIBS= -lm -lboost_timer -lboost_filesystem -lboost_system
OPT = -O3 -Wall  -ggdb -D__STDC_FORMAT_MACROS -std=c++0x -fipa-matrix-reorg

all: clean $(RESULT) ctags

$(RESULT): $(SRCS)
    $(CC) $(LIBS) $(OPT) $(INCLUDE) $(SRCS) -o $@

# Rules for generating the tags.
# #-------------------------------------
ctags: $(CTALL)
        $(CTAGS) $(CTALL)

clean:
    @echo "cleaning ..."
    $(DEL) $(RESULT)


texts:
I have been working on a certain task these days and after several hours of torture, I have done it! However, I believe the code that I have "crafted" is quite difficult to be understood and to be honest, I wouldn't be able to understand it if I wasn't the one who made it. Anyways, this is my code. I would like to receive some advice about what I could do to make it a little bit more simple and, by any chance, shorter:

 using System;
 class BitExchangeAdvanced
  {
    static void Main()
{
    int  num1, num2,  p, q, k, loop;
    uint n, n1, bit;
    while (true)
    {
     // input number

        Console.WriteLine("Input n:");
        if (uint.TryParse(Console.ReadLine(), out n))
        {
            if (n >= 0)
            {
                break;
            }
        }
    }

    // input first position
    while (true)
    {
        Console.WriteLine("Input p:");
        if (int.TryParse(Console.ReadLine(), out p))
        {
            if (p >= 0)
            {
                break;
            }
        }
    }

    // input second position

    while (true)
    {
        Console.WriteLine("Input q:");
        if (int.TryParse(Console.ReadLine(), out q))
        {
            if (q >= 0)
            {
                break;
            }
        }
    }

    // input the limit
    while (true)
    {
        Console.WriteLine("Input k:");
        if (int.TryParse(Console.ReadLine(), out k))
        {
            if (k > 0)
            {
                break;
            }
        }
    }

        // check which position is first
    if (p>q)
    {
        num1 = q;
        num2 = p;
    }
    else
    {
        num1 = p;
        num2 = q;
    }

        // the loop is used in the "for" loop
    loop = num1;

        // check if the inpputs are valid for completing the operation
    if (num2 - num1 < k || num1 + k > 32 || num2 + k > 32)
    {
        Console.WriteLine("Overlapping or out of range");
    }
    else
    {

        // use "for" in order to complete the formula {p, p+1, …, p+k-1}
        for (num1 = loop; num1 < (loop + k); num1++)
        {
                bit = (n >> num1) & 1; // check the first value
                if (bit == 1)
                {
                    n1 = (bit << num1 + (num2 - num1)) | n; // input the value to its analog in num2
                    bit = (n >> num1 + (num2 - num1)) & 1; // complete the opposite operation
                    if (bit == 1)
                    {
                        n1 = (bit << num1) | n1;
                    }
                    else
                    {
                        n1 = ~((bit + 1) << num1) & n1;
                    }
                }
                else
                {
                    n1 = ~((bit + 1) << num1 + (num2 - num1)) & n; // same as the above but with different operations
                    bit = (n >> num1 + (num2 - num1)) & 1; // complete the opposite operation again
                    if (bit == 1)
                    {
                        n1 = (bit << num1) | n1;
                    }
                    else
                    {
                        n1 = ~((bit + 1) << num1) & n1;
                    }
                }
                n = n1;
                num2 = num2 + 1; // completes the second formula {q, q+1, …, q+k-1}
        }

        Console.WriteLine("The result is: {0}", n); // print the result
    }

  }
 }

The task is: Write a program that exchanges bits {p, p+1, …, p+k-1} with bits {q, q+1, …,q+k-1} of a given 32-bit unsigned integer. The first and the second sequence of bits may not overlap.


texts:
I'm currently working on the Student Attendance Record II problem:

  Given a positive integer \$n\$, return the number of all possible
  attendance records with length \$n\$, which will be regarded as
  rewardable. The answer may be very large, return it after mod 109 + 7.

  A student attendance record is a string that only contains the
  following three characters:

'A' : Absent.
'L' : Late.
'P' : Present.

  A record is regarded as rewardable if it doesn't contain more than one 'A' (absent) or more than two continuous 'L' (late).

The idea is to use Dynamic Programming to use the results for smaller n to calculate the results of bigger n. I'm currently keeping two lists - one to track L and P and the other - to track A:

MODULO = 10 ** 9 + 7

class Solution(object):
    def checkRecord(self, n):
        lates = [[0, 0, 0], [1, 1, 0]] + [[0, 0, 0] for _ in xrange(2, n + 1)]
        absences = [[0, 0, 0], [1, 0, 0]] + [[0, 0, 0] for _ in xrange(2, n + 1)]

        for i in xrange(2, n + 1):
            last_late_row = lates[i - 1]
            last_late_row_sum = last_late_row[0] + last_late_row[1] + last_late_row[2]

            last_absence_row = absences[i - 1]
            last_absence_row_sum = last_absence_row[0] + last_absence_row[1] + last_absence_row[2]

            lates[i] = last_late_row_sum % MODULO, last_late_row[0], last_late_row[1]
            absences[i] = ((last_late_row_sum + last_absence_row_sum) % MODULO, last_absence_row[0], last_absence_row[1])

        return (sum(lates[n]) + sum(absences[n])) % MODULO

The code works, but it does not pass the Time Limit requirements for big n. Even though, for n = 100000 LeetCode OJ runs it for only ~220ms.

How would you recommend to improve on running time?


texts: Singly Linked List implementation in Java

texts:
Here's my implementation of a Singly Linked List. Would appreciate a review.

public class SList<T> {

    private Node head;
    private int size;

    private class Node<T>{
       public  Node(){
            item = null;
            next = null;
        }
        public  Node(T item){
            this.item = item;
            this.next = null;
        }
        private T item;
        private Node next;
    }//end of node

    //constructor
    public SList(){
        head = null;
        size = 0;
    }
    public void add(T item){
        Node p = new Node(item);
        if(head == null){
            head = p;
            size++;
            return;
        }
        p.next = head;
        head = p;
        size++;
    }
    public boolean isEmpty(){
        return size == 0;
    }

    public int getSize(){
        return size;
    }
    public void remove(T item){
        Node current = head;
        while(current.next != item){

            if(current.next == null) {
                System.out.println("Item doesn't exist in the list:");
                return;
            }
            current = current.next;
        }
        current.next = current.next.next;
        size--;
    }

    public void insertAfter(T item1, T item2){
        Node current = head;
        Node p = new Node(item2);
        do{
            if(current == null) {
                System.out.println("Item doesn't exist in the list:");
                return;
            }
            current = current.next;
        }while(current.item != item1);
        Node q = current.next;
        current.next = p;
        p.next = q;
        size++;

    }

    public void insertBefore(T item1, T item2){
        Node current = head;
        Node p = new Node(item2);
        do{
            if(current.next == null) {
                System.out.println("Item doesn't exist in the list:");
                return;
            }
            current = current.next;
        }while(current.next.item != item1);
        Node q = current.next;
        current.next = p;
        p.next = q;
        size++;
    }
}


texts:
The idea I have in my head is this:

I am not sure if I need the index variable in consumer and producer.

Moreover, I want to know if it is OK like this (it seems to work), or it is just some stupid working code. Can it be more clever/efficient? Leave the readability for me.

My code will use the POSIX semaphore mutex in order to access the CS (which is writing/reading from the shared buffer of words).

full and empty are there to indicate if the buffer is full, or empty, so that we don't write a word if the buffer is full (we will overwrite the first word if we do that, before consumer reads it). Similarly, we don't want to read from any empty buffer!

When the producer is done, it sets a shared flag (initialized in 0). However, in the consumer side I had to check not only for the flag but for the values of full and empty.

The size of the buffer is 15. n (and the typo m) in the picture below is in our case 15.

Producer:

int index = 0;
size_t str_len;
while (fgets(buf, sizeof(buf), fp) != NULL) {
  str_len = strlen(buf);
  if(buf[str_len - 1] != '\n')
    printf("Didn't read whole line!\n");
  else {
    buf[str_len - 1] = '\0';
    sem_wait(&(sh->empty));
    sem_wait(&(sh->mutex));
    printf("|%s|\n", buf);
    strcpy(sh->words[index], buf);
    index = (index + 1) % N;
    sem_post(&(sh->mutex));
    sem_post(&(sh->full));
  }
}
sem_wait(&(sh->mutex));
sh->done = 1;
sem_post(&(sh->mutex));
int full_val;
sem_getvalue(&(sh->full), &full_val);
while(full_val++ <= 0) { // 'if' instead of 'while' should be OK too
  sem_post(&(sh->full));
}

Consumer:

int index = 0;
while(1) {
  sem_wait(&(sh->full));
  sem_wait(&(sh->mutex));
  int full_val, empty_val;
  sem_getvalue(&(sh->full), &full_val);
  sem_getvalue(&(sh->empty), &empty_val);
  if(empty_val != 15)
    printf("got: %s\n", sh->words[index]);
  if(sh->done == 1 && full_val == 0)
    break;
  index = (index + 1) % N;
  sem_post(&(sh->mutex));
  sem_post(&(sh->empty));
}

I am obliged to use sem_wait() and sem_post() by the way.

After the answers, I think that the main question is that if I can avoid the extra post in full semaphore after the while of producer is ended.

The problem if I remove the posting of full is in the following case:

Producer puts all the words in the buffer.
Scheduler gives the CPU to consumer.
Consumer reads all the words and gets suspended because on the full
semaphore.
Now, scheduler gives the CPU to producer which now sets the shared
flag to 1.
Scheduler goes back to consumer, which is suspended on full
semaphore, forever.


texts:
This is my implentation of Bucket Sort, but I see myself using way too many for loops, is this necessary?

  public static void bucketSort(Student[] students) {
    final String[] courses = { "IB", "IG", "IN", "IS", "IT" };
    final int amountOfBuckets = courses.length;
    final int n = students.length;

    if (n == 0) return;

    LinkedList<LinkedList<Student>> buckets = new LinkedList<>(); //create buckets
    for (int i = 0; i < amountOfBuckets; i++) {
        buckets.add(new LinkedList<>()); //fill bucketlist with buckets
    }

    for (int i = 0; i < courses.length; i++) {
        for (Student student : students) {
            if (student.getClassNumber().startsWith(courses[i])) {
                buckets.get(i).add(student);
            }
        }
    }

    for (int i = 0; i < amountOfBuckets; i++) {
        LinkedList<Student> studentLinkedList = buckets.get(i);
        Student[] s = studentLinkedList.toArray(new Student[studentLinkedList.size()]);
        insertionSortByClass(s);
        studentLinkedList = new LinkedList<>(Arrays.asList(s));
        buckets.set(i, studentLinkedList);
    }

    LinkedList<Student> result = new LinkedList<>();
    for (LinkedList<Student> bucket : buckets) {
        result.addAll(bucket);
    }

    for (int i = 0; i < result.size(); i++) {
        students[i] = result.get(i);
    }
}

As requested:

    public static void insertionSortByClass(Student[] student) {
    Student temp;
    for (int i = 1; i < student.length; i++) {
        for (int j = i; j > 0; j--) {
            if (student[j].compareTo(student[j - 1]) < 0) {
                temp = student[j];
                student[j] = student[j - 1];
                student[j - 1] = temp;
            }
        }
    }
}


texts: How to dynamically Generate Sort strings for Data Layer from Controller

texts:
I need help refactoring this code to dynamically generate a sort string that I can send to my data layer so that my database does the sorting instead of it happening in memory. I am using MVC4 with EF5 as my data layer.

public ActionResult InstanceSearch(int? page, string sortOrder, string computerName, string instanceName,
                                       string productName, string version)
    {
        int pageSize = 10;

        int pageNumber = (page ?? 1);
        if (pageNumber < 1)
        {
            pageNumber = 1;
        }

        if (string.IsNullOrEmpty(sortOrder))
        {
            sortOrder = "Computer";
        }

        ViewBag.CurrentSort = sortOrder;
        ViewBag.ComputerSort = sortOrder == "Computer" ? "ComputerDesc" : "Computer";
        ViewBag.InstanceSort = sortOrder == "Instance" ? "InstanceDesc" : "Instance";
        ViewBag.VersionSort = sortOrder == "Version" ? "VersionDesc" : "Version";
        ViewBag.ProductSort = sortOrder == "Product" ? "ProductDesc" : "Product";

        //IEnumerable<Instance> instances = ecuWebDataContext.Instances;

        IQueryable<Instance> instances
        = string.IsNullOrEmpty(computerName) == true ? ecuWebDataContext.Instances : ecuWebDataContext.Instances.Where(i => i.Computer.Name == computerName);

        if (string.IsNullOrEmpty(instanceName) == false)
        {
            instances = instances.Where(i => i.Name == instanceName);
        }

        if (!string.IsNullOrEmpty(productName))
        {
            ProductName product = (ProductName)Enum.Parse(typeof(ProductName), productName);
            instances = instances.Where(i => i.Product.Name == product);
        }

        if (!string.IsNullOrEmpty(version))
        {
            instances = instances.Where(i => i.Version == version);
        }

        switch (sortOrder)
        {
            case "Computer":
                instances = instances.OrderBy(i => i.Computer.Name);
                break;

            case "ComputerDesc":
                instances = instances.OrderByDescending(i => i.Computer.Name);
                break;

            case "Instance":
                instances = instances.OrderBy(i => i.Name);
                break;

            case "InstanceDesc":
                instances = instances.OrderByDescending(i => i.Name);
                break;

            case "Version":
                instances = instances.OrderBy(i => i.Version);
                break;

            case "VersionDesc":
                instances = instances.OrderByDescending(i => i.Version);
                break;

            case "Product":
                instances = instances.OrderBy(i => i.Product.Name);
                //instances = instances.OrderBy(i => Enum.Parse(typeof(ProductName), i.Product.Name));
                break;

            case "ProductDesc":
                instances = instances.OrderByDescending(i => i.Product.Name);
                //instances = instances.OrderByDescending(i => Enum.Parse(typeof(ProductName), i.Product.Name));
                break;
        }
        ViewBag.SortOrder = sortOrder;

        var instanceSearchModel = new InstanceSearchModel { ComputerName = computerName, InstanceName = instanceName };
        ViewBag.ComputerName = computerName;
        ViewBag.InstanceName = instanceName;
        ViewBag.ProductName = productName;
        ViewBag.InstanceCount = instances.Count();
        ViewBag.Version = version;
        return View(instances.ToPagedList(pageNumber, pageSize));
    }

I tried returning an IQueryable from the data layer, but then I run into connection problems because I never close it.


texts:
Is there any problem in checking PHP PDO connection this manner?

Is this way reliable?

function pdo_mysql()
{
$mysql_string  = "xxxxxxxxxxx";
$mysql_user = "xxxxxxxxxxx";
$mysql_pass = "xxxxxxxxxxx";

try
{
    $pdo_mysql = new PDO( $mysql_string, $mysql_user, $mysql_pass );
    $pdo_mysql->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
    $pdo_mysql->setAttribute( PDO::ATTR_EMULATE_PREPARES, false );
    return true;
}
catch( PDOException $ex )
{
    log_action( "pdo_mysql", $ex->getCode() . ": " . $ex->getMessage() );
    return false;
}
return false;

}

and then checking the return like this:

if( $pdo_mysql = pdo_mysql() )


texts:
I've been doing a lot of form submission using Ajax now and being used to it than having a normal submission. What's been troubling me is that I always ran with a double submission issue when the user clicks twice the submit button to make sure hey hit it.

One way I handle it is by using a flag:

ajaxIsLoading = false; // initiate flag
function listItem() {
  // check if ajax is not loading anymore
  if(!ajaxIsLoading) {
    ajaxIsLoading = true;
    $.post( "/post")
      .done(function( data ) {
       // data successfully submitted
       // set flag to false since post is done
       ajaxLoading = false;
    });
  }
}

One problem I know using this is when your internet connection stops in the middle of it and didn't make through setting the flag back to false.

What I want to ask:

Is this a good way to handle this kind of circumstance?
Is it worth to check your network in case it went down so I can set the flag back to false knowing there's a very little chance it will happen?


texts: Provide true clock-modulus operation for arbitrary sign values

texts:
I wrote this template to do as stated in the title; did I miss anything?

template<typename T> T clockmod(T v, T m) //todo: test T is numeric
{
    typedef long double D;
    T t=(m-m); //zero default
    D dv=std::fabs((D)v);
    D dm=std::fabs((D)m);
    if ((dv>0.0)&&(dm>0.0))
    {
        int id=int(dv/dm);
        D d=(dm*id);
        D dr=(dv-d);

        if (v>0)
        {
            if (m>0) t=(T)dr;
            else if (m<0) t=(T)(dr-dm);
        }
        else if (v<0)
        {
            if (m>0) t=(T)(dm-dr);
            else if (m<0) t=(T)(-dr);
        }
    }
    return t;
}

Where:
v / m may be any numeric type;
m (the modulus base) always range from 0 to m, m<0 or m>0;
the sign of v indicates the 'direction of counting' round the clock, positive increments from 0, negative decrements from m


texts: Basic commenting structure for commenting on objects

texts:
I would dearly love some feedback on the model below.  It's a basic commenting structure where users can comment on a variety of objects in the model.  I have denormalised it to make querying simpler, but I'm not sure if I've over/under done it.  The model tests fine, but it all feels a little clunky.

#####################################################################
# Base ##############################################################
class Base():
    def __init__(self, **kwargs):
        self._ClassName = self.__class__.__name__
        self._Created = datetime.now()
        self.__dict__.update(kwargs)

    def __repr__(self):
        return '<%s>' % self.__class__.__name__

#####################################################################
# Comment ###########################################################
class Comment(Base):
    def __init__(self, username, person, comment, parent, **kwargs):
        self.Username = username
        self.Person = person
        self.Comment = comment
        self.Parent = parent
        self.__dict__.update(kwargs)

    def _save(self):
        #save to Comments
        db.Comments.save(self.__dict__)
        #save to parent collection
        parent_obj = db.dereference(self.Parent)
        query = {'_id':parent_obj['_id']}
        update = {'$addToSet':{'Comments':self.__dict__}}
        db[parent_obj['_Collection']].find_and_modify(query, update, safe=True)
        #save to people collection
        query = {'_id':self.Person.id}
        db.People.find_and_modify(query, update, safe=True)

    def _remove(self):
        #remove from Comments
        query = {'_id':self._id}
        db.Comments.remove(query, safe=True)
        #remove from parent collection
        query = {'Comments._id':self._id}
        update = {'$pull':{'Comments':self.__dict__}}
        db[self.Parent.collection].find_and_modify(query, update, safe=True)
        #remove from people collection
        db.People.find_and_modify(query, update, safe=True)

    def __str__(self):
        return '%s - %s...' % (self.Username, self.Comment[:10])

person = {'Username':'foobarman'}
db.People.save(person, safe=True)

program = {'Title':'the foobar', '_Collection', 'Programs'}
db.Programs.save(program, safe=True)

comment = Comment(
                person['Username'],
                DBRef('People', person['_id']),
                'this is a comment about the foobar program',
                DBRef(program['_Collection'], program['_id']))

comment._save()

# find latest 10 comments
list(db.Comments.find().sort('_Created', -1).limit(10))

# find all comments for username
db.People.find_one({'Username':'foobarman'})['Comments']

# find all comments for program
db.Programs.find({'Title':'the foobar'})['Comments']

# find all comments for program by user
list(db.Comments.find({
                'Parent':DBRef(program['_Collection'], program['_id']),
                'Username':'foobarman'}))


texts: Python command-line Tic Tac Toe for two humans

texts:
I’d love some feedback on this human v. human, tic tac toe game I wrote in Python 2.7.10. I’d love to hear your thoughts on optimization and making the code simpler and more “pythonic”.

Also, I’m wondering if passing the player and turn variables around the way I have is the best approach, or if I should consider global variables (which is how I might do it in Javascript, in a closure).

# Command-line Tic Tac Toe for two humans written in Python.
# Play in a terminal by running 'python tictactoe.py'.

boxes = [ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ]
first_player = 'X'
turn = 1
winning_combos = [  [0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6],
                    [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6], ]

def print_board(initial=False):
    """ Print the game board. If this is the beginning of the game,
        print out 1-9 in the boxes to show players how to pick a
        box. Otherwise, update each box with X or 0 from boxes[].
    """
    print('''
             {} | {} | {}
            -----------
             {} | {} | {}
            -----------
             {} | {} | {}
        ''').format(*([x for x in range(1, 10)] if initial else boxes))

def take_turn(player, turn):
    """ Create a loop that keeps asking the current player for
        their input until a valid choice is made.
    """
    while True:
        box = raw_input('Player %s, type a number from 1-9 to select a box: ' % player)

        try:
            box = int(box) - 1 # subtract 1 to sync with boxes[] index numbers
            if 0 <= box <= 8:
                if boxes[box] == ' ': # initial value
                    boxes[box] = player # set to value of current player
                    break
                else:
                    print('That box is already marked, try again.\n')
                    continue
            else:
                print('That number is out of range, try again.\n')
                continue

        except ValueError:
            # Not an integer
            print('That\'s not a valid number, try again.\n')
            continue

def switch_player(turn):
    """ Switch the player based on how many moves have been made.
        X starts the game so if this turn # is even, it's 0's turn.
    """
    current_player = '0' if turn % 2 == 0 else 'X'
    return current_player

def check_for_win(player, turn):
    """ Check for a win (or a tie). For each combo in winning_combos[],
        count how many of its corresponding squares have the current
        player's mark. If a player's score count reaches 3, return a win.
        If it doesn't, and this is already turn # 9, return a tie. If
        neither, return False so the game continues.
    """
    win = False
    tie = False
    if turn > 4: # need at least 5 moves before a win is possible
        for x in range(len(winning_combos)):
            score = 0
            for y in range(len(winning_combos[x])):
                if boxes[winning_combos[x][y]] == player:
                    score += 1
                if score == 3:
                    win = True

        if turn == 9:
            tie = True

    return win, tie

def play(player, turn):
    """ Create a loop that keeps the game in play
        until it ends in a win or tie
    """
    while True:
        take_turn(player, turn)
        print_board()
        win, tie = check_for_win(player, turn)
        if win or tie:
            if win:
                print('Game over. %s wins!\n' % player)
            else:
                print('Game over. It\'s a tie.\n')
            break
        turn += 1
        player = switch_player(turn)

# Begin the game:
print('\n\nWelcome to Tic Tac Toe for two humans!')
print_board(initial=True)
play(first_player, turn)


texts: Recovering permutation from its image sequence

texts:
Recently while practicing I came across this problem , here is an excerpt from it,

  A permutation of the numbers 1, ..., N is a rearrangment of these
  numbers. For example

  2  4  5  1  7  6  3  8

  is a permutation of 1,2, ..., 8. Of course,

  1  2  3  4  5  6  7  8

  is also a permutation of 1, 2, ..., 8.

  Associated with each permutation of N is a special sequence of
  positive integers of length N called its inversion sequence. The ith
  element of this sequence is the number of numbers j that are strictly
  less than i and appear to the right of i in this permutation. For the
  permutation

  2  4  5  1  7  6  3  8

  the inversion sequence is

  0  1  0  2  2  1  2  0

  The 2nd element is 1 because 1 is strictly less than 2 and it appears
  to the right of 2 in this permutation. Similarly, the 5th element is 2
  since 1 and 3 are strictly less than 5 but appear to the right of 5 in
  this permutation and so on.

  As another example, the inversion sequence of the permutation

  8  7  6  5  4  3  2  1

  is

  0  1  2  3  4  5  6  7

  In this problem, you will be given the inversion sequence of some
  permutation. Your task is to reconstruct the permutation from this
  sequence.

I cooked up two solutions but both fail to deliver the result in time for the last three testcases,

here is the code,

Solution 1

#include <iostream>
#include <vector>

int main(){
    int n;
    std::cin >> n;
    std::vector<int>nums(n);
    int key;

    for( int k = 0; k < n; k++ ){
        std::cin >> key;
        int value = k+1;
        int i = 0;
        for(i = 0; i < key; i++){
            int j = k - i;
            nums[j] = nums[j - 1];
        }
        nums[k - i] = value;
    }

    for(int i = 0;i < n;i ++){
        std::cout << nums[i] << " ";
    }

    std::cout << std::endl;

return 0;
}

Simple and easy to understand , get the key and shift the integers to right to accommodate the new integer.

Solution 2

#include <iostream>
#include <vector>

int main(){
    int n;
    std::cin >> n;
    std::vector<int>nums(n,0);
    std::vector<int>inverse(n);

    for(int k = 0; k < n; k++ ){
        std::cin >> inverse[k];
    }

    for(int i=n-1;i>=0;i--){
        int onRight = inverse[i];
        int pos = i;
        for(int j=n-1;j>=0;j--){
            if(nums[j] == 0){
                pos = j;
                break;
            }
        }
        while(onRight){
            if(nums[pos] == 0){
                onRight--;
            }
            pos--;
        }
        if(nums[pos] != 0){
            for(int j=pos;j>=0;j--){
                if(nums[j] == 0){
                    pos = j;
                    break;
                }
            }
        }
        nums[pos] = i+1;
    }

    for(int i = 0;i < n;i ++){
        std::cout << nums[i] << " ";
    }

    std::cout << std::endl;

return 0;
}

This one is a little bit complicated in code but it follows a simple concept that push the integer from back , if the block is empty then decrement the number small of integers right of it , if not skip it to the next block and fill the array.

Both the solutions take almost same time , is there any better approach for it available?

Here are the testcases.


texts:
I was wondering wether my implementation of the PreferenceService below is thread safe or could cause memory leaks.

Android Studio gives me the warning "Do not place Android context classes in static fields". But since this warning is known to show in some cases where it does not really apply I am not sure if this is actually one of those cases. Replacing this._context = context; with this._context = context.getApplicationContext(); removes the warning...

Is there anything else that should stop me from using this in my release build?

package my.package.service;

// Android
import android.content.Context;
import android.content.SharedPreferences;

// Android X
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;

// Internal dependencies
import my.package.R;

public class PreferenceService
{
    /* SINGLETON */

    private static PreferenceService instance;

    /* ATTRIBUTES */

    private Context _context;
    private SharedPreferences _preferences;

    /* LIFECYCLE */

    /**
     * TODO
     * @param context
     */
    private PreferenceService(@NonNull Context context)
    {
        this._context = context;
        this._preferences = PreferenceManager.getDefaultSharedPreferences(this._context);
    }

    /**
     * TODO
     * @return
     */
    @NonNull
    public static synchronized PreferenceService create(@NonNull Context context)
    {
        if(PreferenceService.instance == null)
        {
            PreferenceService.instance = new PreferenceService(context);
        }

        return PreferenceService.instance;
    }

    /**
     * TODO
     * @return
    */
    @NonNull
    public static PreferenceService use()
    {
        if(PreferenceService.instance != null)
        {
           return PreferenceService.instance;
        }
        else throw new IllegalStateException("PreferenceService must be created before usage.");
    }

    /* GETTER & SETTER */

    /**
     * TODO
     * @return
     */
    public boolean getNightModePreference()
    {
        return this._preferences.getBoolean(this._context.getString(R.string.preference_key_night_mode), false);
    }

    /**
     * TODO
     * @param newNightModePreferenceValue
     * @return
     */
    public void setNightModePreference(boolean newNightModePreferenceValue)
    {
        this._preferences.edit().putBoolean(this._context.getString(R.string.preference_key_night_mode), newNightModePreferenceValue).apply();
    }
}


texts: Shortening Script - Add new class/css to an li in setIntervals

texts:
I am currently working on a site where I have a bunch of tiles "fly in" to the screen.  I need to add a class to each tile on a delay so they come in one after another.  I have the following code that works, but if I want to add more tiles, I will have to edit the jQuery each time.

Is there a way to trim this script down so I don't have to manually add new animations to the new tiles?

function tilesAnimation() {

    setInterval(function () {
        $("ul.homepageTabs li").eq(0).css("display", "inline-block");
        $("ul.homepageTabs li").eq(0).addClass('animated fadeInDown');
        $(".loader").fadeOut();
    }, 1800);
    setInterval(function () {
        $("ul.homepageTabs li").eq(1).css("display", "inline-block");
        $("ul.homepageTabs li").eq(1).addClass('animated fadeInDown');
    }, 2100);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(2).css("display", "inline-block");
        $("ul.homepageTabs li").eq(2).addClass('animated fadeInDown');
    }, 2400);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(3).css("display", "inline-block");
        $("ul.homepageTabs li").eq(3).addClass('animated fadeInDown');
    }, 2700);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(4).css("display", "inline-block");
        $("ul.homepageTabs li").eq(4).addClass('animated fadeInDown');
    }, 3000);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(5).css("display", "inline-block");
        $("ul.homepageTabs li").eq(5).addClass('animated fadeInDown');
    }, 3300);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(6).css("display", "inline-block");
        $("ul.homepageTabs li").eq(6).addClass('animated fadeInDown');
    }, 3600);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(7).css("display", "inline-block");
        $("ul.homepageTabs li").eq(7).addClass('animated fadeInDown');
    }, 3900);
    setTimeout(function () {
        $("ul.homepageTabs li").eq(8).css("display", "inline-block");
        $("ul.homepageTabs li").eq(8).addClass('animated fadeInDown');
    }, 4200);

}


texts:
Problem:

  Given an sorted array of N distinct integers, find floor value of input 'key'. Say, A = {1, 2, 3, 5, 6, 8, 9, 10} and key = 7, we should return 6 as outcome.

How can I optimize my solution?

     private static int CalclualteFloorValue(int[] _sortedarray, int l, int r, int key)
        {
            if (_sortedarray[l] == key)
                return -1;

            int m = -1;

            while (l<=r)
            {
                 m = (r+l)/ 2;

                if (_sortedarray[m] == key)
                {
                    return  _sortedarray[m - 1];

                }
                else if (_sortedarray[m] < key)
                {
                    l = m+1;
                }
                else
                {
                    r = m-1;
                }
            }

            return _sortedarray[m];

        }

  int _floorValue = CalclualteFloorValue(_sortedarray, 0, _sortedarray.Length - 1,7);


texts:
This class is similar to QDoubleValidator, but it improves slightly on the editing comfort. The comments mention "comma" but it's actually the decimal point of your locale (comma for me).

class DecimalValidator(QDoubleValidator):
    def __init__(self, *args):
        QDoubleValidator.__init__(self, *args)
        self.setNotation(QDoubleValidator.StandardNotation)
    def validate(self, input, pos):
        sep = self.locale().decimalPoint()
        if pos and (input[pos-1]==sep) and (sep in input[pos:]):
            # When we're left of the comma, and comma is pressed,
            # remove the inserted comma and move right of the old comma.
            input = input[:pos-1] + input[pos:]
            pos = input.find(sep)+1
        elif sep in input[:pos] and (len(input.split(sep)[1]) > self.decimals()):
            # When we're right of the comma, and all decimal places are used already,
            # go into overwrite mode (by removing the old digit)
            input = input[:pos] + input[pos+1:]
        return QDoubleValidator.validate(self, input, pos)


texts: Improvements for a C getline implementation

texts:
I wrote a function in C that reads an entire line from a stream into a dynamically allocated buffer. What would you suggest I should do to improve its performance? Also, are there any errors that could occur and are not handled?
This is the code:
#define ERRALLOC(ptr)                                        \
if (ptr == NULL) {                                           \
    printf("Unable to allocate memory for %s", #ptr);        \
    exit(1);                                                 \
}

#define PACK_SIZE 512

size_t readLine(FILE *istream, char **line_buffer, size_t *bufsize) {
    size_t line_size = 0;
    int eol_flag = 0;
    char temp_buffer[PACK_SIZE];
    while (fgets(temp_buffer, PACK_SIZE, istream) != NULL) {
        size_t temp_len = strlen(temp_buffer);
        line_size += temp_len;

        if (line_size+1 > *bufsize) {
            *bufsize = line_size+1;
            *line_buffer = realloc(*line_buffer, *bufsize * sizeof(char));
            ERRALLOC(*line_buffer)
        }

        if (temp_buffer[ temp_len - 1 ] == '\n') {
            temp_buffer[ temp_len - 1 ] = '\0';
            eol_flag = 1;
        }
        strcpy(*line_buffer + (line_size-temp_len), temp_buffer);

        if (eol_flag) break;
    }

    return line_size;
}


texts:
Ok, code reviewers, I want you to pick my code apart and give me some feedback on how I could make it better or more simple. Also its really hard to make this code work if preorder array contains duplicate. Any code/psuedocode is useful.

public class PreOrderTraversalBST {

    private TreeNode root;

    private static class TreeNode {
        TreeNode left;
        int item;
        TreeNode right;

        TreeNode (TreeNode left, int item, TreeNode right) {
            this.left = left;
            this.item = item;
            this.right = right;
        }
    }

    /**
     * QQ: is there any alternative for this ?
     */
    private static class Counter {
        int counter;

        Counter(int counter) {
            this.counter = counter;
        }

    }

    public void preOrderRecursive (int[] a) {
        root = dpPreOrderRecursive (a, new Counter(0), Integer.MIN_VALUE, Integer.MAX_VALUE );
    }

    private TreeNode dpPreOrderRecursive (int[] arr, Counter counter, int min, int max) {

        if (counter.counter < arr.length && arr[counter.counter] > min && arr[counter.counter] < max) {

            int item = arr[counter.counter];

            TreeNode treeNode = new TreeNode(null, item, null);

            counter.counter++;
            treeNode.left = dpPreOrderRecursive(arr, counter, min, item);
            treeNode.right = dpPreOrderRecursive(arr, counter, item, max);

            return treeNode;
        }
        return null;
    }

    public void preOrderWithStack (int[] arr) {

       final Stack<TreeNode> stack = new Stack<TreeNode>();
       root = new TreeNode(null, arr[0], null);
       stack.push(root);
       int i = 1;

       while (arr[i] < root.item) {
           TreeNode node = new TreeNode(null, arr[i], null);
           if (arr[i] < stack.peek().item) {
               stack.peek().left = node;
           } else {
               TreeNode temp = null;
               while (!stack.isEmpty() && arr[i] >= stack.peek().item) {
                   temp = stack.pop();
               }
               temp.right = node;
               stack.push(temp);
           }
           stack.push(node);
           i++;
       }

       TreeNode rightNode = new TreeNode(null, arr[i], null);
       root.right = rightNode;
       stack.push(rightNode);
       i++;

       while (i < arr.length) {
           TreeNode node = new TreeNode(null, arr[i], null);
           if (arr[i] >= stack.peek().item) {
               stack.peek().right = node;
               stack.push(node);
           } else {
               TreeNode temp = null;
               while (!stack.isEmpty() && arr[i] < stack.peek().item) {
                   temp = stack.pop();
               }
               temp.left = node;
               stack.push(temp);
           }
           stack.push(node);
           i++;
          }
        }
}

Complexity check. Does stack based solution account to O(nlogn) time comlexity or O(n2) ?


texts: Get title from database based on member country

texts:
I asked this question before. However, I realized that I had to edit some of my code after I got good answers. Therefore, I'm asking a new question here.

I have the following database:

Each member may have multiple addresses (1:n) stored in table address. It's possible that one member has multiple addresses within one country.
Further, each member may have  multiple titles (m:n) mapped in table title2memb. Each entry idRank has a name which can be found in title.
I want to get the first N members that have at least one address in the country "US"  and I want to display all their titles.
Here is working code, using two JOINS and two where statements for N=2:
<?php

$db       = new mysqli("localhost","root","","example");
$sql      = "SELECT DISTINCT m.name, m.id FROM member m
              INNER JOIN address a ON m.id = a.idMember AND a.country='US' LIMIT 2";
$membersResult   = $db->query($sql);

while($member = $membersResult->fetch_assoc()){
  $id            = $zeile['id'];

  echo $zeile['name'] . ": ";

  $sub_sql       = "SELECT t.name FROM title t INNER JOIN title2memb tm ON
                    t.id = tm.idRank AND tm.idMember='$id'";
  $sub_result    = $db->query($sub_sql);
  while($rank = $sub_result->fetch_assoc())
  {
    echo $rank['name'] . " ";
  }

  echo "<br>";
}

?>

And as a result I get:

Bernd: Bee
Tom: Bear Dog

Is it really necessary to have here 2 nested while clauses? Or can I get both in one SQL?
Some remarks:

I had to use the DISTINCT keyword in my first SQL, otherwise I would get Bernd twice.
I have avoided using prepared statements and encoding the input to make the code more readable. I know that the here presented version is vulnerable to XSS.


texts:
I am writing a small chunk of code (a module>?) that I will use to create a view on a page using angular. The angular directive will take care of generating the html.
The sole purpose of this module is expose a given month's data, specifically on what day it starts for the given year and how many days it has. I want to make this module as clean as possible and would appreciate anyfeedback.

function Calendar(month, year) {
var days = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
var months = [
    'January', 'February', 'March', 'April',
    'May', 'June', 'July', 'August', 'September',
    'October', 'November', 'December'
];
var daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];

this.getMonthData = function() {
    var startingDay = new Date(this.year, this.month, 1).getDay();
    var monthLength = daysInMonth[this.month];

    if (this.month === 1) {
        if ((this.year % 4 === 0 && this.year % 100 !== 0) || this.year % 400 === 0) {
            monthLength = 29;
            }
        }
    };
}


texts: Ruby script that deletes servers from Red Hat Satellite

texts:
This script uses the Red Hat Satellite v5.4 API to delete servers which are read in from a file. The servers are listed in the file by hostname but the Satellite API deletes servers by ID number. The script runs the getId call using the hostname and stores the ID ( val[0]["id"] ) in the system_ids array (assuming it is not empty). It then deletes the servers in bulk.

The script assumes the server name is in the host.sub-domain.domain format. One improvement that I can make is to check each hostname and kick it out if the format is not correct. This would make the need to test for an empty system_ids array prior to attempting to delete the servers.

I could also add some error handling, but that is low on my list of priorities.

It works as designed. I'm just hoping to get some tips on streamlining or improving the code.

#!/usr/bin/ruby

require "xmlrpc/client"
require "io/console"

print "Username: "
user = STDIN.gets.chomp
print "Password: "
pass = STDIN.noecho(&:gets).chomp
puts

# These are the parameters we use to create our XMLRPC client
params = {
  host:  "tcecapm1r6cm01.ecap.cciio",
  path:  "/rpc/api",
  use_ssl:  "false",
  user:  user,
  pass:  pass
}

# Get the file we are reading from the command line and
# initialize the array that is used for storing system IDs
server_list = ARGV[0]
system_ids = Array.new

# Create our client using the parameters above
client = XMLRPC::Client.new(params[:host],params[:path])

# Create our Satellite API session
session = client.call("auth.login",params[:user],params[:pass])

# Open the file containing the servers to be deleted and build
# an array of their system IDs for further processing
File.open(server_list, "r") do |file|
  file.each_line do |line|
    val = client.call("system.getId", session, line)
    if val.nil?
      next
    else
      system_ids.push(val[0]["id"]) unless val.empty?
    end
  end
end

client.call("system.deleteSystems", session, system_ids)


texts: Capitalize all words in sentence string in Ruby

texts:
I have created the following code:

def LetterCapitalize(str)
  str = str.split(" ").each {|word| word.capitalize!}
  str = str.join(" ")
  return str
end

This takes in a basic string and capitalizes the first letter of all of the words. It looks kind of awkward to reassign things to str twice. What is wrong with my style here, if anything at all?


texts: Check syntax (string and character comparison)

texts:
I would like to know if my function that checks if a string syntax is correct. It's currently very messy, but seems to do the job.

//Example Valid String
[12345678]
{
something
whatever
}

Function:

private static bool CheckIfSyntaxIsValid(string input)
        {
            int mode = 1;
            char last = ' ';
            foreach (char c in input)
            {
                if (last == '{' && c == '}')
                {
                    last = ' ';
                    mode = 1;
                    continue;
                }
                if (last == '{' && c == '{')
                    return false;

                if (last == '[' && c == ']')
                {
                    last = ' ';
                    mode = 2;
                    continue;
                }
                if (last == '[' && !Char.IsDigit(c))
                    return false;

                if (c == '[')
                {
                    if (mode == 2)
                        return false;
                    last = c;
                    mode = 1;
                }
                if (c == '{')
                {
                    if (mode == 1)
                        return false;

                    last = c;
                    mode = 2;
                }

                if (c == ']' || c == '}')
                    return false;
            }

            if (last != ' ')
                return false;

            return true;

        }

The rule is basically:

[] must contain only numbers/digits
It must start with [] before {}, and they must come after each other

So, [] {} [] {} etc. Anything else is simply invalid.

Okay, not everything else is invalid. Text outside of those are ignored,
so the only thing that matters is that the bracket orders are correct, etc.


texts: Basic console calculator with four operations

texts:
I'm an absolute beginner in programming, and Today I decided to put my knowledge to the test and create a basic c# calculator. I've Done it, but now I'm looking for ways to Make it more shorter and readible. If you Have any suggestions, please give them!

using System;

namespace lol
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hi! What is your name?");
            string name = Console.ReadLine();

            Console.WriteLine(name + " What do you wanna do");

            Console.WriteLine("Type \"+\" for addition");
            Console.WriteLine("Type \"-\" for subtraction");
            Console.WriteLine("Type \"*\" for multiplication");
            Console.WriteLine("Type \"/\" for division");

            string operation = Console.ReadLine();

            Console.Write("Now, Give me number one: ");
            double num1 = Convert.ToDouble(Console.ReadLine());

            Console.Write("Now give me number two: ");
            double num2 = Convert.ToDouble(Console.ReadLine());

            if (operation == "+")
            {
                Console.WriteLine(num1 + num2);
            }
            else if (operation == "-")
            {
                Console.WriteLine(num1 - num2);
            }

            else if (operation == "*")
            {
                Console.WriteLine(num1 * num2);
            }

            else
            {
                Console.WriteLine(num1 / num2);

            }

        }
    }
}


texts: Memory cache implementation with a static class inside a normal class

texts:
I'm trying to implement a cache available in a data provider (repository).

The data provider is a normal class, instanciated at every request made to the application.

The reason I have a static class is that I want all requests to share the same _lock object.

The data being cached doesn't change very often and is quite small (a few deserialized JSON documents) but they are often requested by other logic in the application.

Is this good design? I have test ran it under stress and it seems to work fine.

I think the locking in the Cache class should do what it is supposed to be doing (making sure data is not changed by two concurent requests and data that is being read is always up to date).

I also lock when reading from the database in the case where a request comes in and for some reason is slower than a second one (the first request would then populate the cache with possibly outdated data).

Are there any obvious flaws you can spot? Is the use of MemoryCache overkill in this case? I don't really need managing expiration and other options MemoryCache offers, so I'm split about just using a Dictionary.

public class DataProvider
{
    static SemaphoreSlim dbLock = new SemaphoreSlim(1);

    //This class has a bunch of methods to access the DB directly, when needed.

    /// <summary>
    /// Get items from the MemoryCache
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <returns></returns>
    public async Task<List<T>> GetCacheItems<T>() where T : IDocumentModel
    {
        if (Cache.Items<T>() == null)
        {
            await dbLock.WaitAsync();
            try
            {
                var items = await GetItemsFromDatabase<T>();
                Cache.SetItems(items);
            }
            finally
            {
                dbLock.Release();
            }
        }

        return Cache.Items<T>();

    }

    /// <summary>
    /// Update a cached item when DataProvider updates one
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="item"></param>
    /// <returns></returns>
    public async Task UpdateCacheItem<T>(string itemData) where T : IDocumentModel
    {
        var item = JsonConvert.DeserializeObject<T>(itemData);
        var cachedItems = await GetCacheItems<T>();

        if (cachedItems == null)
            throw new Exception($"Error retrieving cached items of type '{typeof(T).Name}'");

        var cachedItem = cachedItems.SingleOrDefault(x => x.Id == item.Id);

        if (cachedItem == null)
        {
            cachedItems.Add(item);
        }
        else
        {
            cachedItems.Remove(cachedItem);
            cachedItems.Add(item);
        }

        Cache.SetItems(cachedItems);

    }

    public static class Cache
    {
        private static object _lock = new object();
        private static DateTimeOffset offset = DateTimeOffset.UtcNow.AddYears(5);

        /// <summary>
        /// Retrieve items of specified type
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<T> Items<T>()
        {
            var itemKey = typeof(T).Name;

            lock (_lock)
            {
                return MemoryCache.Default.Get(itemKey) as List<T>;
            }

        }

        /// <summary>
        /// Load items in MemoryCache
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="items"></param>
        public static void SetItems<T>(List<T> items)
        {
            var itemKey = typeof(T).Name;

            lock (_lock)
            {
                MemoryCache.Default.AddOrGetExisting(itemKey, items, offset);
            }
        }
    }

}


texts: Sending large data package with TCP - winsock

texts:
A small struct is sent beforehand to the client that specifies package_size amount of data should be received which is what p->data_value_1 contains.

Server side:

void Server::sendDataSingleUser(char *data_in, int user, unsigned int package_size){
    package_size_sent_ = 0;
    FD_ZERO(&write_set_);
    FD_SET(sockets_[user], &write_set_);

    while(package_size_sent_ < package_size){
        timeout_.tv_sec = 3;
        timeout_.tv_usec = 0;
        i_result_ = select(0, 0, &write_set_, 0, &timeout_);

        // Socket free, send a package
        if(i_result_ > 0){
            i_result_ = send(sockets_[num_clients_], data_in+package_size_sent_, package_size - package_size_sent_, 0);
            // Move buffer pointer
            if(i_result_ > 0){
                package_size_sent_ += i_result_;
            }

            // send error
            if(i_result_ == SOCKET_ERROR){
                // Handle the error
            }
        }
        // Socket still bussy
        else{
            // Disconnect the client
        }
    }
}

Client side:

*size_p = new char[(unsigned int)p->data_value_1];
int temp_count = 0, data_received, package_size = p->data_value_1;

while(temp_count < package_size){
    data_received = recv(connect_socket_, size_p+temp_count, package_size - temp_count, 0);
    // Move buffer pointer
    if(data_received > 0){
        temp_count += data_received;
    }
}

What can be improved/what's incorrect?


texts: Project Euler 67 | Maximum sum path II reading from file

texts:
I tried to solve the Problem Euler 67 with golang, because I started to study Go recently.
This is my solution:
package main

import (
    "flag"
    "fmt"
    "io/ioutil"
    "os"
    "strconv"
    "strings"
    "time"
)

func calculateMaxPath(trianglePointer *[][]int, lines int) int {
    trisums := make([][]int, lines)
    triangle := *trianglePointer

    for row := lines - 1; row > -1; row-- {
        trisums[row] = make([]int, row+1)
        for col := 0; col < row+1; col++ {
            if row == lines-1 {
                trisums[row][col] = triangle[row][col]
            } else {
                if trisums[row+1][col] > trisums[row+1][col+1] {
                    trisums[row][col] = triangle[row][col] + trisums[row+1][col]
                } else {
                    trisums[row][col] = triangle[row][col] + trisums[row+1][col+1]
                }
            }
        }
    }

    return trisums[0][0]
}

func openFile() (*[][]int, int) {
    flag.Parse()

    ifile := flag.Arg(0)

    if len(ifile) == 0 {
        println("No File Specified")
        os.Exit(1)
    }

    content, err := ioutil.ReadFile(ifile)

    if err != nil {
        println("Error reading", ifile)
        os.Exit(1)
    }

    strRows := strings.Split(string(content), "\n")
    content = nil

    lines := 0
    for i := len(strRows) - 1; i > 0; i-- {
        if lines == 0 && strRows[i] != "" {
            lines = i + 1
            break
        }
    }

    var strs []string

    pyramid := make([][]int, lines)
    for row := 0; row < lines; row++ {
        strs = strings.Fields(strRows[row])
        pyramid[row] = make([]int, len(strs))

        for col := 0; col < len(strs); col++ {
            pyramid[row][col], _ = strconv.Atoi(strs[col])
        }
    }

    return &pyramid, lines
}

func main() {
    start := time.Now()

    pyramid, lines := openFile()

    greatestSum := calculateMaxPath(pyramid, lines)

    fmt.Printf("\nTotal sum: %v, Elapsed time: %v\n", greatestSum, time.Since(start))
}

What could be a better approach? Coud I use go routines to increase performance?


texts: Implementing use of 'with CustomClass() as foo' in own class with DB-Connection

texts:
I'm building a GameClient-Class in Python which handles user input and has to read from a database (MongoDb). I want to know if that is the best practice to implement it, so that I can use it with Python's with statement.

Because I want to use different functions of my Client class, __enter__ has to return self, so that I can use the instance of that class like normal. Is that best practice?

class Client(object):

    def __init__(self, playerid):
        self.MongoClient = MongoClient()
        self.db = self.MongoClient['worldbg-database']
        self.id = playerid

    def __exit__(self, exception_type, exception_val, trace):
        self.MongoClient.close()

    def __enter__(self):
        return self

    def handle_input(self, input):
    if input == "exit":
        return False

with Client("id") as GameClient:
    GameClient.select_my_tile(GameClient.get_my_tiles()[0]['_id'])
    while GameClient.handle_input(raw_input('command: ')):
        pass


texts: Getting target IDs from promotions related to an order item

texts:
I have a awful code with a big cyclomatic complexity. I have tried different variants, but haven't had good result. Please, help me to refactor this code:

public Set<String> getTargetIdsFromPromotion(String itemToRefundId, RepositoryItem orderItem) {
    Set<String> result = new HashSet<String>();
    List<RepositoryItem> relationships = getRelationships(orderItem);
    for (RepositoryItem relationship : relationships) {
        if (isValidShippingType(relationship)) {
            List<RepositoryItem> adjustments = getAdjustments(relationship);
            for (RepositoryItem adjustment : adjustments) {
                RepositoryItem promotion = getPromotion(adjustment);
                if (promotion != null){
                    Set<String> targetIds = getTargetIdsByQualifier(itemToRefundId, promotion);
                    if (!targetIds.isEmpty()) {
                        return targetIds;
                    }
                }
            }
        }
    }
    return new HashSet<String>();
}


texts:
I want to use structs as a container for data packets for asynchronous networking in C#. Found out that you can create a union style struct without the need to mark the struct itself as unsafe--instead marking the field as unsafe.
Example:
[StructLayout(LayoutKind.Explicit, CharSet = CharSet.Ansi, Size = 8, Pack = 4)]
struct DataPacketStruct {
    private unsafe fixed byte bytes[8];
    // Publicly accessible fields.
    public byte header;
    public int size;

    public void Serialize(ref byte[] buffer, int startIndex) {
        unsafe {
            for (int i = 0; i < 8; i++) buffer[startIndex + i] = bytes[i];
        }
    }

    public void Deserialize(byte[] buffer) {
        unsafe {
            for (int i = 0; i < 8; i++) bytes[i] = buffer[i];
        }
    }

    public int SizeOf() { unsafe { return sizeof(DataPacketStruct); } }
}

I know I need array out of bounds checking--but apart from that. Potential downsides or undefined behaviors? Or is this usage valid? Also are there any potential performance concerns or any alternatives with similar performance?
Also an issue I can see right off the bat is not having compile-time numeric constants like in C++. Unfortunately have to hard code in the field offsets and structure size because of this: Size = 8 and byte[8].


texts: Simple POST function in ClojureScript and Node.js

texts:
Node's HTTP library provides a handy shorthand function for GET requests. Something similar doesn't exist for POST requests. I'm trying to write one in ClojureScript that compiles to node-readable JavaScript.

In JavaScript (+ underscore.js) it would look like so:

var _ = require("underscore");
var url = require("url");
var http = require("http");

function postData (url_str, data, cb) {
   var parsed_url = url.parse(url_str);
   var options = _.extend(parsed_url, {method: "POST"});
   var req = http.request(options, cb);
   req.write(data);
   req.end();
}

postData("http://myurl:55555", "the data", function(res) {
   console.log(res.statusCode);
});

(Note: error handling should be added + passing the whole parsed_url object, extended by the method is maybe not necessary, but doesn't hurt either).

Now this should be transfered to ClojureScript. Here's an approach which technically works, however I'm asking myself if this is really the best solution:

(def url (node/require "url"))
(def http (node/require "http"))

(defn post-data [url_str data cb]
  (let [parsed_url (.parse url url_str)]
    (aset parsed_url "method" "POST")
    (let [req (.request http parsed_url cb)]
      (doto req
        (.write data)
        (.end)))))

(post-data "http://localhost:55555" "my data" #(println (.-statusCode %1)))

Does anybody have some comments/improvements for this?


texts: React Higher Order Components - export wrapped component or wrap it in parent?

texts:
I've been learning about about how to use context, and how to make a higher order component to provide context values through props.
So, I've created my HOC to pass down the props, and it looks like this, in a file called ConsumerWrapper.jsx:
import React from "react";
import {ThemeContext} from "../context/fakeContext";
import hoistNonReactStatic from 'hoist-non-react-statics';

export function ConsumerWrapper(WrappedComponent) {
    const EndComponent = props => {
        return (
            <ThemeContext.Consumer>
                {({theme, toggleTheme}) => (
                    <WrappedComponent {...props} theme={theme} toggleTheme={toggleTheme}/>
                )}
            </ThemeContext.Consumer>
        )
    };
    EndComponent.displayName = `ConsumerWrapper(${getDisplayName(WrappedComponent)})`;
    hoistNonReactStatic(EndComponent, WrappedComponent);
    return EndComponent;
}

function getDisplayName(WrappedComponent) {
    return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

Then I made a component which was made to be Wrapped, in WC.jsx:
import React from "react";
import {ConsumerWrapper} from "./ConsumerWrapper";

function WC(props) {
    const {theme, toggleTheme} = props;
    return (

hello world from WC

{props.secondaryMessage}

    )
}

export default ConsumerWrapper(WC);

As you can see, in that file I export the component already pre-wrapped. That way, in my other files, I can just use it like so:
import WC from "./components/WC";
...
return (<WC secondaryMessage="second message here"/>)
...

HOWEVER, it occurs to me that there's an alternative: that instead of exporting the wrapped component in WC, I wrap it in the files that use it. So my WC.jsx would look like this:
import React from "react";

export default function WC(props) {
    const {theme, toggleTheme} = props;
    return (

hello world from WC

{props.secondaryMessage}

    )
}

And then when I want to use it, I have to wrap it first:
import WC from "./components/WC";
import {ConsumerWrapper} from "./ConsumerWrapper";
const WrappedWC = ConsumerWrapper(WC);

...
return (<WrappedWC secondaryMessage="second message here"/>)
...

In general, is the second one preferred to the first? The second one allows me, in the future, to provide alternative (maybe even non-context related) props for theme and toggleTheme, so in the second one, the component seems less "bound to the implementation" so to speak, less coupled.
Was hoping I could get some advice on this. Thanks.


texts:
Here is my solution to Project Euler 23: Non Abundant Sums. I know I'm doing the Divisors function brute force, but I can't seem to get it to work any other way. Any improvements are welcome.

#include <iostream>
#include <vector>

//Calculates divisors
void Divisors(unsigned number, std::vector<unsigned> &result){
    for(unsigned a = 1; a < number; a++){
        if(number % a == 0){
            result.push_back(a);
        }
    }
}
//Calls for divisors and adds them
unsigned SumOfDivisors(unsigned number){
    unsigned result = 0;
    std::vector<unsigned> divisors;
    Divisors(number, divisors);
    for(unsigned a = 0; a < divisors.size(); a++){
        if(divisors[a] < number)
            result += divisors[a];
    }
    return result;
}
//Calls calculates the sum of divisors to see if it is Abundant
bool IsAbundant(unsigned number){
    if(SumOfDivisors(number)> number){
        return true;
    }
    else{
        return false;
    }
}
//pushes back abundant numbers
void Abundant(unsigned limit, std::vector<unsigned> &abunNumbers){
    for(unsigned a = 1; a < limit; a++){
        if(IsAbundant(a)){
            abunNumbers.push_back(a);
        }
    }
}

//Find's all number's that are the sum of two abundant numbers
void SumOfAbundant(unsigned limit, std::vector<unsigned> const& abunNumbers, std::vector<bool> &sumAbun){
    for(unsigned a = 0; a < abunNumbers.size(); a++){
        for(unsigned b = a; b < abunNumbers.size(); b++){
            if(abunNumbers[a]+abunNumbers[b] <= limit){
                sumAbun[abunNumbers[a]+abunNumbers[b]] = true;
            }
        else{
            break;
        }
        }
    }
}

int main(){
    const unsigned limit = 28123;
    unsigned result = 0;

    std::vector<unsigned>abunNumbers;
    Abundant(limit, abunNumbers);

    std::vector<bool>sumAbun(limit,false);
    SumOfAbundant(limit, abunNumbers, sumAbun);

    for(unsigned a = 0 ; a < sumAbun.size() ; a++){
        if(!sumAbun[a]){
        result += a;
        }
    }
    std::cout << result;
}