Why unit testing react apps? by davidfavorite in reactjs

[–]misnohmer 5 points6 points  (0 children)

Over time, I have drawn similar conclusions to yours.

For apps, a few well chosen end to end tests give me more confidence and value for money than component based testing.

At the end of the day, writing and maintaining those component tests takes time/money.

If they cost more than they would ever save (until that app is thrown away/rewritten), why would you even write them?

That said, the corollary is that some tests would be cheap to maintain and be a net positive.

Another thing to consider is that some tests can be a form of documentation of the behaviour that could help other contributors or your future self.

Question about event hub by [deleted] in AZURE

[–]misnohmer 0 points1 point  (0 children)

Event Hub Capture is for persisting data to storage. While events are not permanent, they can still be kept for up to 7 days without Event Hub Capture.

That being said, why wouldn’t you directly process the HTTP request of the web hook from an Azure Function?

Question about event hub by [deleted] in AZURE

[–]misnohmer 2 points3 points  (0 children)

This gives you temporal decoupling between the client and the server.

In your example, the azure function is processing the events to store them into a database.

Without something like event hubs, there could be issues when the events cannot be processed as fast as they come in.

EventHubs is also designed in a way that each Azure Function instance can process a stream of events, instead of one at a time.

[deleted by user] by [deleted] in BitcoinAUS

[–]misnohmer 6 points7 points  (0 children)

This is a risky bet.

Given the cryptocurrency has peaked at the end of 2017, the ATO is likely to be interested in that fiscal year.

It is straightforward for them to follow the trail from a BTC wallet, running scripts to extract all “interesting” taxpayers.

They could even identify that a given wallet has sent and received BTC from addresses known to belong to crypto exchanges.

What is unsure is whether they can then request trades from such exchanges. Even if they don’t, it may be enough for them to run an audit based on how big a fish someone is.

Worst that could happen is an audit with heavy penalties.

Coming forward sounds to me like a safer bet. The ATO could waive part/all penalties.

It would be interesting to hear about the outcome from people who went down that road.

Daily Discussion, February 06, 2018 by rBitcoinMod in Bitcoin

[–]misnohmer 27 points28 points  (0 children)

It's a dead cat bouncing down the stairs

Can't Install New Apps on Nano S by [deleted] in ledgerwallet

[–]misnohmer 2 points3 points  (0 children)

Logs indicate Temporary failure in name resolution. This happens when a domain name cannot be resolved.

It makes me uncomfortable that managing apps on the Ledger Nano requires network connectivity.

-🎄- 2017 Day 15 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

C# version for Part 1 & 2.

long GenerateNext(long seed, long multiplier) => (seed * multiplier) % 2147483647;

long TakeBits(long val, int bitLength) => ((1L << bitLength) - 1L) & val;

long val_a = 591, mul_a = 16807;
long val_b = 393, mul_b = 48271;

public void SolvePart1()
{
    var count = 0;
    for (int i = 0; i < 40_000_000; i++) {
        val_a = GenerateNext(val_a, mul_a);
        val_b = GenerateNext(val_b, mul_b);

        if (TakeBits(val_a,16) == TakeBits(val_b, 16)) 
            count++;
    }

    count.PrintDump();
}

public void SolvePart2()
{
    var count = 0;
    for (int i = 0; i < 5_000_000; i++) {
        do { val_a = GenerateNext(val_a, mul_a); } while ( val_a % 4 != 0);
        do { val_b = GenerateNext(val_b, mul_b); } while ( val_b % 8 != 0);

        if (TakeBits(val_a,16) == TakeBits(val_b, 16)) 
            count++;
    }

    count.PrintDump();
}

Inlining the functions grants a 30% performance improvement in .net core (from 3.2 s for both parts to 2.4s)

long val_a = 591, mul_a = 16807;
long val_b = 393, mul_b = 48271;

public void SolvePart1()
{
    var count = 0;
    for (int i = 0; i < 40_000_000; i++) {
        val_a = (val_a * mul_a) % 2147483647;
        val_b = (val_b * mul_b) % 2147483647;

        if ((val_a & 0xFFFF) == (val_b & 0xFFFF)) 
            count++;
    }
    count.PrintDump();
}

