Recent Entries 10
- pattern minor 112d agoMass and length calculator using Perl 6 custom operatorI am studying chemistry in the university, and then I try to write all the things in the textbook with Perl6 or Perl, like balancing the chemical formula or other process! Then I encountered the problem is on perl6 custom operator. I feel I have been repeating my code and myself when i use the feature. It is hard to read and write, and what is the way to deal with such problems? ``` #!/usr/bin/env perl6 use v6; #basic SI(International System of Units) type role MetricPrefix { method baseOn ( Str $base , Numeric $input ) { given $base { when 'pico' { return $input * 10**-12 } when 'namo' { return $input * 10**-9 } when 'micro' { return $input * 10**-6} when 'milli' { return $input * 10**-3 } when 'centi' { return $input * 10**-2 } when 'hecto' { return $input * 10**2 } when 'kilo' { return $input * 10**3 } when 'mega' { return $input * 10**6 } when 'giga' { return $input * 10**9 } when 'tera' { return $input * 10**12 } default { fail "you must input a metric prefix which allow pico to tera" } } } } class Mass does MetricPrefix { #basic Mass is g is different form si statda has $.g; submethod BUILD ( :$!g ) { } } class Length does MetricPrefix { has $.Length ; submethod BUILD ( :$!Length ) { } } multi postfix:( $input ) { return Mass.new( g => Mass.baseOn("kilo",$input) ) or fail "you Must input a number"; } multi postfix:( $input ) { return Mass.new( g => $input ) or fail "you Must input a number"; } multi infix:( Mass $inputOne , Mass $inputTwo ) is assoc { return Mass.new( g => $inputOne.g + $inputTwo.g) or fail "error in there "; } multi infix:( Mass $inputOne , Mass $inputTwo ) is assoc { return Mass.new( g => $inputOne.g - $inputTwo.g) or fail "error in there "; } multi infix:( Mass $inputOne , Mass $inputTwo ) is assoc is tighter( &infix: ) is tight
- pattern minor 112d agoField Can Be Made ReadonlyHere is my Field Can Be Made Readonly analyzer and quick fix. I would appreciate tips on how to improve my code, and on missed test cases. First, the rules it works with: - It will only fire on `private` fields to make things simpler (fields in other scopes should be properties, anyway). - If the field is only assigned inline or in the ctor, it should be `readonly` - Fields cannot be `readonly` if they are: A. Assigned in any scope other than a ctor or inline. B. Passed as a `ref` or `out` argument. C. Incremented or decremented with the prefix or postfix `++` or `--` operators. Here is the analyzer code: ``` [DiagnosticAnalyzer(LanguageNames.CSharp)] public class FieldCanBeReadonlyAnalyzer : DiagnosticAnalyzer { private const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; private static readonly string Category = VSDiagnosticsResources.GeneralCategory; private static readonly string Message = VSDiagnosticsResources.FieldCanBeReadonlyAnalyzerMessage; private static readonly string Title = VSDiagnosticsResources.FieldCanBeReadonlyAnalyzerTitle; internal static DiagnosticDescriptor Rule => new DiagnosticDescriptor(DiagnosticId.FieldCanBeReadonly, Title, Message, Category, Severity, true); public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) => context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.ClassDeclaration, SyntaxKind.StructDeclaration); private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context) { var classSymbol = (ITypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node); if (classSymbol.TypeKind != TypeKind.Class && classSymbol.TypeKind != TypeKind.Struct) { return; } var nonReadonlyFieldMembers = new List(); foreach (var item in classSymbol.GetMembers()) { var symbol = item as IFieldSymbol;
- pattern minor 112d agoClass decorator in Python to set variables for the constructorI personally don't like the boilerplate of most `__init__` methods: ``` self.a = a self.b = b ... ``` So I thought this would be a nice opportunity to learn a bit more about decorators. As this is my first attempt on a class decorator I'm sure there is a lot to improve so fire away: Implementation ``` from collections import namedtuple def autofill(*args, **kwargs): """ This class decorator declares all attributes given into the constructor followed by a call of __init__ without arguments (beside reference to self). Order is the same than namedtuple with the possibility of default elements. Note that in this decorator alters the existing class instance instead of returning a wrapper object. """ def filler(cls, *args, **kwargs): """ This is our custom initialization method. Input sanitation and ordering is outsourced to namedtuple. """ for key, val in InputSanitizer(*args, **kwargs)._asdict().items(): setattr(cls, key, val) filler.super_init(cls) def init_switcher(cls): filler.super_init = cls.__init__ cls.__init__ = filler return cls # Taken from http://stackoverflow.com/questions/11351032/named-tuple-and- # optional-keyword-arguments InputSanitizer = namedtuple('InputSanitizer', args + tuple(kwargs.keys())) InputSanitizer.__new__.__defaults__ = tuple(kwargs.values()) return init_switcher ``` Some test cases ``` import unittest class TestAutoFill(unittest.TestCase): @autofill('a', b=12) class Foo(dict): pass def test_zero_input(self): with self.assertRaises(TypeError): self.Foo() def test_one_input(self): bar = self.Foo(1) self.assertEqual(bar.a, 1) self.assertEqual(bar.b, 12) bar = self.Foo(a=1) self.assertEqual(bar.a, 1) self.assertEqual(bar.b, 12) with self.assertRaises(TypeError): self.Foo(b=1) with self.assertR
- pattern minor 112d agoRemoving XML Doc Comment NodesI recently wrote a code fix to handle many of the C# and VB.NET compiler diagnostics that was merged into Roslyn. Because it handles both, I implemented it as an abstract class with only the sections that are specific to the different languages in the language-specific implementations to eliminate code duplication. If you are interested, you can find my full test suites here: C# and VB.NET. The abstract class controls most of the implementation. Before you tell me to use `CodeAction.Create` for my code action implementation, Roslyn has an internal diagnostic telling me not to use that. ``` internal abstract class AbstractRemoveDocCommentNodeCodeFixProvider : CodeFixProvider where TXmlElementSyntax : SyntaxNode { public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer; public abstract override ImmutableArray FixableDiagnosticIds { get; } protected abstract string DocCommentSignifierToken { get; } protected abstract SyntaxTriviaList GetRevisedDocCommentTrivia(string docCommentText); public async sealed override Task RegisterCodeFixesAsync(CodeFixContext context) { var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); if (GetParamNode(root, context.Span) != null) { context.RegisterCodeFix( new MyCodeAction( c => RemoveDuplicateParamTagAsync(context.Document, context.Span, c)), context.Diagnostics); } } private TXmlElementSyntax GetParamNode(SyntaxNode root, TextSpan span, CancellationToken cancellationToken = default(CancellationToken)) { // First, we get the node the diagnostic fired on // Then, we climb the tree to the first parent that is of the type XMLElement // This is to correctly handle XML nodes that are nested in other XML nodes, so we only // remove the node the diagnostic fired on and its children, b
- debug minor 112d agoMemoizing decorator with retries, part 2A while ago I asked this question Memoizing decorator that can retry and then promptly forgot about it. I more recently saw Python decorator for retrying w/exponential backoff and wanted to add backoff, but figured I should improve what I already have first. I have taken some of the suggestions of the original, but really I've just completely reimagined it (and if I do say so myself, rather cleverly too). My biggest issue with this is that I'm not sure that my current distinction between "exceptions that get suppressed but not remembered" and "exceptions that get remembered" seems like it might be a bit confusing - is there a friendlier interface here? ``` import functools from types import MappingProxyType as FrozenDict class Memoizer: def __init__(self, retry_times=0, suppressed_exceptions=tuple(), capture_exceptions=False): self.retry = retry self.retry_times = retry_times self.suppressed_exceptions = suppressed_exceptions self.capture_exceptions = capture_exceptions def __call__(self, function): d = {} @functools.wraps(function) def wrapper(*args, **kwargs, __forget=False): key = (args, FrozenDict(kwargs)) if key not in d or __forget: i = self.retry_times while i > 1: try: d[key] = function(*args, **kwargs) except self.suppressed_exceptions: continue except Exception as e: if self.capture_exceptions: d[key] = e break raise else: break i -= 1 else: # If we didn't already break out, the last attempt shouldn't suppress exceptions d[key] = function(*args, **kwargs) return d[key] return wrapper ``
- debug minor 112d agoPython decorator for retrying w/exponential backoffThis is my first decorator in Python! I found some of it on the internet but have tweaked it to our needs. Here is the couple concerns of mine: - Multiple python version compatibility - Is grabbing the `self` or `arg[0]` the best way to get the instance of the class? - Any other general improvements! Here is the decorator. ``` import logging import time def retry_and_catch(exceptions, tries=5, logger=None, level=logging.ERROR, logger_attr=None, delay=0, backoff=0): """ Retries function up to amount of tries. Backoff disabled by default. :param exceptions: List of exceptions to catch :param tries: Number of attempts before raising any exceptions :param logger: Logger to print out to. :param level: Log level. :param logger_attr: Attribute on decorated class to get the logger ie self._logger you would give "_logger" :param delay: initial delay seconds :param backoff: backoff multiplier """ def deco_retry(f): def f_retry(*args, **kwargs): max_tries = tries d = delay exs = tuple(exceptions) log = logger while max_tries > 1: try: return f(*args, **kwargs) except exs as e: message = "Exception {} caught, retrying {} more times.".format(e.message, max_tries) # Get logger from cls instance of function # Grabbing 'self' instance = args[0] if not log and logger_attr and hasattr(instance, logger_attr): log = getattr(instance, logger_attr, None) if log: log.log(level, message) else: print(message) # Sleep current delay if d: time.sleep(d) # Increment delay if backoff:
- pattern minor 112d agoLombokython - Automatic __eq__, __hash__, __repr__I recently decided to code some in Python after coding in Java using lombok for quite some time. However, I got bit real hard when I forgot to implement `__eq__`, since Lombok normally does it for you. I decided to try to implement something similar to Lombok's `@EqualsAndHashCode`, which I called `eqhash`. Then, I added a similar way to generate a `__repr__` method. How well did I follow python style? I developed this using TDD, so I would like to know how my tests are as well. genmethods.py ``` def eqhash(cls: type): """Adds __eq__, __ne__, and __hash__ methods to the class""" class NewCls(cls): def __eq__(self, other): if self is other: return True if not isinstance(other, NewCls): return False svars = vars(self) ovars = vars(other) return svars == ovars def __ne__(self, other): return not (self == other) def __hash__(self): return hash(vars(self).values()) return _pass_attrs(NewCls, cls) def repr_(cls: type): """Adds a __repr__ method to the class""" class NewCls(cls): def __repr__(self): return '{clsname}({variables})'.format( clsname=cls.__name__, variables=', '.join(repr(o) for o in vars(self).values()) ) return _pass_attrs(NewCls, cls) def _pass_attrs(new_cls, cls): new_cls.__name__ = cls.__name__ new_cls.__qualname__ = cls.__qualname__ for attr, value in vars(cls).items(): try: setattr(new_cls, attr, value) except AttributeError: pass return new_cls ``` test_genmethods.py ``` import unittest import genmethods class SData: def __init__(self, value): self._value = value def test(self): return self._value def ensure_not_mangled(self: unittest.TestCase, cls: type, name: str): self.assertEqual((1, 2), cls((1, 2)).test()) self.assertEqual(name, cls.__name__) class EqH
- pattern minor 112d agoCode Explorer View ModelsContinuing the series of Code Explorer posts, here is the collection of view models for the tree nodes: This is the interface for nodes with a declaration. ``` public interface ICodeExplorerDeclarationViewModel { Declaration Declaration { get; } } ``` And here is the abstract view model they are all based on: ``` public abstract class CodeExplorerItemViewModel : ViewModelBase { private List _items = new List(); public List Items { get { return _items; } protected set { _items = value; OnPropertyChanged(); } } public bool IsExpanded { get; set; } public abstract string Name { get; } public abstract string NameWithSignature { get; } public abstract BitmapImage CollapsedIcon { get; } public abstract BitmapImage ExpandedIcon { get; } public abstract CodeExplorerItemViewModel Parent { get; } public abstract QualifiedSelection? QualifiedSelection { get; } public CodeExplorerItemViewModel GetChild(string name) { foreach (var item in _items) { if (item.Name == name) { return item; } var result = item.GetChild(name); if (result != null) { return result; } } return null; } public Declaration GetSelectedDeclaration() { return this is ICodeExplorerDeclarationViewModel ? ((ICodeExplorerDeclarationViewModel)this).Declaration : null; } public void AddChild(CodeExplorerItemViewModel item) { _items.Add(item); } public void ReorderItems(bool sortByName, bool sortByType) { if (sortByType) { Items = sortByName ? Items.OrderBy(o => o, new CompareByType()).ThenBy(t => t, new CompareByName()).ToList() : Items.OrderBy(o => o, new CompareByType()).ThenBy(t => t, new CompareBySelection()).To
- pattern minor 112d agoCode Explorer CommandsRubberduck's Code Explorer was recently redesigned from scratch: Anything from modern features, such as virtual folders (limitation of the VBE--it doesn't support real folders), to ancient features in the original VBE, such as printing. Here are some of the commands I wrote that I'd like to get reviewed: The Indent command. This command calls our Smart Indenter port and works on any node. On member nodes, procedures are indented (nothing happens if the node is a field); for component nodes, the selected component is indented; on folders, all components in the folder are indented; and on project nodes, all components in the project are indented. ``` public class CodeExplorer_IndentCommand : CommandBase { private readonly RubberduckParserState _state; private readonly IIndenter _indenter; private readonly INavigateCommand _navigateCommand; public CodeExplorer_IndentCommand(RubberduckParserState state, IIndenter indenter, INavigateCommand navigateCommand) { _state = state; _indenter = indenter; _navigateCommand = navigateCommand; } public override bool CanExecute(object parameter) { if (parameter is CodeExplorerComponentViewModel) { var node = (CodeExplorerComponentViewModel)parameter; if (node.Declaration.Annotations.Any(a => a.AnnotationType == AnnotationType.NoIndent)) { return false; } } if (parameter is CodeExplorerProjectViewModel) { if (_state.Status != ParserState.Ready) { return false; } var declaration = ((ICodeExplorerDeclarationViewModel)parameter).Declaration; return _state.AllUserDeclarations .Any(c => c.DeclarationType.HasFlag(DeclarationType.Module) && c.Annotations.All(a => a.AnnotationType != AnnotationType.NoIndent) && c.Project == declar
- debug minor 112d agoDetect and Fix Switching over an Enum Without Handling all MembersVSDiagnostic's latest refactoring and code fix detects when a `switch` does not contain `case` statements for each of the `enum` members and adds any missing members. So, for example, with the following `enum` and `switch`, VSDiagnostics will detect that some members are missing and add them as shown in the second `switch`: ``` enum MyEnum { Fizz, Buzz, FizzBuzz } ``` ``` var e = MyEnum.Fizz; switch (e) { case MyEnum.Buzz: break; default: break; } ``` ``` var e = MyEnum.Fizz; switch (e) { case MyEnum.FizzBuzz: throw new System.NotImplementedException(); case MyEnum.Fizz: throw new System.NotImplementedException(); case MyEnum.Buzz: break; default: break; } ``` The full test suite can be found on GitHub here: Tests for SwitchDoesNotHandleAllEnumOptions. All comments are welcome, but I am especially interested in utilizing the Roslyn framework better if I am misusing it or not using any helpful features. ``` [DiagnosticAnalyzer(LanguageNames.CSharp)] internal class SwitchDoesNotHandleAllEnumOptionsAnalyzer : DiagnosticAnalyzer { private const DiagnosticSeverity Severity = DiagnosticSeverity.Warning; private static readonly string Category = VSDiagnosticsResources.GeneralCategory; private static readonly string Message = VSDiagnosticsResources.SwitchDoesNotHandleAllEnumOptionsAnalyzerMessage; private static readonly string Title = VSDiagnosticsResources.SwitchDoesNotHandleAllEnumOptionsAnalyzerTitle; internal static DiagnosticDescriptor Rule => new DiagnosticDescriptor(DiagnosticId.SwitchDoesNotHandleAllEnumOptions, Title, Message, Category, Severity, true); public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(Rule); public override void Initialize(AnalysisContext context) { context.RegisterSyntaxNodeAction(AnalyzeSymbol, SyntaxKind.SwitchStatement); } private void AnalyzeSymbol(SyntaxNodeAnalysi