texts: Find 4 points which form a square with the biggest area

texts:
I have set of points on the coordinate plane. I need to find the 4 points which form a square with the biggest area.

I'm new in JavaScript so I'd like to get any suggestions about code style, patterns, code idioms, etc. Thank you in advance!

"use strict";

/*
 * Point
 */

(function() {
    function numbersEqual(a, b) {
        return Math.abs(a - b) < Number.EPSILON;
    }

    function Point(x, y) {
        this.x = x;
        this.y = y;
    }

    Point.distance = function(a, b) {
        return Math.sqrt((a.x - b.x) ** 2 + (a.y - b.y) ** 2);
    }

    Point.equal = function(a, b) {
        return numbersEqual(a.x, b.x) && numbersEqual(a.y, b.y);
    }

    Point.pointsFormsQuadrangle = function(a, b, c, d) {
        if (Point.equal(a, b) || Point.equal(a, c) || Point.equal(a, d))
            return false;

        if (Point.equal(b, c) || Point.equal(b, d))
            return false;

        if (Point.equal(c, d))
            return false;

        const center = new Point((a.x + b.x + c.x + d.x) / 4, (a.y + b.y + c.y + d.y) / 4);

        const ac = Point.distance(a, center);
        const bc = Point.distance(b, center);
        const cc = Point.distance(c, center);
        const dc = Point.distance(d, center);

        return numbersEqual(ac, bc) && numbersEqual(bc, cc) && numbersEqual(cc, dc);
    }

    Point.pointsFormsSquare = function(a, b, c, d) {
        if (!Point.pointsFormsQuadrangle(a, b, c, d))
            return false;

        const ab = Point.distance(a, b)
        const ac = Point.distance(a, c);
        const ad = Point.distance(a, d);
        const triangle = [ab, ac, ad].sort((a, b) => a - b);

        return numbersEqual(triangle[0], triangle[1]);
    }

    window.Point = Point;
})();

/*
 * Square
 */

(function () {
    function Square(a, b, c, d) {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }

    Square.prototype.area = function() {
        const findSquareDiagonalLength = (a, b, c, d) => {
            const ab = Point.distance(a, b);
            const ac = Point.distance(a, c);
            const ad = Point.distance(a, d);

            return Math.max(ab, ac, ad);
        };

        const d = findSquareDiagonalLength(this.a, this.b, this.c, this.d);
        return d * d / 2;
    }

    window.Square = Square;
})();

/*
 * Solution
 */

function formSquaresFromPoints(points) {
    let squares = [];

    for (let a = 0; a < points.length; a++)
        for (let b = a + 1; b < points.length; b++)
            for (let c = b + 1; c < points.length; c++)
                for (let d = c + 1; d < points.length; d++)
                    if (Point.pointsFormsSquare(points[a], points[b], points[c], points[d]))
                        squares.push(new Square(points[a], points[b], points[c], points[d]));

    return squares;
}

function sortSquaresByArea(squares) {
    squares.sort((a, b) => {
        if (a.area() > b.area())
            return 1;
        else if (a.area() < b.area())
            return -1;
        else
            return 0;
    });

    return squares;
}

const POINTS = [
    new Point(1, 1),
    new Point(1, 3),
    new Point(3, 1),
    new Point(3, 3),
    new Point(1, 6),
    new Point(6, 1),
    new Point(6, 6),
    new Point(1, 9),
    new Point(9, 1),
    new Point(9, 9),
    new Point(4, 5),
    new Point(4, 8),
    new Point(7, 8),
    new Point(7, 5),
    new Point(6, 3),
    new Point(5, 3),
    new Point(5, 1)
];

const sortedSquares = sortSquaresByArea(formSquaresFromPoints(POINTS));
const squareWithBiggestArea = sortedSquares[sortedSquares.length - 1];

console.log(squareWithBiggestArea); // Gives: {(1, 1), (1, 9), (9, 1), (9, 9)}


texts:
This is some of my first real F# code ever. I have done a bit of reading and watched a few videos however. I chose to do a code kata for string calculator to try it out.

The kata I was working on is here by Roy Osherove, though I may have strayed a bit.

I am pretty happy with this, but wonder if there are things that could be better, or more idiomatic F#.  I am specifically wondering if there is a better option to having the overloaded Add members.  I'm also curious about the last test and exception handling best practices.

module Tests
open Xunit
open System

type Calculator() =
    let delimiters = ",\n"
    member x.Add (m:int, n:int list) =
        match n with
        |[] -> m
        |y::ys ->
            if y < 0 then failwith "No Negative Numbers"
            x.Add((m+y),ys)
    member x.Add (y:string) =
        let numList = List.map (fun x -> x.ToString() |> Convert.ToInt32) (delimiters.ToCharArray() |> y.Split |> Seq.toList)
        x.Add(0,numList)

[<Fact>]
let ReturnsNotNull() =
    let calc = new Calculator()
    Assert.NotNull (calc.Add "0,0")

[<Fact>]
let ReturnsZeroWhenZeros() =
    let calc = new Calculator()
    Assert.Equal(0,(calc.Add "0,0"))

[<Fact>]
let ReturnsOneWhenShouldBeOneOnLeft() =
    let calc = new Calculator()
    Assert.Equal(1,(calc.Add "1,0"))