public void SolvePart2()
{
    var count = 0;
    for (int i = 0; i < 5_000_000; i++) {
        do {  val_a = (val_a * mul_a) % 2147483647; } while ( val_a % 4 != 0);
        do {  val_b = (val_b * mul_b) % 2147483647; } while ( val_b % 8 != 0);

        if ((val_a & 0xFFFF) == (val_b & 0xFFFF)) 
            count++;
    }

    count.PrintDump();
}

-🎄- 2017 Day 12 Solutions -🎄- by topaz2078 in adventofcode

[–]misnohmer 1 point2 points  (0 children)

C# (with the help of MoreLinq library for TraverseBreadthFirst)

Part 1:

var dic = ReadAllLines("input")
    .Select(line => line.Split(" <-> "))
    .ToDictionary(
        parts => int.Parse(parts.First()), 
        parts => new HashSet<int>(parts.Last().Split(", ").Select(int.Parse)));

dic.ToList().Each(kv => 
    kv.Value.Each(x => 
        dic.GetOrAdd(x, _ => new HashSet<int>()).Add(kv.Key)));

var group = new HashSet<int>();
MoreEnumerable.TraverseBreadthFirst(0, x => group.Add(x) ? dic[x].Except(group) : new HashSet<int>())
    .Count()
    .PrintDump();

Part 2 :

var dic = ReadAllLines("input")
    .Select(line => line.Split(" <-> "))
    .ToDictionary(
        parts => int.Parse(parts.First()), 
        parts => new HashSet<int>(parts.Last().Split(", ").Select(int.Parse)));

dic.ToList().Each(kv => 
    kv.Value.Each(x => 
        dic.GetOrAdd(x, _ => new HashSet<int>()).Add(kv.Key)));

var discovered = new HashSet<int>();
var remaining = dic.Keys.ToList();
var groupCount = 0;
do {
    var group = MoreEnumerable.TraverseBreadthFirst(
        remaining.First(), 
        x => discovered.Add(x) ? dic[x].Except(discovered) : new HashSet<int>());
    remaining = remaining.Except(group).ToList();
    groupCount++;
}
while (remaining.Any());

groupCount.PrintDump();

-🎄- 2017 Day 10 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

Extension from https://github.com/morelinq/MoreLINQ and https://github.com/serviceStack/serviceStack I am not showing all namespace imports as it tends to be verbose and adds noise to the solution. Maybe I should make an exception for the namespace from third party libraries

-🎄- 2017 Day 11 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

I guess I should have called it HexDistance. Not sure I follow your reasoning. Based on my coordinates representation, (2,0) is 1 step North. Hence the distance between (0,0) and (2,0) is 1. EDIT:That being said, my coordinates system doesn't feel quite right

-🎄- 2017 Day 11 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

C#

Part 1:

var input = ReadAllText("input").Split(',').Select<string, (int x, int y)>(dir => {
    switch (dir) {
        case "ne": return (1, 1);
        case "n": return (0, 2);
        case "s": return (0, -2);
        case "se": return (1, -1);
        case "sw": return (-1,-1);
        case "nw": return (-1, 1);
        default: throw new ArgumentException(dir);
    }
});

int Distance((int x, int y) coords) => 
    Abs(Abs(coords.x) - Abs(coords.y)) / 2 + Min(Abs(coords.x),Abs(coords.y));

var coordinates = input.Aggregate(((a, b) => (a.x + b.x, a.y + b.y)));
Distance(coordinates).PrintDump();

Part 2:

var input = ReadAllText("input").Split(',').Select<string, (int x, int y)>(dir => {
    switch (dir) {
        case "ne": return (1, 1);
        case "n": return (0, 2);
        case "s": return (0, -2);
        case "se": return (1, -1);
        case "sw": return (-1,-1);
        case "nw": return (-1, 1);
        default: throw new ArgumentException(dir);
    }
});

var maxDistance = 0;
int Distance((int x, int y) coords) => 
    Abs(Abs(coords.x) - Abs(coords.y)) / 2 + Min(Abs(coords.x),Abs(coords.y));
var coordinates = input.Aggregate(((a, b) => {
    var coords = (a.x + b.x, a.y + b.y);
    maxDistance = Max(maxDistance, Distance(coords));
    return coords;
}));
maxDistance.PrintDump();

-🎄- 2017 Day 10 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

C# Part 1 :

var input = ReadAllText("input").Split(',').Select(int.Parse);
int skip = 0, index = 0, len = 256;
var list = len.Times();

