texts: Generating unique names for things like filenames

texts:
There are systems that when you duplicate an asset, the new assets are created with an index, so that the name do not collide. For instance, if I have an asset called House, and I press "Duplicate", a new asset will be created called House (1), and if I press again, it will be called House (2)
I wanted to make a system to duplicate that behavior, but I'm not sure if I am making it too complicated, or faulty. I'm also scared of infinite loops.
How would you improve this?
    public class NameGenerator
    {
        private readonly string baseName;

        private readonly Func<string, bool> isValid;

        public NameGenerator(string baseName, Func<string, bool> isValid)
        {
            this.baseName = baseName;
            this.isValid = isValid;
        }

        public string Generate()
        {
            if (isValid(baseName)) return baseName;

            for (var i = 0; ; i++)
            {
                var candidate = $"{baseName} ({i})";
                if (isValid(candidate)) return candidate;
            }
        }
    }
```


texts:
I've just created my first tests using mock classes. So far my tests are running much faster and now I guess I'm solely focusing on a single class (in this case I'm testing UserTable and mocking the DatabaseAdapter instance I inject into it)

I haven't proceeded to do the write tests for the other methods of this class (just testing "create" method for now), I was hoping someone could comment on my tests for this method. It simply creates a new record in the user table. I'm trying to test all possibilities that I should be testing. I'm a little new to this and not quite sure if I've got it right yet.

<?php

use app\models\UserTable;
use app\models\User;

/**
*    UserTableTest
*/
class UserTableTest extends PHPUnit_Framework_TestCase
{
    protected $dbAdapter;
    protected $userTable;

    public function setUp()
    {
        // create mock database adapter
        $this->dbAdapter = $this->getMockBuilder('framework\Db\DatabaseAdapter')
            ->disableOriginalConstructor()
            ->getMock();

        // create our instance of the class to be tested
        $this->userTable = new UserTable;
    }

    // create method

    public function testCreateMethodWhenSuccessfullyInsertsRow()
    {
        // set mock class

        // set the mock object's methods for this test
        $this->dbAdapter->expects( $this->any() )
            ->method('insert')
            ->will( $this->returnValue(true) );

        $this->userTable->setDatabaseAdapter($this->dbAdapter);

        // perform test

        // assert user is created when valid argument is passed
        $result = $this->userTable->create( array() );

        $this->assertTrue($result);
    }

    public function testCreateMethodWhenFailsToInsertsRow()
    {
        // set mock class

        // set the mock object's methods for this test
        $this->dbAdapter->expects( $this->any() )
            ->method('insert')
            ->will( $this->returnValue(false) );

        $this->userTable->setDatabaseAdapter($this->dbAdapter);

        // perform test

        // assert user is created when valid argument is passed
        $result = $this->userTable->create( array() );

        $this->assertFalse($result);
    }

    /**
    * @expectedException InvalidArgumentException
    */
    public function testCreateMethodWithInvalidArguments()
    {
        // set mock class

        // set the mock object's methods for this test
        $this->dbAdapter->expects( $this->any() )
            ->method('insert')
            ->will( $this->returnValue(false) );

        $this->userTable->setDatabaseAdapter($this->dbAdapter);

        // perform test

        // pass invalid argument, should be an array of values
        $result = $this->userTable->create('invalid argument type');
    }

    /**
    * @expectedException RuntimeException
    */
    public function testCreateMethodWithMissingDatabaseAdapter()
    {
        // assert user is created
        $result = $this->userTable->create( array() );
    }
}


texts: Detecting a combination of characters from input

texts:
Write a program that reads input up to # and reports the number of times that
  the sequence ei occurs.

Is this a decent code?

#include <stdio.h>

int main(void)

{
    int index = 0, combinationTimes = 0, total = 0;
    char userInput;
    char wordChar[index];

    printf("please enter your input:\n");

    while ((userInput = getchar()) != '#')
    {
        if (userInput == '\n')
            continue;

        wordChar[index] = userInput;
        index++;
        total++;
    }

    for (index = 1; index < total; index++)
    {
        if (wordChar[index] == 'i')
        {
            if (wordChar[--index] == 'e')
            {
            combinationTimes++;
            ++index;
            }
        }
    }

    printf("number of combination is: %d", combinationTimes);

    return 0;
}


texts:
I am developing my first website in Flask using PostgreSQL and I want my database to have professors from all universities and courses in the USA.

As I am not very familiar with databases I have experienced some issues with my database model design.

Basically, I want to have a Professor, College and  Course models.

1) A professor has:

An id (primary key)
A name
A college (foreign key)
A course (foreign key)

2) A college has:

An id (primary key)
A name (e.g. Harvard University)
Many professors

3) A course in my model is not a college-specific course (e.g. Harvard CS) but a subject which can be identical throughout many colleges, e.g. Biology. It therefore has:

An id (primary key)
A name (e.g. Biology)
Many professors

My end goal is just to have a list of all professors and people can search through them by filtering according to a subject, college, or both.

As you can see I haven't implemented a relationship between colleges and courses.

This is my code:

class Professor(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(80), unique=False)
  college_id = db.Column(db.Integer, db.ForeignKey('college.id'))
  course_id = db.Column(db.Integer, db.ForeignKey('course.id'))

class College(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(120), unique=True)
  professors = db.relationship('Professor', backref='college', lazy='dynamic')

class Course(db.Model):
  id = db.Column(db.Integer, primary_key=True)
  name = db.Column(db.String(120), unique=True)
  professors = db.relationship('Professor', backref='course', lazy='dynamic')

I was wondering if this is a good database design. Am I going to be able to do what I'm aiming for with the DB models staying the same?


texts: Break a full name into a dictionary of its parts

texts:
It seems like I'm repeating myself here. Is there a standard way to deal with code like this?

def getNameParts(name):
    """Return a dictionary of a name's parts.
    name: e.g. 'JOHNSON, John Roberts, Jr. (Jack)'
    Ignores nicknames.
    """
    csSplit = name.split(', ')
    try:
        last = csSplit[0]
    except:
        last = ''
    try:
        first = csSplit[1].split(' ')[0]
    except:
        first = ''
    try:
        middle = ' '.join(csSplit[1].split(' ')[1:])
    except:
        middle = ''
    try:
        suffix = csSplit[2].split(' ')[0]
    except:
        suffix = ''
    partsDict = {'first': first,
                 'last': last,
                 'middle': middle,
                 'suffix': suffix}
    return(partsDict)


texts:
I am experimenting with streams and lambdas in Java 8. This is my first serious foray using functional programming concepts; I'd like a critique on this code.

This code finds the Cartesian product of three sets of ints. My questions/complaints about this snippet are:

Are nested flatMaps really the best (most understandable, most CPU/memory efficient) way to do an arbitrary Cartesian product? Or should I stick to imperative style for Cartesian products?
Is there a better way to format nested lambdas (see, e.g., my use of flatMap)?

I just learned about Collectors; those might be what I need. I'm still learning how to best combine these things.

long count = IntStream.rangeClosed(0,9) /* 0 <= A <= 9 */
    .parallel()
    .mapToObj(Integer::valueOf)
    .flatMap(a ->
            IntStream.rangeClosed(0,9) /* 0 <= B <= 9 */
            .mapToObj(Integer::valueOf)
            .flatMap(b ->
                    IntStream.rangeClosed(0,9) /* 0 <= C <= 9 */
                    .mapToObj(c -> (new Product()).A(a).B(b).C(c))
            )
     ).count();
System.out.println("Enjoy your Cartesian product." + count);

UPDATE: I deliberately omitted boilerplate code and class/method definitions, for brevity. The only important thing about Product is that it stores three ints.


texts:
I'm trying to dynamically generate some MarkDown formatted documents, with header fields of arbitrary lengths.

I want to have a title of arbitrary length underlined like this
---------------------------------------------------------------

This should work to
-------------------

The code I came up with to do this in my ERB views.

<%= @title %>
<%= @title.length.times.map{"-"}.join %>

Is there a more efficient way to make this happen?


texts:
I want to implement a d-max heap using a bottom-up approach. This way I will start from the last parent in the tree and build myself up to the root of the heap. We will compare children and parents in order to create a d-max heap.

template <typename Comparable>
void buildHeapBottomUp(Comparable arr[], int n, int d)
{
    bool check;
    do
    {
        check = false;
        for (int i = n - 1; i >= 0; i--)
        {
            if (arr[i] > arr[(i - 1) / d])
            {
                int current = i;
                int parent = (i - 1) / d;

                while (arr[current] > arr[parent]) //swap to create d-max heap
                {
                    check = true;
                    swap(arr[current], arr[parent]);
                    current = parent;
                    parent = (current - 1) / d;
                }
            }
        }
    } while (check == true);
}

The code above is not really sufficient, as I'm starting from the last element in the array and not the last parent. This way I'm not building the d-max heap correctly bottom up, as some elements seem to get out of place. To fix this I have implemented a do-while loop to keep track of the process and which will continue to loop until the d-max heap is correct. But as you can guess this approach is just patching the process.

Therefore, I want to do this correctly and I'm hoping to get some help to build a d-max heap bottom up.


texts: Notification script | from RSS to Email | Bash

texts:
This is a script that must send an email at each new article published on a specific website. Any suggestions or improvements to do?

SENDER_EMAIL="sender@example.com"
TO_EMAIL="myemail@example.com"
RSS_SITE="example.com/feed.xml"
CHECK_INTERVAL=10

while [ 1 ]; do

    LINK_ARTICLE=$(rsstail -i 1 -u $RSS_SITE -l -n 0 -1 | grep -oP "Link:+ \K.*")
    TITLE_ARTICLE=$(rsstail -i 1 -u $RSS_SITE -n 0 -1 | grep -oP "Title:+ \K.*")

    if [ "$LINK_ARTICLE" != "" ] && [ "$TITLE_ARTICLE" != "" ]; then
        echo "New article published on the site. TITLE: $TITLE_ARTICLE - LINK: $LINK_ARTICLE" | EMAIL="$SENDER_EMAIL"  mutt -s "Nuovo Articolo BDO" "$TO_EMAIL"
        echo "New article published on the site. TITLE: $TITLE_ARTICLE - LINK: $LINK_ARTICLE"
    fi

    sleep $CHECK_INTERVAL
done


texts: Incrementing letter-spacing of one line of text

texts:
I was asked to create a script which will increment the letter-spacing of one line of text, until its width matches that of the first line; for use in headline/subheadline text to maintain a block effect as illustrated:

The problem is, it's very slow.  Is there a faster way of calculating this?

$(window).resize(function() {
var h1,h2;
var x = 1;
h1 = $('#header').find('h1');
h2 = $('#header').find('h2');
h2.css( { 'letter-spacing':'1px' } );

while(h1.width() !== h2.width() && x < 1000) {
    if (x == 1000) { break; }
    h2.css( 'letter-spacing','+=0.1px' );
    x++;
}
} );


texts: Take a number and return English language representation

texts:
Like many, I started out with procedural programming.  Of course, when learning a functional language, old habits may die hard, so I wrote a fairly trivial little thing which takes an integer and returns a list of the english-language representation.

A few days later, I re-wrote it to try to take advantage of tail recursion in the main order-of-magnitude function; I freely admit that no attempt has been made to add tail-recursion to the calculation of numbers less than 1000, but since those have a fixed maximum depth of 3 (and a maximum of 5 calls in any case) I opted not to worry about it for now.

Any notes and criticisms, please lob them at me, that I may learn to do things in a less procedural way.

-module(titoa).
-export([itoa/1]).

itoa(0)                    -> "zero";
itoa(N) when is_float(N)   -> no_float_support;
itoa(N) when N < 0         -> "negative " ++ itoa(abs(N));
itoa(N) when is_integer(N) -> itoa_render(N);
itoa(_)                    -> severe_error.

itoa_render(N) when N >= 1100, N < 10000, N rem 100 == 0, N rem 1000 /= 0 ->
    itoa_render(N, ["", "hundred"], 100, []);
itoa_render(N) when N >= 1000 ->
    itoa_render(N,["",
        "thousand","million","billion","trillion","quadrillion","quintillion",
        "sextillion","septillion","octillion","nontillion","dectillion"
        ],1000, []
    );
itoa_render(N) when N >= 100, N rem 100 == 0 ->
    itoa_render(N div 100) ++ " hundred";
itoa_render(N) when N >= 100 ->
    Hun_diff = N rem 100,
    itoa_render(N - Hun_diff) ++ [32 | itoa_render(Hun_diff)];
itoa_render(N) when N > 19, N rem 10 == 0 ->
    lists:nth(N div 10 - 1, [
        "twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"
    ]);
itoa_render(N) when N > 19 ->
    Ten_diff = N rem 10,
    itoa_render(N - Ten_diff) ++ "-" ++ itoa_render(Ten_diff);
itoa_render(N) when N > 0 ->
    lists:nth(N, [
        "one","two","three","four","five","six","seven","eight","nine",
        "ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen",
        "seventeen","eighteen","nineteen"
    ]);
itoa_render(_) -> []. % 0

itoa_render(0, _, _, After) -> After;
itoa_render(_, [], _, _) -> overflow;
itoa_render(N, [Magnitude | Remaining_Magnitudes], Factor, After) ->
    This_OOM = itoa_render(N rem Factor),
    This_Rep = if
        This_OOM  == [] -> [];
        Magnitude == [] -> This_OOM;
        true            -> This_OOM ++ [32 | Magnitude] ++ if
            After     == [] -> [];
            true            -> [32]
        end
    end,
    itoa_render(N div Factor, Remaining_Magnitudes, Factor, This_Rep ++ After).


texts: Parsing Websites and transferring Data between Objects

texts:
I have a DiningHall class that has the 3 properties: openingTime, closingTime, and nextMealOpeningTime, and I need to set these NSDate properties from the data from this website.

Each DiningHall object corresponds to a particular meal. For example, there is a separate "De Neve" dining hall object  for breakfast, lunch, and dinner.

As an example, if I have a De Neve hall object corresponding to "Lunch", and the times were

  breakfast (9-11) lunch (12-2) dinner (5-8)

then openingTime is 12pm, closingTime is 2pm, and nextMealOpeningTime is 5pm.

The general algorithm is:

given a particular meal:

for each hall

    in data, find row corresponding to hall

    find column corresponding to current meal

    parse text, convert toNSDate

    pass 3 NSDate's to DiningHall as array

I'm using an open source DOM parser, and below is the code for extracting the text once I obtain the correct row.  Specific concerns are dealing with "Closed" meals and a better way to pass data to DiningHall class, but any optimizations will help.

- (NSArray*) getHourDataForRow:(TFHppleElement*)row Meal:(NSString*)meal {

    NSArray *meals = [row childrenWithTagName:@"td"];
    NSArray *mealNames = [NSArray arrayWithObjects:@"breakfast", @"lunch", @"dinner", nil];
    int index = [mealNames indexOfObject:meal]+1;
   TFHppleElement *cell = meals[index];
NSArray *strong = [cell childrenWithTagName:@"strong"];

NSMutableArray *retArr = [NSMutableArray array];

NSString *opening = [strong[0] firstChildWithTagName:@"text"].content;
NSDate *openingAsDate = [self dateFromString:opening];
if (openingAsDate){
    [retArr addObject:openingAsDate];
    NSString *closing = [strong[1] firstChildWithTagName:@"text"].content;
    [retArr addObject:[self dateFromString:closing]];
}
else{
    [retArr addObject:[NSNull null]];
    [retArr addObject:[NSNull null]];
}
    if (index +1 <= 3) {

        TFHppleElement *nextCell = meals[index+1];
        NSArray *strong1 = [nextCell childrenWithTagName:@"strong"];
        NSString* nextOpening = [strong1[0] firstChildWithTagName:@"text"].content; //strong[0] is opening time, don't need closing time from next cell
        [retArr addObject:[self nextOpening.content]];
    }
    else // nextMealOpeningTime is always nil for dinner
        [retArr addObject:[NSNull null]];

    return retArr;

 }

- (NSDate*) dateFromString:(NSString*)time {

    if ([time isEqualToString:@"CLOSED"])
        return nil;

        NSArray *digits = [time componentsSeparatedByCharactersInSet:[[NSCharacterSet decimalDigitCharacterSet] invertedSet]];

        int hour = [digits[0] intValue];
        hour+= (([time rangeOfString:@"pm"].location == NSNotFound) ? 0:12) ; //add 12 for pm
        int minutes = [digits[1] intValue];
        //format nsdate
        NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *components = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit | NSWeekCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit ) fromDate:[NSDate date]];
        [components setHour:hour];
        [components setMinute:minutes];
        return [calendar dateFromComponents:components];

}

In DiningHall class

- (void) setHoursFromData:(NSArray*)data {

    if (data[0] != [NSNull null] && data[1] != [NSNull null]){
    _openingTime = data[0];
    _closingTime = data[1];

    }

    if (data[2] != [NSNull null])
    _nextOpeningTime = data[2];

}


texts:
I would like some feedback on whether this follows MVVM principles well.

The MainPage has a Login button that opens the login modal page. Upon successful login, the LoginPageViewModel will raise an event which is handled in the parent viewmodel.

I use Action objects to do the show/hide modals. The Actions are defined in a page's codebehind and invoked in its viewmodel.

MainPage.xaml

<Button Command="{Binding ShowLoginModalCommand}" Text="Login"/>

MainPage.xaml.cs

public MainPage()
{
    var vm = new MainPageViewModel();
    vm.ShowLoginModal += (lvm) => Navigation.PushModalAsync(new LoginPage(lvm));
    vm.HideLoginModal += () => Navigation.PopModalAsync();
    BindingContext = vm;
    InitializeComponent();
}

MainViewModel.cs

public Action<LoginViewModel> ShowLoginModal;
public Action HideLoginModal;

public ICommand ShowLoginModalCommand => new Command(() =>
{
    var lvm = new LoginViewModel();

    lvm.LoginSucceeded += (se, ev) =>
    {
        this.Customer = ev.Customer;
        HideLoginModal();
    };

    ShowLoginModal(lvm);
}

public Customer Customer
{
    get => _customer;
    set
    {
        _customer = value;
        OnPropertyChanged(nameof(Customer));
    }
}

LoginPage.xaml

<Button Command="{Binding LoginCommand}" Text="Login"/>

LoginViewModel.cs

public ICommand LoginCommand => new Command(async () =>
{
    var customer = await VerifyLogin(); // Assume valid login.
    LoginSucceeded(this, new LoginSuccessEventArgs(customer));
}

public class LoginSuccessEventArgs : EventArgs
{
    public Customer Customer { get; set; }
    public LoginSuccessEventArgs(Customer customer) => Customer = customer;
}
public event EventHandler<LoginSuccessEventArgs> LoginSucceeded;


texts:
On machines where I don't have C# 6 I use this named string interpolation method. I tried to make it as pretty a possible as far as good coding practices are concerned but I just can't get rid of the repeating code for braces validation and index incrementation. Somehow I don't like it.

public static string FormatFrom(this string text, object args, bool ignoreCase = true)
{
    var substrings = Regex.Split(text, "({{?)([A-Za-z_][A-Za-z0-9_]+)(}}?)");
    var argsType = args.GetType();
    var result = new StringBuilder(text.Length);

    const int leftBraceOffset = 0;
    const int propertyNameOffset = 1;
    const int rightBraceOffset = 2;

    for (int i = 0; i < substrings.Length; i++)
    {
        var leftBraceIndex = i + leftBraceOffset;
        var propertyNameIndex = i + propertyNameOffset;
        var rightBraceIndex = i + rightBraceOffset;

        var isPropertyName = substrings[leftBraceIndex] == "{" && substrings[rightBraceIndex] == "}";
        if (isPropertyName)
        {
            var propertyName = substrings[propertyNameIndex];
            var property = argsType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
            result.Append(property.GetValue(args));
            i += 2;
            continue;
        }

        var isEscapedPropertyName = substrings[leftBraceIndex] == "{{" && substrings[rightBraceIndex] == "}}";
        if (isEscapedPropertyName)
        {
            result.Append("{").Append(substrings[propertyNameIndex]).Append("}");
            i += 2;
            continue;
        }

        result.Append(substrings[i]);
    }

    return result.ToString();
}

var text = "Lorem {ipsum} {dolor} {{sit}} met.";
var obj = new { ipsum = "abc", dolor = 2.1 };
var text2 = text.FormatFrom(obj);

Result:

  Lorem abc 2.1 {sit} met.


texts: Console Application Customizer - GetBootstrap v2.7.0

texts:
GetBootstrap v2.7.0 Update from GetBootstrap v2.5

I add a progress bar feature in my console application customizer and update the #region grouping and convert the switch statement to Dictionary that suggested in the last version.

For now I need help in reviewing my codes in ProgressBar.cs. You can also review my source code and contribute in my GitHub if you want. DOWNLOAD GetBootstrap v2.7.0

My objective is to create a progress bar that can be modify to 4 different size (small, normal, medium, and large) and change color.

This is the best code I can make. Any Suggestion?

ProgressBar.cs

public class ProgressBar
{
    public int Max { get; set; }
    public int Value { get; set; }
    public ConsoleColor Color { get; set; }
    public ProgressBarSize Size { get; set; }
    float _Calculation { get; set; }

    public ProgressBar()
    {
        Max = 100;
        Value = 0;
        Color = ConsoleColor.Blue;
        Size = ProgressBarSize.Normal;
    }

    public void Increment(int value)
    {
        Value += value;

        if (Value <= Max)
        {
            SetUpProgressBar();

            WriteProgressBar();
        }

    }

    private void WriteProgressBar()
    {
        ProgressBarSize size = Size;
        object valueSize = Convert.ChangeType(size, size.GetTypeCode());

        int position = 1;
        for (int i = 0; i <= _Calculation * Value; i++)
        {
            Console.BackgroundColor = Color;
            Console.CursorLeft = position++;
            Console.Write(" ");
        }

        for (int i = Value; i <= (int)valueSize + 1; i++)
        {
            Console.BackgroundColor = ConsoleColor.Gray;
            Console.CursorLeft = position++;
            Console.Write(" ");
        }

        WriteProgressBarStatus((int)valueSize);
    }

    private void WriteProgressBarStatus(int p)
    {
        Console.CursorLeft = p + 5;
        Console.ResetColor();
        Console.Write(Value + " of " + Max);
    }

    private void SetUpProgressBar()
    {
        ProgressBarSize size = Size;
        object valueSize = Convert.ChangeType(size , size.GetTypeCode());

        Console.CursorLeft = 0;
        Console.Write("|");
        Console.CursorLeft = (int)valueSize + 2;
        Console.Write("|");
        Console.CursorLeft = 1;
        _Calculation = ((int)valueSize + 0.0f) / Max;
    }
}

public enum ProgressBarSize
{
    Small = 20,
    Normal = 30,
    Medium = 40,
    Large = 60
}


texts:
My problem is that I have a piece of code logic that I'm having trouble fitting into an OO approach, and I was looking for design patterns so that the following code would no longer rely on the ugly

  if class is of type A do X else do Y

In Python, we can say I have three "fighting method" classes, class Fight, class Manoeuvre, and class Dodge.

I also have a control class that takes two inputs, attackMode and defendMode. The inputs will always be objects whose classes extend from or are of one of the above three.

The piece of script causing issue is as follows:

from random import Random

# Following are example "Action" objects which are to be compared
# For results

class Action:
    "Base Action all others inherit from"
    __random = Random()

    def __init__(self):
       self.health = 100

    @classmethod
    def getSuccess(cls):
        return cls.__random.randint(-2,3)

class Dodge(Action):
    def __init__(self):
       super(Dodge, self).__init__()
class Attack(Action):
    def __init__(self):
        super(Attack, self).__init__()

    def performActionOn(self, subject, sucessLevel=0):
        damage = 5 if successLevel > 1 else 3
        subject.health -= damage

class Manoeuvre(Action):
    def __init__(self):
        super(Manoeuvre, self).__init__()

    def performActionOn(self, subject, successLevel=0):
        pass

# Following is the results configuration

class CombatControl:
    def fight(self, actionAttack, actionDefend):

        if isinstance(actionDefend, Dodge):
            __attackDodge(actionAttack, actionDefend)
        else:
            __attackAttack(actionAttack, actionDefend)

    def __attackAttack(self, attack, defend):
        """
        " Defender Attacks back
        """
        resultAttack = attack.getSuccess()
        resultDefend = defend.getSuccess()

        # Both failed. No action.
        if resultAttack < 0 and resultDefend < 0:
            return
        # Attack wins or draw
        elif resultAttack >= resultDefend:
            attack.performActionOn(defend, successLevel=resultAttack)
        # Defend wins
        else:
            # Does not get damage bonus
            defend.performActionOn(attack)

    def __attackDodge(self, attack, defend):
        """
        " Defender is dodging
        """
        resultAttack = attack.getSuccess()
        resultDefend = defend.getSuccess()

        if resultAttack > resultDefend:
            attack.performActionOn(actionAttack, successLevel=resultAttack)

As you can see in the final case, there's a bit of jiggery-pokery going on where resolution is based upon the type of class. This is undesired.

Ideally I'd want a solution which would allow for something more polymorphic. The structure can change however required if it leads to an elegant solution, as long as the results are the same.


texts: PE4: Largest Palindrome Product (Clojure)

texts:
I solved Project Euler 4 using Clojure Lisp.

  A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 × 99.
  Find the largest palindrome made from the product of two 3-digit numbers.

I'm not very experienced with Clojure yet. I tried to break the logic down into small, easy to understand functions. I added documentation and input type assertions to each function.

How can I improve this code? Is :pre a good method for asserting correct input types, or is there a better way of doing that?

(defn palindrome? [arg]
  "Returns true if arg is a palindrome, i.e., it reads the same both ways"
  (= (seq (str arg))
     (reverse (str arg))))

(defn pow [N X]
  "Returns N to the power of X"
  {:pre [(number? N) (number? X)]}
  (reduce * (repeat X N)))

(defn nums-with-n-digits [digits]
  "Return list of all numbers comprised of a certain number of digits"
  {:pre (number? digits)}
  (let [max (pow 10 digits)
        min (/ max 10)]
    (range min max)))

(defn products-of-nums-list [nums]
  "Returns a descending order list of distinct products of each of the numbers in nums"
  {:pre (list? nums)}
  (sort > (distinct (for [x nums y nums] (* x y)))))

(defn solve-pe4 [digits]
  "Returns list of solutions of largest palindrome products of all numbers with a certain number of digits"
  {:pre (number? digits)}
  (first (filter palindrome? (products-of-nums-list (nums-with-n-digits digits)))))

(defn -main []
  (println (solve-pe4 2)) ; 9009
  (println (solve-pe4 3))); correct answer


texts: 90 year data simulation in need of performance increase

texts:
I developed some code for my masters project that will simulate 90 years daily data using 1000 different data sets. The code is working fine and gives the correct output that I wanted but the processing time are very high. It took about 8 hours to finish the simulation.

    tic
%% importing the csv file with selected column
files=dir('*_scen_*.csv');
for i=1:length(files);
    LHR=importcsv(files(i).name);

%% Definable variables
% Define These Value
TAW=-216;     %total available water
RAW=-129;     %readily available water
KC=1.0;       %crop coefficient
IRL=15;       %intense rain level
RC=(80/100);  %percentage of recharge
RO=(1-RC);    %percentage of runoff

% The very first row of Soil Moisture Deficit
for j=1
    SMD(j,i)=(LHR.RAIN(j)-LHR.PET(j));
 if     SMD(j,i)>0;
        SMD(j,i)=0;
 elseif SMD(j,i)<RAW;
        SMD(j,i)=(LHR.RAIN(j)-(LHR.PET(j)*((TAW-SMD(j-1))/(TAW-RAW))));
 end
end

%for the following SMD Calculation
for k=2:(length(LHR.RAIN));
    SMD(k,i)=SMD(k-1,i)+(LHR.RAIN(k)-LHR.PET(k));
    % The SMD conditions
    if SMD(k,i)>0;
       SMD(k,i)=0;
 elseif SMD(k,i)<RAW;
     SMD(k,i)=SMD(k-1,i)+(LHR.RAIN(k)-(LHR.PET(k)*((TAW-SMD(k-1,i))/(TAW-RAW))));
    end
end
%Convert negative SMD to Positive
SMD=abs(SMD);

 %%Evapotranspiration Calculation
 for l=1:(length(SMD));
    if SMD(l,i)<abs(RAW);
        AET(l,i)=LHR.PET(l);
    elseif SMD(l,i)>abs(RAW);
        AET(l,i)=KC*LHR.PET(l)*((abs(TAW)-(SMD(l,i)))/(abs(TAW)-abs(RAW)));
    end
end
for m=2:(length(SMD));
    if SMD(m,i)<abs(RAW);
        AET(m,i)=LHR.PET(m);
    elseif SMD(m,i)>abs(RAW);
       AET(m,i)=KC*LHR.PET(m)*((abs(TAW)-(SMD(m-1,i)))/(abs(TAW)-abs(RAW)));
    end
end
%% HER calculation
for n=1:length(SMD);
    if SMD(n,i)<(LHR.RAIN(n)-AET(n,i));
        HER(n,i)=(LHR.RAIN(n)-AET(n,i)-SMD(n,i));
    elseif SMD(n,i)>(LHR.RAIN(n)-AET(n,i));
        HER(n,i)=0;
    end
end
%% Calculation of recharge anf runoff
for o=1:(length(HER));
    if (HER(o,i)+(abs(TAW)-SMD(o,i)))<abs(TAW);
        RUNOFF(o,i)=0;
    elseif (HER(o,i)+(abs(TAW)-SMD(o,i)))>abs(TAW);
        if HER(o,i)>IRL;
            RUNOFF(o,i)=RO*HER(o,i);
        elseif HER(o,i)<IRL;
            RUNOFF(o,i)=0;
        end
    end
    if (HER(o,i)+(abs(TAW)-SMD(o,i)))<abs(TAW);
        RECHARGE(o,i)=0;
    elseif (HER(o,i)+(abs(TAW)-SMD(o,i)))>abs(TAW);
        if HER(o,i)>IRL;
            RECHARGE(o,i)=RC*HER(o,i);
        elseif HER(o,i)<IRL;
            RECHARGE(o,i)=HER(o,i);
        end
    end
end
%% rainfall
for p=1:length(LHR.RAIN);
RAINFALL(p,i)=LHR.RAIN(p);
PET(p,i)=LHR.PET(p);
end

end
clear i
clear j
clear k
clear l
clear m
clear n
clear o
clear p

toc

Is there any improvement scope for this code that might reduce the processing time? Sorry if the code looks unprofessional; I am in the beginner stage for MATLAB programming.


texts:
I have implemented a zigzag array which will sort smaller greater smaller and goes on...
For example :
3 7 4 8 2 6 1 is a valid ordering.
The relationship between numbers is
3 < 7 > 4 < 8 > 2 < 6 > 1
3 smaller than 7
7 greater than 4
4 smaller than 8
8 greater than and so on

the ordering always has to be "smaller than" then "greater than" then "smaller than"...
Are there any other suggestions for improving the solution?
Thanks.
package main.algorithms;

public class ZigZag {

    public static void main(String[] args) {
        int[] array = {4,3,7,8,6,2,1};
        zigZag(array);
        for (int i: array){
            System.out.println(i);
        }
    }

    // Time O(n)
    // Space O(1)
    private static int[] zigZag(int[] array) {

        int status = 0;
        int counter = 0;
        while(counter < array.length-1){
            if(status ==0) {
                if (array[counter] > array[counter + 1]) {
                    int temp = array[counter + 1];
                    array[counter + 1] = array[counter];
                    array[counter] = temp;
                }
                status = 1;
            } else {
                if (array[counter] < array[counter + 1]) {
                    int temp = array[counter + 1];
                    array[counter + 1] = array[counter];
                    array[counter] = temp;
                }
                status = 0;
            }
            counter++;
        }
        return array;
    }
}


texts: SO golang example with infinite for / channel workers

texts:
I whipped this up as an example of how infinite loops can often be used to great effect in golang, and also to discuss closing channels and worker communications.  It was strictly off the cuff, but I was curious if anybody would like to offer a critique.  In particular, I feel as though inflight is a crude implementation detail.  I've done it many times, and looking at wait group implementation, seems like it is a synchronized version of the same thing.
package main

import (
  "log"
)

func doStuff(datachan <-chan map[string]string, reschan chan<- int) {
  for {
    data, ok := <-datachan
    if !ok {
      log.Print("Channel closed.")
      break
    }
    log.Printf("Data had %d length: %+v", len(data), data)
    reschan<-len(data)
  }
  return
}

const workers = 3

func main() {
  var datachan = make(chan map[string]string)
  var reschan = make(chan int)
  var inflight = 0
  var inputs = []map[string]string {
    map[string]string{ "hi": "world" },
    map[string]string{ "bye": "space", "including": "moon" },
    map[string]string{ "bye": "space", "including": "moon" },
    map[string]string{ },
    map[string]string{ },
  }
  // an inline funciton definition can change inflight within main()'s scope
  processResults := func (res int) {
    log.Printf("Main function got result %d", res)
    inflight--
  }
  // start some workers
  for i := 0; i < workers; i++{
    go doStuff(datachan, reschan)
  }
  for _, data := range inputs {
      //Select allows reading from reschan if datachan is not available for
      // writing, thus freeing up a worker to read from datachan next loop
      written := false
      for written  != true {
        select {
          case res := <-reschan:
            processResults(res)
          case datachan <- data:
            inflight++
            written = true
        }
      }
  }
  close(datachan)
  for inflight > 0 {
    processResults(<-reschan)
  }
}


texts:
I wrote a little module for making quick CLIs in Python and I wanted to get your thoughts on areas of improvement (as well as to see what can break it).

One of the issues I had from the start was with looping and multi-threading, I wound up just adding a 1 second delay to make sure I've enough time to do some basic processing, but it seems a bit hackish. I'd like to perform some basic tests on the variable first (e.g. make sure it's not going to cause an overflow) and then actually copy the variable into an entirely separate memory space, although I'm not terribly knowledgeable about python's memory management practices and could use some guidance in the right direction.

A quick brief on how it works, functions which are to be made available to the user are stored in a dictionary with command:function key-pair, if a user enters a command which isn't recognized it will simply print the help screen message, right now it only has support for space separated values. It should be fairly trivial to add additional deliminator functionality like commas, dashes, etc. but I am also a bit worried about adding too many features as well and making it cumbersome to work with.

You can download the source on the GitHub repo or install with pip/pip3:

$ pip3 install -i https://test.pypi.org/simple/ pycli

And I've included the source code for reference:

#!/usr/bin/python3
"""Basic CLI in Python3"""

import threading as th
import time

cont=True
text=None

class InputThread:
    def __init__(self):
        global cont
        global text
        while True:
            self.loop_thread()
            time.sleep(1)
            text=None
            cont=True

    def loop_thread(self):
        global cont
        global text
        text = input()
        cont=False

class CLI:
    def __init__(self):
        self.cmds = {
            'help':self.help,
            }
        self.init_message = ''

    def help(self, args=None):
        """Use help 'command' for more information on a specific command."""
        if args==None:
            print("Available Commands:")
            for key in self.cmds.keys():
                print(key)
            print(self.help.__doc__)

        else:
            print(self.cmds[args[0]].__doc__)

    def set_message(self, message):
        """Sets the initialization message"""
        self.init_message = message

    def add_function(self, name, function):
        """Adds a function to the command dictionary"""
        self.cmds[name] = function

    def cli(self, a):
        global cont
        args = a.split(' ')
        if args[0] not in self.cmds.keys():
            print('Command "', args[0], '" Not Found.')
            self.help()
        else:
            if len(args) == 1:
                self.cmds[args[0]]()
            else:
                self.cmds[args[0]](args[1:])
        cont=True

    def loop(self):
        global cont
        global text
        print(self.init_message)
        th.Thread(target=InputThread, args=(), name='user_input_thread', daemon=True).start()
        while True:
            if not cont:
                self.cli(text)

if __name__ in '__main__':
    x = CLI().loop()

and here's an example CLI made using the module:

#!/usr/bin/python3

from pycli import CLI as cli
import random

def random_function(x, y):
    """Generates a random number between x and y.
    Usage:
      random x y
    """
    print(random.randint(x,y))

if __name__ in '__main__':
    x = cli()
    x.set_message("""Welcome to my super awesome python CLI!
With this new tool you can quickly generate command line
interfaces that capture user input without having to figure
out how to handle all those inputs yourself!
""")
    x.add_function('random', random_function)
    x.loop()

I've only tested this on Linux Mint (don't have Windows or Mac), so if you've got one of those OS's can you let me know if the code works as expected and any bugs?


texts:
For my project I need a (partial) .slk (SYLK) parser which need to load 10+ fairly large tables (30.000-50.000 lines) quickly. The subset is very limited to just the following format:

  ID;PWXL;N;E

Always first and it's only important if "ID" is there

  B;X79;Y838;D0

The size of the table, always comes before "C" rows. X is the width and Y is the height.

  C;X25;K0.25
  C;X26;K"always"
  C;X26;Y32;K"never"

X is the column and an optional Y sets the row (if missing the last row or 0 is used). The "K" part can either be in quotes or without. Either way the storage format is std::string (for now).

Now for the actual code

std::vector<std::vector<std::string>> table_data;
std::unordered_map<std::string, int> header_to_column;
std::unordered_map<std::string, int> header_to_row;

std::ifstream stream(path);

std::string line;

size_t position = 0;
size_t length = 0;

size_t column = 0;
size_t row = 0;

const auto parse_int_part = [&]() {
    position++;
    length = line.find_first_of(';', position) - position;
    position += length;
    return std::stoi(line.substr(position - length, length));
};

if (std::getline(file, line)) {
    if (line.substr(0, 2) != "ID") {
        std::cout << "Invalid SLK file, does not contain \"ID\" as first record" << std::endl;
        return;
    }
} else {
    return;
}

while (std::getline(stream, line)) {
    position = 2;

    switch (line.front()) {
        case 'B':
            while (true) {
                switch (line[position]) {
                    case 'X':
                        columns = parse_int_part();
                        break;
                    case 'Y':
                        rows = parse_int_part();
                        break;
                    default:
                        table_data.resize(rows, std::vector<std::string>(columns));
                        goto nextline;
                }
                if (position < line.size() - 1) {
                    position++;
                }
            }
        case 'C':
            while (true) {
                switch (line[position]) {
                    case 'X':
                        column = parse_int_part() - 1;
                        break;
                    case 'Y':
                        row = parse_int_part() - 1;
                        break;
                    case 'K': {
                        position++;
                        if (line[position] == '\"') {
                            position++;
                        }

                        length = line.size() - position - ((line.back() == '\r') ? 1 : 0);
                        const std::string part = line.substr(position, length - ((line[position + length - 1] == '\"') ? 1 : 0) );

                        if (row == 0) {
                            header_to_column.emplace(part, column);
                        }

                        if (column == 0) {
                            header_to_row.emplace(part, row);
                        }
                        table_data[row][column] = part;
                        goto nextline;
                    }
                }
                if (position < line.size() - 1) {
                    position++;
                }
            }
        case 'E':
            goto exitloop;
    }
    nextline:
    position = 2;
}
exitloop:;

I use some gotos which are probably ok to use here since the other solutions are a lot more verbose, but are apparently bad practice? And since the file may have "\r\n" line endings those have to be handled manually, but it feels like there should be a better way.

How could the parsing be improved while keeping the same performance?

Edit
I've changed the example so it can be run easily and a simple [test .slk].3.


texts: Optimizing Code for Project Euler Problem 14

texts:
For Project Euler problem 14 I wrote code that runs for longer than a minute to give the answer. After I studied about memoization, I wrote this code which runs for nearly 10 seconds on Cpython and nearly 3 seconds on PyPy. Can anyone suggest some optimization tips?

import time
d={}
c=0
def main():
    global c
    t=time.time()
    for x in range(2,1000000):
        c=0
        do(x,x)
    k=max(d.values())
    for a,b in d.items():
        if b==k:
            print(a,b)
            break

    print(time.time()-t)

def do(num,rnum):
    global d
    global c
    c+=1
    try:
        c+=d[num]-1
        d[rnum]=c
        return
    except:
        if num==1:
            d[rnum]=c
            return
        if num%2==0:
            num=num/2
            do(num,rnum)
        else:
            num=3*num+1
            do(num,rnum)

if __name__ == '__main__':
    main()


texts:
Please comment on my DFS implementation and test, I would like to get comments about algorithm correctness.

  Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace JobInterviewTests
{
    [TestClass]
    public class DFSUnitTest
    {
        [TestMethod]
        public void CheckCorrectOrder()
        {
            GraphNode root = new GraphNode("A");
            root.Neighbors.Add(new GraphNode("F"));
            root.Neighbors.Add(new GraphNode("E"));
            var temp = new GraphNode("B");
            var temp2 = new GraphNode("C");
            var temp3 = new GraphNode("D");
            temp2.Neighbors.Add(temp3);
            temp.Neighbors.Add(temp2);
            root.Neighbors.Add(temp);

            List<string> result =TraverseDFS(root);
            Assert.AreEqual("A",result[0]);
            Assert.AreEqual("B",result[1]);
            Assert.AreEqual("C",result[2]);
            Assert.AreEqual("D",result[3]);
            Assert.AreEqual("E",result[4]);
            Assert.AreEqual("F",result[5]);
        }

        private List<string> TraverseDFS(GraphNode root)
        {
            if (root == null)
            {
                return null;
            }

            List<string> result = new List<string>();
            Stack<GraphNode> s = new Stack<GraphNode>();
            s.Push(root);
            while (s.Any())
            {
                GraphNode curr = s.Pop();
                result.Add(curr.Value);
                foreach (var node in curr.Neighbors)
                {
                    s.Push(node);
                }
            }
            return result;
        }
    }

    public class GraphNode
    {
        public string Value { get; set; }
        public List<GraphNode> Neighbors { get; set; }

        public GraphNode(string s)
        {
            Value = s;
            Neighbors = new List<GraphNode>();
        }
    }
}


texts: List contents of a folder using a shell script and mail the folder

texts:
I want to list the contents of a folder and mail the list using a shell script. I Came up with the following script, please let me know if it is okay:

for file in *
do
  if [ -f "$file" ]; then
      echo "$file" | mail -s "List of files" Someone@somewhere.com
  fi
done


texts: Get all possible subsets from a set of distinct integers using OOP

texts:
An assignment at school required me to write a program for this task:

  Create a class and define two methods in the class.
  Method f1 is used to pass an empty list and the sorted list is taken from the user to method f2.
  Method f2 is used to compute all possible subsets of the list.
  Then the result is returned from the function and printed.
  Exit

Here is my solution to this task, using Python:

class sub:
    def f1(self, s1):
        return self.f2([], sorted(s1))

    def f2(self, current, s1):
        if s1:
            return self.f2(current, s1[1:]) + self.f2(current + [s1[0]], s1[1:])
        return [current]
a = []
n = int(input("Enter number of elements of list: "))
for i in range(0,n):
    b = int(input("Enter element: "))
    a.append(b)
print ("Subsets: ")
print (sub().f1(a))

NOTE - Method f2 is a recursive function.

Here are some example inputs and outputs:

Enter number of elements of list: 2
Enter element: 4
Enter element: 5
Subsets:
[[], [5], [4], [4, 5]]

Enter number of elements of list: 4
Enter element: 3
Enter element: 5
Enter element: 7
Enter element: 28
Subsets:
[[], [28], [7], [7, 28], [5], [5, 28], [5, 7], [5, 7, 28], [3], [3, 28], [3, 7], [3, 7, 28], [3, 5], [3, 5, 28], [3, 5, 7], [3, 5, 7, 28]

So, I would like to know whether I could make this program shorter and more efficient.

Any help would be highly appreciated.


texts:
This is my code to populate a Class and later convert it to JSON object.

public List<CSATGraphJSON> convertListToCSATGraphJSON(List<Object[]> list) throws ParseException{
        List<CSATGraphJSON> customers=new ArrayList<CSATGraphJSON>();
        //going through each list of object
        for (int i = 0; i < list.size(); i++) {
            CSATGraphJSON graphJSON=new CSATGraphJSON();
            Object eachObject=list.get(i);
            int index=0;
            //iterating the each object array
            for(Object obj: (Object[]) eachObject){
                System.out.println(obj.toString());
                System.out.println(obj.getClass());
                switch(index){
                    case 0:{
                        if(obj!=null){
                            // if not null
                            /*DateFormat df = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
                            Date parsedDate = null;
                            parsedDate = df.parse(obj.toString());
                            // gives you java.util.Date
                            customerList.setResponsedatestr(parsedDate);*/
                            graphJSON.setX(obj.toString());
                        }
                        break;
                    }
                    case 1:{
                        if(obj!=null){
                            graphJSON.setVery_poor(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    case 2:{
                        if(obj!=null){
                            graphJSON.setPoor(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    case 3:{
                        if(obj!=null){
                            graphJSON.setAverage(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    case 4:{
                        if(obj!=null){
                            graphJSON.setGood(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    case 5:{
                        if(obj!=null){
                            graphJSON.setVery_good(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    case 6:{
                        if(obj!=null){
                            graphJSON.setTotal(Integer.parseInt(obj.toString()));
                        }
                        break;
                    }
                    default:{
                        break;
                    }
                }
                index++;

            }
            customers.add(graphJSON);
        }

        return customers;
    }

Here List list the result of createSQLQuery() in hibernate as it returns List of Object ,so it is converted to List of CSATGraphJSON object.

Please suggest any alternative method for the switch statement as it is making the code lengthy.


texts: Creating Simple New Elements, Object Instances and Assigning IDs

texts:
I've created a simple demo that creates new elements on a page. After clicking the button, new elements are created, and when clicking remove, the relevant element is deleted. Each element has a 'data-id' data attribute, which matches the id object property that's also created.

Check out the code on this page, or see this codepen demo I created: https://codepen.io/anon/pen/xMqodd

I'm essentially looking for ways which this code can be improved. Could anyone advise me here? Thanks for any help - the code is below:

HTML:

<button id='btn' onclick='createEntry()'>Create</button>

CSS:

button { display: block }
    .entry {
        width: 100%;
        display: block;
        padding: 10px;
        border: 1px solid #f5f5f5;
    }
    span {
        display: block;
        width: 100%;
    }
    section { background: lightgreen }

JS:

// note: beware of using eccessive nested functions as they can cause problems
    var id = 0, objects = [], removes;

    function createEntry() {
        id++;

        // create new element, append to #container & create new object
        var container = document.querySelector('#container'),
            newEntry = document.createElement("div"),
            title = 'title text here',
            description = 'description text here',
            remove = 'remove',
            dataId = id,
            obj = new Entry(title, description, remove);
        newEntry.classList.add("entry");
        newEntry.innerHTML = '' + title + '' + description + '' + remove + '';
        container.appendChild(newEntry);
        newEntry.setAttribute('data-id', id);

        updateElements();

        // constructor & push into array
        function Entry(title, description, remove) {
            this.title = title;
            this.description = description;
            this.remove = remove;
            this.id = id;

            objects.push(this);
        }

        // tests
        console.log('JSON.stringify(obj): ' + JSON.stringify(obj));
        console.log('obj.id: ' + obj.id);
    }

    function updateElements() {
        removes = document.querySelectorAll(".remove");
        listenForRemoves();

        function listenForRemoves() {
            for (let remove of removes) {
                remove.removeEventListener("click", removeElements);
                remove.addEventListener("click", removeElements);
            }
        }
    }

    function removeElements() {
        let removedId = this.parentNode.getAttribute('data-id'),
            objToRemove = objects.find(obj => obj.id == removedId); // not used

        this.parentNode.remove(); console.log('removed id ' + removedId);
            console.log('objects before: '); for (let object of objects) { console.log(JSON.stringify(object))};
            objects = objects.filter(obj => obj.id != removedId); // doesn't use objToRemove
            console.log('objects now: '); for (let object of objects) { console.log(JSON.stringify(object))};
    }


texts:
I have created an NBT format reader (NBT is a binary serialization format that Minecraft uses to store its data). I made a node-like class that can be a data entry or the root of a subtree (that's how NBT is defined). The public interface of it currently looks like this:

class Tag
{
    Tag();

    void read(std::istream& stream);
    void write(std::ostream& stream);

    void print(int indent = 0);

    int8_t byteValue() const;
    int16_t shortValue() const;
    int32_t intValue() const;
    int64_t longValue() const;
    float floatValue() const;
    double doubleValue() const;
    ByteArray byteArrayValue() const;
    IntArray intArrayValue() const;
    UTF8String stringValue() const;
    std::vector<Tag> children() const;

    UTF8String name() const;
};

Is this the right design though? Originally I wanted to do the *Value methods with templates, but the problem is that the value of a Tag is dynamic, so that does not play nicely with the compile-time genericity.

Is it a blasphemy not to make the various types derived classes? I couldn't really take advantage of a virtual value method because the return types would need to differ. Is there a better way to implement a data structure like this? The aim is to make it easy to use and fast.


texts: HackerRank "Bot Saves Princess" beginner code

texts:
I submitted the following Python 3 code for this HackerRank challenge. Given an n × n grid with an m in the center and a p in one corner, it prints the directions to move the m to the p.

I wanted to know how improve it or other observations.

#!/usr/bin/python
def displayPathtoPrincess(n,grid):
    #first, find where p is located
    flag = True
    n = n-1
    while(flag):
        if grid[0][n] == 'p':
            flag = False
            a = 0
            b = n
        if grid[n][0] == 'p':
            flag = False
            a = n
            b = 0
        if grid[0][0] == 'p':
            flag = False
            a = 0
            b = 0
        if grid[n][n] == 'p':
            flag = False
            a = n
            b = n
        #else:
            #print("Something broke?") #Why does this execute?
        y = a - int(n/2)
        x = b - int(n/2)
        while 0 != y:
            if y < 0:
                y = y+1
                print("UP")
            if y > 0:
                y = y-1
                print("DOWN")
        while 0 != x:
            if x <0:
                x = x+1
                print("LEFT")
            if x >0:
                x = x-1
                print("RIGHT")

m = int(input())
grid = []
for i in range(0, m):
    grid.append(input().strip())

displayPathtoPrincess(m,grid)


texts:
Beginner functional programmer... (but not beginner programmer)

Currently, I have the following code:

import Control.Monad (mapM_)

main = gridMaker 3

gridMaker :: Int -> IO ()
{-Creates a nxn matrix filling the lower triangle with "O"'s
  and filling the rest with "X"s
  Example:
  O --- X --- X
  O --- O --- X
  O --- O --- O
  -}
gridMaker gridSize =
  -- Creates the indicators
  let startingIter = 1
      indicators = indicatorListCreator gridSize startingIter
  -- Print each indicator out to IO
  in mapM_ linePrinter indicators

indicatorListCreator :: Int -> Int -> [[String]]
{- Build the indicators of
   [["O", "X", "X"],["O", "O", "X"] ... and so forth.
   Recursively determines how many iterations we've been through,
   and determines how many "X"s and "O"s we should have
   per each line. -}
indicatorListCreator gridLen iterNum
  | iterNum > gridLen = []
  | otherwise =
    let itersRemaining = gridLen - iterNum
        indicator = replicate iterNum "O" ++
                    replicate itersRemaining "X"
    in
      indicator: indicatorListCreator gridLen (iterNum + 1)

linePrinter :: [String] -> IO ()
{- Takes the indicators and prints each line accordingly. -}
linePrinter [indicator1, indicator2, indicator3] =
  let between = " --- "
      outString = indicator1 ++ between ++
                  indicator2 ++ between ++
                  indicator3
  in putStrLn outString
linePrinter _ = error"Stupidly hardcoded to only show 3x3"

Running and compiling this code results in:

O --- X --- X
O --- O --- X
O --- O --- O

Some of my thoughts...

Is it possible to build indicatorListCreator out of folds?
How can I circumvent hardcoding linePrinter
Is this optimal?
Where should I improve on coding conventions / style?
Any other glaring shortcomings?

Thank you in advance!


texts:
Note: This code was first posted on another forum by me under the name Candy. Read this note before you declare this code copied.

Since I was bored, I decided to code a Rock Paper Scissors game in Python in my iOS device (There are offline interpreters available). The very first version of my code was ugly and large, so I decided to re-write the whole thing from scratch. I have tried to keep the code short because coding in mobile was a bit difficult.

I would like to know your suggestions for improvement of this game. Also point out any bad/wrong practices that you find. I don't even know whether I follow the right way of naming variables. So please tell me the 'correct' naming conventions in Python. And yeah, try not to be too harsh on this one. After all, it's my first game in Python :)

import random
import os

pad = "||  "

def GetInput():
    print(pad + "(1)Rock, (2)Paper or (3)Scissor?")
    sInput = raw_input(pad + "User: ").lower()

    if sInput in ["rock", "r", "1"]:
        return 1
    elif sInput in ["paper", "l", "2"]:
        return 2
    elif sInput in ["scissor", "s", "3"]:
        return 3
    else:
        return -1

def GetResult(pA, pB):
    res = (3 + pA - pB) % 3
    if res == 1:
        return "win"
    elif res == 2:
        return "lose"
    elif res == 0:
        return "draw"
    pass

def GetAIOutput():
    out = random.randint(1, 3)
    return out

Stats = { "Win" : 0, "Lose" : 0, "Draw" : 0, "Total" : 0 }
def UpdateStats(state):
    Stats["Total"] += 1
    if state == "win":
        Stats["Win"] += 1
    elif state == "lose":
        Stats["Lose"] += 1
    else:
        Stats["Draw"] += 1

def DisplayStats():
    print("///////Stats//////////////////////////")
    for key, value in Stats.items():
        print(pad + key + " : " + str(value))
    print(pad)

def DisplayIntro():
    print(      "=======================================")
    print(pad + "    Rock, Paper, Scissors")
    print(pad + "         by CandyV3rm")
    print(      "=======================================")
    print(      "#######Game############################")

def DisplayOutro():
    print(pad + "\n" + pad + "End of current game")
    print("==============================\n\n\n")

def ClearScreen():
    os.system('cls' if os.name=='nt' else 'clear')

def StartRPSGame():
    bAgain = True

    # Repeat if user wants to play again
    while bAgain:
        # Clear the screen
        ClearScreen()
        # Display the intro
        DisplayIntro()
        # Get user input
        uInput = GetInput()
        # Handle invalid input
        if uInput < 1:
            print(pad + "Invalid Input")
            DisplayOutro()
            continue
        # Get AI output
        eOutput = GetAIOutput()
        # Display AI output
        print(pad + "Computer: " + str(eOutput))
        # Determine result - win, lose or draw
        result = GetResult(uInput, eOutput)
        # Display results
        print(pad + "Result = " + result + "\n" + pad)
        # Update the scores
        UpdateStats(result)
        # Display the scores
        DisplayStats()
        # Ask if user wants to play again
        print("==============================")
        print(pad + "Play again? (yes=1;no=0)")
        bAgain = bool(input(pad + "Enter: "))
        # Display the outro
        DisplayOutro()
        raw_input("Press enter.")

# Start Rock, Paper Scissors game
StartRPSGame()

Edit: Me and my friend are challenging each other on who will code a better version. Here's his version in c++: Rock, Paper, Scissor Game


texts: Checking for a date and compare 2 different files

texts:
From snippets around the web, I was able to put together this .bat file to check for a date and compare 2 different files.

This works below but I want to clean it up so it can be much lighter and faster and MUCH less code.

As you can see, it uses the same code to check date with hour and number. It is basically checking to see if the .xml file is older than 15 minutes and then will download a new version if over 15 minutes.

@echo off
cls
setlocal EnableDelayedExpansion

SET execTime=15

REM lets get XML date
SET xml=my.xml
FOR %%i IN (%xml%) DO SET fileDate=%%~ti
SET timeString=%fileDate%

:: Get the "AM PM" string to check the HOUR interval
FOR /F "tokens=1-3 delims= " %%A IN ('echo %timeString%') DO SET AM_PM=%%C

:: first  split so can delele the date
FOR /F "tokens=1-5 delims= " %%A IN ('echo %timeString%') DO SET theDate=%%A& SET HOUR=%%B

:: fix up the date to only numeric
set fixDate=%theDate%
set xmlDate=%fixDate: =%
set xmlDate=%fixDate:/=%

::split by ":" using "HOUR" set above
FOR /F "tokens=1-5 delims=:" %%A IN ('echo %HOUR%') DO SET H_NUM=%%A& SET M_NUM=%%B

:: Set HOUR intervals to "24 hour" format
IF %AM_PM%==PM (
IF %H_NUM%==01 (SET H_NUM=13)
IF %H_NUM%==02 (SET H_NUM=14)
IF %H_NUM%==03 (SET H_NUM=15)
IF %H_NUM%==04 (SET H_NUM=16)
IF %H_NUM%==05 (SET H_NUM=17)
IF %H_NUM%==06 (SET H_NUM=18)
IF %H_NUM%==07 (SET H_NUM=19)
IF %H_NUM%==08 (SET H_NUM=20)
IF %H_NUM%==09 (SET H_NUM=21)
IF %H_NUM%==10 (SET H_NUM=22)
IF %H_NUM%==11 (SET H_NUM=23)
) ELSE (
IF %H_NUM%==12 (SET H_NUM=12)
IF %H_NUM%==1 (SET H_NUM=01)
IF %H_NUM%==2 (SET H_NUM=02)
IF %H_NUM%==3 (SET H_NUM=03)
IF %H_NUM%==4 (SET H_NUM=04)
IF %H_NUM%==5 (SET H_NUM=05)
IF %H_NUM%==6 (SET H_NUM=06)
IF %H_NUM%==7 (SET H_NUM=07)
IF %H_NUM%==8 (SET H_NUM=08)
IF %H_NUM%==9 (SET H_NUM=09)
)

SET TIMESTAMP=%H_NUM%%M_NUM%
SET timeXmlCreated=%TIMESTAMP%

REM <<<-------------   NOW lets create bat to check time to compare time now  ----------------->>>

echo/|set /p =%date% >time.bat
time /t >>time.bat

SET mktime=time.bat
FOR %%i IN (%mktime%) DO SET timeFile=%%~ti
SET timeString=%timeFile%

:: Get the "AM PM" string to check the HOUR interval
FOR /F "tokens=1-3 delims= " %%A IN ('echo %timeString%') DO SET AM_PM=%%C

:: first  split so can delele the date
FOR /F "tokens=1-5 delims= " %%A IN ('echo %timeString%') DO SET theDate=%%A& SET HOUR=%%B

:: fix up the date to only numeric
set fixDate=%theDate%
set todaysDate=%fixDate: =%
set todaysDate=%fixDate:/=%

::split by ":" using "HOUR" set above
FOR /F "tokens=1-5 delims=:" %%A IN ('echo %HOUR%') DO SET H_NUM=%%A& SET M_NUM=%%B

:: Set HOUR intervals to "24 hour" format
IF %AM_PM%==PM (
IF %H_NUM%==01 (SET H_NUM=13)
IF %H_NUM%==02 (SET H_NUM=14)
IF %H_NUM%==03 (SET H_NUM=15)
IF %H_NUM%==04 (SET H_NUM=16)
IF %H_NUM%==05 (SET H_NUM=17)
IF %H_NUM%==06 (SET H_NUM=18)
IF %H_NUM%==07 (SET H_NUM=19)
IF %H_NUM%==08 (SET H_NUM=20)
IF %H_NUM%==09 (SET H_NUM=21)
IF %H_NUM%==10 (SET H_NUM=22)
IF %H_NUM%==11 (SET H_NUM=23)
) ELSE (
IF %H_NUM%==12 (SET H_NUM=12)
IF %H_NUM%==1 (SET H_NUM=01)
IF %H_NUM%==2 (SET H_NUM=02)
IF %H_NUM%==3 (SET H_NUM=03)
IF %H_NUM%==4 (SET H_NUM=04)
IF %H_NUM%==5 (SET H_NUM=05)
IF %H_NUM%==6 (SET H_NUM=06)
IF %H_NUM%==7 (SET H_NUM=07)
IF %H_NUM%==8 (SET H_NUM=08)
IF %H_NUM%==9 (SET H_NUM=09)
)

SET TIMESTAMP=%H_NUM%%M_NUM%
SET timeNow=%TIMESTAMP%
GOTO :dateDiff

:dateDiff
:: lets check dates now
SET /a dateDiff=%xmlDate%-%todaysDate%
set dateDiff=%dateDiff:-=%
if %dateDiff% GTR 0 goto timeDiff

:: do something here if more than zero

:timeDiff
::get time difference
::  must add a "1" to fix errors if starts with a "zero"
SET /a timeDiff=1%timeXmlCreated%-1%timeNow%
set timeDiff=%timeDiff:-=%
if %timeDiff% GTR %execTime% goto greaterThan

:lessThan
echo less than %execTime% min just leave alone
GOTO cleanUp

:greaterThan
echo more than %execTime% min lets delete
GOTO cleanUp

:cleanUp
Del  time.bat

endlocal
PAUSE > NUL


texts: Counting the number of alerts by type and partition from a JSON object

texts:
Here is my problem, I receive these kind of json data and I don't know in advance the keys (unknownProperty#) but the different objects in this data array have the same keys. What I need to do is to calculate the number of each level of alert (these levels are fixed).
Here is what my end result should look like

var result = { unknownProperty1: { unknown: 0, ok: 2, warning: 0, ko: 1 },
  unknownProperty2: { unknown: 0, ok: 0, warning: 2, ko: 1 },
  unknownProperty3: { unknown: 3, ok: 0, warning: 0, ko: 0 },
  unknownProperty4: { unknown: 0, ok: 0, warning: 3, ko: 0 },
  unknownProperty5: { unknown: 0, ok: 0, warning: 2, ko: 1 } }

My script is working but I would like to know if there is any way to optimize/clean it with map/reduce/filter javascript function

const data = [
  {
    unknownProperty1: { alert: "ok", unusedItem1: "something" },
    unknownProperty2: { alert: "warning", unusedItem1: "something" },
    unknownProperty3: { alert: "unknown", unusedItem1: "something" },
    unknownProperty4: { alert: "warning", unusedItem1: "something" },
    unknownProperty5: { alert: "ko", unusedItem1: "something" }
  },
  {
    unknownProperty1: { alert: "ok", unusedItem1: "something" },
    unknownProperty2: { alert: "warning", unusedItem1: "something" },
    unknownProperty3: { alert: "unknown", unusedItem1: "something" },
    unknownProperty4: { alert: "warning", unusedItem1: "something" },
    unknownProperty5: { alert: "warning", unusedItem1: "something" }
  },
  {
    unknownProperty1: { alert: "ko", unusedItem1: "something" },
    unknownProperty2: { alert: "ko", unusedItem1: "something" },
    unknownProperty3: { alert: "unknown", unusedItem1: "something" },
    unknownProperty4: { alert: "warning", unusedItem1: "something" },
    unknownProperty5: { alert: "warning", unusedItem1: "something" }
  }
];

var result = new Object();
var dataKeys = data.map(function(element) {
  return Object.keys(element);
});
dataKeys[0].map(function(element) {
  result[element] = { unknown: 0, ok: 0, warning: 0, ko: 0 };
});
//At this point the result is like what we expect but no calculation has been made yet

//We then increment the right values
data.map(function(element) {
  for (var prop in element) {
    if (Object.prototype.hasOwnProperty.call(element, prop)) {
      // element correspond to the current object
      // prop corresponds to the name of the key, for example 'unknownProperty1'
      switch (element[prop].alert) {
        case "ok":
          result[prop].ok++;
          break;
        case "warning":
          result[prop].warning++;
          break;
        case "unknown":
          result[prop].unknown++;
          break;
        case "ko":
          result[prop].ko++;
          break;

        default:
          break;
      }
    }
  }
});
console.log(result);


texts:
I have written an implementation of Quicksort in Python. I am new to Python. Any suggestions for improvement or criticism on my use of Python?

def partition(a, lo, hi):
    i, j, v = lo+1, hi, a[lo]
    while(True):
        while(a[i] < v):
            i += 1
            if (i == hi): break
        while(a[j] > v):
            j -= 1
            if (j == lo): break
        if (i >= j): break
        a[i], a[j] = a[j], a[i]
    a[lo], a[j] = a[j], a[lo]
    return j

def sort(a, lo, hi):
    if (hi <= lo):
        return
    q = partition(a, lo, hi)
    sort(a, lo, q-1)
    sort(a, q+1, hi)
    assert isSorted(a, lo, hi)

def quick_sort(a):
    shuffle(a)
    sort(a, 0, len(a)-1)
    assert isSortedArray(a)

def isSorted(a, lo, hi):
    for i in range(lo, hi):
        if a[i+1] < a[i]:
            return False
    return True

def isSortedArray(a):
    for i in range(0, len(a)-1):
        if a[i+1] < a[i]:
            return False
    return True


texts:
Could you please review the following code, and point out how I can make it cleaner, more idiomatic and easier to understand?

module Cabbage (
  solve
) where

data Place = Here | There deriving (Eq, Show)

data Pos = Pos { cabb :: Place
               , goat :: Place
               , wolf :: Place
               , farmer :: Place
               } deriving (Eq, Show)

opp :: Place -> Place
opp Here = There
opp There = Here

valid :: Pos -> Bool
valid (Pos {cabb = c, goat = g, wolf = w, farmer = f}) = (c /= g && g /= w) || g == f

findMoves :: Pos -> [Pos]
findMoves pos@(Pos {cabb = c, goat = g, wolf = w, farmer = f}) =
    filter valid $ moveCabb ++ moveGoat ++ moveWolf ++ moveFarmer where
    moveCabb | c == f = [pos {cabb = opp c, farmer = opp f}] | otherwise = []
    moveGoat | g == f = [pos {goat = opp g, farmer = opp f}] | otherwise = []
    moveWolf | w == f = [pos {wolf = opp w, farmer = opp f}] | otherwise = []
    moveFarmer = [pos {farmer = opp f}]

findSolution :: Pos -> Pos -> [Pos]
findSolution from to = head $ loop [[from]] where
    loop pps = do ps <- pps
                  let moves = filter (flip notElem ps) $ findMoves $ head ps
                  if to `elem` moves
                    then return $ reverse $ to:ps
                    else loop $ map (:ps) moves

solve :: [Pos]
solve = findSolution (setAll Here) (setAll There) where
            setAll x = Pos{ cabb = x, goat = x, wolf = x, farmer = x }

IMHO the findMoves function seems to be quite verbose, and the findSolutions function looks confusing.

Thank you!


texts:
I am trying to refactor a large application to use more DDD principles as and when I get chance.  I am concentrating on the very simple areas first.  The app currently has a very simple Domain Service (one of many) as it stands (see option 1).  Please see the code below:

Option 1 - Live

public IEnumerable<System.Collections.Generic.KeyValuePair<decimal, int>> CalculateDenominations(decimal cost, ICurrency currency)
        {
            var target = cost;
            foreach (var denomination in currency.AvailableDenominations)
            {
                var numberRequired = target / denomination;
                if (numberRequired >= 1)
                {
                    int quantity = (int)Math.Floor(numberRequired);
                    yield return new KeyValuePair<decimal, int>(denomination, quantity);
                    target = target - (quantity * denomination);
                }
            }
        }

Option 2

public sealed class DenominationsRequired
    {
        private readonly decimal _cost;
        private readonly ICurrency _currency;

        public DenominationsRequired(decimal cost, ICurrency currency)
        {
            if (currency == null)
                throw new ArgumentNullException("Currency cannot be null", "ICurrency");
            if (cost < 0)
                throw new ArgumentException("Cost cannot be less than zero", "Cost");
            if (decimal.Round(cost, 2) != cost)
                throw new ArgumentException(string.Concat("Cost has too many decimal places.  It should only have: ", currency.DecimalPlaces), "Cost");
            _cost = cost;
            _currency = currency;
        }

        public decimal Cost
        {
            get { return _cost; }
        }

        public ICurrency Currency
        {
            get { return _currency; }
        }

        public IEnumerable<System.Collections.Generic.KeyValuePair<decimal, int>> CalculateDenominations()
        {
            var target = _cost;
            foreach (var denomination in _currency.AvailableDenominations)
            {
                var numberRequired = target / denomination;
                if (numberRequired >= 1)
                {
                    int quantity = (int)Math.Floor(numberRequired);
                    yield return new KeyValuePair<decimal, int>(denomination, quantity);
                    target = target - (quantity * denomination);
                }
            }
        }
    }

I am thinking about refactoring the Domain Service (option 1 - live) into a Value Object (option 2) so that I can add validation.  I would be grateful for critical comments about this approach.  Is a ValueObject (option 2) "better" than a domain service (option 1) for this?  I believe it is acceptable to put caclculations in Value Objects as long as they do not mutate state.

I am specifically interested to know:

Is a Value Object "better" than a Domain Service for this specific requirement?
Is it wise to have a property called: Currency.DecimalPlaces (indicates how many decimal places the currency allows e.g. 2 for pounds and 2 for dollars - some currencies allow 3 or 4 decimal places), which is used in the DenominationsRequired constructor for validation?
Should I keep option 1 or go with option 2? If option 1, then how do I approach validation?


texts: Trials, tribulations, and tributaries (Rainfall challenge)

texts:
This is a fairly simple Ruby solution to the August 2016 community challenge.

Ok, the title is way too dramatic. But tributary is a nice word, and the alliteration was too good to pass up.
Besides, konijn started it!

I didn't bother to output a 2D "map" of the basins, I just print their sizes as the challenge requires. (Printing a map wouldn't be a difficult thing graft onto this, but I just wanted to keep things clean.)

Anyway, the script:

# Simple class that models a point on the terrain
class Cell
  attr_reader :altitude

  # Init with the cell's altitude
  def initialize(altitude)
    @altitude = altitude
    @neighbors = []
  end

  # Add another cell instance as a neighbor of the receiver
  def add_neighbor(cell)
    @neighbors << cell
  end

  # Returns the "drain" of the receiver (lowest of lower neighbors),
  # or nil if no such neighbor exists
  def drain
    @drain ||= @neighbors
      .select { |neighbor| neighbor.altitude < altitude }
      .min_by(&:altitude)
  end

  # Returns the sink of the receiver, i.e. the drain's drain (ad fundum),
  # or self if the cell is itself a sink
  def sink
    @sink ||= drain.nil? ? self : drain.sink
  end
end

# Helper method. Given an array of cells, register adjacent
# cells as neighbors of each other
def link_cells(cells)
  cells.each_cons(2) do |a, b|
    a.add_neighbor(b)
    b.add_neighbor(a)
  end
end

# Get the terrain size (first line of input)
size = gets.chomp.to_i

# Init the altitude cells (as a 2D array) from input
terrain = size.times.map do
  gets.strip.split.map { |altitude| Cell.new(altitude.to_i) }
end

# Register neighbors (first row-wise, then column-wise)
terrain.each { |row| link_cells(row) }
terrain.transpose.each { |col| link_cells(col) }

# Divide into basins (cells sharing same sink) and print basin sizes
basins = terrain.flatten.group_by(&:sink).values
puts basins.map(&:size).sort.reverse.join(" ")

It passes the test cases given in the challenge. It also works with non-square terrains for that matter.

To my eyes, the code suffers a bit from the 2-step process needed to create a useful Cell. It's initialized with an altitude, but that isn't really useful until a 2nd pass links all cells to their neighbors. Just seems crude.
I considered having each cell know its coordinates and adding a Terrain class to handle the neighbor-lookups, but that seemed like overkill. And it'd introduce a pet peeve of mine: The circular referencing between a cell and the collection it's part of. I've run into this tons of times (e.g. board game-type code), and never found a solution that didn't irk me a little.

Anyway, there are probably more efficient solutions out there; I just went for simple and (hopefully) readable.

Looking at it again, I see a couple of issues related to the memoizing, but I'll wait and see what reviewers find.


texts: Match a simple balanced language using a queue

texts:
I asked a similar question here which is:

  The language L={anbn} where n ≥ 1, is a language of all words with
  the following properties:

  The words consist of strings of a’s followed by b’s.
  The number of b’s is equal the number of a’s.
  Examples of words that belong to L are:

  ab, where n=1;

  aabb, where n=2;

  aaabbb, where n=3;

  aaaabbbb, where n=4.

  One way to test if a word w belong to this language L is to use a
  stack to check if the number of a’s balances the number of b’s. Use
  the following header and write a function isInLanguageL2 that
  uses a stack to test if any word belongs to L. If w belongs to L
  then the isInLanguageL2 should return true otherwise
  isInLanguageL2 should return false.

  bool isInLanguageL(string w);

  Note the following:

  Only words belonging to L should be accepted.
  The word bbaa does not belong to L.
  Do not count the number of a’s or b’s.

A follow up to that question asks to redo the question using queues (I realize a queue probably isn't the best way to do this, however that's not the point of the exercise):

  Repeat the previous question using the following header:

  bool isInLanguageL(queueType< char> & w);

My solution for doing this without actually counting the a's and b's is below. It uses two queues. I "copy" all the a's from the original queue into a temp queue and remove them from the original queue which should have only b's remaining. I then iterate through the temp queue and pop the original queue for every a that is in the temp queue. After checking through the temp queue and if both queues are empty at the end, then the word is valid.

My question: How can I accomplish this using a single queue as I think using a temporary queue would be a waste of memory.

My code:

bool isInLanguageL(linkedQueueType<char> &w){

    linkedQueueType<char> temp;

    if(w.front() != 'a')    //queue must start with an a
        return false;

    while(w.front() == 'a'){ //iterate through the a's and add them to temp queue
        temp.addQueue(w.front());
        w.deleteQueue();    //remove a's from original queue
    }

    while(!temp.isEmptyQueue() && !w.isEmptyQueue()){    //delete b for each a
        if(w.front() != 'b')    //only b's should remain in original queue
            return false;
        else{
            w.deleteQueue();
            temp.deleteQueue();
        }
    }

    //both stacks must be empty then number of b=a and word is valid
    if(w.isEmptyQueue() && temp.isEmptyQueue())
        return true;
    return false;
}

int main()
{

    linkedQueueType<char> wordQueue;
    std::string word;

    std::cout << "Enter a word belonging to language L. ";
    std::cin >> word;

    for(int i = 0; i < word.length(); i++){
        wordQueue.addQueue(word[i]);
    }

    if(isInLanguageL(wordQueue))
        std::cout << word << " is a valid word.";
    else
        std::cout << word << " is not a valid word.";

    return 0;
}


texts: Bifurcating recursive calculation with redundant calculations

texts:
def T(n):
  if n <= 0:
    return 1
  else:
    return T(n-1) + (n-1) * T(n-2)

print T(4)

I need an effective way to print out the output of the function T(n) generated using the recurrence relation above. Is there any way to make the above code more efficient?
Sample output:
10


texts:
Please help me improving this code(golang), thanks!

Why I need built a API for xkcd

Can't get the data provided by xkcd directly in front-end(CORS).
So we can package the data to 10 comics per request. Instead of 1 request match one comic.

main.go

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"
    "strings"
)

type comicInfo struct {
    Number int    `json:"num"`
    Img    string `json:"img"`
    Title  string `json:"title"`
    Alt    string `json:"alt"`
}

var comicInfoMap = make(map[int]comicInfo)
var newestComic comicInfo

func fetch(url string, ch chan<- comicInfo) {
    if res, err := http.Get(url); err == nil {
        if res.StatusCode == http.StatusOK {
            newComic := comicInfo{}
            if err := json.NewDecoder(res.Body).Decode(&newComic); err == nil {
                fmt.Println(newComic)
                ch <- newComic
            }
        }
    }
}

func init() {
    ch := make(chan comicInfo)
    if res, err := http.Get("http://xkcd.com/info.0.json"); err == nil {
        if res.StatusCode == http.StatusOK {
            newComic := comicInfo{}
            if err := json.NewDecoder(res.Body).Decode(&newComic); err == nil {
                newestComic = newComic
                comicInfoMap[newestComic.Number] = newestComic
                for j := 0; j < 10; j++ {
                    addtion := 100 * j
                    for i := addtion + 1; i < addtion+101; i++ {
                        indexStr := strconv.Itoa(newComic.Number - i)
                        url := "http://xkcd.com/" + indexStr + "/info.0.json"
                        go fetch(url, ch)
                    }
                    for i := addtion + 1; i < addtion+101; i++ {
                        newComic := <-ch
                        comicInfoMap[newComic.Number] = newComic
                    }
                }
            }
        }
    }
}

func main() {
    http.HandleFunc("/", handler)
    log.Fatal(http.ListenAndServe(":9020", nil))
}

func handler(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Access-Control-Allow-Origin", "*")
    w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
    w.Header().Set("Access-Control-Allow-Headers",
        "Origin, X-Requested-With, Content-Type, Accept")

    var encoder = json.NewEncoder(w)
    if r.URL.Path == "/" {
        encoder.Encode(newestComic)
    } else {
        res := strings.Split(r.URL.Path, "/")
        r.Body.Close()
        path, err := strconv.Atoi(res[1])
        if err != nil {
            return
        }
        if path < 100 {
            number := path
            newComicInfoSlice := []comicInfo{}
            for i := 0; i < 10; i++ {
                index := newestComic.Number - i - 10*number
                newComicInfoSlice = append(newComicInfoSlice, comicInfoMap[index])
            }
            encoder.Encode(newComicInfoSlice)
        }
    }
}


texts: Using enum descriptions to string/text binding

texts:
In my WP8 application I need to show a couple of radio buttons to let the user select a value out of an enum. I don't want to hardcode either the value or the text (description) showed to the user. I would like my Model/ViewModel drive them for me.

As of now, this is what I have:

//enum defined in model
 public enum Units
    {
        [Description ("Meters/km")]
        Metric,
        [Description ("Feet/Miles")]
        Imperial
    }

Converters defined to handle string and Boolean conversions

//Converts ENum to boolean and back
// Convert: uses parameter passed in, returns true if current value of the Enum matches parameter
//ConvertBack: if value is true, sets the value of the ENum to parameter passed in
//
[ValueConversion (typeof (Enum), typeof (Boolean))]
public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if ( parameterString == null )
            return DependencyProperty.UnsetValue;

        if ( Enum.IsDefined (value.GetType (), value) == false )
            return DependencyProperty.UnsetValue;

        object parameterValue = Enum.Parse (value.GetType (), parameterString);

        return parameterValue.Equals (value);

    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        return value.Equals (true) ? Enum.Parse(targetType, parameter as String) : DependencyProperty.UnsetValue;
    }
}

//Converts ENum to strings, uses Description for the parameter passed in, or parameter as string
[ValueConversion (typeof (Enum), typeof (String))]
public class EnumToStringConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if ( parameterString == null )
            return DependencyProperty.UnsetValue;

        if ( Enum.IsDefined (value.GetType (), value) == false )
            return DependencyProperty.UnsetValue;

        var desc = (value.GetType ().GetField (parameterString).GetCustomAttributes (typeof (DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute);
        if ( desc != null )
            return desc.Description;
        else
            return parameter.ToString ();
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException ();
    }
}

In the XAML:

   <Grid  Margin="0,10,0,0">
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="Auto" />
        <ColumnDefinition Width="Auto" />
    </Grid.ColumnDefinitions>
    <TextBlock Text="How do you measure distance?"
               Margin="6,0,0,0"
               Grid.ColumnSpan="2"
               Grid.Row="0" />
    <RadioButton Grid.Row="1"
                 Grid.Column="0"
                 Content="{Binding PreferredUnit, ConverterParameter=Metric, Converter={StaticResource EnumToStringConverter}}"
                 IsChecked="{Binding PreferredUnit, ConverterParameter=Metric, Converter={StaticResource EnumToBooleanConverter}, Mode=TwoWay}" />
    <RadioButton Grid.Row="1"
                 Grid.Column="1"
                 Content="{Binding PreferredUnit, ConverterParameter=Imperial, Converter={StaticResource EnumToStringConverter}}"
                 IsChecked="{Binding PreferredUnit, ConverterParameter=Imperial, Converter={StaticResource EnumToBooleanConverter}, Mode=TwoWay}" />
</Grid>

Does anyone here think I am on the right track with my approach? Any suggestions on improving the code (in terms of logic, clarity, performance)?


texts:
I hope that the word "decompose" is correct, but the problem is simple:
I got two lists after an operation and I want to know what change happend from one list to the other.
As such I want to "decompose" the two lists A and B into "Both", "Only A" and "Only B".
template <class T>
void decompose(std::vector<T*> &a, std::vector<T*> &b, std::vector<T*> &only_a, std::vector<T*> &only_b, std::vector<T*> &both) {
    only_a = a;
    only_b = b;
    for (T* x : a) {
        for (T* y : b) {
            if (x == y) {
                both.push_back(x);
            }
        }
    }

    {
        auto it = only_a.begin();
        while (it != only_a.end()) {
            bool erase = false;
            for (T* x : both) {
                if (x == *it) {
                    it = only_a.erase(it);
                    erase = true;
                }
            }
            if (!erase) {
                it++;
            }
        }
    }

    {
        auto it = only_b.begin();
        while(it != only_b.end()) {
            bool erase = false;
            for (T* x : both) {
                if (x == *it) {
                    it = only_b.erase(it);
                    erase = true;
                }
            }
            if (!erase) {
                it++;
            }
        }
    }
}

I feel like there should be a faster way to do this than three twice intertwined loops.


texts:
I've never done anything in java, but today I had a couple hours of free time so I decided I would learn it and make a Tic Tac Toe game. Please give me some constructive criticism on anything you would do differently.

import java.util.Scanner;
import java.util.stream.IntStream;;

public class TicTacToe {

    static Scanner scan = new Scanner(System.in);
    static char board[] = {'A','B','C','D','E','F','G','H','I'};
    static final int scoreboard[] = {1,2,7,6,0,4,3,8,9};
    static int player = 0;
    static boolean gameOver = false;
    static int score[][] = {{0,0,0,0,0},{0,0,0,0}};
    static int turn[] = {0,0,5};

    public static void main(String[] args) {
        while (gameOver == false) {

            askForTurn();

        }
    }

    public static void askForTurn() {

        System.out.printf("\n-------------\n| %s | %s | %s |\n-------------\n| %s | %s | %s |\n-------------\n| %s | %s | %s |\n-------------",board[0],board[1],board[2],board[3],board[4],board[5],board[6],board[7],board[8]);
        boolean valid = false;
        System.out.printf("\nPlayer %o's turn:", (player+1));
        char input = scan.next().toUpperCase().charAt(0);
        int i;
        for (i = 0; i < 9; i++) {

            if (input == board[i]) {

                if (player == 0) {

                    valid = true;
                    board[i] = 'O';
                    score[0][turn[0]] = scoreboard[i];
                    turn[0]++;

                } else {

                    valid = true;
                    board[i] = 'X';
                    score[1][turn[1]] = scoreboard[i];
                    turn[1]++;

                }

            }

        }

        if (valid == false) {

            System.out.print("\nInvalid square");
            askForTurn();

        } else {

            checkForWin();
            player++;

            if (player%2 == 0) {

                player = 0;
            }

        }

    }

    public static void checkForWin() {

        int sum1 = IntStream.of(score[0]).sum();
        int sum2 = IntStream.of(score[1]).sum();
        int x;

        ifWin(1, 0, 3, sum1%10, 0);
        ifWin(1, 0, 3, sum2%10, 1);

        for (x = 0; x < turn[0]; x++) {

            ifWin(1, 0, 4, (sum1 - score[0][x])%10, 0);

        }

        for (x = 0; x < (turn[1] - 1); x++) {

            ifWin(1, 0, 4, (sum2 - score[1][x])%10, 1);

        }

        if (turn[0] == 5) {

            for (x = 0; x < 3; x++) {

                ifWin(1, 0, 5, (sum1-score[0][0]-score[0][x+1])%10, 0);
                ifWin(x, 0, 5, (sum1-score[0][1]-score[0][x+1])%10, 0);
                ifWin(x, 1, 5, (sum1-score[0][2]-score[0][3])%10, 0);
                ifWin(x, 1, 5, 0, 2);

            }

        }

    }

    public static void endGame(int player) {

        if (player == 3) {

            System.out.print("\nTie!");

        } else {

            System.out.printf("Player %o wins!", player);

        }

        gameOver = true;

    }

    public static void ifWin(int x, int z, int turnCheck, int statement, int player) {

        if (x > z && turn[player] == turnCheck && statement == 0) {

            endGame(player + 1);

        }

    }

}


texts: Lock Using "Interlocked" vs lock Statement ("Monitor")

texts:
A followup question can be found here, based on this question and it's answer.

Considering:

Interlocked.CompareExchange generates a memory barrier,
Intended to be used with very fast operations (like generating an
id),
SpinWait starts sleeping in milliseconds after 10 or so spins (and
does some other smart stuff),

What are characteristics (pros & cons) of this code?

public class SpinMutex
{
    const long Locked = 1;
    const long Unlocked = 0;

    long _locked;

    public SpinMutex() { _locked = Unlocked; }

    public void Lock()
    {
        SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Locked);
    }

    public bool Lock(int millisecondsTimeout)
    {
        return SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Locked, millisecondsTimeout);
    }

    public bool Lock(TimeSpan timeout)
    {
        return SpinWait.SpinUntil(() => Interlocked.CompareExchange(ref _locked, Locked, Unlocked) == Locked, timeout);
    }

    public void Unlock()
    {
        Interlocked.Exchange(ref _locked, Unlocked);
    }
}

And some extra points to consider:

Does it help if SpinMutex be defined as struct instead of a
class (I'm aware there would be hurdles with say readonly fields
of struct type and the like)?
Should Interlocked.CompareExchange be used in Unlock too, instead of
Interlocked.Exchange to ensure generating of a memory barrier? Or
Interlocked.Exchange generates a memory barrier itself? Is a memory barrier needed at all at Unlock?


texts:
Recently I've written some code which implements snap-to-edge functionality for some windows.

There is some code duplication as you can see. I think this code can be simpler or possibly improved.

// If 'rtParent' and 'rtChild' are closed each other as 'ENABLE_STICK_VALUE', return true;
auto IsNearEachOther = []( const QRect& rtParent, const QRect& rtChild ) -> std::tuple< bool, QPoint>
{
    bool isNear = false;
    QPoint ptMoveTarget;

    // If 'rtChild's left position is closing to 'rtParent's right position.
    if ( rtChild.left() > rtParent.right() )
    {
        if ( ( ( rtChild.left() - rtParent.right() ) <= ENABLE_STICK_VALUE )
            && ( rtChild.top() >= ( rtParent.top() - ENABLE_STICK_VALUE ) )
            && ( rtChild.top() <= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
        {
            isNear = true;
            ptMoveTarget = QPoint( rtParent.right(), rtParent.top() );
        }
    }

    // If 'rtChild's right position is closing to 'rtParent's left position.
    if ( rtChild.right() < rtParent.left() )
    {
        if ( ( ( rtParent.left() - rtChild.right() ) <= ENABLE_STICK_VALUE )
            && ( rtChild.top() >= ( rtParent.top() - ENABLE_STICK_VALUE ) )
            && ( rtChild.top() <= ( rtParent.bottom() + ENABLE_STICK_VALUE ) ) )
        {
            isNear = true;
            ptMoveTarget = QPoint( rtParent.left() - rtChild.width() , rtParent.top() );
        }
    }

    return std::make_tuple( isNear, ptMoveTarget );
};

QRect rtParent = m_pParentChatRoom->geometry();
QRect rtCurrent = geometry();

bool result = false;
QPoint ptMoveTarget;
std::tie( result, ptMoveTarget ) = IsNearEachOther( rtParent, rtCurrent );
if ( result )
{
    move( ptMoveTarget );
}


texts:
I have a file named feedback.js that I would like to improve.

function feedback(feedbackform) {

    // collect the feedbackform data while iterating over the inputs
    var data = {};
    for (var i = 0; i < feedbackform.length; i++) {
        var input = feedbackform[i];
        if (input.name && input.value) {
            data[input.name] = input.value;
        }
    }

    // construct an HTTP request
    var xhr = new XMLHttpRequest();
    xhr.open(feedbackform.method, feedbackform.action);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    // send the collected data as JSON
    xhr.send(JSON.stringify(data));
    feedbackform.send.disabled = true;

    xhr.onloadend = function () {
        if (xhr.status == 200) {
            feedbackform.send.value = "Sent!";
            feedbackform.send.className = "success";
        } else {
            feedbackform.send.value = "Failed to send";
            feedbackform.send.className = "fail";
        }
    };

    return false;
}

Is there a modern way to collect form inputs? E.g. json enctype?
Is disabling the submit button a good idea to prevent multiple form submissions?
If the form fails to send, what's a good recourse (to prevent data loss of the filled form) I can give the user? Perhaps munge it into a mailto: command?

Are there any other tweaks I can make without relying on any dependencies, such as trying to reduce code size?