[<Fact>]
let ReturnsOneWhenShouldBeOneOnRight() =
    let calc = new Calculator()
    Assert.Equal(1,(calc.Add "0,1"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalEleven() =
    let calc = new Calculator()
    Assert.Equal(11,(calc.Add "0,1,1,1,1,1,6"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalElevenDelimitedByNewLine() =
    let calc = new Calculator()
    Assert.Equal(11,(calc.Add "0,1,1\n1,2\n6"))
[<Fact>]
let ReturnsElevenWithStringOfNumbersThatTotalElevenDelimitedByNewLineNoNegativeNumbers() =
    let calc = new Calculator()
    try
        calc.Add("0,1,-1\n1,2\n6") |> ignore
        Assert.False true
    with
        | _ -> Assert.True true


texts: Randomized response generator for number-guessing game

texts:
I am currently learning C and playing around with the rand() and if/else statement. This code looks long, just curious if there is another way to make the code shorter?

The code below works fine, it's just randomize the output every time someone answers the question incorrectly.

while(input != c){
    srand(time(NULL));
    int i;
    i = rand() % 5 + 1;
    if (i == 1)
    {
        printf("No. Please try again.\n");
        scanf("%d", &input );
    }
    else if(i == 2){
        printf("Wrong. Try once more.!\n");
        scanf("%d", &input );
    }
    else if(i == 3){
        printf("Don't give up!\n");
        scanf("%d", &input );
    }
    else if(i == 4){
        printf("No. Keep trying.!\n");
        scanf("%d", &input );
    }
}

Is there any way to make it shorter, instead of using if/else over and over?


texts:
I've seen plenty of examples and questions on how to do this, but the issue is that they all rely on a massive database on the server-side. I figured I could try to move that to the client-side. Here's what I have:

(function() {
var data, pos, read, write, fcnt, tcnt, i, forums, threads, l, fid, id, t, allunread, post;
data = {forum:{},thread:{}};
if( localStorage[USERID+'.forumhistory']) {
         data = JSON.parse(localStorage[USERID+'.forumhistory']);
}
switch(FORUM_READ.mode) {
     // in the initialisation, FORUM_READ is an object with:
     //   mode: "index" for the list of forums, "forum" for an individual forum
     //         "thread" for an individual thread.
case "forum":
    threads = document.querySelectorAll('.f_thread');
              // each thread element has a "data-id" attribute indicating the thread's ID
              // and a "data-ts" attribute indicating the timestamp of the most recent post
    l = threads.length;
    fid = FORUM_READ.id;
    for( i=0; i<l; i++) {
        id = threads[i].getAttribute("data-id");
        data.thread[fid] = data.thread[fid] || {};
        data.thread[fid][id] = data.thread[fid][id] || data.forum[fid] || DATE;
        if( threads[i].getAttribute("data-ts")*1000 > data.thread[fid][id]) {
            threads[i].cells[0].children[0].src = "/img/misc/f_unread.gif";
        }
        else delete data.thread[fid][id];
    }
    data.forum[fid] = DATE;
    allunread = true;
    for( i in data.thread[fid]) {
        allunread = false;
        break;
    }
    if( allunread) {
        delete data.thread[fid];
    }
    // Fall through to deal with subforums
case "index":
    forums = document.querySelectorAll('.f_forum');
              // similarly to threads, forums have "data-id" and "data-ts" attributes
    l = forums.length;
    for( i=0; i<l; i++) {
        id = forums[i].getAttribute("data-id");
        data.forum[id] = data.forum[id] || DATE;
        if( forums[i].getAttribute("data-ts")*1000 > data.forum[id])
                           forums[i].cells[0].children[0].src = "/img/misc/f_unread.gif";
    }
    break;
case "thread":
              // the last post, #f_post, has a "data-ts" attribute giving its timestamp
    post = document.getElementById('f_post').getAttribute("data-ts")*1000;
    fid = FORUM_READ.forum;
    id = FORUM_READ.id;
    if( data.thread[fid] && data.thread[fid][id] && data.thread[fid][id] < post) {
        data.thread[fid][id] = post;
    }
    break;
}
localStorage[USERID+'.forumhistory'] = JSON.stringify(data);
})();

Now, as far as I can tell this works. However, I haven't really been able to test much due to not having anyone else who can test for me (sometimes working alone sucks...). So I'm hoping that someone here will be able to spot any errors in my logic.


texts: Determine dependency injection type at runtime from config

texts:
I have a .NET application with a .config file that has content like this:
<appSettings>
    <add key="SmtpConfiguration" value="Db" />
</appSettings>

Inside the application's code I define an ISmtpConfiguration interface and several different implementations. DbSmtpConfiguration gets configuration data from a database, AppSettingsSmtpConfiguration reads from some other entries in the .config, and DefaultSmtpConfiguration has values written directly in the code.
In my service provider configuration, I have this:
switch (ConfigurationManager.AppSettings["SmtpConfiguration"])
{
    case "Db":
        services.AddSingleton<ISmtpConfiguration, DbSmtpConfiguration>();
        break;
    case "AppSettings":
        services.AddSingleton<ISmtpConfiguration, AppSettingsSmtpConfiguration>();
        break;
    default:
        services.AddSingleton<ISmtpConfiguration, DefaultSmtpConfiguration>();
}

I'm not thrilled with that, so I have created a factory:
public class SmtpConfigurationFactory
{
    public static ISmtpConfiguration GetSmtpConfiguration()
    {
        var type = Type.GetType(ConfigurationManager.AppSettings["SmtpConfiguration"] + "SmtpConfiguration");

        if (type == null)
        {
            type = typeof(DefaultSmtpConfiguration);
        }

        return (ISmtpConfiguration) Activator.CreateInstance(type);
    }
}

I then use the factory like this:
services.AddSingleton(SmtpConfigurationFactory.GetSmtpConfiguration());

I'm not terribly thrilled with that either. My final thought was to change consumers of ISmtpConfiguration to accept SmtpConfigurationFactory instead, make the method not static, and then add the factory to my services:
services.AddSingleton<SmtpConfigurationFactory>();

Then the constructor for the consumer looks like:
public SmtpEmailService(SmtpConfigurationFactory configurationFactory)
{
    Configuration = configurationFactory.GetSmtpConfiguration();
}

I like that the best, but is there a better solution? The factory introduces the issue that implementations of ISmtpConfiguration cannot require dependencies of their own. DbSmtpConfiguration for example couldn't receive an IDbConfiguration telling it which database to connect to.


texts:
I found myself writing code of the form...

val foo : Foo = ???

val step1 : Foo = {
  if ( someCharacteristic( foo ) )
    someTransformation( foo )
  else
    foo
}
val step2 : Foo = {
  if ( otherCharacteristic( foo ) )
    otherTransformation( foo )
  else
    foo
}

val result = step2;

That seemed awkward, and it seemed like this sort of ugly stepwise processing could be monadified. I've used but not written Scala monads; I thought I'd give it a shot. What I have seems to work, but I found proving the monad laws surprisingly challenging. I'm not sure I've got a valid monad, and wonder whether there is some subtle problem that would bite me someday if I haven't. FWIW, here's the code, any comments would be very welcome.

package dumbmonad;

import scala.language.implicitConversions;

object If {
  implicit def unwrap[T]( ift : If[T] ) = ift.value;

  def evaluate[T]( ift : If[T] ) : T = if ( ift.condition( ift.value ) ) ift.transformation( ift.value ) else ift.value;

  def flatten[T]( outer : If[If[T]] ) : If[T] = evaluate( outer );

  def apply[T]( value : T ) : If[T] = apply( value, _ => false, identity );
}

case class If[T]( val value : T, val condition : (T)=>Boolean, val transformation : (T)=>T ) {

  lazy val evaluate : T = If.evaluate( this );

  def map[S]( f : (T) => S ) : If[S] = If( f( this.evaluate ) )
  def flatMap[S]( f : (T) => If[S] ) : If[S] = If.flatten( this.map( f ) )
}

I use it like this:

import dumbmonad._;
import dumbmonad.If._;

val foo : Foo = ???

for {
  a <- If( foo, someCharacteristic, someTransformation )
  b <- If( a, otherCharacteristic, otherTransformation )
} yield b;

val result : Foo = b; // implicit call to If.unwrap( ... )

Is this terrible?


texts: Calculating daily project drilling hours

texts:
I've got this method, and it's quite a big method. I look at it, and I feel... dirty. I feel that it's doing too much, and that there might be a better way to accomplish what I'm trying to.

/// <summary>
/// Calculates daily project drilling hours
/// </summary>
/// <param name="daily">Bool: True for daily, false for total project</param>
/// <param name="timeFrame">Bool: True for specific time frame, false for whole day </param>
/// <returns>Double:  Drilling hours for time frame</returns>
public double CalculateDrillingHours(bool daily = false, bool timeFrame = false)
{
    Logger.Info("Calculating Drilling Hours");

    var query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0";

    query = BuildQuery(query, daily, timeFrame);

    var tempList = ExecuteQuery(query);

    // The user needs to know if there was no data for the time frame chosen
    var noData = new Exception("There was no data for the selected time frame.  Please select another. (Drilling Hours)");

    if (tempList.Count < 1)
    {
        throw noData;
    }

    if(!daily)
    {
        TotalProjectDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero));

        Logger.Info("Total Drilling Hours calculated");

        return TotalProjectDrillingHours;
    }

    DailyDrillingHours = Convert.ToDouble(Math.Round(TimeCalculations(ConvertStringListToDateTimeList(tempList)).TotalHours, 2, MidpointRounding.AwayFromZero));

    Logger.Info("Daily Drilling Hours calculated");

    return DailyDrillingHours;
}

This method returns 1 of 2 items: Either Daily Drilling Hours, or Total Project Drilling Hours. This was originally two methods, but I combined them because a lot of the code was being duplicated, and it made sense at the time (about 6 months ago). But now, looking at it, I'd like to improve this. Is there a better way?

Yes, I know about parameterized queries. I've already incorporated those in the final query, which would look something like this:

query = "SELECT timestamp FROM myDatabase WHERE measured_dist = bit_loc AND rop > 0 AND date = @Date AND timestamp BETWEEN @StartTime AND @EndTime";


texts: Magento MySQL search based on phone number

texts:
I'm building a search for Magento. Magento API doesn't provide an easy way to look up a customer using a phone number so I created a custom solution. My MySQL/PHP OOP skills are limited. Did I miss anything or is there a better way to do this?

<?php

    DEFINE ('DB_HOST',      'localhost');
    DEFINE ('DB_USER',      'theuser');
    DEFINE ('DB_PASSWORD',  'thepassword');
    DEFINE ('DB_NAME',      'magento');

    $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);

    $search_query = "5555555555";

    // find customers with matching phone numbers
    $query = "SELECT value, entity_id FROM customer_address_entity_varchar WHERE value=$search_query LIMIT 100";

    $response = mysqli_query($dbc, $query);

    // save found phone numbers to $found_customers array
    $found_customers = array();
    $position = 0;

    while($row = mysqli_fetch_array($response)) {

        $found_customers[$position]['entity_id']    = $row['entity_id'];
        $found_customers[$position]['value']        = $row['value'];

        $position++;
    }

    // reset everything just in case
    unset($query, $response, $row);
    $position = 0;

    // find matching parent_ids and save to $found_customers array
    foreach($found_customers as $found_customer) {
        $friendly_entity_id = $found_customer['entity_id'];

        $query = "SELECT parent_id FROM customer_address_entity WHERE entity_id=$friendly_entity_id LIMIT 1";
        $response = mysqli_query($dbc, $query);
        $row = mysqli_fetch_array($response);
        $found_customers[$position]['parent_id'] = $row['parent_id'];

        $position++;
    }

    var_dump($found_customers);

?>


texts:
Right now I am finding ways to write better code in javascript and I see many coding styles used by different authors but right now I am thinking to write code which adheres to the object oriented paradigm better suited for this type of language.

Code

// Terminal

'use strict';

class Terminal {
  constructor() {
    this.cols = process.stdout.columns || 80
    this.rows = process.stdout.rows || 60
  }

  width() {
    return this.cols
  }

  height() {
    return this.rows
  }
}

module.exports = Terminal

// Box

'use strict';

const Terminal = require('./terminal')

class Box {
  constructor(opts) {
    let terminal = new Terminal()
    const defaults = {
      w: terminal.width(),
      h: terminal.height(),
      t: '══',
      tr: '╗',
      r: '║',
      br: '╝',
      b: '══',
      bl: '╚',
      l: '║',
      tl: '╔',
      fill: '░░'
    }
    this.settings = Object.assign(defaults, opts)
  }

  toString() {
    const res = [];
    const { t, tr, r, br, b, bl, l, tl } = this.settings
    const { w , h } = this.settings
    // Filling row wise
    for (let i = 0; i < h; i++) {
      for (let j = 0; j < w; j++) {
        if (i === 0 && j === 0) {
          res.push(tl)
        }
        else if (i === 0 && j === w - 1) {
          res.push(tr)
        }
        else if ((i === h - 1) && (j === w - 1)) {
          res.push(br)
        }
        else if ((i === h - 1) && j === 0) {
          res.push(bl)
        }
        else if (this.isFirstRow(i) || this.isLastRow(i)) {
          res.push(t)
        }
        else if (this.isFirstCol(j) || this.isLastCol(j)) {
          res.push(l)
        }
        else {
          const { fill } = this.settings
          res.push(fill)
        }
      }
      res.push('\n')
    }
    return res.join('')
  }

  isFirstRow(row) {
    return row === 0
  }

  isLastRow(row) {
    const { h } = this.settings
    return row === h - 1
  }

  isFirstCol(col) {
    return col === 0
  }

  isLastCol(col) {
    const { w } = this.settings
    return col === w - 1
  }
}

class TopRight {
  constructor() {
    this.symbol = '╗'
  }

  toString() {
    return this.symbol
  }
}

class BottomRight {
  constructor() {
    this.symbol = '╝'
  }

  toString() {
    return this.symbol
  }
}

class BottomLeft {
  constructor() {
    this.symbol = '╚'
  }

  toString() {
    return this.symbol
  }
}

class TopLeft {
  constructor() {
    this.symbol = '╔'
  }

  toString() {
    return this.symbol
  }
}

module.exports = Box

// O/P
/*
> const B = require('./box')
> console.log(new B({w: 8, h: 8, fillSymbol: '||'}).toString())
╔════════════╗
║░░░░░░░░░░░░║
║░░░░░░░░░░░░║
║░░░░░░░░░░░░║
║░░░░░░░░░░░░║
║░░░░░░░░░░░░║
║░░░░░░░░░░░░║
╚════════════╝
*/

I would like to know how to improve the above code to make better use of prototypal inheritance and delegation which is widely advocated in javascript world.

Note

I thought to use classes for printing symbols but I see that they make code more bloated. I left them there hear opinion of others.


texts: Mysql multiple queries from one PHP file

texts:
I'm running the below code to populate a HTML table using several calls to mysqli_query(). The below snippet only shows three however I'm running ten in my file for various other date columns and may need more over time. I've attached a file below showing the basic database layout and required output.

The required output is basically just a list of times from various columns

The below code works fine, however it is probably not the most efficient and other options like MySQL JOIN or UNION don't seem to work.

Do we have any another options to perform the desired output?

 $result = mysqli_query($con,"SELECT * FROM livescores WHERE actualstart >= '$datefilter'");
 $resulthalf = mysqli_query($con,"SELECT * FROM livescores WHERE actualhalftime >= '$datefilter'");
 $actualft = mysqli_query($con,"SELECT * FROM livescores WHERE actualft>= '$datefilter'");

while($row = mysqli_fetch_array($result))
{
echo "
";
echo "" . $row['actualstart'] . "	";
echo "" . $row['League'] . "	";
echo "KO	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";
}
while($row = mysqli_fetch_array($resulthalf))
{
echo "
";
echo "" . $row['actualhalftime'] . "	";
echo "" . $row['League'] . "	";
echo "HT	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";
}
while($row = mysqli_fetch_array($actualft))
{
echo "
";
echo "" . $row['actualft'] . "	";
echo "" . $row['League'] . "	";
echo "FT	";
echo "" . $row['HomeTeam'] .' v '. $row['AwayTeam'] . "	";
echo "	";
echo "
";

Many Thanks


texts:
I use console a lot, so I thought this may help me. It's supposed to be simple, safe, and fast. Any ideas?

http://ideone.com/INXub0

#include <iostream>
using namespace std;

class Console
{
public:
    template<typename ...Args>
    static bool WriteLine(const std::string& format, Args&&... args)
    {
        bool success = write(format.c_str(), std::forward<Args>(args)...);
        std::cout << std::endl;
        return success;
    }

    template <typename ...Args>
    static bool Write(const std::string& format, Args&&... args)
    {
        return write(format.c_str(), std::forward<Args>(args)...);
    }

    template<typename T>
    static void WriteLine(T&& value)
    {
        std::cout << std::forward<T>(value) << std::endl;
    }

    template<typename T>
    static void Write(T&& value)
    {
        std::cout << std::forward<T>(value);
    }

private:
    template<typename ...Args>
    static bool write(const char * format, Args&&... args)
    {
        while (*format)
        {
            if (*format == '{')
            {
                bool found_closing_brace = false;
                short value_position = -1;

                while (*(++format))
                {
                    if (*format == '}')
                    {
                        if (value_position == -1)
                            return false;  // {} is not allowed.

                        write_value(value_position, 0, std::forward<Args>(args)...);
                        found_closing_brace = true;
                        break;
                    }
                    else
                    {
                        if (value_position >= 10)
                            return false; //Only range {0 ~ 99} is allowed.

                        if (value_position == -1)
                            value_position = *format - '0';
                        else
                            value_position = (value_position * 10) + (*format - '0');
                    }
                }

                if (!found_closing_brace)
                    return false;

                // Continue back to the main loop. This is required.
                // We need to process the next character, because it could be a '\0' or a '{'
                format++;
                continue;
            }

            std::cout << *format;
            format++;
        }

        return true;
    }

    template<typename T, typename ...Args>
    static void write_value(int x, int i, T&& value, Args&&... values)
    {
        if (i == x)
            std::cout << std::forward<T>(value);
        else
            write_value(x, ++i, std::forward<Args>(values)...);
    }

    static void write_value(int x, int i) { }
};

int main()
{
    Console::WriteLine("Big {11} Bang {0} Theory {6} [{11}, {12}]",

        "Zero", "One", "Two", "Three", "Four", "Five",
        "Six", "Seven", 8, "Nine", "Teen", 11, 12.5f);

    // your code goes here
    return 0;
}


texts:
I've made a program which reads from the console and writes it in a .txt file. This programm should write in a file with \n.
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main() {
    ofstream fich("file.txt");

    if (!fich)
        cerr << "Error!\n";

    char fst = 'l';
    string c;
    while (fst != '\0') {
        getline(cin, c);
        fst = c[0];
        fich << c << endl;
    }

    fich.close();

    return 0;
}

This program ends when the user inputs nothing and then a \n, because, doing that, the string c will only have a \0 end of string element.
I was wondering if there is any way of doing this more efficiently, maybe without needing a "void \n" line to finish the program.


texts: Determine if a std::string has all of the same character

texts:
I'm working on an algorithm to determine if a std::string has all of the same character. Here is what I have:

bool string_has_all_of_the_same_chars(const std::string& s) {
    return std::all_of(s.begin(), s.end(), [&s](char ch) { return ch == s[0]; });
}

Are there any improvements that can be made to this? I am guaranteed by another function that s is not empty.


texts:
I needed a utility function/method that would get the next available filename to save as.

An example would be, if I need to save a file as MyTestFile.html but it already exists.

This method would then check to see what the next availble filename would be, and it would return
MyTestFile2.html. If MyTestFile2.html exists, then it would return MyTestFile3.html, and so on.

I wrote the method, but it feels sloppy, and isn't really very elegant.

Any ideas for improving the readability of this code, or a better way to do it?

public string GetNextAvailableName(List<string> files, string baseFile)
{
    var baseFileWithoutExt = Path.GetFileNameWithoutExtension(baseFile);
    var baseExt = Path.GetExtension(baseFile);

    //clean files and get the ones containing oure baseFileName
    var cleanFiles = files
                        .Select(i => Path.GetFileNameWithoutExtension(i.ToLower()))
                        .Where(i => i.Contains(baseFileWithoutExt.ToLower()));

    var count = cleanFiles.Count();

    if (count == 0)
        return baseFile;

    int indexCount = 1;

    do
    {
        indexCount++;
    } while (cleanFiles.Contains(baseFileWithoutExt.ToLower() + indexCount));

    return baseFileWithoutExt + indexCount + baseExt;
}

This would then be called like this:

GetNextAvailableName(Directory.GetFiles("C:\\MyFiles\\", "MyTestFile.html");

Then if MyTestFile.html is already in use, it will return MyTestFileX.html, where X is the lowest positive integer where the filename doesn't exist yet.


texts: Returning Function Calls from an Array within a JavaScript Function

texts:
I'd like to use JavaScript to generate HTML.

I've made a JavaScript function object that has two parameters; a string and generic object. The string is used to specify the type of HTML element you want to generate and the generic object is a container for key value pairs specifying the element's attributes -- or a string for simple elements like paragraphs containing only text that needs no id or class specification.

I'm drafted some functions that generate some HTML elements. I then contained the functions in an array that is a local variable of a function called html.

When html is called with appropriate arguments (e.g. html("element", {id:"myElement"})), a string of HTML text is returned.

I wonder what the drawbacks of the approach are. More specifically, is there a better method to achieve the same results?

var html = function (type, spec={}) {
  html_element = [];

  html_element["table"] = function() {
    markup = "
";

    if (spec.cols)
    {
      markup += "
";

      for (value in spec.cols)
        markup += "" + spec.cols[value] + "	";

      markup += "
";
    }

    while (spec.rows.length)
    {
      markup += "
";

      for (data in (row = spec.rows.shift()))
        markup += "" + row[data] + "	";

      markup += "
";
    }

    return markup += "
";
  };

  html_element["button"] = function() {
    if (spec.hasOwnProperty("value")) value = spec.value;
    else                              value = "";

    return "<button id=\"" + id + "\">" + value + "</button>";
  };

  html_element["p"] = function() {
    if (typeof spec === Object) text = spec.text;
    else                        text = spec;

    return "
" + text + "
";
  };

  ...

  return html_element[type]();

}


texts: Finds all the prime numbers up to n using a strange pattern

texts:
Here's an odd pattern I found for sieving out composite numbers to find primes. I wrote it myself, originally thinking I made an indexing error, but it turned out to work after removing squares.

import bitarray
def sieve(n):
    """bitarray sieve"""
    b=bitarray.bitarray([1]*(n+1))
    x=int(n**.5)+1
    for k in range(2,x):
        if b[k]:
            f=k+1 #this line is indexing error
            e=n//k +1
            for g in range(f,e):
                if b[g]:
                    b[g*k]=0
    return sorted(list(to_numbs(b)-squares_set(b)))

def squares_set(ba):
    """this returns a set of all primes**(2n).
note 0**2==0, 1**2==1"""
    return {i**2 for i in range(int(len(ba)**.5)+1) if ba[i]}

def to_numbs(b_ar):
    """converts the bit array to a set of numbers"""
    return {i for i in range(len(b_ar)) if b_ar[i]}
if __name__=="__main__":
    print(sieve(100))

I'm not entirely sure what causes this pattern to work so I figured it would be fun to post here.


texts: Using Pythagoras' Theorem to Check Point Distance

texts:
I want to procedurally generate several points on a graph that are suitably distant from each-other. These points are meant to represent castles that are part of towns in the world-map of my game. However, I still find these points very close or touching. How can I create a set of points that are all at least a certain distance from each-other?

Here is a picture of one of the maps I've generated. The castles are black/dark grey.

Here is the function I'm using to generate the castles. I return a set which I iterate through in another function. This adds elements of appropriate int values to a list matrix which is iterated through with Pygame to display the map.

import random as r
import math as m

def createTiles(num, xBounds, yBounds, dist, tileSet):

    """
    Creates num amount of tuple tile locations and returns them in a set.

    :param num: int
        The amount of tile locations to be returned.

    :param xBounds: tuple of 2 ints
        The first element is the minimum x-values should be.
        The second element is the maximum x-values should be.

    :param yBounds: tuple of 2 ints
        The first element is the minimum x-values should be.
        The second element is the maximum x-values should be.

    :param dist: string or tuple of 2 strings.
        Each string contains a greater or less than sign, and a number.
        This indicates whether to cap the distance between points,
        or to keep points at least a certain distance away from each-other.
        For example, "<30" would keep points within 30 tiles of each-other.
        If a tuple is used,
        it must both cap the distance and maintain a distance.

    :param tileSet: set of tuples
        Contains already existing tile locations to be checked for distance.

    :return: set of tuples
        Returns tileSet with new tile locations.
    """
    tempSet = set()
    # handle different object types of dist
    if type(dist) == tuple or type(dist) == list:
        for d in dist:
            if d[0] == "<":
                cap = int(d[1:])
            else:
                keep = int(d[1:])
    elif type(dist) == str:
        if dist[0] == "<":
            cap = int(dist[1:])
        else:
            keep = int(dist[1:])
    else:
        keep = 0
        cap = 255

    # create tile locations and check distance against the tiles in tileSet.
    for n in range(num):
        x = r.randint(xBounds[0], xBounds[1])
        y = r.randint(yBounds[0], yBounds[1])
        for t in tileSet:
            distance = m.sqrt((x - t[0]) ** 2 + (y - t[1]) ** 2)
            while distance < keep or distance > cap or (x, y) in tileSet:
                x = r.randint(xBounds[0], xBounds[1])
                y = r.randint(yBounds[0], yBounds[1])
                distance = m.sqrt((x - t[0]) ** 2 + (y - t[1]) ** 2)

        tempSet.add((x, y))

    # Combine tileSet and tempSet.
    tileSet = tileSet.union(tempSet)
    # Check distance for all tiles in tileSet:
    for t1 in tileSet:
        for t2 in tileSet:
            distance = m.sqrt((t1[0] - t2[0]) ** 2 + (t1[1] - t2[1]) ** 2)
            while distance < keep or distance > cap:
                t1 = (r.randint(xBounds[0], xBounds[1]),
                      r.randint(yBounds[0], yBounds[1]))
                distance = m.sqrt((t1[0] - t2[0]) ** 2 + (t1[1] - t2[1]) ** 2)

    return tileSet

Thanks for looking through this. If you want any more information or anything just comment.


texts:
Here's a trivial example:

if type(length) != int:
    length = 16

as opposed to:

try:
    len_mod = (length + 33) / 32 + 1
except TypeError:
    #recover here somehow, over-ride input?
    len_mod = (16 + 33) / 32 + 1

I don't need an authoritative answer, but some opinion on this approach would be fine.

Some info about the surrounding code, as it stands now:

I don't expect anything but an int for length. I will never expect anything else.
There's no purpose in showing an error message (this is a stand-alone method)
There's no harm in suppressing the error (for now, nothing else uses this method)

With that information, is it still alright to hijack (albeit, bad) user input and suppress the resulting error by replacing it with what would have been the default value in the function?

I ask because I've never read anyone else's code where this happens, and I have wondered if there was a reason for that I'm missing.

Feel free to invent some cases where I might regret this decision, or any other points you'd like to highlight for the sake of example.

Thanks.

EDIT

Another angle: my goal is to make a useful, single serving website, quite similar to tinyurl. I tested their site using a similar bit of invalid data, and it didn't report anything back to me. It just let me be stupid:

They didn't check if my site matched a regex for syntactically valid domains, they didn't even bother mentioning that my original link was 6 characters shorter than what they gave back. I think this is a good thing, from a user's perspective. Why tell me what the site can and can't do?

I understand that this code, being for a stand-alone, single-serving application, may or may not be subject to some of the same rules as other, more modular functions are. Given the circumstances, how do I write my code to suffer fools lightly, and still be durable and extendable? So far, I'm quite happy with the short, direct try:except block acting as a guardian.


texts: Move object by one up or down algorithm in a custom order

texts:
Basically, I did an object (using hibernate) with a field called sorting_order. This field needs to be unique and I wish to swap two object by one. So one element has to be after or before the current element to be able to move. My object can only move by one up or down. I came up with this code, but I was wondering if there was a better way to do this.

Thank you!

/**
     * Move two personal task macro
     *
     * @param userProfileModel - The {@link UserProfileModel}.
     * @param move - true = up or false = down.
     */
    private void movePersonnalTaskMacro(UserProfileModel userProfileModel, boolean move) {
        Assert.notNull(userProfileModel, "userProfileModel required.");

        logger.info("Preparing to move a personnal task macro.");

        PersonnalTaskMacro selectedPersonnalTaskMacro = userProfileModel.getSelectedPersonnalTaskMacro();

        /* Initialize sorting order (increment/decrement) */
        int selectedPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacro.getSortingOrder();
        int nextPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacroSortOrder + 1;
        int previousPersonnalTaskMacroSortOrder = selectedPersonnalTaskMacroSortOrder - 1;

        /* Condition validation */
        int personnalTaskMacroListSize = userProfileModel.getPersonnalTaskMacroList().size();
        int selectedPersonnalTaskMacroIndex = userProfileModel.getPersonnalTaskMacroList().indexOf(
                selectedPersonnalTaskMacro);

        if (personnalTaskMacroListSize > 1) {
            if (move == false && selectedPersonnalTaskMacroIndex >= 1) {
                int previousPersonnalTaskMacroIndex = selectedPersonnalTaskMacroIndex - 1;
                PersonnalTaskMacro previousPersonnalTaskMacro = userProfileModel.getPersonnalTaskMacroList().get(
                        previousPersonnalTaskMacroIndex);

                previousPersonnalTaskMacro.setSortingOrder(selectedPersonnalTaskMacroSortOrder);
                selectedPersonnalTaskMacro.setSortingOrder(previousPersonnalTaskMacroSortOrder);

                logger.info("Moved the selected personnal task macro down by one");
            }

            if (move == true && nextPersonnalTaskMacroSortOrder <= personnalTaskMacroListSize) {
                int nextPersonnalTaskMacroIndex = selectedPersonnalTaskMacroIndex + 1;
                PersonnalTaskMacro nextPersonnalTaskMacro = userProfileModel.getPersonnalTaskMacroList().get(
                        nextPersonnalTaskMacroIndex);

                nextPersonnalTaskMacro.setSortingOrder(selectedPersonnalTaskMacroSortOrder);
                selectedPersonnalTaskMacro.setSortingOrder(nextPersonnalTaskMacroSortOrder);

                logger.info("Moved the selected personnal task macro up by one");
            }

            Collections.sort(userProfileModel.getPersonnalTaskMacroList());
        }
    }


texts: Inserting robot moves into an SQLite3 database

texts:
I'm just wondering if you would consider this to be safe from SQL injection.

A peculiarity of my program is I need to dynamically access table names depending on my scenario.

This is not for publishing online, but I wish to know if this approach is any good.

I'm using Python3 and SQLite3. My database object contains the table name, and is not controlled by any user. It comes from another class in a config.cfg file.

def save_record(state_int, database):
    query = '''INSERT INTO %s (state_int, turn_left, turn_right, move_forward) VALUES (?,?,?,?)''' %(database.records_table_name)
    database.cursor.execute(query, (state_int, 0, 0, 0))
    database.robot_memory.commit()

save_record(10012, database)


texts: When should I call set_exception_handler with this exception handler class?

texts:
This is a simplified version of ExceptionHandler.php:

<?php
class ExceptionHandler
{
    public function __construct()
    {
        set_exception_handler(array($this, 'handle'));
    }

    public function handle($exception)
    {
        // output some information about the exception
    }
}

I'm wondering where the best place is to call set_exception_handler:

Register itself in the constructor, as above? Usage would simply be:

$exceptionHandler = new ExceptionHandler;

Move the set_exception_handler call into a separate method, and call after instantiation:

$exceptionHandler = new ExceptionHandler;
$exceptionHandler->register();

Outside of the class entirely:

$exceptionHandler = new ExceptionHandler;
set_exception_handler(array($exceptionHandler, 'handle'));


texts: Automatically implement operator+ using CRTP

texts:
I have multiple classes that should support addition. For each of them, the operator += is implemented as T& operator+=(const T& rhs). I also want to add the operator +, but this implementation will use += and will therefore be similiar in all classes. My idea was to implement a template class using the Curiously Recurring Template Pattern that provides an implementation. The result is code like this:

template<class T>
class Sumable {
private:
    Sumable() = default;

public:
    Sumable(const Sumable<T>&) = delete;
    Sumable(Sumable<T>&&) = delete;

    T operator+(const T&) const&;
    T operator+(const T&) && ;
    T operator+(T&&) const&;
    T operator+(T&&) && ;

    friend T;
};

template<class T>
inline T Sumable<T>::operator+(const T & rhs) const&
{
    T result(*static_cast<const T*>(this));
    return std::move(result += rhs);
}

template<class T>
inline T Sumable<T>::operator+(const T & rhs) &&
{
    return std::move<T&>(*static_cast<T*>(this) += rhs);
}

template<class T>
inline T Sumable<T>::operator+(T && rhs) const&
{
    return std::move(rhs += *this);
}

template<class T>
inline T Sumable<T>::operator+(T && rhs) &&
{
    return std::move(rhs += *this);
}

Classes that support addition would extend from Sumable<T> like for example class Vector : public Sumable<Vector>

The operator is overloaded four times to prevent the creation of unnecessary temporary objects. The idea is described here https://stackoverflow.com/questions/6006527/overloading-on-r-value-references-and-code-duplication, but I return T by value to prevent the problems described in this question.
I also follow this idea https://stackoverflow.com/questions/11224838/prevent-user-from-deriving-from-incorrect-crtp-base/11241079 to prevent incorrect use of the class.

In a simple test, this worked like expected. Are there any edge cases in which this design can cause problems? And is it a good idea to use this design in production code?

Edit
The code I used to test this, compiles under MSVS 2017:

#include "stdafx.h"
#include <iostream>
#include "Sumable.h"

using namespace std;

struct Test : public Sumable<Test>{
    int data;

    Test(int data) : data(data) {};
    Test(const Test& that) : data(that.data)
    {
        cout << "copy" << endl;
    };
    Test(Test&& that) : data(that.data)
    {
        cout << "move" << endl;
    };
    Test& operator+=(const Test& that) {
        this->data += that.data;
        return *this;
    }
};
int main()
{
    Test a{ 1 };
    Test b{ 2 };
    Test c{ 3 };
    cout << (a + b + c + a + b + c).data << endl;
    return 0;
}


texts:
I recently attended an interview for a C++ position in a very reputed bank.

The interviewer started off by asking me to implement a string class but was only interested in constructor, copy-constructor, assignment operator and destructor.

Basically, he wanted to know how I would implement Rule of Three and nothing else.  He was not even interested in move operations.

So, I implemented the assignment operator in terms of copy constructor:

class String
{
  /*....*/
String& operator=(String other)
{
   std::swap(m_data, other.m_data);
   return *this;
}

private:
   char* m_data;
};

Since this is pretty common way to implement assignment operator, I thought he would like it. The problem started with that.

He questioned why I implement it that way. When I explained that this is exception safe way of implementing it, he asked what's wrong in implementing it:

String& operator=(const String& other)
{
   if (this != &other)
   {
     delete[] m_data;
     m_data = new char[strlen(other.m_data) + 1] {'\0'};
     strcpy(m_data, other.m_data);
     return *this;
   }
}

His argument was:

  We are about to overwrite the data anyways so what's wrong in deleting first even if it's not exception safe?

In the moment it did not occur to me that code will crash in the event of an exception but I did try to argue that internal data should retain original values in the event of an exception.

Had he argued on the basis that copy-and-swap will always do reallocation even if there is enough size, etc, I would have felt happy. But his argument was that he wants performance at any cost.

Can somebody help me with a comparative review of these two operator= implementations so that I am in a better position to argue my case / understand the interviewer's position if I encounter similar situations in the future?


texts:
Is there a better way of doing this? I heard that BinaryReader and Exif parsing to get the property item is faster, but I have no idea how to do that, thanks for the help.
//we init this once so that if the function is repeatedly called
//it isn't stressing the garbage man
static Regex r = new Regex(":");

//retrieves the datetime WITHOUT loading the whole image
string[] GetDateTakenFromImage(string path)
{
    try
    {
        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
        {
            using (Image myImage = Image.FromStream(fs, false, false))
            {
                PropertyItem propItem = myImage.GetPropertyItem(36867);
                string dateTaken = r.Replace(Encoding.UTF8.GetString(propItem.Value), "-", 2);
                if(string.IsNullOrEmpty(dateTaken))
                    return null;
                else
                    return DateTime.Parse(dateTaken).ToString("yyyy-MM-dd").Split('-');
            }
        }
    }
    catch
    {
        return null;
    }
}


texts:
I have created a database logger for ASP:NET Core's logging API and I'd like to publish it on NuGet when ready. The GitHub repository is here.

The library is partly modeled after Microsoft.Extensions.Logging.Console and I tried to follow good practices of object-oriented design.

I am slightly concerned about some decisions I made while implementing ILogWriter interface in SqlServerLogWriter class AND while designing the interface for the WriteBulk method (the method is called from the LogRecordCache class).

Have I managed threading well enough? It works fine, but it might not look OK.
Should I hide exceptions or let them propagate? Logging should be redundant in production environment, so I think hiding them would be fine.
Is there a better way for column mapping (in SqlServerLogWriter)?
Any advice or contribution would be appreciated.

LogRecordCache.cs

internal static class LogRecordCache
{
    private static readonly List<LogRecord> _logs;
    private static bool _flushingInProgress = false;
    private static object _lockObject = new object();

    public static bool IsEmpty { get { return _flushingInProgress || _logs.Count == 0; } }

    static LogRecordCache()
    {
        _logs = new List<LogRecord>();
    }

    public static void Add(LogRecord log)
    {
        if (_flushingInProgress)
        {
            lock (_lockObject)
            {
                _logs.Add(log);
            }
        }
        else
        {
            _logs.Add(log);
        }
    }

    public static bool IsFull(int maxCount)
    {
        return !_flushingInProgress && _logs.Count >= maxCount;
    }

    public static void Flush(ILogWriter writer)
    {
        if (!_flushingInProgress)
        {
            _flushingInProgress = true;
            Task.Run(() => writer.WriteBulk(_logs, _lockObject, ref _flushingInProgress));
        }
    }
}

WriteBulk() method

/// <summary>
/// Writes a collection of log records to database at once
/// </summary>
/// <param name="logs">List of <see cref="LogRecord"/> objects</param>
/// <param name="lockObject">Locking object</param>
/// <param name="flushingInProgress">Indicates if writing process is still in progress; set to false at the end of this method</param>
/// <exception cref="SqlException">If opening a connection through the provided connection string was not possible</exception>
public void WriteBulk(List<LogRecord> logs, object lockObject, ref bool flushingInProgress)
{
    var lockTaken = false;
    var connection = new SqlConnection(_connectionString);
    connection.Open();
    var transaction = connection.BeginTransaction();

    try
    {
        using (var bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.TableLock, transaction))
        {
            bulkCopy.DestinationTableName = "Logging";
            foreach (var mapping in _columnMappings)
                bulkCopy.ColumnMappings.Add(mapping.Key, mapping.Value);

            Monitor.TryEnter(lockObject, ref lockTaken);
            if (lockTaken)
            {
                using (var reader = ObjectReader.Create(logs, _columnMappings.Keys.ToArray()))
                {
                    bulkCopy.BatchSize = logs.Count;
                    bulkCopy.WriteToServer(reader);
                }

                transaction.Commit();
            }
        }
    }
    catch
    {
        if (connection.State == ConnectionState.Open)
            transaction.Rollback();
        throw;
    }
    finally
    {
        if (lockTaken)
        {
            logs.Clear();
            Monitor.Exit(lockObject);
        }

        transaction.Dispose();
        connection.Close();
        flushingInProgress = false;
    }
}


texts:
I'm looking for advice and ways on making it better.

Code

<?php

Class Validate {

    private $_errors = array();

    public function __construct()
    {
        require_once 'errors.php';
        $this->errorText = $errorText;
    }

    public function rule($value, $name, $inputRules)
    {

        $inputRules = explode('|', $inputRules);
        foreach ($inputRules as $inputRule) {

            if (!strlen($value) && $inputRule != 'required') {
                break;
            }

            if (preg_match('/\[(.*?)\]/', $inputRule, $match)) {

                $rule = explode('[', $inputRule);
                $rule = $rule[0];
                $param = $match[1];
                if (!method_exists($this, $rule)) {
                    throw new Exception("Method {$rule} does not exist");
                    exit;
                }

                $call = array($value, $param);
            }
            else {
                if (!method_exists($this, $inputRule)) {
                    throw new Exception("Method {$inputRule} does not exist");
                    exit;
                }
                $rule = $inputRule;
                $call = array($value);
            }

            $response = call_user_func_array(array($this, $rule), $call);

            if ($response) {
                $error = $this->errorText[$rule];
                $replace = array(
                    ':name' => $name,
                    ':param' => (isset($param)) ? $param : NULL
                );
                $response = str_replace(array_keys($replace), array_values($replace), $error);

                $this->_errors[] = $response;
            }

        }

    }

    public function exec()
    {
        return (empty($this->_errors)) ? false : $this->_errors;
    }

    /*
    * Rule functions
    */

    public function min_length($value, $param)
    {
        return (strlen($value) < $param);
    }

    public function max_length($value, $param)
    {
        return (strlen($value) > $param);
    }

    public function email($value)
    {
        return !filter_var($value, FILTER_VALIDATE_EMAIL);
    }

    public function required($value)
    {
        return (strlen($value) !== 0);
    }

    public function ip($value)
    {
        return !filter_var($value, FILTER_VALIDATE_IP);
    }

    public function match($value, $param)
    {
        return ($value != $param);
    }

    public function match_exact($value, $param)
    {
        return ($value !== $param);
    }

    public function match_password($value, $param)
    {
        return ($value !== $param);
    }

    public function alphanum($value)
    {
        return !ctype_alnum($value);
    }

    public function url($value)
    {
        return !filter_var($value, FILTER_VALIDATE_URL);
    }

    public function numeric($value)
    {
        return !(is_numeric($value));
    }

    public function min($value)
    {
        return ($value < $param);
    }

    public function max($value) {
        return ($value > $param);
    }

}


texts:
As a Java programmer who's trying his hand at C++, I thought I'd start building a library for working with matrices as my first C++ project. I've got very little C++ experience and it's been a long time since I've even so much as dabbled in it.

So far I've only implemented an addition function, but I think this should be enough code to establish my current coding style.

I was wondering if anyone would be able to give my code a look over and see if it conforms to standards and if there are any cleaner ways of doing anything.

Here is my matrix.h file:

#ifndef MATRIX_H
#define MATRIX_H

#include <iostream>

using namespace std;

class Matrix {

    private:
        int** array;

    public:
        int m, n;
        Matrix(int m, int n);

        static Matrix* add(Matrix* m1, Matrix* m2);
        int get(int i, int j);
        void set (int i, int j, int e);

        ~Matrix();

};

#endif

and my matrix.cpp file:

#include <iostream>
#include "matrix.h"

using namespace std;

Matrix::Matrix(int var_m, int var_n) {
    m = var_m;
    n = var_n;
    array = new int*[n];
    for (int i = 0; i < n; i++)
        array[i] = new int[m];
    cout << "foo" << endl;
    cout << m << " " << n << endl;
}

Matrix* Matrix::add(Matrix* m1, Matrix* m2) {

    if (m1->m != m2->m or m1->n != m2->n) {
        cerr << "Error: Mismatched sizes in Matrix.add()" << endl;
        throw;
    }

    Matrix* res = new Matrix(m1->m, m1->n);

    for (int i = 0; i < res->m; i++) {
        for (int j = 0; j < res->n; j++) {
            res->array[i][j] = m1->array[i][j] + m2->array[i][j];
        }
    }

    return res;
}

int Matrix::get(int i, int j) {
    return array[i][j];
}

void Matrix::set(int i, int j, int e) {
    array[i][j] = e;
}

Matrix::~Matrix() {
    delete array;
}

and just some test code thrown together in my main.cpp:

#include <iostream>
#include "matrix.h"

using namespace std;

int main() {

    // --- Test code ---
    int m, n;
    Matrix* mat1;
    Matrix* mat2;
    Matrix* mat3;

    cout << "m: ";
    cin >> m;
    cout << "n: ";
    cin >> n;

    mat1 = new Matrix(m, n);
    mat2 = new Matrix(m, n);

    mat1->set(0,2,5);

    mat3 = Matrix::add(mat1, mat2);

    for (int i = 0; i < mat3->m; i++) {
        for (int j = 0; j < mat3->n; j++) {
            cout << mat3->get(i,j);
        }
        cout << endl;
    }

    delete mat1, mat2, mat3;

    return 0;
}


texts:
I coded the following program to solve the n-puzzle problem with n = 3. Are there any suggestions regarding readability and variable names?

import heapq
from random import shuffle
import math

n=3
fBoard = [1,2,3,
          4,5,6,
          7,8,0]

board = [i for i in range(9)]
shuffle(board)

print(board)
aStar()

class Board():

    def __init__(self,boardList,cost,parent):
        self._array = boardList
        self.heuristic = calcHeuristic(self._array)
        self.cost = cost
        self.totalCost = self.cost + self.heuristic
        self.parent = parent
        self.hashvalue = hash(tuple(self._array))

    def _printBoard(self):
        for var in range(len(self._array)):
            if var%3==0 and var!=0:
                print "\n",self._array[var],",",
            else:
                print self._array[var],",",

    def __hash__(self):
        return self.hashvalue

    def __eq__(self,other):
        return self._array == other._array

def aStar():
    pq = []
    cost = {}
    visited = {}
    start = Board(board,0,None)
    end = Board(fBoard,99,None)
    heapq.heappush(pq,(start.totalCost,start))
    while pq:
        tmp_tuple = heapq.heappop(pq)
        tmp_board = tmp_tuple[1]
        if tmp_board.heuristic == 0:
            end = tmp_board
            break

        index = tmp_board._array.index(0)
        x = index/3
        y = index%3
        listOfMoves = checkMove(x,y)

        for move in listOfMoves:
            moveBoard = tmp_board._array[:]
            moveIndex = move[0]*3 + move[1]
            moveBoard[index],moveBoard[moveIndex] = moveBoard[moveIndex],moveBoard[index]
            newBoard = Board(moveBoard,tmp_board.cost+1,tmp_board)
            new_cost = newBoard.totalCost
            if newBoard not in visited or new_cost < cost[newBoard]:
                cost[newBoard] = new_cost
                visited[newBoard] = 1
                newBoard.parent = tmp_board
                heapq.heappush(pq,(newBoard.totalCost,newBoard))

    var = end
    while var != start:
        print "\n"
        var._printBoard()
        var = var.parent

    print "\n"
    var._printBoard()

def manhattanDist(index,element):
    idx = fBoard.index(element)
    manhattan = 0
    fBoard_x = idx/3
    fBoard_y = idx%3
    x = index/3
    y = index%3
    manhattan += math.fabs(x-fBoard_x)
    manhattan += math.fabs(y-fBoard_y)
    return manhattan

def calcHeuristic(array):
    boardList = array
    heuristic = 0
    for var in boardList:
        x = var/3
        y = var%3
        if fBoard.index(var) != boardList.index(var):
            heuristic+=1
        heuristic+=manhattanDist(boardList.index(var),var)
    return heuristic

def checkMove(x,y):
    listOfMoves = [[x,y]]
    if(x+1<n):
        listOfMoves.append([x+1,y])
    if(x-1>=0):
        listOfMoves.append([x-1,y])
    if(y-1>=0):
        listOfMoves.append([x,y-1])
    if(y+1<n):
        listOfMoves.append([x,y+1])

    return listOfMoves


texts:
I have made this little program for fun, to add on my personal webpage. I remember seeing something like it some time ago, don't remember exactly where, and I tried to reproduce it myself.

As it turns out, I figured out that it isn't quite fun to have your CPU stressed out by 25% because of a funny single homepage, so I won't be using it anymore, but I thought it'd be a good chance to put my efforts to test here on Code Review.

Any thoughts are welcome. I'm specially curious if the way I'm creating the dots looks good or if it is of good performance or not. I profiled the code a few days ago and realized that the main source of processing tasks were related to canvas drawing.

Working example here

var canvas,
    ctx,
    colors = ['#FF6600', '#0099FF', '#BCBCBC', '#3D3D3D'],
    dots = [],
    maxDots = 35;

function Dot() {
    this.alive = true;
    this.x = Math.round(Math.random() * canvas.width);
    this.y = Math.round(Math.random() * canvas.height);
    this.size = Math.round(Math.random() * 7);
    this.velocity = {
        x: (Math.random() < 0.5 ? -1 : 1) * Math.random() * 0.7,
        y: (Math.random() < 0.5 ? -1 : 1) * Math.random() * 0.7
    }
    this.alpha = 0.01;
    this.hexColor = colors[Math.round(Math.random() * (colors.length - 1))];
    this.rgbaStringColor = getRGBA(this.hexColor, this.alpha);
}

Dot.prototype.draw = function () {
    ctx.beginPath();
    ctx.fillStyle = this.rgbaStringColor;
    ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI);
    ctx.fill();
}

function getRGBA(hex, alpha) {
    var r = parseInt(hex.substring(1, 3), 16),
        g = parseInt(hex.substring(3, 5), 16),
        b = parseInt(hex.substring(6, 8), 16),
        a = alpha;
    return 'rgba(' + r + ', ' + g + ', ' + b + ', ' + a + ')';
}

/*updates both colors and position of the dot*/
Dot.prototype.update = function () {
    if (this.alpha < 0.7) {
        this.alpha += 0.01;
        this.rgbaStringColor = getRGBA(this.hexColor, this.alpha);
    }

    this.x += this.velocity.x;
    this.y += this.velocity.y;

    if (this.x > (canvas.width) + 5 || this.x < -5) {
        this.alive = false;
    }
    if (this.y > (canvas.height) - 15 || this.y < -5) {
        this.alpha -= 0.05;
        if (this.alpha <= 0.1) {
            this.alive = false;
        }
    }
}

function createDots() {
    dots = dots.filter(function (dot) {
        return dot.alive;
    });
    for (var length = dots.length; length < maxDots; length++) {
        dots.push(new Dot());
    }
}

function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < dots.length; i++) {
        dots[i].draw();
        dots[i].update();
    }
    createDots();
    window.requestAnimationFrame(update);
}