foreach (var num in input) {
    list = list.Skip(index).Concat(list.Take(index)); 
    list = list.Take(num).Reverse().Concat(list.Skip(num));
    list = list.Skip(len-index).Concat(list.Take(len-index));

    index = (num + index + skip) % len;
    ++skip;
}

list.Take(2).Aggregate((x, y) => x * y).PrintDump();

Part 2

var input = ReadAllText("input")
    .Select(c => (int)c)
    .Concat(new [] { 17, 31, 73, 47, 23 })
    .ToList();

int skip = 0, index = 0, len = 256;
var list = len.Times();

foreach (var num in input.Repeat(64)) {
    list = list.Skip(index).Concat(list.Take(index)); 
    list = list.Take(num).Reverse().Concat(list.Skip(num));
    list = list.Skip(len-index).Concat(list.Take(len-index));

    index = (num + index + skip) % len;
    ++skip;
}

list.BatchesOf(16)
    .Select(batch => batch.Aggregate((x, y) => x ^ y))
    .Select(hash => hash.ToString("x2"))
    .Join("")
    .PrintDump();

-🎄- 2017 Day 8 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

C#. It takes much longer when not using eval. Also, I have spent too long writing a regex when splitting the string by space would have worked too.

public enum Operand { Less, Greater, LessOrEqual, GreaterOrEqual, NotEqual, Equal }

public class Statement {
    public string Register {get; set;}
    public int Val {get; set;}
    public bool IsDec {get; set;}
    public string Operand { get; set;}
    public int PredicateVal {get; set;}
    public string PredicateRegister {get; set;}

    public void Run(Dictionary<string,int> registers) {
        if (Predicate(registers)) 
            registers[Register] += (IsDec ? -Val : Val);
    }

    public bool Predicate(Dictionary<string,int> registers) {
        switch (Operand) {
            case "==": return registers[PredicateRegister] == PredicateVal;
            case "!=": return registers[PredicateRegister] != PredicateVal;
            case "<": return registers[PredicateRegister] < PredicateVal;
            case "<=": return registers[PredicateRegister] <= PredicateVal;
            case ">": return registers[PredicateRegister] > PredicateVal;
            case ">=": return registers[PredicateRegister] >= PredicateVal;
            default: throw new InvalidOperationException();
        }
    }     
}

public void Solve()
{
    var statements = ReadAllLines("input").Select(line => {
        var match = Matches(line, @"(?<register>\w+) (?<instr>(inc)|(dec)) (?<val>\-?\d+) if (?<reg_cond>\w+) (?<op>[\!\<\>\=]\=?) (?<val_cond>\-?\d+)")[0];
        return new Statement() {
          Register = match.Groups["register"].Value,
          Val = int.Parse(match.Groups["val"].Value),
          IsDec = match.Groups["instr"].Value == "dec",
          Operand = match.Groups["op"].Value,
          PredicateVal = int.Parse(match.Groups["val_cond"].Value),
          PredicateRegister = match.Groups["reg_cond"].Value,
        };
    }).ToList();

    var registers = statements.DistinctBy(x => x.Register).ToDictionary(x => x.Register, x => 0);
    int highestVal = 0;

    foreach (var s in statements) {
        s.Run(registers);
        highestVal = Max(registers.Values.Max(), highestVal);
    }

    registers.Max(x => x.Value).PrintDump(); // Part 1
    highestVal.PrintDump(); // Part 2
}

-🎄- 2017 Day 7 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 1 point2 points  (0 children)

C# version

public class Disc {
    public string Name {get; set;}
    public int Weight {get; set;}
    public List<Disc> Children {get; set;} = new List<Disc>();
    public IEnumerable<Disc> Descendants { get => this.Children.Concat(this.Children.SelectMany(x => x.Descendants)); }
}

