Hot answers tagged

22

If you need to store a result of a method you should just create a method for it. private bool IsInRange(DateTime dateTime, decimal min, decimal max) { decimal totalMinutes = Math.Round((dateTime - DateTime.Now).TotalMinutes, 0); return totalMinutes > min && totalMinutes <= max; } now your expression looks like so .Where(m =>...


18

I would have probably applied the following changes: Make size a static constexpr variable in CallerTraits instead of simply static const. Wherever a function simply passes variadic arguments whose types have been deduced, I would have passed args by universal reference (now officially called forwarding reference) and used std::forward to forward the ...


17

I find your implementation a bit more complex than necessary. What you want to do is fetch arguments from your "result set" row by calling its getValue() in a particular order; use them (as arguments) to call operator() on function object action. This can be done without recursion in two lines: Do{row->getValue(std::get<N>(args))...}; action(std::...


16

Why not use Regex.Match instead of using those confusing joins/splits? Unless you are purposely trying to code golf this, doing it using regular expression is much easier to follow logically. After taking into account delegates used with Regex.Replace (as explained in svick's comment), here is a functionally superior solution to the previous answer I posted....


15

Your code is odd in the sense that it is going to a lot of effort to calculate that 103 is 1000. I understand why you are doing it, but I took the liberty of changing the count() terminating function and replacing it with: StringBuilder sb = new StringBuilder(); ....... .forEachOrdered(prod -> sb.append(prod.toString()).append("\n"); This way we can ...


15

One way is to use query-style LINQ and the let keyword: var finalList = (from m in initialList let value = Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes where value <= 30 && value > 0 select m).ToList();


12

I like your usage of Java 8. I'm learning a lot just by reading your code. I'm loving Java 8 a lot and I haven't even used it myself yet. Use a GestureRule class. Take a look at The Mug's Main class and/or The Monkey's static initializer in his enum. Your current way is error prone and causes some duplicated code. Currently you can by accident create a ...


12

Don't try to be a badass cowboy. ☺ Stuffing everything onto one line of code is trying to be badass. You could improve clarity simply by adding whitespace. Producing an incremented version number by careless string processing is trying to be a cowboy. I suggest introducing some kind of abstraction, such as this SemVer class. If you don't want to ...


12

The first step is to shift out duplicate code from the if branch. def func(x): list = data.parseJSON(fileName) if x == 1: person = [l for l in list if l['worker'] == sys.argv[1]] displayPeople(flatten(person)) elif x == 2: person = [l for l in list if sys.argv[1] in set(l['children'])] displayPeople(person) elif x == 3: person = [...


12

Say what you mean and mean what you say You named your class "Window" when it should really be something more like "Viewport". There are no "Windows" (in the GUI sense) in your code. If you decide to incorporate this into an application that does contain Windows in the GUI sense, this will be hopelessly confusing. Don't omit essential documentation from ...


11

I do not have much to add to @rofl's answer, but I do have another way to show to create Cartesian Products while using streams, which I think might be very interesting aswell. Important note I have made a mistake while reading the intention of the OP's post. I have confused Cartesian Products with calculating products of the elements of Cartesian Products....


11

By using an IEqualityComparer<Person> which only compares the Value property like public class PersonValueComparer : IEqualityComparer<Person> { public bool Equals(Person x, Person y) { if (x == null && y == null) { return true; } if (x == null || y == null) { return false; } return x.Value == y.Value; ...


11

Since you mentioned in the comments that you want the union of the two lists, you could perform a LINQ Union. There are a few ways to do it: Use IEnumerable<T>.Union(IEnumerable<T>) If you go with the simpler overload for Union, you need to implement IEquatable<T> and override GetHashCode on Person. For simplicity, my example will look ...


11

I agree with @JanDotNet that by using a separate method you will gain readability but that's just my subective view. As you are asking about C#7 stuff I assume that you will use .NET >= 4.6. Starting with .NET 4.6 the X509Store implements IDisposable hence you should enclose the using of the X509Store inside a using block. Instead of using a concrete ...


10

There is way too much code in that last line. I'm not a stickler for wrapping at 80 character, but 280 characters seems like a bit much. Just because this is a build step script doesn't mean you code doesn't have to be readable. Write a real function to do this operation so I don't have to trust that you are writing the line back the correct way.


10

I think it's not completely terrible to cram a lot of stuff in a single chain of instructions. But, for the love of god, you have to break that line. Perhaps something like this: if (File.Exists(file)) { File.WriteAllLines(file, File.ReadAllLines(file) .Select(s => !s.Trim().StartsWith("[assembly: AssemblyFileVersion(")...


10

I wouldn't obfuscate → to &#8594;. Google Java Style says Never make your code less readable simply out of fear that some programs might not handle non-ASCII characters properly. If that should happen, those programs are broken and they must be fixed. and I can only agree. I'm rather unfamiliar with Java 8, but final AtomicLong c = new ...


10

Write an IsBetween extension method: public static bool IsBetween<T>(this T item, T start, T end) { return Comparer<T>.Default.Compare(item, start) >= 0 && Comparer<T>.Default.Compare(item, end) <= 0; } And use it like this: .Where(m => Math.Round((m.DateAndTime - DateTime.Now).TotalMinutes, 0).IsBetween(0, ...


9

It is becoming really good, but there are still a few things that can be done: There already is a standard way to "clean" a type: std::decay. It does a little bit more than just removing the reference and the const qualification though, but it does basically what you need. Therefore, you can totally get rid of CleanType and use std::decay instead: using ...


9

This seems as efficient as it gets, to me. In terms of elegance, Joshua Bloch (in Effective Java) recommends to stop using bit fields, use EnumSet instead. The first step is to change your bit fields to an enum: public enum Mode { COMPARE_REVERSED, COMPARE_CASE_INSENSITIVE, COMPARE_SPACE_INSENSITIVE } Next, change your method to take a Set ...


9

Is the purpose and implementation of this function easier to read with the lambda expression? Or is this utterly confusing? IMHO a separate function is more readable: public X509Certificate FindClientCertificate(string serialNumber) => Find(StoreLocation.CurrentUser, serialNumber) ?? Find(StoreLocation.LocalMachine, serialNumber); private ...


8

I think the overall design is good, although make the main method create a new PokemonTypeChecker and then move all the stuff currently in the main method to a run method or similar - doing logic in the constructor is bad practice, and not writing OO code (i.e. making everything static) is too. You could also perhaps consider JavaFX over swing/awt too. ...


8

The urge to use Java8 features is strong, but, you need to look at the patterns of the problem, and not try to force the lambda to fit, rather, use the lambda to express the problem. In this case, you have a stream of values that represent a Collatz sequence, but, that's not true. A Collatz sequence is terminated when the value is 1, but your initial Stream ...


8

There's an existing technique which is not dissimilar referred to as "exception vomiting". Observe: void f(void(*p)()) { p(); } template<typename F> void real_f(F func) { try { throw func; } catch(...) { f([] { try { throw; } catch(F func) { func(); } ...


8

How about this: var peopleToAdd = secondList.Where(p1 => initialList.Any(p2 => p1.Value == p2.Value)).ToList(); initialList.RemoveAll(p1 => secondList.Any(p2 => p1.Value == p2.Value)); initialList.AddRange(peopleToAdd); Step 1 - look at the second list and find all people that need to be added to the first list. We are looking for all the ...


8

Unit testing Hi again @Legato, I'll probably bug you with unit testing until you start writing them ;-) @Test public void test_ABbCcc() { assertEquals(152, computeMaxBeauty("ABbCcc")); } @Test public void test_This_is_from_Facebook_Hacker_Cup_2013_() { assertEquals(551, computeMaxBeauty("This is from Facebook Hacker Cup 2013.")); } @Test public ...


8

Don't use String labels of GUI elements in flow control It's not good to use the String labels of GUI elements to make decisions. It would be slightly better if you made "Sum", "Difference", ... global constants, but only slightly. An enum would be better for this purpose: enum Operation { Sum("Sum", (x, y) -> x + y), Difference("Difference", (...


8

Use a block-lambda and extract a variable You can use a block-lambda instead of a statement lambda, and extract a variable: var now = DateTime.Now; List<Meeting> finalList = initialList.Where(m => { var minutesToNow = Math.Round((m.DateAndTime - now).TotalMinutes, 0); return minutesToNow <= 30 && minutesToNow > 0 }).ToList(); ...


8

I'm a little sure if this is well suited for Code Review, but here goes a little analysis: Using anonymous functions This doesn't look right as it is repeating too much code, which is a clear code smell. When quickly looking at it, it is unclear what the actual difference is between the two. So this is not a good option. Using eval An old saying says "...


8

I wouldn't use either ordering on the server side because it looks like the ordering only matters for displaying the data. I cannot imagine why it should matter from the programmatic point of view. Let the client, its view, its display control, or whatever sort the items according to its needs.


Only top voted, non community-wiki answers of a minimum length are eligible