function init() {
    createDots();
    update();
}

function setCanvasSize() {
    canvas.width = window.innerWidth;
    canvas.height = 300;
}

document.addEventListener('DOMContentLoaded', function () {
    canvas = document.getElementById('universe');
    ctx = canvas.getContext('2d');
    setCanvasSize();
    init();
});


texts: optimizing a bash script chain - speed suggestions?

texts:
i am testing an application that i wrote and want to test the solution my algorithm produces to a Monte carlo solution. I use the harddisk a lot and i was wondering if there was a solution that uses writing data to a file a lot less, since it is really slowing the process down.

The solutions are computed on the nodes of a cluster and examined using this script ( that runs on a node): Parameter $1 is an outputfile that the program wrote.

file=$1
script=/home/hefke/ov_paper/scripts
mv $file.out $file.out.old
grep "Overlapscore:" $file.monte > $file.grepped
awk '/./{print $2}' $file.grepped > $file.overlap
print "$script/std_dev.sh $file.overlap > $file.out"
$script/std_dev.sh $file.overlap > $file.out
cat $file.analy >> $file.out
cat "DONE" >> $file.out

Here is the script that collects the data on the main node. Analy and Monte files are my output files.

echo "Processing outputfiles for the mc_stdev_of_ov"
script=/home/hefke/ov_paper/scripts
curdir=`pwd`
folder=filedata
for file in `ls -1 $curdir/temp_output/$folder/*.analy| sed 's/\(.*\)\..*/\1/'|uniq`
do
    echo $file
    $script/submitter.sh $curdir "processonefile.sh $file.out"