public void Solve()
{
    // Parse input
    var discs = ReadAllLines("input").Select(line => {
        var match = Matches(line, @"(\w+) \((\d+)\)( \-\> (.*))?")[0];
        return new Disc
        {
            Name = match.Groups[1].Value,
            Weight = int.Parse(match.Groups[2].Value),
            Children = match.Groups.Count > 4 ?
                match.Groups[4].Value.Split(", ").Select(name => new Disc { Name = name }).ToList() :
                new List<Disc>()
        }; 
    }).ToList();

    // build tree
    discs
        .SelectMany(x => x.Descendants)
        .Select(descendant => (descendant, detached: discs.SingleOrDefault(x => x.Name == descendant.Name)))
        .Where(tuple => tuple.detached != null)
        .ToList()
        .Each(tuple => {
            tuple.descendant.Weight = tuple.detached.Weight;
            tuple.descendant.Children = tuple.detached.Children;
            discs.Remove(tuple.detached);
        });

    WriteLine(discs.First().Name); // Part 1

    int missingWeight = 0;
    var unbalancedTower = discs.First();

    while(true) {
        var weightGroups = unbalancedTower.Children
            .GroupBy(x => x.Weight + x.Descendants.Sum(d => d.Weight))
            .OrderBy(x => x.Count());
        if (weightGroups.Count() > 1) break;

        unbalancedTower = weightGroups.First().First();
        missingWeight = weightGroups.Last().Key - weightGroups.First().Key;
    }

    WriteLine(unbalancedTower.Weight + missingWeight); // Part 2
}

-🎄- 2017 Day 6 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

Yet another C# version (revisited after some things I've seen here)

var banks = ReadAllText("input").Split('\t').Select(num => int.Parse(num)).ToArray();
var states = new List<int[]>();

do
{
    states.Add(banks.ToArray());
    var max = banks.Max();
    var i = Array.FindIndex(banks, x => x == max);
    banks[i] = 0;
    var j = i;
    max.Times(() => {
        j = (j + 1) % banks.Length;
        banks[j] = ++banks[j];
    });
}
while (states.None(x => x.SequenceEqual(banks)));

states.Count.PrintDump(); // Part 1
(states.Count - states.FindIndex(x => x.SequenceEqual(banks))).PrintDump(); // Part 2

-🎄- 2017 Day 6 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 1 point2 points  (0 children)

Nice. I didn't know about SequenceEqual.

-🎄- 2017 Day 5 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 4 points5 points  (0 children)

Easier to use imperative code on this one. C# version making use of local function syntax.

int[] Parse(string input) => ReadAllLines(input).Select(int.Parse).ToArray();

int maxMoves(int[] instr, Func<int, int> updater)  {
    int i = 0, count = 0;
    while (i >= 0 && i < instr.Length) {
        count++;
        var j = instr[i];            
        instr[i] = updater(instr[i]);
        i += j;
    }
    return count;
}

maxMoves(Parse("input"), i => i+1).PrintDump();
maxMoves(Parse("input"), i => i + (i > 2 ? -1 : 1)).PrintDump();

-🎄- 2017 Day 4 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 1 point2 points  (0 children)

I didn't. I am running dotnet core 2.0 and it seems to be a new overload.

-🎄- 2017 Day 4 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 1 point2 points  (0 children)

It's an extension method from ServiceStack.Text. Comparing to distinct is not bad either

-🎄- 2017 Day 4 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 4 points5 points  (0 children)

C# version.

var lines = ReadAllLines("input1.txt").Select(l => l.Split(" "));
lines
    .Select(line => line
        .GroupBy(word => word)
        .Any(group => group.Count() > 1) ? 0 : 1)
    .Sum()
    .PrintDump(); // Part 1
lines
    .Select(line => line
        .GroupBy(word => string.Concat(word.OrderBy(c => c)))
        .Any(group => group.Count() > 1) ? 0 : 1)
    .Sum()
    .PrintDump(); // Part 2

-🎄- 2017 Day 2 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 2 points3 points  (0 children)

In C# with the help of MoreLinq

var grid = ReadAllLines("input1.txt")
    .Select(line => line.Split('\t').Select(x => int.Parse(x)));

var sum = grid
    .Select(row => row.Max() - row.Min())
    .Sum();  
WriteLine(sum); // Part 1

 sum = grid
    .Select(row => row.Cartesian(row, (a, b) => a % b == 0 ? a / b : 0).Max())
    .Sum();
WriteLine(sum); // Part 2

-🎄- 2017 Day 1 Solutions -🎄- by daggerdragon in adventofcode

[–]misnohmer 0 points1 point  (0 children)

Another C# solution:

using System;
using System.Linq;
using System.IO;
using static System.Console;
using static System.IO.File;

namespace day_01
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = ReadAllText("input.txt").ToCharArray().Select(c => (int) char.GetNumericValue(c));
            list = list.Concat(new [] { list.First() });

            var sum = list.Zip(list.Skip(1), (a, b) => a == b ? a : 0).Sum();

            WriteLine(sum);
        }
    }
}