done
echo "$file.out now contains what stdtev spat out."
cat $curdir/temp_output/$folder/*.out >> $curdir/temp_output/tmp.out
awk -f keys.awk $curdir/temp_output/tmp.out >> table.out
cat table.out

How can i optimize this procedure for speed?


texts:
This is the code I currently have for adding various elements inside the svg and then inside a circle. On the text element I added 3 attributes that are the same. But I haven't found a way to remove this to minimize code.

var node = svg.selectAll("circle")
  .data(nodes)
  .enter()
  .append('g')
  .append("circle")
  .style("fill", function (d) {
    return 'rgb(108,181,205)';
  }).on("click", function (d, i) {
    if (i < 5) {
      d.radius *= 1.1;
      d3.select(this).attr("r", d.radius);
      force.resume();
    }
  }).call(force.drag);

// Adding the text
svg.selectAll('g')
  .append('text')
  .attr("text-anchor", "middle")
  .attr("alignment-baseline", "before-edge")
  .attr('font-family', 'FontAwesome')
  .attr('font-size', function(d) { return '1.9em'})
  .append('tspan')
  .attr('x', '0')
  .attr('dy', '-0.2em')
  .style('fill', 'white')
  .style('display', function(d, i) {
    if (i < 5) {
      return 'block';
    }
    else {
      return 'none';
    }
  })
  .text(function(d, i) {
    return circlesText[i].icon;
  });

svg.selectAll('g')
  .append('text')
  .attr("text-anchor", "middle")
  .attr("alignment-baseline", "before-edge")
  .attr('font-family', 'FontAwesome')
  .attr('font-size', function(d) { return '0.9em'})
  .append('tspan')
  .attr('x', '0')
  .attr('dy', '0.9em')
  .style('fill', 'white')
  .style('display', function(d, i) {
    if (i < 5) {
      return 'block';
    }
    else {
      return 'none';
    }
  })
  .text(function(d, i) {
      return circlesText[i].text[0];
  });

svg.selectAll('g')
  .append('text')
  .attr("text-anchor", "middle")
  .attr("alignment-baseline", "before-edge")
  .attr('font-family', 'FontAwesome')
  .attr('font-size', function(d) { return '0.9em'})
  .append('tspan')
  .attr('x', '0')
  .attr('dy', '1.8em')
  .style('fill', 'white')
  .style('display', function(d, i) {
    if (i < 5) {
      return 'block';
    }
    else {
      return 'none';
    }
  })
  .text(function(d, i) {
      return circlesText[i].text[1];
  });

svg.selectAll('g')
  .append('text')
  .attr("text-anchor", "middle")
  .attr("alignment-baseline", "before-edge")
  .attr('font-family', 'FontAwesome')
  .attr('font-size', function(d) { return '1.9em'})
  .append('tspan')
  .attr('x', '0')
  .attr('dy', '1.8em')
  .style('fill', 'white')
  .style('display', function(d, i) {
    if (i < 5) {
      return 'block';
    }
    else {
      return 'none';
    }
  })
  .text(function(d, i) {
      return '\uF056';
  });


texts: Checking balance of a travel card with Selenium

texts:
A Leap Card is essentially a travel card for Dublin, Ireland that can be used to pay for a bus or tram fare. It has to be topped up and I often forget how much I have left on it.

To get familiar with Selenium, I wrote some code that gets the balance for me. I haven't worked with this framework before, so I'd like to know if there's room for improvement here.

import json

from selenium import webdriver

def get_credentials():
    """Get user credentials from a JSON file"""
    with open('auth.json', 'r') as f:
        auth = json.load(f)
        username = auth['username']
        password = auth['password']
    return username, password

class LeapHandler:
    """Class to handle any interactions with Leap Card website"""

    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://www.leapcard.ie/en/login.aspx')
        self.login()

    def get_login_elements(self):
        """Find and return elements necessary to log in"""
        username_id = 'ContentPlaceHolder1_UserName'
        password_id = 'ContentPlaceHolder1_Password'
        login_id = 'ContentPlaceHolder1_btnlogin'
        username_field = self.driver.find_element_by_id(username_id)
        password_field = self.driver.find_element_by_id(password_id)
        login_button = self.driver.find_element_by_id(login_id)
        return username_field, password_field, login_button

    def login(self):
        """Login into user account"""
        username_field, password_field, login = self.get_login_elements()
        username, password = get_credentials()
        username_field.send_keys(username)
        password_field.send_keys(password)
        login.click()

    def get_balance(self):
        """Return current Leap Card Balance"""
        balance = self.driver.find_element_by_css_selector('div.pull-left').text
        return balance

if __name__ == '__main__':
    lh = LeapHandler()
    balance = lh.get_balance()
    print(f'LepaCard balance is €{balance}')


texts: Find the smallest element in a sorted and rotated array

texts:
I was solving a question asked in interview by Uber. It says:

  Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. Find the minimum element in \$O(\log n)\$ time. You may assume the array does not contain duplicates.

#include <iostream>

int find_smallest(int a[], int l, int r){
    if (l ==r)
        return a[l];
    else if (l+1 == r)
        return ((a[l] < a[r]) ? a[l] : a[r]);
    else {
        int m = (l + r) / 2;
        int d1 = find_smallest(a, l, m);
        int d2 = find_smallest(a, m+1, r);
        return  ((d1 < d2) ? d1 : d2);
    }
}

int main(){
    int a[] = {5,3,2,5,6,7};
    std::cout << find_smallest(a, 0, 5);
}

Please ignore the hardcoding of values. It was just for testing.
Also, is the runtime of the code \$O(\log n)\$?


texts: Readers-writers problem using wait notify

texts:
Description of the Readers–writers problem.

It looks like it works, but I have some doubts:

class ReadWriteBuffer<T> {

    private static final Object writeLock = new Object();

    private static final Object readWriteLock = new Object();

    private int numberReaders = 0;

    private int numberWriters = 0;

    private int numberWriteRequests = 0;

    public void write(T object) throws InterruptedException {

        numberWriteRequests++;

        synchronized (readWriteLock) {
            while (numberReaders > 0) {
                readWriteLock.wait();
            }
        }

        synchronized (writeLock) {

            numberWriteRequests--;

            numberWriters++;

            System.out.println("Writer #" + Thread.currentThread().getId() + " started writing.");
            Thread.sleep(3000);
            System.out.println("Writer #" + Thread.currentThread().getId() + " finished writing.");

            numberWriters--;

            synchronized (readWriteLock) {
                readWriteLock.notifyAll();
            }
        }
    }

    public void read() throws InterruptedException {

        synchronized (readWriteLock) {
            while (numberWriters > 0 || numberWriteRequests > 0) {
                readWriteLock.wait();
            }
        }

        numberReaders++;

        System.out.println("Reader #" + Thread.currentThread().getId() + " started reading.");
        Thread.sleep(1000);
        System.out.println("Reader #" + Thread.currentThread().getId() + " finished reading.");

        numberReaders--;

        synchronized (readWriteLock) {
            readWriteLock.notifyAll();
        }
    }
}

class Reader implements Runnable {

    private final ReadWriteBuffer<Object> buffer;

    private int priority;

    public Reader(int priority, ReadWriteBuffer<Object> buffer) {
        this.priority = priority;
        this.buffer = buffer;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(priority);
                buffer.read();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Writter implements Runnable {

    private final ReadWriteBuffer<Object> buffer;

    private int priority;

    public Writter(int priority, ReadWriteBuffer<Object> buffer) {
        this.priority = priority;
        this.buffer = buffer;
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(priority);
                buffer.write("Object");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ReadersWriters {

    public static void main(String[] args) {

        ReadWriteBuffer<Object> sharedBuffer = new ReadWriteBuffer<Object>();

        new Thread(new Reader(1, sharedBuffer)).start();
        new Thread(new Reader(700, sharedBuffer)).start();
        new Thread(new Reader(100, sharedBuffer)).start();
        new Thread(new Writter(2000, sharedBuffer)).start();
        new Thread(new Writter(4000, sharedBuffer)).start();
    }
}


texts:
Purpose of this small module is to allow memoization of slow URL get requests. I intend to send many of these to download a bunch of files from internal (rather slow, old) website. Some requests may repeat many times - thus the memoization. Website is old so I'm limiting concurrent requests to 100.

I would love to hear code review remarks as I'm not a profession programmer but a user of python, so love to learn.

Thank you!

import os
import asyncio
import aiohttp
import functools
import aredis

proxy = os.environ.get("https_proxy")
redis = aredis.StrictRedis()
sem = asyncio.Semaphore(100)

async def cache_in(url, body):
    """Keep url-> body key value in redis"""
    return await redis.set(url, body)

async def cache_out(url):
    """Get url body out from redis"""
    return await redis.get(url)

def redismem(func):
    """Redis memoize decorator."""
    @functools.wraps(func)
    async def inner(url):
        if body := await cache_out(url):
            return body
        body = await func(url)
        await cache_in(url, body)
        return body
    return inner

@redismem
async def get(url):
    """Get url"""
    async with aiohttp.ClientSession() as session:
        async with sem, session.get(url, proxy=proxy) as resp:
            body = await resp.read()
            return body


texts: Calculating the determinants of data entered

texts:
This program is supposed to calculate the determinants of the data entered. I believe it does. Within the guidelines of this exercise we were not to break this down to functions but all out of main. We will be breaking it down into functions in part a and b of this overall exercise.

However, I don't know enough about matrices and determinants yet to know if I am using the equation given to me correctly. I know this out puts the data given to the screen correctly and the formula given was:

determinant = (AEI) + (BFG) + (CDH) - (BDI) - (AFH) - (CEG)

which equates to the array elements:

00 * 11 * 22 + 01 * 12 * 20 + 02 * 10 * 21- 01 * 10 * 22 - 00 * 12 * 21 - 02 * 11 * 20

Given the 3x3 block where the first row is ABC, second row of DEF and third row of GHI.

I am asking that it be analyzed and critiqued.

# include <iostream>
# include <stdio.h>
# include <iomanip>

using namespace std;

int main()
{
    int x,y,z,;
    char ch;
    float  My3DMatrix[3][3];
    int mReader[9];
    for (x = 0 ; x <= 8 ; x++)//This array is for accessing the Matrix elements in
    {                     //the prescribed manner to calculate the determ.
        y = x;
        if( x == 3 || x == 8 )y = 1;
        if(x == 4 || x ==6 )y = 2;
        if(x == 5 || x == 7 )y = 0;
        mReader[x] = y;
    }
    do  //This initiates the main loop
    {
        cout<<"Calculation of  3 x 3 Determinant"<<endl<<endl;
        for(x = 0; x<=2 ;x++) // This loop querries the user for
        {                     //input and feeds the My3DMatrix
            cout<<"What is row "<<x+1<<" of the matrix? ";
            for (y = 0 ; y <=2 ; y++)
            {
                cin>>My3DMatrix[x][y];
            }   //The matrix is now fed
        }
        cout<<"\nThe 3 x 3 Matrix entered is: "<<endl; //Now the Raw
        cout<<setprecision(3)<<fixed; //Matrix data is displayed
        for(x = 0 ; x<=2 ; x++)
        {
            cout<<My3DMatrix[x][0]<<"\t"<<My3DMatrix[x][1]<<"\t"
                <<My3DMatrix[x][2]<<endl;
        }
        float Determinant[6]; //This array is for storing the 6
        y = -1 ; z = 0; //products from each row of the matrix
        for(x = 0 ; x <= 8 ; x++)// There are 9 indexes to create 3 products from
        {   //This loop pulls the correct indexes from My3DMatrix then  creates
            if (z>=3) z = 0; //and stores the products into Determinant[x] 0 - 2
            if ((x % 3) == 0 || x == 0)
            {
                y = y + 1;
                Determinant[y] = 1;
            }
            Determinant[y] =  Determinant[y] * My3DMatrix[z][mReader[x]];
            z = z + 1;
        }
        y = 2 ; z = 0;
        for(x = 9 ; x >= 1 ; x--)// There are 9 indexes to create 3 products from
        {       //This loop pulls the correct indexes from My3DMatrix then creates
            if (z>=3) z = 0;//and stores the products into Determinant[x] 3 - 5
            if ((x % 3) == 0 || x == 0)
            {
                y = y + 1;
                Determinant[y] = 1;
            }
            Determinant[y] =  Determinant[y] * My3DMatrix[z][mReader[x - 1]];
            z = z + 1;
        }
        float myAnswer;
        myAnswer = 0;//Here with Determinant[6] loaded with the correct index products:
        myAnswer = Determinant[0] + Determinant[1] + Determinant[2] ; //The deternm.
        myAnswer = myAnswer -  Determinant[3] - Determinant[4] - Determinant[5]; //and simple calculation is plain
            cout<<"The determinant of the above matrix is: "<< myAnswer<< endl;
        cout<<"Would you like to Do another Matrix (Y/N)? ";

        cin>>ch ;
    }while(ch == 'Y' || ch == 'y');

    cin.get();

    return 0;
}


texts: Hide/un-hide directory and open directory based on argument

texts:
This code checks to make sure a directory is hidden and if not hides it.  Then if hidden it will prompt for password and if password matches it will un-hide it.  There is also an argument to open un-hidden directory too.

#! /bin/bash

DIR="path/untitled"
DIR2="path/.untitled"
password="Z2FsdGVkX18vy4f4QRB3qnb5vIWR0x+tlZmdAmPxX8Y="
input=""
result=""

basic()
{
    if [ -d "$DIR" ]
    then
        clear
        mv $DIR $DIR2
    elif [ -d "$DIR2" ]
    then
        echo -n ": "
        read -s input
        result=$(echo "$password"| openssl enc -aes-128-cbc -a -d -salt -pass pass:wtf)

        if [ "$result" = "$input" ]
        then
            clear
            mv $DIR2 $DIR
        else
            clear
        fi
    else
        :
    fi
exit
}

opendir()
{
    if [ -d "$DIR" ]
    then
        clear
        mv $DIR $DIR2
    elif [ -d "$DIR2" ]
    then
        echo -n ": "
        read -s input
        result=$(echo "$password"| openssl enc -aes-128-cbc -a -d -salt -pass pass:wtf)

        if [ "$result" = "$input" ]
        then
            clear
            mv $DIR2 $DIR
            open $DIR
        else
            clear
        fi
    else
        :
    fi
exit
}

#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Main ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
if [ $# -eq 0 ]
then
    basic
elif [ $# -eq 1 ]
then
    if [ "$1" = "-o" ]
    then
       opendir
    else
        :
    fi
fi
clear
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ End of File ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


texts:
I've been making a program for an assignment that converts fractions to mixed numbers, and I'm done, but I was wondering if I could simplify it in any way, since it seems quite complicated right now.

Also, keep in mind that I am not allowed to use any Math or String methods to do this assignment, and I can only use +, -, *, and / as arithmetic operators. I also cannot use % or a modulus function.

I realize this is an assignment, and it's fine if you choose not to give me an answer. In fact, I'd actually prefer to have some tips or hints to help figure out how to solve it, rather than just telling me the answer.

Also, the 'c.print' is basically a print statement. I'm importing/using a different custom class, which is why it is different from the normal print statement.

    int numerator = 0; //can change to any value
int denominator = -2; //can change to any value
public int[] reducedFraction (int numerator, int denominator)
{
    int GCD = numerator;
    int tempN = numerator;
    int tempD = denominator;
    int[] fractionParts = {0, numerator, denominator};

    if (numerator == 0) //if the numerator is 0
    {
        return fractionParts;
    }

    //Making sure the program works with negative values by temporarily converting GCD and fractionParts[2] to positive values
    GCD = (numerator < 0) ? -numerator:
    numerator;

    tempD = (denominator < 0) ? -denominator:
    denominator;

    //Finding the GCD of the numerator and denominator
    while (GCD != tempD)
    {
        if (GCD > tempD)
            GCD -= tempD;
        else
            tempD -= GCD;
    }

    //Simplfying numerator and denominator
    fractionParts [1] /= GCD;
    fractionParts [2] /= GCD;

    //Temporarily making the numerator and denominator positive
    tempN = (fractionParts [1] < 0) ? -fractionParts [1]:
    fractionParts [1];

    tempD = (fractionParts [2] < 0) ? -fractionParts [2]:
    fractionParts [2];

    //if the numerator is not greater than the denominator return the simplified fraction.
    if (tempN < tempD)
    {
        return fractionParts;
    }

    //Finding value of whole number, numerator and possibly converting denominator to original sign
    fractionParts [0] = fractionParts [1] / fractionParts [2];
    fractionParts [1] = fractionParts [1] - (fractionParts [1] / fractionParts [2]) * fractionParts [2];

    if (fractionParts [1] < 0 && fractionParts [2] < 0) //if the numerator and denominator are both negative
    {
        fractionParts [1] = (fractionParts [1] < 0) ? -fractionParts [1]:
        fractionParts [1];

        fractionParts [2] = (fractionParts [2] < 0) ? -fractionParts [2]:
        fractionParts [2];
    }

    return fractionParts;
}

public void display ()
{
    if (reducedFraction (numerator, denominator) [1] == 0)
        c.print (reducedFraction (numerator, denominator) [0]);

    else if (reducedFraction (numerator, denominator) [0] == 0)
        c.print (reducedFraction (numerator, denominator) [1] + "/" + reducedFraction (numerator, denominator) [2]);

    else
        c.print (reducedFraction (numerator, denominator) [0] + " " + reducedFraction (numerator, denominator) [1] + "/" + reducedFraction (numerator, denominator) [2]);
}


texts:
I have found the convert_to function in the lua-user wiki, and I created the convert_to_time function which does what I want it to do. Which is, basically: Having a number, return its value in a Time format.

The values range is:  [0..863999] as we want the data in 0..24 hours format by step of 0.1 second.

The code from the lua-user-wiki, had a step of 1 second so I had to change the base to fit my specifications, but because of that I've had to create too many conditions to be able to always print out the value I want. I had issues with printing 01:00:00 for example.

If someone of you can give it a view and suggest me a simpler way to achieve what I want in ALL situations I would appreciate it.

intervals={
 {"seconds",1}, --the "1" should never really get used but
 {"minutes",60},
 {"hours",60},
 {"days",24},
}

positions={}
for i=1,4 do
 positions[intervals[i][1]]=i
end

function convert_to(value, sourceunits, targetunits)

local sourcei, targeti = positions[sourceunits], positions[targetunits]
assert(sourcei and targeti)

if sourcei<targeti then

  local base=10
  for i=sourcei+1,targeti do
    base=base*intervals[i][2]
  end

  return value/base

elseif sourcei>targeti then

  local base=10
  for i=targeti+1,sourcei do
    base=base*intervals[i][2]
  end

  return value*base
else return value end
end

function convert_to_time(value)
  local returnString = "", horas, minutos, segundos

  horas = tostring(convert_to(value,"seconds","hours")) -- return : 12.888888889
  if(tonumber(string.match(horas, "%.(%w+)"))==nil) then return (horas ..":00:00") end
  minutos = tostring(convert_to("0."..string.match(horas, "%.(%w+)"),"hours","minutes")/10) -- returns : 53.33333334
  if(tonumber(string.match(minutos, "%.(%w+)"))==nil) then return (string.match(horas, "(%w+)%.") .. minutos ..":00") end
  segundos = tostring(convert_to("0."..string.match(minutos, "%.(%w+)"),"minutes","seconds")/10) -- returns : 20.0000000004

  horasStr = string.match(horas, "(%w+)%.")
  minutosStr = string.match(minutos, "(%w+)%.")
  if string.match(segundos, "%.") then
    segundosStr = string.match(segundos, "(%w+)%.")
  else
  segundosStr = segundos
  end

  -- Ñapa para que los numeros se vean en formato hh:mm:ss
  if (tonumber(horasStr) < 10) then if (tonumber(horasStr)==nil) then horasStr = "00" end horasStr = "0"..horasStr end
  if (tonumber(minutosStr) < 10) then if (tonumber(minutosStr)==nil) then minutosStr = "00" end minutosStr = "0"..minutosStr end
  if (tonumber(segundosStr) < 10) then if (tonumber(segundosStr)==nil) then segundosStr = "00" end segundosStr = "0"..segundosStr end

  returnString = horasStr .. ":" .. minutosStr .. ":" .. segundosStr

  return returnString

 end

You can test the code for this example:

print(convert_to_time(36000))


texts: Multiplying and adding big numbers represented with strings

texts:
I got a very unusual problem of adding and multiplying very big numbers (≥ 1e+100). So I've written simple functions that would operate on string representations of numbers, both as an input and an output.

Multiplication:

function multiply(a, b) {
    if ((a | 0) == 0 || (b | 0) == 0) {
        return '0';
    }

    a = a.split('').reverse();
    b = b.split('').reverse();
    var result = [];

    for (var i = 0; a[i] >= 0; i++) {
        for (var j = 0; b[j] >= 0; j++) {
            if (!result[i + j]) {
                result[i + j] = 0;
            }

            result[i + j] += a[i] * b[j];
        }
    }

    for (var i = 0; result[i] >= 0; i++) {
        if (result[i] >= 10) {
            if (!result[i + 1]) {
                result[i + 1] = 0;
            }

            result[i + 1] += parseInt(result[i] / 10);
            result[i] %= 10;
        }
    }

    return result.reverse().join('');
}

Addition:

function add(a, b) {
    if ((a | 0) == 0 && (b | 0) == 0) {
        return '0';
    }

    a = a.split('').reverse();
    b = b.split('').reverse();
    var result = [];

    for (var i = 0; (a[i] >= 0) || (b[i] >= 0); i++) {
        var sum = (parseInt(a[i]) || 0) + (parseInt(b[i]) || 0);

        if (!result[i]) {
            result[i] = 0;
        }

        var next = ((result[i] + sum) / 10) | 0;
        result[i] = (result[i] + sum) % 10;

        if (next) {
            result[i + 1] = next;
        }
    }

    return result.reverse().join('');
}

Are there better ways of doing this job? Some additional edge cases or better loop conditions, maybe?


texts:
I am trying to parse this XML file. I have the extension and I need to get the description, icon, and class from the XML. My code works(ish) (I know how to continue from where I am), but it doesn't seem very elegant. Is there a better way of doing this?

Here is the PHP code:

<?php
if($xml = simplexml_load_file('formats.xml')) {
    echo 'the file was loaded successfully';

    $extn = 'log';

    $xmltypes = $xml->xpath('//type');

    foreach($xmltypes as $node) {
        foreach($node->attributes() as $name => $attrib) {
            if($name=='extension') {
                if($attrib==$extn) {
                    $parent = $node->xpath('..');
                    foreach($parent[0]->attributes() as $a => $b) {
                        if($a=='class')
                            $class = $b;
                        if($a=='icon')
                            $icon = $b;
                    }
                }
            }
        }
    }
    echo $extn.'
';
    echo $icon.'
';
    echo $class.'
';
}
else {
    echo 'the file was not loaded';
}
?>

Here is the XML file:

<?xml version="1.0"?>
<extensions>
<group class="doc">
    <group icon="./.images/doc.png">
        <type extension="doc" description="Legacy Word Document" />
        ...
        ...
        <type extension="wps" description="Works Document" />
    </group>
</group>

<group class="video">
    <group icon="./.images/video.png">
        <type extension="asf" description="Advanced Streaming Format" />
        ...
        ...
        <type extension="mpeg" description="Motion Picture Experts Video" />
    </group>
</group>
</extensions>


texts:
I was wondering if there's a better way of doing LINQ projections than what I'm doing below. This method is one of many methods creating a view of an object tree.

The first thing that I don't like is that I'm returning an anonymous object. Should I create a BreakdownReport class or something else instead?

Also, the copying of property values from right to left is a bit of a hassle.

public object GetBreakdownsReport()
{
    return CurrentSecurity
        .Breakdowns
        .SelectMany(b => b.BreakdownLines, (b, bdl) => new
        {
            AccountId = b.Account.Id,
            Structure = b.Account.Structure,
            Market = b.Account.Market,
            BeneficiaryId = bdl.Beneficiary.Id,
            BeneficiaryType = bdl.Beneficiary.BeneficiaryType,
            CountryCode = bdl.Beneficiary.CountryCode,
            CountryName = bdl.Beneficiary.CountryName,
            DtaRate = bdl.Beneficiary.DtaRate,
            HoldingCode = b.HoldingCode,
            InstructionAmount = bdl.InstructionAmount,
            NarrativeText = bdl.Narrative.Text,
            Chapter = bdl.Narrative.Chapter,
            Paragraph = bdl.Narrative.Paragraph,
            Subparagraph = bdl.Narrative.Subparagraph,
            TaxRate = bdl.Narrative.TaxRate,
        })
        .ToList();
}


texts:
This questions is originally from http://contestcoding.wordpress.com/2013/06/28/fizz-buzz-bizz-fuzz/.

  Print the integers from 1 to 100,
  but for the multiples of 3, print "Fizz" instead and
  for multiples of 5, print "Buzz".
  If the number contains a 3 (for example 23), print "Bizz" and
  if the number contains a 5, print “Fuzz”
  (if it contains multiple 3s or 5s, just print one "Bizz" or "Fuzz").
  If the number contains more than one of these attributes, print every word (for example 33 prints "FizzBizz", as 33 is both a multiple
  of 3 and contains the digit 3).

My Java solution is:

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i < 101; i++) {
            // Set this to true when one of the special conditions is met.
            boolean printed = false;

            if (i % 3 == 0) {
                // When i is divisible by 3, then print "Fizz"
                printed = true;
                System.out.print("Fizz");
            } else if (i % 5 == 0) {
                // When i is not divisible by 3 but is divisible by 5, then print "Buzz"
                printed = true;
                System.out.print("Buzz");
            }

            if (Integer.valueOf(i).toString().indexOf("3") != -1) {
                // When i has the digit 3 in it, then print "Bizz"
                printed = true;
                System.out.print("Bizz");
            } else if (Integer.valueOf(i).toString().indexOf("5") != -1) {
                // When i has the digit 5 in it, then print "Fuzz"
                printed = true;
                System.out.print("Fuzz");
            }

            if (printed == false) {
                // The number does not satisfy any of the special conditions above.
                System.out.print(i);
            }
            System.out.println();
        }
    }
}

Please provide code review comments.


texts:
Example Script is located in /home/insp/public_html/deploy/

I want to return the /home/insp/ section

$path = realpath(__DIR__);

        $parts = explode('/', $path);

        $newPath = array(
            $parts[0],
            $parts[1],
            $parts[2],
        );

        $realPath = implode('/', $newPath);

Is there a better/more effeicent way to acheve this?


texts: Project Euler, problem # 9, Pythagorean triplet

texts:
Project Euler #9, Pythagorean triplet is

  A Pythagorean triplet is a set of three natural numbers \$a < b < c\$
  for which \$a^2 + b^2 = c^2\$.

  For example, \$3^2 + 4^2 = 9 + 16 = 25 = 5^2\$.

  There exists exactly one Pythagorean triplet for which \$a + b + c = 1000\$.   Find the product \$a b c\$.

Here is my implementation in Python, awaiting your feedback.

def get_triplet():
    for c in range(2, 1000):
        for b in range(2, c):
            a = 1000 - c - b
            if a ** 2 + b ** 2 == c ** 2:
                return 'n1 = %s\nn2 = ' \
                       '%s\nn3 = %s\nproduct = %s' \
                       % (a, b, c, a * b * c)

if __name__ == '__main__':
    print(get_triplet())


texts: Migrating data from multiple spreadsheets to multiple text files

texts:
This is like the reverse functionality of Text file to spreadsheet.

One or multiple .xlsx files in the path of the script get opened and the content is split into multiple .txt files.

For example, say you have two excel files in the folder:

file1.xlsx

file2.xlsx

The output created:

spreadsheet_to_text.py

"""
Reads in .xlsx files from path were the script is located.
Then the data of each column is split into a .txt file
"""

import glob
import openpyxl
from openpyxl.utils import get_column_letter

def get_text_filename(filename: str, column: int)->str:
    """
    Creates a text filename based on .xlsx file filename and column
    """
    return (filename.rstrip(".xlsx")
            + "_" + get_column_letter(column) + '.txt')

def xlsx_to_txt(filename: str):
    """
    Extract data from a .xlsx file in the script folder into
    multiple .txt files
    """
    workbook = openpyxl.load_workbook(filename)
    sheet_names = workbook.sheetnames
    sheet = workbook[sheet_names[0]]

    for column in range(1, sheet.max_column + 1):
        if sheet.cell(row=1, column=column).value:
            text_filename = get_text_filename(filename, column)
            with open(text_filename, mode='w') as textfile:
                for row in range(1, sheet.max_row + 1):
                    if sheet.cell(column=column, row=row).value:
                        textfile.writelines(
                            sheet.cell(column=column, row=row).value + '\n')

def spreadsheet_into_text():
    """main logic for split spreadsheet data into multiple text files"""
    for filename in glob.iglob("*.xlsx"):
        xlsx_to_txt(filename)

if __name__ == "__main__":
    spreadsheet_into_text()

I already incorporated some improvements from Text file to spreadsheet. I wonder how the code can get further improved.


texts: Teamwork challenge for Timus Online Judge

texts:
Question is here:

  Input

  The first line contains an integer \$N\$, which is the quantity of numbers written down by Vasya (\$1 \le N \le 1000\$). The second line contains these numbers separated by spaces. All the numbers are positive integers not greater than 10.

  Output

  Output the numbers Petya would write down separated by space.

For instance, the sequence "1 1 2 3 3 3 10 10" will be told by Vasya as "two ones, one two, three threes, two tens". Petya also wants to be concise, so he writes down the numbers pronounced by Vasya instead of the whole words. For the example above, Petya would write: "2 1 1 2 3 3 2 10".

public class TestClass {

    static String firstLine = "8";
    static String secondLine = "1 1 2 3 3 3 10 10";

    public static void main(String[] args) {
        int countOfIntegersToBeProcessed = Integer.parseInt(firstLine);
        String[] integersAsStringArray = secondLine.split(" ");
        int localCounterForASpecificInteger = 1;
        for (int integersToBeProcessedCounter = 0; integersToBeProcessedCounter < countOfIntegersToBeProcessed; integersToBeProcessedCounter++) {
            String integerBeingProcessed = integersAsStringArray[integersToBeProcessedCounter];
            if (integersToBeProcessedCounter == countOfIntegersToBeProcessed - 1) {
                System.out.print(localCounterForASpecificInteger + " " + integerBeingProcessed);
                return;
            }
            if (integerBeingProcessed.equals(integersAsStringArray[integersToBeProcessedCounter + 1])) {
                localCounterForASpecificInteger++;
            } else {
                System.out.print(localCounterForASpecificInteger + " " + integerBeingProcessed + " ");
                localCounterForASpecificInteger = 1;
            }
        }
    }

}

And the output will be:

  2 1 1 2 3 3 2 10


texts:
I was testing the RGB color mechanic on Excel, so I did the following:

sub paint()
red = 255
blue = 0
green = 0
Max = 48
For col = 1 To Max
    For Row = 1 To Max
        Cells(Row, col).Interior.Color = RGB(red - col * Int(256 / (Max * 2)) - Row * Int(256 / (Max * 2)), green + col * Int(256 / Max), blue + Row * Int(256 / Max))
    Next Row
Next col
end sub

This makes an RBG chart on Excel filling the interior color of every cell on a max x max square. It was just made as a test and I think it worked pretty well.

I am looking for improvement, if possible.


texts: Checking if an event is not null before firing it in C#

texts:
I often see this for custom events:

void InvokeCustomEvent(EventArgs e)
{
    var handler = CustomEvent;
    if (handler != null) handler(this, e);
}

But is creating the handler variable required, best practice, or superfluous, when compared to:

void InvokeCustomEvent(EventArgs e)
{
    if (CustomEvent != null) CustomEvent(this, e);
}

?