Contribute to Open Source. Search issue labels to find the right project for you!

Effect.stackSafetyOnRepeatedAttempts is too strong

typelevel/cats-effect

Hi folks,

We’ve got the following law in EffectLaws:

  lazy val stackSafetyOnRepeatedAttempts = {
    val result = (0 until 10000).foldLeft(F.delay(())) { (acc, _) =>
      F.attempt(acc).map(_ => ())
    }

    F.runAsync(result)(_ => IO.unit).unsafeRunSync() <-> (())
  }

Trying to run this law for Monix’s Task revealed that the implementation freezes, because the process is left without memory. This is due to how its “attempt” was implemented.

I then redesigned the run-loop of both Monix’s Task and Coeval to be optimal for repeated and eagerly specified attempts like this. The code is specified in this PR: https://github.com/monix/monix/pull/353

Anyway, this law is too strong and I don’t think eager evaluation is needed, because at this moment:

  1. cats.Eval fails with a StackOverflowError … I might port my fix for Monix’s Coeval type, but I’m not sure if it’s actually needed
  2. cats.effect.IO, even if it works, is actually building an in memory data-structure like … Right(Right(Right(Right(.... 10,000 levels ...)))); note that after optimising the encoding of these attempts, the Monix Task no longer does this

So even though this test was useful in seeing a potential problem for Monix’s Task, which I then fixed, I don’t feel that it is a problem that users will have. Note that this wouldn’t happen in a flatMap-powered loop, it’s only problematic because that foldLeft is initialising a huge data-structure.

Updated 30/04/2017 15:24 4 Comments

A book keeper

foundersandcoders/london-money

I would quite like to handover book keeping at some point. I estimate it is about a half-day per week. I believe decent bookkeepers generally cost around £20 or more per hour in London, so I guess we would need to set aside £300/month for it, although it could largely be done remotely, so we might not need to restrict ourselves to the local employment market.

Updated 30/04/2017 14:40 1 Comments

Support for has_many-through with a join table that "has many targets"

rom-rb/rom-sql
require 'rom'
require 'sqlite3'

rom = ROM.container(:sql, 'sqlite::memory') do |conf|
  conf.default.create_table(:bookings) do
    primary_key :booking_id
  end

  conf.default.create_table(:tickets) do
    primary_key :ticket_id
    column :booking_id, Integer
  end

  conf.default.create_table(:passes) do
    primary_key :pass_id
    column :ticket_id, Integer
  end

  conf.relation(:bookings) do
    schema(infer: true) do
      associations do
        has_many :tickets
        has_many :passes, through: :tickets
      end
    end

    def with_passes
      join(passes)
    end
  end

  conf.relation(:tickets) do
    schema(infer: true) do
      associations do
        belongs_to :booking
        has_many :passes
      end
    end
  end

  conf.relation(:passes) do
    schema(infer: true) do
      associations do
        belongs_to :tickets
      end
    end
  end
end

joined = rom.relation(:bookings).join(rom.relation(:passes))

Expected SQL:

SELECT `bookings`.`booking_id`
FROM `bookings`
INNER JOIN `tickets` ON (`bookings`.`booking_id` = `tickets`.`booking_id`)
INNER JOIN `passes` ON (`tickets`.`ticket_id` = `passes`.`pass_id`)
ORDER BY `bookings`.`booking_id`

Actual SQL:

SELECT `bookings`.`booking_id`
FROM `bookings`
INNER JOIN `tickets` ON (`bookings`.`booking_id` = `tickets`.`booking_id`)
INNER JOIN `passes` ON (`bookings`.`booking_id` = `tickets`.`booking_id`)
ORDER BY `bookings`.`booking_id`
Updated 30/04/2017 12:32 3 Comments

Problem: PumpkinScript interpreter is inefficient

PumpkinDB/PumpkinDB

Parsing and analyzing PumpkinScript in runtime comes at a cost and can’t be nicely optimized by the compiler.

Proposed solution: develop a CPS (Continuation Passing Style) interpreter. The scope of this solution would be rather big, so we can track thoughts/progress/discussions here.

I’ve started doing some experimental work in a private branch.

HT @5HT

Updated 30/04/2017 09:34

Would an <organisationalConcept> annotation be useful?

edamontology/edamontology

We used this in EFO to indicate concepts which were mostly for organisational purposes (structuring the tree) and were not really intended for annotation. There are lots of examples of these in EDAM (including all terms at the topic level).

Should we do it for EDAM? I imagine the value could be in two parts: 1. to see what concepts we don’t think are very useful for annotation (and so, do we really need them?) 2. having bio.tools use the annotation, e.g. as a hint for the end-user when picking terms

Thoughts welcome …

Updated 30/04/2017 08:26 1 Comments

Infos about updates on Auth, Identity, Cookies with AspnetCore 2.0

OrchardCMS/Orchard2

@jersiovic @PinpointTownes just for infos.

Working on the razor-page branch we use an aspnetcore 2.0 preview version. When trying to use the last packages by using 2.0.0-preview*, i saw some updates around Identity, Cookies ..., new services extensions … I could do some updates but not all, just to be able to build and to do my tests.

Maybe you already know this, otherwise i think there are not so much updates to do. Not urgent at all for me, but maybe better that you know this, then you will have more time to update the code.

For infos it’s when i tried to use the nightly built 2.0.0-preview* versions on all Microsoft.AspNetCore... and Microsoft.Extensions... packages, and from this feed.

https://dotnet.myget.org/F/aspnetcore-ci-dev/api/v3/index.json

Best.

Updated 30/04/2017 01:15

Open radio on base action point instead of sub-action

IDI-Systems/acre2

When merged this pull request will: - Title - Close #281 - Fix rack radio actions (all the actions that you can do on personal radios didn’t show up, such as spatial… etc.)

Opening radio on base action should be done for racks as well, there is currently no way apart from keybind (which is broken from where this was branched off). I will leave that to @TheMagnetar as he knows the code.

I think there is no need for an “Open” text either, should be pretty self-explanatory that the radio icon opens the radio.

Updated 30/04/2017 07:15

Realistic data for RealWorld?

gothinkster/realworld

I wonder if it’s possible/feasible/helpful to fill the production db with more realistic data from some open data sets that might be floating around. It would look better in FE demos than “aaaaa”, “sample title” etc… BE repos could also use it for testing their dbs. Just a thought.

Updated 30/04/2017 16:08 3 Comments

Proposal - reintroduce static scoper factories

uber/AutoDispose

These don’t autocomplete nicely, but they’re sort of nicer to read in code. Want to put this up for discussion to see if there’s interest in having them as an option (albeit @Experimental).

Now you’d do

myObservable
    .to(AutoDipose.<Stuff>observableScoper(this)
    .subscribe()
Updated 29/04/2017 20:56

Youtube Video Ideas

thestonefox/VRTK

Please leave comments on anything you’d like to see covered in a Youtube video as I’m going to be doing 1 a week in May as we’ve reached that patreon goal.

Don’t add the same topic twice, just thumbs up on the message with the suggestion and we’ll consider that a voting system from people!

Updated 29/04/2017 18:30

Is Processing suitable for this project?

evolvio/evolv.io

Processing is a decent introduction into making something, but it lacks things like buttons, efficient rendering and collision detection and response etc. and may not be suitable for this project. Are there any other technologies we could use that are better suited? Or is Processing the best thing to use? Thoughts?

Updated 30/04/2017 10:45 6 Comments

Feature Request : Support JSX

dojo/widget-core

@sebilasse commented on Fri Apr 28 2017

Wondered how my “html preferring” users could write dojo2 widgets in a declarative way and just read https://medium.com/maquette-news/maquette-2-2-now-supports-jsx-7da7b0a1dc98 This is so nice. I could think of a great benefit for dojo users.


@dylans commented on Fri Apr 28 2017

We have support for this in a branch on one of our contributor’s repos. While we think jsx is a step in the wrong direction compared to hyperscript with regards to functional reactive programming, and we’re trying to avoid the temptation of supporting too many different ways of doing things (which can lead to more complexity), we will reconsider adding this as option before the release of Dojo 2.


@dylans commented on Sat Apr 29 2017

I’m going to move this issue to widget-core since that is where it would be supported

Updated 29/04/2017 12:35

Guidelines for tests as a Spec?

gothinkster/realworld

I think that we should push for Tests in all implementations. However a question arises, how and what do we exactly test? I don’t know if there are tools for writing framework/language agnostic tests but something like: Profile assert.equal(ProfileName, 'Alon Bukai', 'Author name is correct');

Updated 29/04/2017 20:52 9 Comments

Make styled-jsx extensible

zeit/styled-jsx

I thought of a way to make styled-jsx a bit more flexible and let users manipulate the CSS both at compile and run time (if they want). This for example would make it possible to use SASS with styled-jsx or I could stop supporting styled-jsx-postcss.

The babel plugin could accept an option transformCss that is a module name. Such a module exports an object with two functions for runtime and compile time. Both signatures would be (css: string) => string (by default an identity function).

// my-styled-jsx-transform/index.js
export default {
  compile: (css) => sass.renderSync({ data: css }),
  runtime: (css) => css
}

and in .babelrc:

{
   "plugins": [
      ["styled-jsx/babel", { "transformCss": "my-styled-jsx-transform" }]
   ]
}

Which we will use as follow:

const {compile: _userCompile} = require(state.opts.transformCss)
// set compile to identity function if it is `undefined`

// TBD

const transformedCss = stylis(
   styleJsxId,
   _userCompile(css)
)

// or

const transformedCss = _userCompile(
  stylis(
     styleJsxId,
     css
  )
)

I am not sure about the runtime one (which for now could be postponed) but probably we would need to unshift an import like we do with _JSXStyle. The result would be:

import {runtime as _styledJsxTransformCss} from 'my-styled-jsx-transform'
// ...
<_JSXStyle id={1235435} css={_styledJsxTransformCss(`div { color: red }`)} />

cc @rauchg @nkzawa

Updated 29/04/2017 10:56

Support the use of var in more cases

dotnet/csharplang

@eamodio commented on Mon Apr 20 2015

Currently var can only be used in cases where the declaration and assignment are linked. It would be great (imo) if var could be used even if those statements weren’t linked but was still verifiable by the compiler (not looking for dynamic here or anything like that).

This would be great for cases like the following silly example:

Before:

IQueryable<PersonViewModel> query;
if (SimpleQuery) 
{
    query = from p in Context.Query<Person> 
                 select new PersonViewModel { Person = p };
}
else
{
    query = from p in Context.Query<Person>
                 select new PersonViewModel { Person = p, Friends = p.Friends };
}

After:

var query;
if (SimpleQuery) 
{
    query = from p in Context.Query<Person> 
                 select new PersonViewModel { Person = p };
}
else
{
    query = from p in Context.Query<Person>
                 select new PersonViewModel { Person = p, Friends = p.Friends };
}

It would be even more awesome if the compiler could infer even more - maybe using some structural typing when generating the anonymous, like:

var query;
if (SimpleQuery) 
{
    query = from p in Context.Query<Person> 
                 select new { Person = p };
}
else
{
    query = from p in Context.Query<Person>
                 select new { Person = p, Friends = p.Friends };
}

@aluanhaddad commented on Wed Apr 22 2015

The example you provide can be easily simplified with the use of the ?: operator.

var query = from p in Context.Query<Person> 
            select SimpleQuery ? 
                new PersonViewModel { Person = p } :
                new PersonViewModel { Person = p, Friends = p.Friends };

That said there are cases where it could be useful, such as in try - catch - finally blocks, but it would have some unpleasant consequences. For instance, the type of the variable cannot be referred to until it has been assigned. Also, the type becomes path dependent so the compiler would need to do flow analysis to make sure that all possible assignments resolve to the same type.


@eamodio commented on Wed Apr 22 2015

Yeah - the example was certainly the most simple version and could be replaced with ?:, but you can imagine much more complex versions, try/catch as you mentioned, usings, multiple ifs, switch statements, etc.

Why couldn’t the type of the variable be referred to? The variable isn’t dynamic - it would still be statically known through some compiler magic ;) – hopefully only needing limited flow analysis over what is currently done for var. And any case the compiler didn’t want to support (because of complexity or whatnot) it could just issue an error that var couldn’t be used in that case.

While I think the simple var case is nice, my guess the bang for the buck wouldn’t necessarily pay off (but wanted to raise it as it would be nice and who knows might be easy). Though I think the really valuable feature would be “structural” typing with anonymous objects. That imo would be a huge win and isn’t just syntactical sugar.


@aluanhaddad commented on Sat Apr 25 2015

@eamodio

To your first point: Yes, there are indeed more cases than just try - catch - finally, an expression form of pattern matching would solve most of these issues (see below).

To your second point: var does not need to use flow analysis as it currently stands. It simply infers the type of the variable as the type of whatever expression is on the right hand of the =. I agree it has nothing to do with dynamic typing. I was suggesting the flow analysis would be complex, especially for tools like intellisense.

To your third point: I think some form of structural typing would be great. The current proposals for tuples, which are expected to have nameable components, might give just this functionality. Also, the proposal for pattern matching, which currently includes property pattern matching, would also benefit in this area.


@GeirGrusom commented on Mon Apr 27 2015

You can’t use var with unsafe code either.

fixed (var* ptr = "abc")
{
  ptr[0] = 'A';
}

@GSPP commented on Sun Oct 25 2015

Also consider var on fields.

Updated 29/04/2017 11:51 2 Comments

Catch multiple exceptions instead of when keyword

dotnet/csharplang

@deepumi commented on Thu Jun 09 2016

Handle multiple exceptions in C# we need to use when keyword, So In C# 7.0 can we please simplify this like below.

Expected Behavior:

try
{
}
catch(FormatException || OverflowException ex)
{
}

Actual Behavior:

catch(Exception ex) when (ex is FormatException || ex is OverflowException ex)
{
}

@HaloFour commented on Thu Jun 09 2016

I think that this would be useful and help to avoid duplicating code or unnecessary casts.

To expand on this it would be nice to allow for the common members between the unioned types to be referenced, e.g.:

class Exception1 : Exception {
    string Foo { get; }
}

class Exception2 : Exception {
    string Foo { get; }
}

// and then

try { ...
}
catch (Exception1 || Exception2 exception) {
    var foo = exception.Foo; 
}

@realbart commented on Thu Jun 09 2016

try
{
  catch(FormatException || OverflowException ex)
}

What would be the type of ex? I can imagine that FormatException needs to be able to castable to OverflowException, or the other way around. I’d exprect the behavior to be similar to:

var ex = booleanCondtion ? new FormatException() : new OverflowException();   

(this yields a compiler error) If ex just returns a general Exception, I fear many the advantages of throwing and catching typed exceptions are gone.

Edit Halo4 proposes a form of duck typing: the exception is either returned as dynamic or as a compiler generated combined type. I’m not sure I like the additional complexity this generates…


@eyalsk commented on Thu Jun 09 2016

@realbart Because C# lacks unions then maybe the type can always be the base class like this:

abstract class MyException
{
    public abstract string Foo { get; }
}

class Exception1 : MyException
{
    public override string Foo { get; }
}

class Exception2 : MyException
{
    public override string Foo { get; }
}

So in the case of @HaloFour the type would be MyException but in most cases it would be Exception.

Same idea just a little different, using inheritance.


@HaloFour commented on Thu Jun 09 2016

Oops, I swore that Java did allow referencing the common members, but that’s not the case. It treats the exception as the common ancestor of the unioned exception types, and you can access any of those members.

I think that it would be possible to allow referencing the common members, but it would require a bit of compiler chicanery. The compiler could duplicate the generated IL, or it could upcast to one of several potential locals:

try { ... }
catch (Exception1 || Exception2 exception) {
    Type type = exception.GetType();
    var foo = exception.Foo;
}

// transpiled into:

try { ... }
catch (Exception exception when (exception is Exception1 || exception is Exception2)) {
    Exception1 $temp1 = exception as Exception1;
    Exception2 $temp2 = exception as Exception2;

    Type type = exception.GetType();
    string foo = ($temp1 != null) ? $temp1.Foo : $temp2.Foo;
}

I think that it would be neat, but I wouldn’t hold up this proposal for it.


@dotnetchris commented on Thu Jun 09 2016

Just define ex as dynamic in catch body. We already suffered the huge penalty of the throw, what does it matter for several more cycles for all the DLR hoops.

Besides, the majority of people that would use this just want to catch a couple of similar-ish exceptions. I doubt anyone will really care whether ex in the original example is anything other than Exception.

So i’d even be fine if ex was just Exception. But i’d prefer dynamic over the base type.

I’m very opposed to some magic constructed/combined type. However typing this, theoretically ex could be AggregateException and from there you could care about the actual specifics.. or not.


@eyalsk commented on Thu Jun 09 2016

@dotnetchris dynamic isn’t really great because people would get really confused about the fact that they don’t get intellisense when they explicitly specified the types so it would be implicitly dynamic, I don’t think that this is such a great idea.

I don’t know if AggregateException is actually suitable here, because in this scenario only one exception is thrown at a time.

Using the base type makes more sense but it also adds more complexity so to do this right maybe C# needs union types first before they add this feature (or similar features that requires it) then it wouldn’t matter because the type would be a union of multiple types.


@jerhon commented on Thu Jun 09 2016

Why not loosen the restrictions and allow to allow single lines to fall through instead of the {} blocks? It would be a similar idea to a case statement. It has precedence in other blocks in the language, in using statements you can do something similar. For example, you could then do something like this to get the base exception using the ?? operator without having to complicate the meaning of the catch.

try 
{
// some code here...
}
catch (IOException io)
catch (Exception ex)
{
    var finalException = (io ?? ex);
}
finaly
{
// some code here...
}

@eyalsk commented on Fri Jun 10 2016

@jerhon how is it different than this?

try
{
    ThrowingMethod();
}
catch (Exception ex)
{
    var finalException = (ex as IOException) ?? (ex as FormatException) ?? ex;
}

@realbart commented on Fri Jun 10 2016

I find myself constantly checking for null.

try {}
catch (Exception1 ex1 || Exception2 ex2) 
{
    ex1?.Foo();
    ex2?.Foo();
    log(ex1??ex2).ToString()
}

try {}
catch (Exception1 ex1)
catch (Exception2 ex2) 
{
    ex1?.Foo();
    ex2?.Foo();
    log((ex1??ex2).ToString())
}

Perhaps it is easier to let ex simply be of the Exception type. You could find the nearest base class, but that would cut off the possibility to replace a base class with an interface. (If not, what interface would you pick?)

class Exception1 : IExceptionA, IExceptionB {...}
class Exception2 : IExceptionA, IExceptionB {...}

try {}
catch (Exception1 || Exception2 ex) // ex is of type Exception.
{
    ((IExceptionA)ex).Foo():
    log(ex.Message);
} 

However, I am not sure if this justifies additional syntax. This is nog that much verbose, and Explicitly specifying the cought exception type does have its advantages.

try {}
catch (Exception ex) 
when (ex is Exception1 || ex is Exception2)
{
    ((IExceptionA)ex).Foo():
    log(ex.Message);
}

@eyalsk commented on Fri Jun 10 2016

@realbart Currently, no matter what the best type/option here is to fall to the base type which is Exception, as you said it yourself but in the future if C# will get union types then this experience is likely to be much better, I think that if we’re going to solve problems that involves multiple types that are treated as a single heterogeneous type then we need to solve this problem first.


@jerhon commented on Fri Jun 10 2016

@eyalsk It is not different than what you pointed out. Perhaps a better example would be,

try
{
}
catch (FormatException fe)
catch (OverflowException oe)
{
       var exception = fe ?? oe as Exception;
}

The advantage to this over the other approach is we could still fit in the when clause and have it apply to the specific exceptions types in those when clauses.

@realbart I agree my suggestion does lead to a lot of null checking which isn’t good.


@HaloFour commented on Fri Jun 10 2016

Fall-through wouldn’t make sense. None of the identifiers would be definitely assigned and assigning null to them would be contrary to how C# normally behaves.

If I were to vote on a syntax/behavior now I would go for the original proposal, which is basically what Java supports:

try {
    doSomething();
}
catch (Exception1 | Exception2 exception) {
    // exception is of the common ancestor here
    exception.printStackTrace(System.err);
}

Personally I think that the whole concept should be put off until union types and/or pattern matching further progresses. Union types would make the above nicer by allowing access to common members, which couldn’t be done after the fact as it would be a breaking change due to member shadowing. Pattern matching with an OR pattern could open up the possibilities further, perhaps allowing deconstruction directly in the catch clause.


@realbart commented on Fri Jun 10 2016

class BaseException : Exception {...}
class Exception1 : BaseException, IExceptionA, IExceptionB {...}
class Exception1 : BaseException, IExceptionA, IExceptionB {...}

try {}
catch (Exception1 || Exception2 ex) 
{
    // I think ex should be of the Exception type
    // NOT of BaseException, IExceptionA or IExceptionB.
    // (Otherwise: why not just catch BaseException
    log(ex.Message);
}

@HaloFour commented on Fri Jun 10 2016

@realbart

You wouldn’t just catch BaseException because you wouldn’t want Exception3 or any other exception class deriving from BaseException. You could, of course, use catch guards to prevent catching those types, e.g. catch (BaseException exception when exception is Exception1 || exception is Exception2), but that is the very syntax that this proposal is seeking to make less verbose.

Updated 30/04/2017 03:32 2 Comments

[Suggestion] Remove/relax CS1738 "Named argument specifications must appear after all fixed arguments have been specified"

dotnet/csharplang

@dsaf commented on Thu Jun 02 2016

I like using named arguments for code readability when passing literals. However the subj limitation forces me to either not use them or specify them for every subsequent argument:

var name = "John";
var age = 30;

DoSomething(isEmployed:true, name, age); //CS1738

@bondsbw commented on Mon Jun 06 2016

I like this, but only if argument order aligns with the parameter list until at least the last unnamed argument.

Example:

public void DoSomething(bool isEmployed, string personName, int personAge) { ... }

DoSomething(true, personName:name, age); // would be legal
DoSomething(name, isEmployed:true, age); // remains illegal
DoSomething(name, age, isEmployed:true); // remains illegal
DoSomething(true, personAge:age, personName:name); // already legal

@dsaf commented on Tue Jun 07 2016

@bondsbw of course.

Updated 29/04/2017 04:42 1 Comments

[Proposal] Operator overloading on Interfaces

dotnet/csharplang

@stefc commented on Thu Oct 01 2015

I really want to see that I can use operator overloading also on Interfaces.

For example I’ve an interface IVector<T> that have for example the immutable Add method :

<code>IVector<T> Add(IVector<T> operand);</code>

instead of <code>IVector<double> x = a.Add(b); </code>

I want to write <code>IVector<double> x = a + b; </code>

I don’t see any reason why operator overloading is restricted to work only on normal classes.


@AlgorithmsAreCool commented on Thu Oct 01 2015

How would we define this operator? Typically they are in static methods in a class. Would you propose to allow static methods on interface definitions?


@stefc commented on Thu Oct 01 2015

I think operator overloading can be defined the same as extension methods, somewhere in a static class besides the interface declaration.


@AlgorithmsAreCool commented on Thu Oct 01 2015

Would this change also allow operator definitions for all types from extension methods?


@AlgorithmsAreCool commented on Thu Oct 01 2015

See also related discussion

Static interface members https://roslyn.codeplex.com/discussions/541436

Possibility to provide operators in interface https://roslyn.codeplex.com/discussions/570704

Static Interfaces Proposal

2204


@daveaglick commented on Thu Oct 01 2015

FYI, there’s also related discussion (particularly of static extensions and static interfaces) at #996 and #2204. #112 also looks related, though it’s about extension properties and not operators.


@stefc commented on Thu Oct 01 2015

I don’t see the operator overloading in the context of a static method inside the interface but that the operator overloading can resides somewhere not neccessary in the class/interface itself. For the sideeffect with an existing operator overloading exsist on the class the compiler should be inform with a warning on that and the developer should be aware of this amigous usage. In my case I use either the interface operators or the class operator, if would define both it would be bad design I think. I see the interface as abstraction of the internals of a class.


@orthoxerox commented on Thu Oct 01 2015

@stefc Interfaces as they exist are very, very OOP-ish in their design, defining only virtual methods. Operators, on the other hand, were designed to be non-virtual, probably because C# is a single dispatch language, and it would be confusing to dispatch only on the runtime type of one of the operands.

I’d rather see operators implemented in templates/traits/“enhanced named generic constraints” than try and shoehorn them into interfaces.


@ashmind commented on Thu Oct 01 2015

I think this should be done through extension operators – so it should be covered by #5165 / #4945.


@aluanhaddad commented on Mon Oct 05 2015

@ashmind agreed. #5165 is definitely the better proposal.

Updated 29/04/2017 15:44 1 Comments

Extension operators

dotnet/csharplang

@dtsiniavskyi commented on Wed Sep 02 2015

Feature request, Language C#

I would love to see more extension like stuff in C#. In this case - extension operators. It would be great to have ability to implement operators outside theirs' class or in other projects. Something like:

public static class Extensions
{
    public static explicit operator ViewModel(Model b)
    {
        return new ViewModel { Foo = b.Foo.ToString() };
    }
}

so var viewModel = (ViewModel)model; code would be compilable like explicit operator was implemented inside ViewModel class.


@orthoxerox commented on Wed Sep 02 2015

+1 to that. string doesn’t implement IReadOnlyList<char>, but an extension implicit cast would solve this issue for my purposes.


@dsaf commented on Wed Sep 02 2015

@orthoxerox I would raise an issue in https://github.com/dotnet/corefx/issues as well.


@orthoxerox commented on Wed Sep 02 2015

@dsaf, it’s already there in coreclr, since System.String is in mscorlib: https://github.com/dotnet/coreclr/issues/542


@aluanhaddad commented on Fri Sep 18 2015

I very much like the idea of being able to write extension operators. This would be particularly useful for writing DSLs.

I think you should expand this proposal to include additional scenarios that demonstrate it’s usefulness as the type casting example is not particularly strong. In particular, a generic extension operator.

I have one gripe with your proposed syntax. Specifically, I think that the this keyboard should be included and required for the sake of both consistency with existing extension forms and because it makes it clear that a type is being extended.


@rftobler commented on Sat Sep 19 2015

@aluanhaddad A few day ago I posted an example of using an extension operator for specializing generics that uses the this keyword: #5165. I think this example shows more of the power of operators as extension methods.


@alrz commented on Fri Apr 15 2016

This would allow to use types themselves as patterns which cause a conversion, e.g.


static class Extensions {
  public static explicit operator int?(string value) {
    return int.TryParse(value, out var result) ? result : null;
  }
}

// assuming a non-static `bool operator is(string, out string[])` for `Regex`
Regex regex = new Regex("...");
if(str is regex({int value})) {
  // ...
}

// translates to
if(regex.op_Match(str, out string[] captures)) {
  if(captures.Length == 1) {
    var temp = Extensions.op_Explicit(captures[0]);
    if (temp.HasValue) {
      var value = temp.GetValueOrDefault();
      // ...
    }
  }
}

Related: #10598, #5811


@gafter commented on Fri Apr 15 2016

@alrz

This would allow to use types themselves as patterns which cause a conversion, e.g.

No, it would not. Pattern-matching does not apply user-defined conversions. If it did, it would use the implicit ones only. Also, there is no “array pattern”.


@alrz commented on Fri Apr 15 2016

@gafter I assumed the “array pattern” part. Anyway, so if we define it as implicit it does apply the conversion right? I’m asking because #10429 states that this would work only for constants.


@gafter commented on Fri Apr 15 2016

@alrz The only implicit user-defined conversion that would apply in any pattern-matching-like context is the conversion from the switch-expression of a switch-statement to a type that was switchable in C# 6: an enum, integral type, string, etc. We do not apply user-defined conversions in any other pattern-matching context.


@alrz commented on Fri Apr 15 2016

@gafter Is there a specific reason for this? Wouldn’t it be more consistent if “it was allowed for all the types that is switchable in C#?”. This statement is still true for C# 6.0 – it applies the conversion to all the possible types for switch. Now that those types are relaxed to almost all types, why still stick to those restricted set of types (or none at all, in other contexts) when it comes to implicit conversion?


@gafter commented on Fri Apr 15 2016

@alrz Those are the types that can have constant expressions (except float, double, and decimal).


@alrz commented on Sat Apr 16 2016

@gafter Ok, if C# had support for extension is operators (I hope) that wouldn’t be much of an issue,

static class StringExtensions {
  public static bool operator is(this string str, out int value) =>
    int.TryParse(str, out value);
}

if(str is regex({ string(int value) })) 
// and if we could omit known types in positional patterns
if(str is regex({ (int value) }))

if(regex.op_Match(str, out string[] captures)) {
  if(captures.Length == 1) {
    if(StringExtensions.op_Match(captures[0], out int value)) {
      // ...
    }
  }
}

That would be just perfect.


@gafter commented on Sat Apr 16 2016

Yes, obviously pattern-matching on something of type string should parse it as an int. </sarcasm>


@alrz commented on Sat Apr 16 2016

@gafter I am sure you saw my point though. I’ve defined an is operator for the type string that has an out parameter of type int so that you could bind it in a pattern to match against a string.

Basically T(..) pattern is only valid if the type T has an applicable is operator overload, right? So if we define something like bool is(string, out int) it would become a fallible positional pattern for the type string that could be bound to a variable of type int (or any other pattern that is compatible with the said type, in this case, int, e.g. a constant pattern) regardless of the implementation. Yes the example above does parse the input, I don’t know what is wrong with that. I’m just saying that an extension operator is would enable us to do these kinds of utterly unreasonable evil dark magic. </sarcasm>


@gafter commented on Sat Apr 16 2016

@alrz I think you’re imagining that pattern-matching does overload resolution on all of the possible operator is methods that it can find, based on the “expected” types of the patterns. It doesn’t do that. If this is the pattern-matching operator for string, then parsing a string as an integer is what pattern-matching on a string (with one subpattern) would mean.


@alrz commented on Sat Apr 16 2016

@gafter So is overloads must have different number of out parameters regardless of their types? That is understandable because something like string(var value) would be ambiguous if it was overloaded. However, that would make some other use cases impossible to implement. What if I want to define two active patterns for string type like bool is(string, out int) for parsing case, and void is(string, out char[]) for extracting the char array? It would be nice if in these cases compiler require the explicit type (i.e. a type pattern) instead of var because the type obviously is not known to be omitted (something akin to “type ascription” to hint the compiler that what is the expected type in this particular case). This would be applied to out var as well; if you have multiple overloads which only differ in types then you cannot use out var and you must explicitly mention the expected type to select the desired overload.


@gafter commented on Sat Apr 16 2016

@alrz

What if I want to define two active patterns for string type like bool is(string, out int) for parsing case, and void is(string, out char[]) for extracting the char array?

You write a class that names each pattern you’re trying to define, and you place the pattern-matching operation there. And then you use that name in the pattern so it is clear to the reader which of them is being used.


@alrz commented on Sun Apr 17 2016

@gafter So that would be something like this:

class Integer {
  public static bool operator is(string str, out int value) => int.TryParse(out value);
  // `Integer` vs `string` ------^
}

if(str is Integer(var value))

I suppose operator is would not be restricted to take the enclosing type as the first parameter, In contrast, conversion operators are restricted (CS0556).

Now, if I want to define it as an extension operator for the type int,

static class IntegerExtensions {
  public static bool operator is(this string str, out int value) => ... ;
}

It would not be clear that which type we are targeting. GetValues method also had this issue:

static class IntegerExtensions {
  public static bool GetValues(this string str, out int value) => ... ;
}

This is still an extension on type string and not int.

I think this needs something like #6136 to be clear about the intended target type.

extension Int32 {
   public static bool operator is(string str, out int value) => ... ;
}

I’m not aware of any plans for supporting extension is operators, though. But I do believe this will be really useful when you want to use positional patterns on types that don’t already provide an operator is like expression trees (#10153 comment).

Updated 28/04/2017 23:04

[Proposal] Extension classes with Interfaces

dotnet/csharplang

@grwGeo commented on Fri Jun 05 2015

I believe that type extensibility (as in extension methods) is a very useful feature that should be viewed as part of a healthy OOP design and not just as compiler deception or syntactic sugar.

Type extensibility can be expanded to the much anticipated extension properties, extension events, indexers etc and even Interface implementation. This last one would be particularly useful should we need to group types owned by others, in interfaces owned by us (or others).

The main advantage of type extension is the ability to intervene high up in an inheritance chain, adding extra functionality to a multitude of types with just one stroke (e.g. imagine adding a custom property to all windows forms controls with just a few lines of code). And with the addition of implementing interfaces this can be a very powerful tool.

I have personally indirectly implemented extension properties and events, so it should be logically consistent to implement these.

A syntax for all these could be similar to partial classes and this could replace current syntax for extension methods as well. So something like this (interface optional of course): (Here is code)

public extension class OtherOwnersNamespace.OtherOwnersClass : ISomeInterface
{
    private int _myExField = 0;
    public int MyExProperty { get { return _myExField; } }

    public event EventHandler<EventArgs> MyExEvent;  //Could add accessors too.

    internal void MyExMethod() { }
    protected virtual void MyExVirtualMethod() { } //Could be overridden in an extension of an OtherOwnersDerivedClass  
    public static void MyExStaticMethod() { }

    public string this[object someObject] { get { return someString; } }


    void ISomeInterface.SomeInterfaceMethod(){}
}

The ‘this’ keyword should give us all properties of the original class plus our extension class. The scope and visibility of the extension class and its members would be the same as if the class was defined normally without the ‘extension’ keyword.

Current syntax could also remain as an alternative to avoid unnecessary lines of code for cases where (for example) lots of different single extension methods for different types are defined and gathered in one static class.


@svick commented on Sat Jun 06 2015

I don’t think extension interfaces can be implemented reasonably well without CLR support.

The only way I can imagine it would be implemented is if casting to that interface returned some wrapper object. But that would mean ReferenceEquals wouldn’t work reliably for such objects. E.g.:

var c = new OtherOwnersClass();                  // c is the original object
ISomeInterface i = c;                            // i is the wrapper object
Console.WriteLine(object.ReferenceEquals(c, i)); // writes "False"

@grwGeo commented on Sun Jun 07 2015

I believe that since class extensibility is logically consistent, it deserves to be part of OOP and therefore have full CLR support (not compiler deception). This is what my proposal is aimed at.


@grwGeo commented on Sun Jun 07 2015

Readers should understand that this is a two part proposal: 1. Simple class extensibility. 2. Interface implementation extensibility. It can be implemented in these two stages and the first stage could be implemented gradually (e.g. an extension class might not support extension events or indexers to start with).


@grwGeo commented on Sun Jun 07 2015

Another useful application of interface extensibility is when the interface might require implementation of an already existing member. E.g. all controls (or base controls) that already have a ‘Caption’ property might be extended to implement an ‘ICaption’ interface (if they don’t implement one). This would allow us to group them into ICaption types and work collectively with their Caption property. This would only require the first line of the proposed syntax and with such one-liners we could “register” a multitude of different base controls (i.e. different hierarchies).


@ufcpp commented on Sun Jun 07 2015

I' m going to implement the same purpose but somewhat different approach by using a Roslyn code fix provider. I call it “MixinGenerator”. (but at this time, this repository contains only test cases: some pairs of an original source and the expected generated result, no implementation.)

The code fix, for instance, will generate a code from

using Mixins.Annotations;

namespace MixinGenerator
{
    [Mixin]
    public struct X
    {
        public string PublicValue => null;

        [Protected]
        public string ProtectedValue => null;

        [Private]
        public string PrivateValue => null;
    }

    public class Sample
    {
        X _x;
    }
}

to

    public class Sample
    {
        X _x;

        public string PublicValue => _x.PublicValue;

        protected string ProtectedValue => _x.ProtectedValue;
    }

If a Mixin struct implements an interface, the code fix will generate a class which implements the same interface.


@paulomorgado commented on Wed Jun 10 2015

Just for the benefit of all,. there really isn’t such a thing as partial classes. There are partial class definitions; meaning, partial definitions of classes.


@grwGeo commented on Wed Jun 10 2015

You are right for ‘partial classes’ but I think that for ‘extended classes’, philosophically speaking, you could argue both ways.

I.e. they are ‘an extended definition of a class’ but they are also an almost (but not fully) independent class of their own (and they would be in cases where they do not refer to any of the original members). Another way of looking at it is that they are ‘portions of classes’ as almost independent data constructions.

So the extended ‘portion’ is attached to the original part.


@grwGeo commented on Wed Jun 10 2015

Extension constructors should also be possible with the restriction that they call an original constructor and of course they do not conflict with the signature of other existing constructors. Something like:

public extension class OtherOwnersNamespace.OtherOwnersClass : ISomeInterface { public OtherOwnersClass(an original set of params, plus a new set of params) : this(an original set of params){ } }


@Przemyslaw-W commented on Wed Jun 10 2015

@grwGeo what advantage has such extension ctor over factory method?


@grwGeo commented on Thu Jun 11 2015

@Przemyslaw-W The whole aim is to treat an extended type just like a normal class, with all the syntax that pertains to a class and all related intellisense. Creating such extension constructors would constrain consumers of the class to initialize instances in a specific way, as long as it is consistent with the initialization of the original class.


@grwGeo commented on Thu Jun 11 2015

I don’t know any F# but looking online today I am under the impression that it has advanced type extensibility features (more than C#). Is this true?


@HaloFour commented on Thu Jun 11 2015

F# type extensions are really just syntax for either amending a partial class defined in the same module, or for defining extension methods. C# has those same features.


@grwGeo commented on Thu Jun 11 2015

So in F# extending fields (properties?) or other members apart from methods in a different assembly (for example) is not possible.

Thanks for the clarification.


@grwGeo commented on Tue Jun 23 2015

It might also be possible for extended controls to have full VS designer support. This would be an alternative to inheriting and as described above preferable in cases where we intervene high up in the hierarchy. This might be the basis for the CLR version of the Dependency Properties pattern in WPF.


@GSPP commented on Wed Jun 24 2015

So you want to add new fields to existing types, right? This is an important capability. Often, you cannot define the necessary fields directly on some type for reasons of modularity.

For example, WinForms controls often need user data attached to them. They expose the object Control.Tag property which can be used to attach it. That’s very specialized, hacky and allows only for a single tag consumer.

For example if your app deals with customers there will be many aspects. The CRM will want different data than some billing application. But ideally all modules would deal with the same customer object instance. For modularity reasons we would not want to add all CRM and billing fields to the customer. Those should be details of the respective modules.

Imagine there were 10 modules operating on customer objects. What a big ball of mud it would be to attach all required data to the customer object. It would need to have an assembly reference to all modules and all modules would need to reference the customer class. That’s cyclic, and a mess.


@grwGeo commented on Thu Jun 25 2015

@GSPP The idea behind extension is not about breaking a class into constituent classes (like partial definitions of classes). The idea behind extension is that the original class is generally unaware of the extensions. These extensions can affect the original class only within their scope of visibility. The original class does not need a reference to the assembly or namespace that extends it, only the other way around.

If your billing module needs to extend the original class, what you would do with what the language provides today is probably define a new class (like CustomerBillingData) and associate an instance of that class with an instance of the Customer class. This class could have its own data, its own logic but it can also interact with the Customer class' data and logic too. The Customer class though would not be aware of the CustomerBillingData class and would not be the cause of any interaction.

Now if you had the extension feature available and IF you believed that conceptually the CustomerBillingData class should have been part of the Customer class then you could achieve the exact same thing by extending the Customer class. This would save you the trouble of associating the instances of Customer-CustomerBillingData plus it should make it conceptually easier to use just one class instead of two (i.e. customer.Order would be more appropriate than customer.CustomerBillingData.Order or customerBillingData.Order). The extension would only be visible from within the extension assembly (same as with CustomerBillingData).

Also if you were to serialize your extended data on a database, the Entity Framework could interpret extension classes as separate tables with a 1-1 relationship with the original class.


@GSPP commented on Thu Jun 25 2015

@grwGeo You could define a CustomerBillingData class but you can’t pass it through code that only expects a Customer. You can pass in the Customer but you can’t get the CustomerBillingData back out. An example would be some kind of session.

With extension fields you could do that.

Updated 29/04/2017 04:58 1 Comments

Yet another idea how commands should look like

advancedtelematic/quickcheck-state-machine-model

While looking at the die hard example I noticed that a lot of the functions had to do a lot of unnecessary pattern matching just to refine the type. So I have an idea.

What if we change the interface (again) to be as follows: ix :: * cmd :: * uses :: cmd ~> [ix] returns :: cmd ~> Response ix

And then we have Untyped :: Sing cmd - > Env (uses @@ cmd) - > Untyped where Env does whatever we would normally go with refs.

I hope this would achieve a couple of things 1. Allow the constraints to be constant, which would allow definitions to not pattern match unnecessary on the command. 2. Not force the user of the library to define IxFunctor and the rest of the type classes we invented. 3. The generator and shrink function we need from the user only operates on cmd which allows us to completely hide the Untyped type from the user.

I’m sure I’m missing something we’re this new scheme is more complicated but since I’m on a mobile I don’t know where that would be.

Extra note, we could split cmd further and have a type function for the arguments that will be used for the command (and the only thing that will shrink). The only reason I have so far for this is that we could write a “generic cheat” function for the property that tests that shrink produces sub sequences. Not a biggie so could still be in the cmd type for now.

Updated 28/04/2017 23:02

"defer" statement

dotnet/csharplang

@gafter commented on Fri Jan 22 2016

Swift recently added the defer statement. Would that make sense for C# and VB? in C# I imagine it would look something like

    {
        SomeType thing = Whatever...;
        defer {
            thing.Free();
        }
        // some code code using thing
    }

The idea is that the code in the defer block would be executed as the last action in the enclosing block. This would be the same as writing

    {
        SomeType thing = Whatever...;
        try
        {
            // some code code using thing
        }
        finally
        {
            thing.Free();
        }
    }

@HaloFour commented on Fri Jan 22 2016

@gafter I’d have to see use cases that aren’t already sufficiently met through try/finally or using. It doesn’t even seem that Apple could provide a worthwhile example of why you’d use it.


@alrz commented on Sat Jan 23 2016

ِDoesn’t RAII (#181) address this?

{
  using Disposable thing = ...;

  // disposed
}

Because that kind of operations for a type without being a IDisposable isn’t idiomatic C#.

However for this to work it should be able to borrow the object, or totally pass the ownership,

void F(Disposable d) { ... } // won't dispose as always
void G(using Disposable d) { ... } // will dispose at the end

{
  using Disposable d = ...;
  F(d); // d is borrowed
  // d is available
  G(d); // pass the ownership (move)
  // d is not available
}

This probably needs a sophisticated ownership system (then we might be able to use let instead).

Related: #160, #161.


@HaloFour commented on Fri Jan 22 2016

@gafter According to NSHipster the defer statement should be avoided for contexts other than ensuring resource cleanup.

I’d say that defer is Swift’s answer to using and my opinion is that C# doesn’t need a rebuttal or to copy a feature that can be as potentially misused/abused as this could be.


@diryboy commented on Fri Jan 22 2016

This reminds me of the defer attribute for the script tag in HTML. It allows the browser to parallel the download of the script while continue parsing html. I don’t see why this is useful in C#.


@jamesqo commented on Sat Jan 23 2016

It’s possible to just simulate this using Disposable.Create from Rx:

using (Disposable.Create(DoSomething))
{
    DoSomethingElse();
} // end of scope, DoSomething is called here

As such I don’t think a defer statement is needed in C#.


@gafter commented on Sun Jan 24 2016

The advantages of the defer statement over the alternatives are - They do not require implementing some interface, such as IDisposable, or creating helper objects that do. - They do not add an indentation level to the code, which would be clumsy when there are more than one. - They do not move the cleanup code to the end, as try-finally does, but rather they keep the cleanup code logically with the declaration and initialization of the thing that is being cleaned up. In this way they make the code easier to understand.


@jamesqo commented on Sun Jan 24 2016

@gafter Hm, I’m not sure. I was skeptical at first, but the arguments you presented are good.

If we’re going to go down that route, we may want to consider adding an option for writing it inline like you can in Go, e.g.

var resource = AcquireResource();

defer resource.Dispose(); // no braces

@paulomorgado commented on Sun Jan 24 2016

Still not sold on that!


@HaloFour commented on Sun Jan 24 2016

@gafter 1. If IDisposable is the pattern for creating resources which should be cleaned up then I don’t see much validity to this argument. Endorsing an additional pattern, or no pattern at all, would only add confusion. 1. Rx provides some fantastic helper methods which can convert any operation into a disposable. Why add language support to something that can be done easily through a library? 2. A corollary to this might be to expand using to support convention-based disposing rather than strictly requiring IDisposable, such as supporting objects that declare an instance Close() method. 2. Neither would #181 or a variation thereof. My personal preferred syntax would be using var disposable = new SomeDisposableObject(); Same mechanism but the resource is attached to the defining scope, no additional indentation required. 3. See point 1, this only matters if you’re not using IDisposable, which you should be using anyway.

If the purpose of defer is to provide resource cleanup I’d rather find ways of improving upon using in a structured way rather than to toss in a completely new language construct with massive abuse potential which appears to have no real use cases aside resource cleanup. To toss some spaghetti against the wall, how about the following:

var resource = new MyNonDisposableResource() using resource.Close();

@alrz commented on Sun Jan 24 2016

@gafter I don’t think that real problem with using statement is additional indentions nor that you have to implement an interface — this is not a bad thing at all, so there is a contract for types that need cleanup. I think the actual problem here is that you might forget to dispose disposable types, defer statement doesn’t help with this at all, it rather encourages you to not implementat IDisposable inetrface and explicitly call methods like Close or Free which in presence of IDisposable seem like code smells.


@HaloFour commented on Sun Jan 24 2016

@alrz Using let as you describe seems like it would be in conflict with #6400 which is proposing that let have a completely different function. Blending the two wouldn’t make much sense. And wasn’t move/ownership semantics one of the tricky issues in considering #161? I’d worry that it would be too easy to lose track of true ownership, particularly if you ever call into an assembly compiled in any other language (or a previous version of C#).


@ufcpp commented on Sun Jan 24 2016

PowerShell has the trap statement, which has similar usage to the defer statement. The trap statement is little confusing and I prefer the try-catch statement.


@alrz commented on Sun Jan 24 2016

@HaloFour If we ever wanted it to be the default behavior but yes, then other languages or even earlier versions of C# might be considered as unsafe. But as I said in my first comment here, RAII (using using) does need a lightweight version of ownership, otherwise if you pass the object to another method then you’re screwed. #161 and #160 are about destructible types and move keyword, but wi th an ownership system it would work for any type and there would be no need for destructible or move keywords.


@HaloFour commented on Sun Jan 24 2016

@alrz Changing the keywords doesn’t change how difficult it may or may not be. And if developers still need to opt-into it then you still haven’t solved any of the problems. At least with destructible types it was a property of the type and the consumer didn’t have to opt-into anything.

RAII doesn’t imply anything about ownership. The convention as it was developed in C++ relies on the lifetime of the object being tied to the stack of the method within which it was created. #181 is a much closer implementation of that than anything involving ownership, reference counting or move semantics.


@alrz commented on Sun Jan 24 2016

@HaloFour This is more related to #160 and #161 and somehow covering #181 but probably out of scope of this proposal, so I just give it up. :smile:


@MgSam commented on Sun Jan 24 2016

If the the use case for defer is resource cleanup, then it would seem to be an anti-pattern to me to not require that the thing implement IDisposable. Implementing IDisposable allows tooling to warn you if you create a disposable as a local variable and then never dispose of it. If you make it accepted for resources to not require IDisposable, you lose this benefit.

I think method scoped using statements would be just as effective while being much more idiomatic.


@gafter commented on Sun Jan 24 2016

I see lots and lots of code like this in Roslyn:

            var oldMethodOrLambda = this.currentMethodOrLambda;
            this.currentMethodOrLambda = node.Symbol;
            ... // process the current lambda
            this.currentMethodOrLambda = oldMethodOrLambda;

I would hate to use IDisposable for this. defer would be perfect, as it keeps the “begin” and related “end” code together.

            var oldMethodOrLambda = this.currentMethodOrLambda;
            this.currentMethodOrLambda = node.Symbol;
            defer this.currentMethodOrLambda = oldMethodOrLambda;
            ... // process the current lambda

@leppie commented on Sun Jan 24 2016

@gafter: That is really dynamic binding. It would be nice to do syntax sugar for what I did in code here http://www.codeproject.com/Articles/153896/Dynamic-Binding-in-C


@GeirGrusom commented on Sun Jan 24 2016

I would like to note that D has had the scope guard statement for some time, but it allows you to do something when scope fails, or succeeds as well.

Anyway wouldn’t this be more useful as a using extension? Allowing a type to determine what happens when the scope fails, succeeds and finishes (which is what using allows) could be useful.

public interface IScopeGuard
{
  void Failed(Exception  ex);
  void Success();
}

public class Transaction : IScopeGuard, IDisposable
{
  private readonly int id;
  public Transaction()
  {
    id = BeginTransaction();
    Console.WriteLine($"Started transaction {id}");
  }
  void Failed(Exception ex)
  {
    FailTransaction(id);
  }
  void Success()
  {
    CommitTransaction(id);
  }
  void Dispose()
  {
    Console.WriteLine($"Transaction {id} completed.");
  }
}

using(new Transaction())
{
   DoTransactionalStuff();
} 

edit: it occurs to me that this is a digression. Sorry about that.


@ghord commented on Mon Jan 25 2016

There is great talk about implementing this feature in C++ by Andrei Alexandrescu. Some string arguemnts in favor of this there.


@alrz commented on Mon Jan 25 2016

@gafter That use case is really similar to what Block function does in Mathematica.

block(this.currentMethodOrLambda = node.Symbol) 
{
}

Then there is no need for temporary variable and explicit defer to assign it back. If anything, I would prefer this (perhaps with another keyword) over defer because it really encourages bad design (for resource cleanup).

As an alternative I’d suggest scoped assignments,

{
  scoped this.currentMethodOrLambda = node.Symbol;
}

But it seems that this is useful only for this specific use case.


@MgSam commented on Mon Jan 25 2016

@gafter But that only works if there is no other logic you want to come after the restoration of this.currentMethodOrLambda. If there is, then you run the risk of the developer adding that into the defer block too, making your method into a confusing mess where the code that runs at the end is written at the top of the method body rather than the bottom. The last thing you want when you’re reading code is to have to remember that there might be extra logic that takes place at the end of the method that was written out somewhere else entirely.


@HaloFour commented on Mon Jan 25 2016

@MgSam Agreed. For the most simple cases that may be suitable, otherwise you end up having to defer multiple operations and be extremely conscious as to the fact that they’ll execute backwards lexically. This task is pretty easily accomplished through try/finally which, while more verbose, is significantly more structured and easier to follow.

var oldMethodOrLambda = this.currentMethodOrLambda;
try
{
    this.currentMethodOrLambda = node.Symbol;
    // ... process the current lambda
}
finally {
    this.currentMethodOrLambda = oldMethodOrLambda;
}

@paulomorgado commented on Mon Jan 25 2016

see lots and lots of code like this in Roslyn:

        var oldMethodOrLambda = this.currentMethodOrLambda;
        this.currentMethodOrLambda = node.Symbol;
        ... // process the current lambda
        this.currentMethodOrLambda = oldMethodOrLambda;

I would hate to use IDisposable for this. defer would be perfect, as it keeps the “begin” and related “end” code together.

        var oldMethodOrLambda = this.currentMethodOrLambda;
        this.currentMethodOrLambda = node.Symbol;
        defer this.currentMethodOrLambda = oldMethodOrLambda;
        ... // process the current lambda

I’m sorry @gafter, but I’m still failing to see the value of this proposal.


@diryboy commented on Mon Jan 25 2016

What is the order of multiple defer blocks, and what if exceptions throw in the middle?


@HaloFour commented on Tue Jan 26 2016

@diryboy If it were to be implemented as it is in Swift, the following C# code:

static void Main() {
    Console.WriteLine("Hello");
    defer {
        Console.WriteLine("Foo");
    }
    defer {
        Console.WriteLine("Bar");
    }
    defer {
        Console.WriteLine("Baz");
    }
    Console.WriteLine("World");
}

would produce the following output:

Hello
World
Baz
Bar
Foo

As far as I can tell it’s illegal to throw from within the defer block.


@alrz commented on Mon Jan 25 2016

It’s like a finally block in the middle of nowhere so why not reusing finally instead of defer. But when I think how messy it can get I tremble.


@diryboy commented on Mon Jan 25 2016

@HaloFour Any method call within defer block could throw. Any code could throw before defer blocks get a chance to execute. The example code is a good example of writing code backwards without any good reason.

To address the org -> current -> org property change, if to introduce language support, IMO it’s better to introduce some feature that could express that one off. For example

stash this.currentMethodOrLambda = node.Symbol;
// compiler generate code to revert this.currentMethodOrLambda to it's original value on exit scope
// should exceptions happen before exit scope, the value is not reverted back

Edit: OK, duplicated with @alrz


@HaloFour commented on Mon Jan 25 2016

@diryboy

Swift is a lot stricter about exceptions than C# and doesn’t permit calling functions that declare that they throw exceptions from within a defer block. As far as I can tell if a function were to fail unexpectedly, such as attempting to forcibly deference a nil, that’s a fatal situation and the entire program stops. If the method throws outside of the defer blocks then those blocks are executed as expected. Not unlike wrapping the entire method body in a bunch of try/finally clauses, exception for being in reverse order. I’m certainly not an expert in Swift, though.

I’m not convinced that a temporary swap is so common as to require its own keyword and semantics. It’s pretty easy to accomplish now with try/finally or one of the helpers from Rx. I’d even argue that such logic depending on changing some shared state to temporarily change how the program behaves is itself a code smell and probably shouldn’t be encouraged.


@diryboy commented on Mon Jan 25 2016

@HaloFour

Thanks for sharing.

Me neither.


@alrz commented on Tue Jan 26 2016

@HaloFour

changing some shared state to temporarily change how the program behaves is itself a code smell

Exactly. They probably chose this pattern to avoid repeating a parameter in every function call and ended up with this.


@HaloFour commented on Tue Jan 26 2016

@paulomorgado Ah yeah, copypasta fail. I’ll update.


@migueldeicaza commented on Thu Jan 28 2016

I love the idea of the defer statement in C#.

It provides an expressive way to state the programmer’s desired intention. While try/finally may accomplish the same work, it pushes the intention far away, and in nested cases becomes inconvenient to navigate.


@GeirGrusom commented on Thu Jan 28 2016

I think defer is a very vague name though.


@lachbaer commented on Thu Mar 24 2016

I wouldn’t recommend ‘mixing’ the execution order of the code with defer for the same reason that return statements should not be present in the middle of a any method or elsewhere where they could easily be overssen.

For the use-case @gafter mentioned I think it is besser to leave the assignment this.currentMethodOrLambda = oldMethodOrLambda; directly before the exit points in the method. This reminds the reader at the exit point that something is reverted to its original state.


@temporaryfile commented on Fri Apr 15 2016

You can mock this up with an IDisposable stack of delegates. Instead of “defer”, push a lambda closure to the stack. Inside Dispose(), run them in reverse order. That’s a lot of overhead for reaching a finally block that’s usually less than a Page Down away. It feels pointlessly clever.

The problem with a struct implementing IDisposable to solve this pattern everywhere is that Dispose() will cause it to be boxed. We need a pattern for the using-statement, not an interface, using method names the compiler knows about, exactly like when I build awaiter/awaitable objects.


@svick commented on Sat Apr 16 2016

@playsomethingsaxman

The problem with a struct implementing IDisposable to solve this pattern everywhere is that Dispose() will cause it to be boxed.

No, it won’t. When you you use using on a struct, the Dispose() method is called using constrained. callvirt, which does not box the value.


@temporaryfile commented on Sat Apr 16 2016

No, it won’t. When you you use using on a struct, the Dispose() method is called using constrained. callvirt, which does not box the value.

Niiice, learn something new every day. Not sure what we really need then.


@gafter commented on Sat Apr 16 2016

@playsomethingsaxman

Not sure what we really need then.

I suggest you rewrite the original post using your suggested mechanism. Don’t modify existing types; if you need to declare a new struct, include it in your solution. Is it easier to read?


@temporaryfile commented on Sun Apr 17 2016

I suggest you rewrite the original post using your suggested mechanism. Don’t modify existing types; if you need to declare a new struct, include it in your solution. Is it easier to read?

I can’t modify existing types but I can create extension methods? Game on. But at some point a .NET-facing library has to do its part and accommodate basic .NET patterns.

To simulate what “defer” really is…

using (var deferrals = new DeferralStack())
{
    SomeType thing = Whatever;
    deferrals.Defer(() => thing.Free());

    SomeType thing2 = Whatever;
    deferrals.Defer(() => thing2.Free());
}

To me that would be a nightmare to step through and debug, especially with GULP locks. Here’s another question: what happens to the remaining deferrals if the first one throws and all of them are guaranteed to run? Do we assemble an AggregateException?


@gafter commented on Sun Apr 17 2016

To me that would be a nightmare to step through and debug

Yes, the alternative is pretty bad. Yet another reason to support the original proposal.


@whoisj commented on Sun Apr 17 2016

The defer statement is fairly novel. It’s basically encouraging developers to perform RAII like operations (d'tors, etc) in immediately following code blocks instead of using scope characters (usually {). However, it also keeps state as to what bits of code get executed based on which defer statements are actually reached at run time. No more of the C clean up of if (foo) free(foo); if (bar) free(bar); or the equivalent of whatever Swift offers.

Given that it is only a compiler trick and should require no run-time support, I think this is a fantastic addition to nearly any language. Kudos to the devs at Swift for inventing it, and to the devs here on Roslyn for considering it.

Only question: what happens if a defer statement “throws”?


@whoisj commented on Mon Apr 18 2016

Another observation/question: does it make more sense for the sequence of defer statements to be stack or queue oriented? For example, with the following snip-it of code what should the expected outcome be?

{
    Console.WriteLine("A");
    defer { Console.WriteLine("One"); }
    Console.WriteLine("B");
    defer { Console.WriteLine("Two"); }
    Console.WriteLine("C");
    defer { Console.WriteLine("Three"); }
}

Should it be:

A
B
C
Three
Two
One

Or

A
B
C
One
Two
Three

As I understand it, with Swift’s implementation the former would be the case, however the later makes more sense to me as that was the order it was declared. Thoughts?

It’s like a finally block in the middle of nowhere so why not reusing finally instead of defer. But when I think how messy it can get I tremble.

I agree, but finally already has meaning and overloading the statement could cause all kinds of real errors to escape the compiler checks.


@HaloFour commented on Mon Apr 18 2016

@whoisj Since the prototypical use case seems to be resource cleanup I think that reverse order makes more sense. The compiler can’t know if cleaning up the first resource might depend on cleaning up subsequent resources. Also, every language I’ve found with this facility seems to invoke in reverse order, including D, Swift, Go, Rust (via defer! macro) and C++ (via RAII, destructors are always called in reverse order).


@svick commented on Mon Apr 18 2016

@whoisj Just like with using and RAII, I think that stack is the only real option. Consider that the non-deferred statements could have dependencies on each other. For example, this code that uses using:

using (var fileStream = File.OpenWrite(@"C:\users\svick\desktop\test.txt"))
using (var gZipStream = new GZipStream(fileStream, CompressionMode.Compress))
using (var writer = new StreamWriter(gZipStream))
{
    writer.WriteLine("Hello World");
}

The natural way to rewrite it with defer would be:

var fileStream = File.OpenWrite(@"C:\users\svick\desktop\test.txt");
defer { fileStream.Close(); }
var gZipStream = new GZipStream(fileStream, CompressionMode.Compress);
defer { gZipStream.Close(); }
var writer = new StreamWriter(gZipStream);
defer { writer.Close(); }
writer.WriteLine("Hello World");

This would only work correctly if defers were executed in reverse order.


@whoisj commented on Mon Apr 18 2016

@svick good point! Explains the decision Swift made.

The using statement is fine, but it does require IDisposable which is less than optimal.

As for RAII, I’d love to see support for it. Sadly, I believe that would require more than compiler ticks to implement correctly and CLR/IL changes are pretty much out of scope.


@aL3891 commented on Mon Apr 18 2016

To me this sounds like a feature that would add alot of complexity and opportunity for misuse for not a lot of benefit. I assume defer would only work inside a perticular method, but resource cleanup is commonly done at a later time, say when the object itself is cleaned up. I do see the charm, but i just don’t think it adds enough to the language to warrant a new keyword.

Also, what is the closure situation? Consider

for(var i = 0; i<10; i++) {
    defer Something(i);
}

Would Foobe called 10 times with 10? or 10,9,8..? i’d imagine the first, unless a local variable is declared, same as if a Func was used?

If defer statements can contain anything, they can also change state i assume, so this would be legal:

var thing = GetThing();
if(Test())
    defer thing.baz = 30
defer thing = GetOtherThing();
defer thing = null;

A bit contrived for sure, but my point is that somewhere half a page up, in some branch something is defered and that might be hard to keep track of. The execution order will jump all over the place (and i guess thats the point) but it will be hard to get an overview, i sort of have to keep stack in my head with all the deferals :)


@alrz commented on Tue Apr 19 2016

We might be able to do this with #6671 and code generators, marking the node we want to defer with a attribute and regenerate the syntax tree,

void Method() {
  var something = new Something();
  [[Defer]] something.Free();
  // blah
}

replace void Method() {
  var something = new Something();
  try { 
    // blah
  } finally {
    something.Free();
  }
}

However, I’m not aware if generator API allows to ReplaceNode or that kind of stuff.


@gafter commented on Tue Apr 19 2016

@aL3891

Also, what is the closure situation? Consider

for(var i = 0; i<10; i++) {
    defer Something(i);
}

Since defer defers until the }, and the } immediately follows, that has the same behavior as

for(var i = 0; i<10; i++) {
    Something(i);
}

Defer would not be an embedded-statement, so you could not use it as the controlled statement of an if. So no, there will be no defers hidden in branches.


@HaloFour commented on Tue Apr 19 2016

@gafter

I think more to the point, what would the behavior of the following be?

void Foo() {
    int i = 1;
    defer Console.WriteLine(i);
    i = 2;
}

@gafter commented on Tue Apr 19 2016

@HaloFour prints 2, just the same as if you wrote

void Foo() {
    int i = 1;
    try
    {
        i = 2;
    }
    finally
    {
        Console.WriteLine(i);
    }
}

(Unless you get an exception between the two assignments)


@aL3891 commented on Wed Apr 20 2016

Oh, it would just defer to the end of the current block? i somehow thought it deferred to the end of the entire method… :) if its just the current block i think the debugging would be much more reasonable.


@lachbaer commented on Tue May 03 2016

When flying over the code above, I think that it might be hard for 3rd party readers to always directly see the defer statement, esp. when the code block is more complex, has complicated algs, etc.

For a better visual experience I think that you should group the blocks where defer belongs to, e.g. using the use keyword:

void Foo() {
    use
    {
        // maybe some more statements
        var fileStream = File.OpenWrite(@"C:\users\svick\desktop\test.txt");
    }
    defer
    {
        fileStream.Close();
    }
}

or shorter:

void Foo() {
    use { 
        var fileStream = File.OpenWrite(@"C:\users\svick\desktop\test.txt"); 
    } defer { fileStream.Close(); }
}

So, the requirement would be that every defer must follow a directly preceding use block.

PS: you could use the more verbose do keyword instead of use, a lookahead behind the do-block would tell if it has a loop or a defer meaning.

PPS: adding the defer statement to the try statement additionally would then also be of use. With try exceptions can also caught by catch blocks, but in contrast to finally those blocks are always excecuted when leaving the function.

void Foo() {
    try { 
        var fileStream = File.OpenWrite(@"C:\users\svick\desktop\test.txt"); 
    }
    catch (IOException e) {
        Debugger.Log(1, "FileErrors", "Cannot open test.txt");
        return;
    }
    defer {   // outer block for defer is the Foo method
        if (fileStream != null) fileStream.Close();
    }
    // try block already ended, but fileStream is still open
    ReadFile(fileStream);
}

(I know that the sample doesn’t make much sense and there are other, better ways, it’s just a coding sample ;-)


@migueldeicaza commented on Thu May 26 2016

Another thought on defer.

The real win here is that it can be used for things that are not IDisposable. And while there was a comment earlier from @HaloFour that he sees no validity in the argument, defer is not limited to resources that must be disposed, nor is every resource or operation that requires some finalization always surface a Dispose().

Defer instead introduces a new construct that can be used not only for releasing resources, but to ensure that certain operations take place before the code completes.

@gafter already provided a common idiom from the Roslyn compiler, but this is not limited to Roslyn, the idiom “var saved = GetState (); ChangeState (newstate); DoOperation (); RestoreState (saved)” is common.

Do not take my word for it, a search here, shows very interesting uses of defer and they are not all bound to releasing resources:

https://github.com/search?l=&o=desc&q=defer+language%3ASwift&ref=advsearch&s=indexed&type=Code&utf8=%E2%9C%93


@HaloFour commented on Thu May 26 2016

@migueldeicaza

Quickly scanning those examples I can easily see that the vast majority of cases are Swift’s reimplementations of using or lock. Surprisingly, much more the latter than the former. Of the remaining cases I mostly see bizarre ways of injecting mutation logic post return, e.g.:

  mutating func unsafePop() -> UTF8.CodeUnit {
    defer { pointer = pointer.advancedBy(1) }
    return pointer.memory
  }

I frankly don’t see how that’s more readable than the equivalent:

  mutating func unsafePop() -> UTF8.CodeUnit {
    let result = pointer.memory
    pointer = pointer.advanceBy(1)
    return result
  }

Sure, one less line of code, which buys you out-of-lexical-order execution of sequential statements.

I don’t doubt that there are some really good novel uses for a statement like defer. I’m not seeing them in those examples. Nor do I think that the rare occasion where it might be useful warrants a language feature that is effectively an alias for try/finally. The idea of having to mentally keep track of implicit scope popping behavior when reading code does not appeal to me. Having to know when to read code backwards does not appeal to me. Encouraging people to write disposable resources that spurn the 15 year old established disposable pattern does not appeal to me.


@bbarry commented on Thu May 26 2016

@migueldeicaza, @HaloFour I suspect by far the most common use case for a defer statement in C# would be lock management structures like ReaderWriterLockSlim changing code like this to:

public class Set<T>
{
  private readonly HashSet<T> set = new HashSet<T>();
  private readonly ReaderWriterLockSlim readerWriterLockSlim = new ReaderWriterLockSlim();

  public bool Add(T value)
  {
    readerWriterLockSlim.EnterReadLock();
    {
      defer { readerWriterLockSlim.ExitReadLock(); }
      if(set.Contains(value))
        return false;
    }

    readerWriterLockSlim.EnterWriteLock();
    defer { readerWriterLockSlim.ExitWriteLock(); }
    return set.Add(value);
  }

  public bool Remove(T value)
  {
    readerWriterLockSlim.EnterWriteLock();
    defer { readerWriterLockSlim.ExitWriteLock(); }
    return set.Remove(value);
  }

  public T[] GetValues()
  {
    readerWriterLockSlim.EnterReadLock();
    defer { readerWriterLockSlim.ExitReadLock(); }
    return set.ToArray();
  }
}

Here, the necessary naked block in the Add method makes me more uneasy about the thought of a defer statement than anything else I’ve seen so far. Other tasks I’d imagine are transaction commits.

Also, how should it play with a switch statement?

void Foo(int state)
{
  int i = 1;
  {
    switch (state)
    {
      case 0: defer {i++;} goto case 1;
      case 1: defer {i *= 2;} break;
      case 2: defer {i = 3;} goto case 1;
      default: defer {i = 5;} break;
    }
  }
  Console.WriteLine(i);
}

Or yield or await?


@alrz commented on Thu May 26 2016

This prints a 0 b 1 because in Swift each case body has its own block.

let state = 0
switch (state) {
    case 0: defer {print("0")}; print("a"); fallthrough
    case 1: defer {print("1")}; print("b");
    case 2: defer {print("2")}; print("c");
    default: defer {print("3")}; print("d");
}

No idea how it should work in C# though.

Updated 28/04/2017 22:51

[Proposal] Syntactic equivalent of object initialization for object properties re-assignment

dotnet/csharplang

@dg2k commented on Tue May 24 2016

Synopsis

Setting properties on object initialization makes the code readable with a single statement.

var customer = new Customer(){OrderID = order.ID, UserID = order.UserID, AddressID = order.AddressID, ... };

If I want to reuse the customer reference by reassigning properties, unless I am missing something, there is no compact form that is similar to initializing a new object. Each property setting requires a statement which means as many code lines.

Proposal

As a proposal, consider a keyword assign in place of new, not for creating an object, rather to assign property values. That is, assign is simply a syntactic equivalent of new initialization, but for assigning property values which otherwise requires more lines.

 customer = assign Customer(){OrderID = order2.ID, UserID = order2.UserID, AddressID = order2.AddressID, ... };

or

customer = assign {OrderID = order2.ID, UserID = order2.UserID, AddressID = order2.AddressID, ... };

Discussion

The above is just a convenience for re-assigning of property values to an existing object. The second version above even drops out the Type Customer as it should be obvious from the reference.

There are numerous usage scenarios where this can be convenient. To ready my reference for next use, for instance, I can assign default property values as:

customer = assign {OrderID = 0, UserID = 0, AddressID = 0, Name = "", IsOrderProssessed = false };

The assignment with object initialization syntactic equivalent makes the code more readable, particularly where a number of properties is large. There are of course caveats – if the reference is not already initialized, the assignment will not work as expected. But then again, assign (or something equivalent) can act as new in this situation, in which case it acts to re-assign if the reference is already initialized, else create a new object. Makes sense?

Apologies in advance if an equivalent of this exists already but haven’t come across yet.


@s-arash commented on Tue May 24 2016

I propose this syntax: With customer .OrderId=0 .UserId=0 End With


@Unknown6656 commented on Wed May 25 2016

Your proposal looks like a C# -equivalent of the VB-keyword with. I am pretty sure, that this proposal has been made about 100 times before and I will reference the according issues when I found them ;)

<hr/>

EDIT: This isssue is/may be a duplicate of: https://github.com/dotnet/roslyn/issues/6553 https://github.com/dotnet/roslyn/issues/7322 https://github.com/dotnet/roslyn/issues/5172#issuecomment-139963589 https://github.com/dotnet/roslyn/issues/5172#issuecomment-140438035 https://github.com/dotnet/roslyn/issues/5676 https://github.com/dotnet/roslyn/issues/5445 (partly mentioned) I can list more similar issues, when I return from University this evening :)


@dg2k commented on Wed May 25 2016

Thank you so much @Unknown6656 for taking the time to dig into similar past proposals. I’ve never assumed no-one thought of such a basic need in C# programming and the last sentence of my proposal confirms my very suspicion for the existence of similar ideas.

But at a different level this confirms an important point – why are proposals widely supported like this one not taken up? Duplication of the same idea are like votes for the same thing. I wish the search system is a bit better, with flagging of similar ideas upon editing (like SO question posting), in which case I could have avoided this duplication.


@Unknown6656 commented on Wed May 25 2016

@dg2k I know exactly, what you mean, I also have the need for the proposal you made ;)

Regarding your point about GitHub’s search system: GitHub is primarily based around source control and team project control, less around issue search etc. (I also absolutely love how SO implemented the posting system)

Regarding your point about why C# does not (yet) have this feature implemented: The developers focus was probably primarily concentrated on performance and other language aspects….

<hr/>

At least, the isssue https://github.com/dotnet/roslyn/issues/5172 is currently marked as 3 - Working, so that is something, I guess….


@dg2k commented on Thu May 26 2016

@Unknown6656 Thanks again for the update and I’m now more in tune with this particular feature request.

I understand GitHub’s particular strength vis-à-vis SO – if there is such thing (or is there?) as the Oscar of online productivity tools (or whatever more suitable phrase you can attach here), GitHub should get it. Of course, in my opinion ;-)

Updated 30/04/2017 15:12 1 Comments

Proposal: Guard statement in C#

dotnet/csharplang

@Eyas commented on Tue Jan 26 2016

Background

Swift has a guard statement that can be very valuable in writing code that is easy to reason about. See Swift Guard Statement - why you should use it.

Problem

If we have a function Foo that takes an integer that must be positive (> 0), we can write that as:

Bar Foo_alt1(int b) {
    if (b > 0) {
        // all of our code is surrounded by checks for the condition.
        // special handling of condition is far away from the statement of what the condition is
        // extra indent, extra nesting, etc.
    } else {
        throw new IllegalArgumentException(nameof(b));
    }
}

Bar Foo_alt2(int b) {
    // 'syntactic sugar' disadvantage is that now we check for the "negative"
    // condition instead of the positive. this might be natural in cases of null checking or
    // other simple checks, but can become burdensome in complex cases of many comparisons
    // and logical operators.
    if (b <= 0) {
        throw new IllegalArgumentException(nameof(b));
    } else {
        // rest of code to handle the normal case is here.
        // 'excessive' nesting and indentation
        return foo;
    }
}

Bar Foo_alt3(int b) {
    // 'syntactic sugar' disadvantage is that now we check for the "negative"
    // condition instead of the positive. this might be natural in cases of null checking or
    // other simple checks, but can become burdensome in complex cases of many comparisons
    // and logical operators.
    if (b <= 0) {
        throw new IllegalArgumentException(nameof(b));
    }

    // rest of code to handle the normal case is here.
    // we choose not to resort to nesting, but in doing so, we lose an important compile-time check:
    // a programmer error might result in the if-block above not returning or throwing, thus
    // causing the control flow to drop off into the "normal" code
    return foo;
}

Proposed Solution: guard statements

Bar Foo(int b) {
    // state that b must be a positive integer
    guard (b > 0) else {
        throw new IllegalArgumentException(nameof(b));
    }
    // compiler verifies that the guard-block throws or returns, thus
    // guaranteeing that code here will satisfy the guard condition.
    // ... do something with b without worrying about edge cases
}

Benefits

The guard statement introduces two benefits over if-based guards: 1. Syntactic sugar of declaring the positive condition we would like to meet after the guard, rather than the negatives 2. Compile-time checking of the fact that the guard clause ends control flow by returning or throwing 3. One less indent :)

Grammar

guard-statement
    : 'guard' ( boolean-expression ) 'else' embedded-statement
    ;

@alrz commented on Fri May 20 2016

Also check out #119 and #6400.


@Eyas commented on Tue Jan 26 2016

@alrz right. unless is what its called in Ruby, Swift is calling it guard. I prefer guard because it relates to the guard refactoring pattern.

While I like contract I think this is quite different from #119: the guard block could result in an exception thrown for an invalid argument, but could also include non-errored handling of edge cases. E.g.:

int fib(int n) {
    guard (n > 1) else return 1;
    return fib(n - 1) + fib(n - 2);
}

The else clause in #6400 is very close to what we want, but: 1. We want to check on boolean-expression rather than pattern. 2. The conditions we check for can span multiple variables and assignments, e.g.:

void Configure(Configuration c) {
    guard (URLExists(c.URL) or FileExists(c.File)) else {
        Console.WriteLine("Supplied configuration does not contain a valid file or URL.");
        return;
    }
    // ...
}

@mburbea commented on Tue Jan 26 2016

And what’s wrong with

if (!(b > 0)){
      throw new InvalidArgumentException(...)
}

It handles your case. I don’t find that unless or guard Adds a lot of value to the language. It adds another way to do the exact same thing, and then developers will have to learn new syntax, and have another form to worry about when reading code.


@Eyas commented on Tue Jan 26 2016

@mburbea This is what I explained in the “Problem” section, the main issue with the if (!(...)) { is that the compiler doesn’t guarantee that the embedded statement after the if-guard terminates. So I can do something like:

if (b == null) {
   // print a complicated error
   // forget to return or throw
}

foo = b.bar(); // <-- control drops here in the b is null case and we get an error

So yes, benefits are: 1. Checking for the positive condition (guard (b > 0) else ...) is “pretty” syntactic sugar 2. Compiler verifies that the else clause will terminate, so that code after the guard clause provably runs only when the guard conditions are true.


@HaloFour commented on Tue Jan 26 2016

@Eyas

6400 does handle that, else must throw or return.

Otherwise I don’t see anything particularly wrong with it but I’m not sure that it’s particularly necessary. I want to dislike it more just because Swift has it, but meh.


@HaloFour commented on Tue Jan 26 2016

I will say that the one reason that I dislike this and #119 is that it doesn’t offer any proposal for metadata attached to the method to declare such constraints. Handling illegal arguments is one thing, preventing them from happening is significantly more.


@Eyas commented on Tue Jan 26 2016

@HaloFour See my examples in the comment above: 1. the guard clause does not constrain parameters or variables passed, but rather provides a guarantee on these variables after the statement. The else clause can simply return (see fib example). This is valuable as-is, and is orthogonal to annotating the “type” of a function or scope. - I dislike #119 because it actually defines valid and invalid parameters yet doesn’t annotate their types appropriately. - Unlike #119, this doesn’t define legal and illegal cases. And so doesn’t interact with type/metadata 2. the guard clause is different than let in that: - the condition is a boolean expression, not a pattern - the condition could be a global thing, or an and of multiple values, or a more complex condition, rather than a condition related to a single variable or assignment. See the Configure example.


@HaloFour commented on Tue Jan 26 2016

@Eyas You’re right. I think after the defer proposal I was looking for a fight. :wink:


@Richiban commented on Mon Feb 08 2016

I still think that the requirements this proposal seeks to address would be supported by pattern matching – I think it would even look fairly similar. Consider this pseudocode:

public int F(int? arg)
{
    match (arg)
    {
        null | x when x < 0 =>
        {
            throw new ArgumentException("arg cannot be null or negative");
        }
        i =>
        {
            // Do something with variable 'i' which is now a regular int
        }
    }
}

You get all the requested features above: - the guard appears first in the method - the body of the guard must return or throw - you get the opportunity to match on the variable given your guards passed - it is possible to match on anything, not just the parameters of your method


@DerpMcDerp commented on Wed May 18 2016

The big problem with guard statements (and pattern matching in general) is that the boolean test isn’t able to be abstractable out e.g.

Bar Foo(int b) {
    guard (b > 0) else {
        throw new IllegalArgumentException(nameof(b));
    }
    body;
}

Forcing you to repeat the guard (b > 0) else throw blah line everywhere. It would be better if C# had an erasable psuedo-type that combines a type and a predicate in a single place once and for all, e.g. if something like this:

[Message("Number isn't positive")]
guard Positive<T>(T value) {
    return value > 0;
}

Bar Foo(Positive<int> b) {
    int c = b;
    if (c is Positive<int>) print("asdf");
    ...
}

was syntax sugar for:

Bar Foo(int b) {
    if (!(b > 0)) throw ArgumentException("Number isn't positive", nameof(b));
    int c = b;
    if (c is int && ((int)c > 0)) print("asdf");
    ...
}

@HaloFour commented on Wed May 18 2016

@DerpMcDerp

I don’t know what that has to do with guard per se, nor what guard has to do with pattern matching aside the potential for patterns to be used in arbitrary conditional expressions. If you want the reusability you can just call a helper function:

public static void GuardIsPositive(int param, string name) {
    guard (x > 0) else throw new ArgumentException("Number isn't positive.", name);
}

Bar Foo(int b) {
    GuardIsPositive(b, nameof(b));
}

That seems significantly cleaner than trying to hack something into the type system.

As for reusability in pattern matching, that sounds like it would be active patterns.


@DerpMcDerp commented on Wed May 18 2016

There are 2 annoyances with the helper function approach that make it less cleaner than hacking it into the type system for common places in code: - it requires you to repeat variable names in places, e.g.

Bar Foo(GuardIsPositive b) {
}

// vs

Bar Foo(int b) {
    GuardIsPositive(b, nameof(b));
}
  • It requires 2 helper functions for boolean tests and exceptions rather than 1 function, e.g.
[Message("Number isn't positive.")]
guard positive(int value) {
    return value > 0;
}

Bar Foo(positive b) {
    object c = b;
    if (c is positive) print("yay");
}

// vs

public static void IsPositive(int value) {
    return value > 0;
}

public static void GuardIsPositive(int value, string name) {
    if (!IsPositive(value)) else new ArgumentException("Number isn't positive.", name);
}

Bar Foo(int b) {
    GuardIsPositive(b, nameof(b));
    object c = b;
    if (c is int and IsPositive((int)c)) print("yay");
}

@HaloFour commented on Wed May 18 2016

@DerpMcDerp It’s less code, but that doesn’t make it cleaner. It hides much of what it does through syntactic voodoo. It blends the concerns of normal conditions and validation. It hijacks the type system in a completely unprecedented way and changes the public contract of methods using them. As “erased” it can’t be reused, requiring all of these common “guards” to be constantly reimplemented over and over again.

If we’re going to go down the path of declarative validation I’d rather explore AOP options through code generators. That or #119.


@gafter commented on Wed May 25 2016

What guard has to do with pattern-matching is that pattern variables introduced in the expression of a guard statement would be in scope in the enclosing block. See #11562

Updated 30/04/2017 02:58 2 Comments

Proposal: Allow unsafe code in iterators

dotnet/csharplang

@stephentoub commented on Tue Apr 21 2015

Today we disallow any usage of pointers in iterators, due to the issues involved with those pointers and the associated state moving to the heap. But we allow pointers in async methods (which have similar constraints) with the restriction that awaits can’t be used in an unsafe context, e.g. this is allowed:

unsafe (...)
{
    ... // no awaits
}
await ...;
unsafe (...)
{
    ... // no awaits
}

but this is not allowed:

unsafe (...)
{
    await ...;
}

We could allow unsafe code in iterators, but with a similar constraint: yield is not allowed in unsafe contexts, e.g. this would be allowed:

unsafe (...)
{
    ... // no yields
}
yield return ...;
unsafe (...)
{
    ... // no yields
}

@paulomorgado commented on Tue Apr 28 2015

That makes sense!


@whoisj commented on Mon May 11 2015

how do I thumbs up this?

er… +1!


@agocke commented on Fri May 13 2016

@stephentoub Seems fine to me.

More broadly, do you know of any CLR restrictions about spilling unmanaged pointers across the state machine? AFAIK, that seems the be the main restriction around async and unsafe, so theoretically the compiler could support spilling unmanaged pointers, as long as there are no issues with doing this in the CLR.


@stephentoub commented on Fri May 13 2016

More broadly, do you know of any CLR restrictions about spilling unmanaged pointers across the state machine?

Are you asking about enabling not just:

unsafe
{
    ... // no yields
}
yield return ...;
unsafe
{
    ... // no yields
}

but also:

unsafe
{
    ...
    yield return ...;
    ...
}

?

If so, even if it could be made to work (e.g. storing the pointers into the state machine), I think it would be dangerous, as it’d be incredibly easy to write bad code, e.g.

unsafe
{
    int* state = stackalloc int[1];
    state[0] = 42;
    yield return ...;
    Use(state[0]);
}

@agocke commented on Fri May 13 2016

@stephentoub Yup, very dangerous, but it is unsafe, to be fair.


@agocke commented on Fri May 13 2016

Certain things, like fixed, would still have to be prohibited outright, obviously.

Updated 28/04/2017 22:42

Sort out GitHub issues for gitbox repos

apache/couchdb

We’ve got ‘em, we want to use 'em instead of JIRA. Everyone on the project is +1, we just need a system. Here’s some proposed rules; I’m keeping them simple.

Assignees

Self-explanatory. * Assign yourself if you start working on an issue. * De-assign yourself if you abandon an issue or won’t be able to address it promptly. * Don’t assign an issue to someone else without their explicit approval. * To avoid cookie-licking, our PMC should consider periodically de-assigning idle issues. How idle is idle? 3 months seems a good timeline to me. Writing a script to do this that runs on a cronjob should be straightforward.

Tagging

I particularly like what Robin have done with their colouring-and-categorizing system. So, inspired by that, here’s the proposal. Remember an issue can (and probably should) have more than one tag.

  • Component: Various sub-components of Apache CouchDB. Can be expanded with search, geo, etc. in the future. (light blue)
    • build (toolchain, CI, etc.)
    • documentation (and/or below in Experience?)
    • dbcore (CouchDB database core)
    • fauxton
    • http_api
    • javascript
    • mango
    • nano (couchdb-nano client)
    • packaging (.deb, .rpm, snap, etc.)
    • plugins
    • replication (debatable, but this comes up enough)
    • testsuite
    • viewserver (the API)
  • Problems (red) - Issues that make the product feel broken. High priority, especially if its present in production.
    • bug
    • security
    • production
  • Mindless (beige) - Reorganizing folder structure, legal stuff, and other necessary (but less impactful) tasks.
    • chore
    • legal
  • Experience (orange) - Affect user’s comprehension, or overall enjoyment of the product. These can be both opportunities and “UX bugs”.
    • UX (could include API debates or installation as well as Fauxton)
    • documentation (and/or above in Components?)
    • design (primarily for Fauxton)
    • website (https://couchdb.apache.org/ and related websites)
  • Environment (pink)
    • windows
    • linux
    • macos
    • freebsd
    • docker
    • etc.
  • Feedback (magenta) - Requires further conversation to figure out the action steps. Most feature ideas start here.
    • discussion
    • rfc
    • question
  • Improvements (blue) - Iterations on existing features or infrastructure. Generally these update speed, or improve the quality of results.
    • enhancement
    • optimization
  • Additions (green) - Brand new functionality.
    • feature
  • Pending (yellow) - Taking action, but need a few things to happen first. A feature that needs dependencies merged, or a bug that needs further data.
    • in progress
    • watchlist
    • waiting on user
  • Inactive (grey) - No action needed or possible. The issue is either fixed, addressed better by other issues, or just out of scope.
    • invalid
    • wontfix
    • duplicate
    • on hold

Projects

Not useful for us right now.

Milestones

We should be using this for version targeting and mass-updating as necessarily. I.e., bugs get targeted for the next minor release, new features that break the API for the next major release, etc. Think v2.1.0, v3.0.0, etc. (Rathole: v or no v?)

Issue template

Going to start with this one.

PR template

Update to change reference from JIRA to GH Issues. Remind people to include text like “Fixes #472” to link a PR to an issue.

Contributing

We’ve had requests for this before, should we add one?

Multi-repo

We still have a number of repos that aren’t likely to be merged into apache/couchdb, like fauxton. I am suggesting we keep primary issue reporting here (in apache/couchdb) for all of our repos, and reference issues here from PRs in other repos (via apache/couchdb#472). We shouldn’t disallow issues in other repos, but my guess is that they’ll be limited to people ‘in the know.’

Updated 28/04/2017 22:44

Update a slider with a custom value (not in the values set) in a slider with fixed values

IonDen/ion.rangeSlider

Hi there:

I have a rangeslider with custom values set ([1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 125, 150, 175, 200, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, 1000, 1500, 2000, 2500, 3000, 4000, 5000])

User can play with this values, but I have an external input when the value of the slider is updated. But I would like this input to be changed by the user and set any number, any custom number, for example: 77.

I have noticed that if I update the number of a rangeslider with fixed values, the “ball” goes to the index number of that numbers set.

How can I move the ball to the exact point when the ball should be if instead a set of values it would be a range from 1 to 5000 (in my case) ?

Difficult, uh ? ;-)

Updated 29/04/2017 07:25 17 Comments

SQL Connection & Go ORM

JackyChiu/realworld-starter-kit

I’m quite new to using SQL with Go, so if anyone has any opinion or design proposals post them here!

As of now:

  • The SQL Connection is global in the main package (Maybe switch to dependency injection to pass it around?)
  • We’re using gorm as our ORM, maybe we don’t need an ORM and sqlx would be enough?
Updated 29/04/2017 07:37 9 Comments

Split apart #1324

bigdatagenomics/adam

Split apart #1324 into separate PR for sorted PR and joins rework PR.

Maintaining sorted knowledge can help in optimizations for downstream applications, but the join part of #1324 is monstrous.

I believe that separating the PR into separate sorted/join PRs can expedite the process for getting the sort and partition map knowledge into ADAM. Thoughts?

Updated 28/04/2017 22:42 1 Comments

Description of our process

rangle/angular-training-slides

Here’s a point-form summary of the process we’re converging on for creating and updating training materials. Considerations are:

  1. Lessons are different from code because they need an over-arching narrative thread.
    • Often more coupling between sections than there is for code
  2. We can’t automate regression testing of lessons.
    • The “regression test” is a human being reading them.
  3. The team is constantly changing.
    • Even when we have dedicated people, they are likely to be pulled sideways for other projects on short notice.

Comments, corrections, additions, and improvements greatly appreciated.


  • Monday morning: slide review

    • Spend 45-50 minutes going through a section of slides at <= 2 minutes/slide with the whole team
    • Everyone offers comment
    • One person adds the comment to a Google Doc while the rest of the group presses on
      • So that people aren’t waiting for one person to type
    • A comment may be:
      • A specific fix (usually small)
      • Something we need to discuss or develop (usually larger)
    • Goals are:
      • Add to the backlog
      • Disseminate knowledge about current state of content and inter-dependencies
    • Note: this is not sprint planning - this is to create backlog
      • Developers are also (kind of) customers, since they’re the ones delivering the training
  • Product Owner then transcribes items to create issues

    • Consolidates and prioritizes
    • Asks note-taker for more information (which hopefully ensures that issues are comprehensible by third parties)
  • Team members have permission to merge small changes by other team members

    • Typo fixes that don’t affect slide ordering: just do it
    • Larger items still merged by PO

Notes

  • Slides are identified by slugs, not slide numbers
    • So that we can re-order at will w/out invalidating slide identifiers in existing tickets
  • American spelling
  • Everyone using the slides creates a branch named after the start date of the training (e.g., 2017-06-02)
    • So that client names don’t appear in the repo
    • And we can easily track evolution of the deck
  • Every contributor/trainer adds a short bio and photo
    • Insert these into the opening slides in the fork for a particular training session
Updated 28/04/2017 20:02

[Discussion] Prefixing "internal global" symbols of jerry-core

jerryscript-project/jerryscript

Problem / Motivation

I’ve looked around the jerry-core library a bit to see what we expose of ourselves. I was especially interested in the global symbols available from the static libjerry-core.a archive. We have two types of global symbols, at least conceptually: there are those which are part of the public API (e.g., jerry_release_value – let’s call these “public globals”), and there are those which should probably not be available to the outside world but cannot be source-local statics because of modularization (e.g., vm_run or ecma_op_to_string – let’s call these “internal globals”). We have had problems with “internal globals” before: internal memory management routines used to have a mem_ prefix but that conflicted with other projects that wanted to embed the library. We ended up renaming the memory management module to jmem and re-prefixing all routines with jmem_. However, I don’t think that the threat of conflicting symbols has been completely lifted.

In the most basic build variant, on OSX, I get the following results when looking for global symbols that don’t have the jerry_ prefix:

$ ./tools/build.py --clean
$ nm ./build/lib/libjerry-core.a -g | grep -v ' U ' | grep -v 'jerry_' | wc -l
     611

This means that there are 600+ global symbols that are only for the internal working of jerry-core but may potentially conflict with code we have no influence on. What’s more frightening (to me, at least) is that these “internal globals” follow quite diverse naming schemes:

$ nm ./build/lib/libjerry-core.a -g | grep -v ' U ' | grep -v 'jerry_' | cut -d ' ' -f 2,3 | cut -d '_' -f 1,2 | sort | uniq -c
   1
   1 ./build/lib/libjerry-core.a(jerry-all-in.c.o):
   2 S _cbc
  35 S _ecma
   2 T _do
 399 T _ecma
  16 T _jmem
  10 T _lexer
  56 T _lit
  15 T _opfunc
  44 T _parser
  19 T _re
   1 T _util
  10 T _vm

I think it’s quite hard to prepare our users: it’s very hard to tell them what identifiers they must avoid if they don’t want to run into cryptic linker/runtime(?) issues. (E.g., a do_, util_, or re_ prefix is not unimaginable to be used elsewhere.)

Note: I’m not concerned about “claiming” the jerry_ prefix. That should not conflict. If someone chooses this project, s/he should live with the fact that this prefix is reserved for the JS engine.

Suggestion / Options

Option 1: The easy route

Let’s rename at least those “internal globals” which do not follow the “prefix with the module name” naming scheme: do_, cbc_, util_. These are the most problematic, I think.

Note: lexer_, parser_, and opfunc_ are actually also in violation of that naming scheme, but it’s not cast to stone after all. My very subjective judgement does not consider them as harmful as the other three prefixes.

Option 2: The middle course

Let’s add a newly chosen prefix to all “internal globals”. E.g., jrs_, jry_, j_, j3y_, j9t_, etc. The key is to have a single prefix we can communicate to our users not to use (in addition to jerry_).

Note: I haven’t listed jerry_ as a potential prefix for “internal globals”. Right now, it’s just my instincts that tell me to have different prefixes for public and internal globals.

Option 3: The hard path

Let’s add a macro that must be used at the definition and at the references of such global symbols, which adds a custom prefix to the symbols. For the biggest flexibility, this macro can have a sensible default for the prefix (see Option 2) but can also allow a config-time override.

#ifndef CONFIG_SYMBOL_PREFIX
#define CONFIG_SYMBOL_PREFIX jrs_
#endif

#define J(SYMBOL) CONFIG_SYMBOL_PREFIX ## SYMBOL

ecma_property_pair_t *
J (ecma_alloc_property_pair) (void)
{
  return J (mem_heap_alloc_block) (sizeof (ecma_property_pair_t));
}

Note 1: The example is a trimmed down variant of real code. Note 2: This option could hopefully also include the reverting of the mem-to-jmem change, because that single j is highly arbitrary IMHO. The example already shows a symbol in reverted form. Note 3: AFAIK, Valgrind uses a solution something like this.

Option 4: Do nothing

We can conclude this, too.

Analysis

  • Option 1:
    • Pro: Can be applied practically at no cost, it’s just the renaming of 5 identifiers in the simplest case.
    • Con: Just scratches the surface. In fact, the issue is not solved.
  • Option 2:
    • Pro: Issue solved (mostly). Provided that we choose a non-uncommon prefix, we will most probably not conflict with any user.
    • Con: This means a HUGE rewrite of the code base. These functions are everywhere. 600+ definitions and I-cannot-guess-how-many references.
  • Option 3:
    • Pro: Issue solved (completely). A user will be able to reconfigure the prefix if that sub-1% chance hits that the default prefix conflicts with its code base.
    • Con: as for Option 3 + with our current coding style (“space before open parenthesis”) the rewritten code will look weird (i.e., we cannot even write J(xxx), we have to add that space J (xxx))

Note 1: Should we conclude for any of the above, it will be possible to enforce the naming scheme with checks using similar techniques as shown in Motivation. Note 2: This should not be a breaking change. Noone should try to access these symbols from outside the library (except for unit tests).

Any feedback would be greatly appreciated!

Updated 30/04/2017 13:15 6 Comments

[WIP] Refactory & Enhancement

phpindonesia/phpindonesia.or.id-membership2

Perubahan

  • [x] Tidak lagi menggunakan folder www sebagai document root & menambahkan folder asset untuk menampung semua file CSS, JS, Fonts & Images.
  • [x] Mengubah codebase, detail perubahan bisa dilihat di tiap commit message.
  • [x] Penggunaan file .env untuk setting dasar. Meminimalisir terjadinya konflik ketika ada perubahan atau penambahan key di file app/settings.php.

Perbaikan

  • [ ] Memperbaiki mailer (terkait #94), disini mailer akan kita ubah dari sebelumnya menggunakan postmark (SMTP) ke sparkpost (ReST API) dimana kelebihan utama dari penggunaan ReST API adalah proses pengiriman email dibebankan ke provider, bukan server production. Selain itu sparkpost juga menawarkan fitur mail marketing secara gratis jadi jika nantinya kita butuh untuk bulk email dapat di-handle oleh sparkpost dengan lebih efisien.
  • [ ] Optimasi tampilan pada mobile (terkait #80)

Penambahan (Experimental)

  • [ ] Optimasi static asset (CSS, JS & Image) dengan tools. Opsi sementara adalah gulp atau webpack.
  • [ ] Menggunakan heroku sebagai staging sekaligus meng-enable fitur review, memungkinkan tiap pull request (nantinya) akan ada online demo yang di generate otomatis oleh heroku.
  • [ ] Menyediakan testing, walaupun tidak semuanya akan di test tapi setidaknya kita punya fitur ini untuk memastikan berjalan semestinya.
Updated 29/04/2017 18:33 4 Comments

Rework command result logic

RogueException/Discord.Net

I’ll use this issue to track the status of result logic in commands. Please discuss changes that you would like to be made here.

  • [x] Use classes instead of structs for results to allow for polymorphism
  • [ ] Refactor result types (especially type readers) to make their public API cleaner
  • [ ] Improve overall use-cases for result types
  • [x] Remove methods from converting one result to another
  • [x] Remove processing of result types in our info classes
Updated 29/04/2017 20:34 4 Comments

change all `props.autoFocus` to `instance.focus()`

ant-design/ant-design-mobile

ref: https://github.com/ant-design/ant-design/issues/3790

https://github.com/ant-design/ant-design-mobile/search?utf8=%E2%9C%93&q=autoFocus&type=

https://github.com/ant-design/ant-design-mobile/search?q=autoFocus&type=Issues&utf8=%E2%9C%93

no messy job, if users want a input be focused automatic, use refs.foo.focus() in componentDidMount

cc @benjycui @pingan1927

Updated 29/04/2017 10:56

Serialize objects for sending them with MPI

KratosMultiphysics/Kratos

I am currently modifying the mapper and enhancing especially the MapperCommunicator. In addition to exchange Variable values I want to be able to extract values from the partner-objects. For this I have to exchange data with MPI, independent of the datatype, which requires serialization of the object.

I took a look at the MPICommunicator and the “AsyncSendAndReceiveObjects” function and intend to do sth similar. @adityaghantasala and I thought that the serialization offered by boost seems to be suitable since it also works for every STL container.

What is your opinion on this?

Updated 30/04/2017 09:20 2 Comments

core(chore): revisit core structure

digitaldeacon/memberhive2

currently we lumb stuff together by module (i.e. person, settings, etc.). Most example on that matter have folders for reducers, effects, actions and models.

We should try to avoid having to name every export as unique. Instead, we could import it in index as a unique name. This would improve code readability and make coding faster.

Further, it would also be great to be able to import only what you need. So instead of doingimport * as fromPerson from 'mh-core', it would be cooler to sayimport * as fromPerson from 'mh-core/person'.

However, this requires more complex module import/exporting.

Updated 28/04/2017 14:13

Convert API spec to Swagger spec?

gothinkster/realworld

I’m a fan of the swagger api specification and I’m just thinking out loud wondering if converting the current realworld api spec to a swagger compliant spec would add some value? There is some nice tooling and testing support and most environments have swagger libraries.

It could give the api spec a “common” documentation and contribution language as it grows and allow for integration with the existing swagger ecosystem.

http://swagger.io/ http://swagger.io/specification/

Updated 28/04/2017 18:45 7 Comments

KILL PLURALIZATION (#1350)

Automattic/mongoose

My two bits. Just drop the pluralization and lowercase requirement all together. Don’t option it, that’s stupid. And making a all lower case requirement is not being compliant with mongoDB.

Think of this AND your next design choices like this: - by removing some unnecessary draconian rules in this world YOU ENABLE ME (US / YOUR USERS & FANS) TO BE THE MORE CREATIVE - AND it costs you LESS OF YOUR EFFORT - AND enabling my creativity you’re BUILDING A BETTER PRODUCT - AND by creating and enforcing additional (and by not removing) arbitrary rules the LESS RELEVANT YOU BECOME TO YOU MARKET YOUR MARKET Just my two bits. Need help removing the .toLower() in your code on the collection name? If the application is structured well this is probably in only one line of code. So you can fix this in no more consideration that the next maintenance release.

On 1350 I saw the remark “most collections are plural” … Really?!! That simply is NOT true. Where you see this is in the work of those sheep who learned, then never challenged finding, a better way. most specifically Microsoft Entity Frameworks. You don’t want mongoose to be associated in the minds of users is Microsoft EF do you? Just let me name it what I want to name it and you earn favor and grow deployments. Make people struggle over stupid design choices and people will walk straight into the arms of your competitors who are not so pointlessly sadistic.

Thanks.

Updated 29/04/2017 21:37 1 Comments

prefix the plugin fields

Books4Languages/pressbooks-metadata

We need to prefix the field-names of the fields we use, in order to make them more clear and understandable. This way when we see for example: - pb_author - s_md_author

We can understand that the first field is from pressbooks and the other one is from the plugin. A good approach for now is “s_md” from metadata

Updated 28/04/2017 12:49 1 Comments

To-do list

mikkpr/cobra-caliber-2

In random order: * [ ] Rewrite music system to persist through state changes * [ ] Fine-tune current levels * [ ] Add some kind of tutorial * [ ] Implement visual effects (glow for neon signs and force fields etc.) * [ ] Use and show level timers

Updated 28/04/2017 06:58

Resize image errors text improve

abantecart/abantecart-src

Please improve image resource errors. Main idea is now not clear how to find an image in Media Library, to what object (product, category or any) it is assigned. If possible please add info about resource name (this will allow to use Media Library search) and object mapped to. - App Error: AbanteCart core v.1.2.11 Image file //resources/image/18/72/e.jpg cannot be resized. Try to decrease original image size 2329x2329px or reduce file size. in /core/lib/image.php on line 258 - App Error: AbanteCart core v.1.2.11 Resize image error. File: /resources/image/18/72/e.jpg in /core/engine/resources.php on line 345

Please show this error in Error log only and do not send Admin Message with App error.

Updated 28/04/2017 12:40

Warning for low feed-rates

LaserWeb/LaserWeb4

We have had a situation recently where a user has accidentally set a very slow feed-rate (10mm/min) in their machines and ran the job. It caused their material to ignite but luckily was picked up in time.

At such slow speeds the potential for ignition of the material goes us significantly and although jobs should always be monitored, sometimes they just aren’t.

For our machine, running it anywhere below 150mm/min is not advised.

I wanted to ask for thoughts on whether a warning is raised if feed-rates below a certain threshold are used?

In light of so many new users working with LW4 every day, I believe this is something worth discussing.

Updated 28/04/2017 14:02 18 Comments

[Discussion] About improvement of tag feature.

BoostIO/Boostnote

refer to #192 #328 #371 #390, thanks for @huettenhain @jasondavis and @kazuhisya!

I think should improve tagarea UX more, especially I want to improve the following two features. Please tell us you guys feedback!

1, Add tagarea at sidebar

<img width=“557” alt=“screen shot 0029-04-28 at 1 32 57 pm” src=“https://cloud.githubusercontent.com/assets/8602615/25514739/eac9a28e-2c19-11e7-84a7-0a322d641f3d.png”>


2, Can make tags inside markdown note and snippet title.

And will delete the tagarea at the top of NoteDetail. <img width=“653” alt=“screen shot 0029-04-28 at 1 32 01 pm” src=“https://cloud.githubusercontent.com/assets/8602615/25514744/f04969e2-2c19-11e7-8457-dc6f0df1dc65.png”>

Updated 28/04/2017 12:44 2 Comments

[Feature Request] New Note Type - Kajero Note

BoostIO/Boostnote

It would be really cool to add a 3rd Note type using this library Kajero https://github.com/JoelOtter/kajero

Features

  • It is a markdown file but it lets you add “blocks” with a button click. The block types includes:
    • Markdown/Text block
    • Graph/chart block using 3 different libraries.
    • JavaScript code snippet block with a Play/Run/Execute code button that will allow the code in the JS snippet to be ran and show the output below it.
  • Data sources - This feature allows you to put in the URL of JSON API’s and it will make the data available for use in any of your code snippet blocks!
  • Static file. The Notebook is saved as a Markdown or HTML file.
  • If you do not wish to save the file it can be uploaded to GitHub Gist and the URL is returned.

Data Sources

Data sources can be defined. These will be automatically fetched when the notebook is loaded, and made available for use inside code blocks.

image


If this was integrated as a new note type, it could instead simply save the doc to Boostnote like the other notes currently are.

The best way to see how amazing it is is to simply look at the demo Notebook Markdown file here http://www.joelotter.com/kajero/

Open that page and click the edit mode button on the top right corner.

In edit mode you can add new blocks, delete blocks, create new blocks, and also move blocks up or down in the page.

Once done you click the “Export notebook” button in the top right corner which shows a screen to save the notebook as Markdown or HTML with a 3rd option of uploading to GitHub Gist.

If integrated to Boostnote, this export note screen could simply over-write the existing “saved file” in boostnote so that the same note can be edited over and over without making a new file.


What are the thoughts on this? I know it is a big request but it is super cool and would be really cool if it was a note type in Boostnote.

I really like how the JS code snippets have a run button to run the snippet of code in the note.


There is a blank note here https://www.joelotter.com/kajero/blank.html


Code Snippet Block with result shown below it

image


Graph Block

image

Updated 28/04/2017 09:41 1 Comments

Payload metadata

archivers-space/recipes

Payload should include following fields (* optional): Author Author Contact info Timestamp of payload creation payload filetype payload filesize hash validation tests to run bibliographic reference (*)

Any additional input, especially from librarians on this topic would be helpful

Updated 27/04/2017 22:50

Overall Structure for classes and API

archivers-space/recipes

Recipe proposed structure ``` classdef Recipe(url):

def run(): context.getMeta(url) # gets metadata from context service payload = recipe.harvest() try: archiveDB.upload(payload) #upload call also runs validation tests except validationError: # User needs to fix the recipe so that it passes the tests

def harvest(): # main function, must return a payload and associated metadata ```

Updated 27/04/2017 22:22

Service init/unload methods

trailsjs/trails

Issue Description

Looking at the Service API (https://trailsjs.io/doc/en/ref/service) I was a bit surprised to see there are no initialize() and unload() methods. Services are singleton instances intended to do the applications heavy lifting right? I had expected the possibility to eg. block the applications start until my Service has connected to a different service. At the moment it would always be necessary to write a trailpack when the service would require any form of bootup and shutdown logic.

Is this an intended design decision? (If not,) would you be open to change that?

Environment

  • trails version: v2
Updated 28/04/2017 18:31 2 Comments

Should indirect mob kills be counted?

ToroCraft/Dailies

Source: https://minecraft.curseforge.com/projects/baileys-dailies?comment=46

I’m thinking I prefer that kill counting stay as it is for simplicity etc, but I’m curious for comments from the team. I’m guessing that the event we’re listening to triggers on direct kill, but I haven’t looked into it.

Updated 27/04/2017 22:42 3 Comments

Make Stash an injectable dependency

AsynkronIT/protoactor-dotnet

As stashing needs to survice between actor restarts, it cannot be created inside the actor. Currently it is created by the Context for this reason. But as with #200, I would like to make as much as possible “opt-in” if it has weight/cost in terms of resources.

e.g. csharp var stash = new Stash() var props = Actor.FromProducer(() => new MyActor(stash)); Then it could be used like so:

```csharp public class MyActor : IActor { private readonly Stash stash; public MyActor(Stash stash) { stash = stash; } public async Task ReceiveAsync(IContext context) { try { switch(context.Message) { case SomeMessage msg: foreach(var message in stash) { //do whatever //maybe we should call an apply method like in the persistence API(?) } break; } catch() { stash.Push(context.Message); break; } } }

Updated 30/04/2017 16:05 17 Comments

Why are Genotype.getAttributeAsX methods deprecated?

samtools/htsjdk

There are a number of deprecated methods in Genotype that seem useful. There’s no explanation why they’re deprecated or what the replacement is.

ex: @Deprecated public int getAttributeAsInt(String key, int defaultValue) { Object x = getExtendedAttribute(key); if ( x == null || x == VCFConstants.MISSING_VALUE_v4 ) return defaultValue; if ( x instanceof Integer ) return (Integer)x; return Integer.valueOf((String)x); // throws an exception if this isn't a string }

Is there something wrong with these methods? Is there a replacement somewhere? There are analogous methods in VariantContext that are not deprecated. They were deprecated before being moved into htsjdk so the history is cut off. Does anyone know?

They seem like necessary functionality, maybe we should dedeprecate them? (and possibly refactor so there isn’t duplicated code between them and the same methods in CommonInfo

Updated 28/04/2017 15:58 7 Comments

I18n

gothinkster/realworld

Internationalisation or i18n is critical for most production apps these days. I recommend adding an API for i18n. Have it return a JSON with all the tokens for all languages. Also an endpoint for only a specific language. Could setup a system to bring language contributers on board. Could implement a select in the UI to change language.

Updated 28/04/2017 01:35 6 Comments

discussion: dom.presentation.*

ghacksuserjs/ghacks-user.js

My understanding is this poses a possible hardware leak/fingerprint. The defaults are all false anyway, so this is for completeness.

https://wiki.mozilla.org/WebAPI/PresentationAPI

Presentation API enables web content to access external presentation-type displays and use them for presenting web content. With this API, web page can initiate and control an presentation request.

More info on retrieving available devices information: https://wiki.mozilla.org/WebAPI/PresentationDeviceInfoAPI

^^ So it can enumerate devices. It can initiate requests, i.e requires user confirmation/action, so that is not an issue.

The Presentation API requires user permission for a page to access any display to mitigate issues that could arise, such as showing unwanted content on a display viewable by others.

/* 2513: disable Presentation API
 * [1] https://wiki.mozilla.org/WebAPI/PresentationAPI
 * [2] https://www.w3.org/TR/presentation-api/ ***/
user_pref("dom.presentation.enabled", false);
user_pref("dom.presentation.controller.enabled", false);
user_pref("dom.presentation.discoverable", false);
user_pref("dom.presentation.discovery.enabled", false);
user_pref("dom.presentation.receiver.enabled", false);
  • Not 100% sure what presentation.discover* do exactly - maybe see https://bugzilla.mozilla.org/show_bug.cgi?id=1180596
    • dom.presentation.discoverable.encrypted default true (the only pref at default true)

Any objections, corrections, enlightenment? Since they all seem to be off (except *encrypted), we can either add this for info, active or inactive, or just drop the whole thing.

Updated 30/04/2017 04:41 1 Comments

Token's SOFA protocol

OpenBazaar/openbazaar-go

See here. SOFA is “A protocol to quickly develop apps for an open financial system.”

Like Coinbase’s Token I think of OpenBazaar as a platform (specifically, a marketplace platform), not as a standalone (ecommerce) app. Is OpenBazaar the next eBay? Or is it also the next Uber, AirBnb and KickStarter?

I believe we eventually want to give developers the power to write their own “OpenBazaar apps”. The SOFA protocol which specifies allowable UI interactions is a possible way forward.

Updated 28/04/2017 19:34 1 Comments

Metakernel

hadim/scijava-jupyter-kernel

Consider making the kernel polyglot.

Choose a default language (Python or Groovy) and let the user choose languages per cell.

That would require some refactoring on the kernel side but nothing too complicated.

Before starting the implementation, we need an UI on the Jupyter client side to let the user easily choose what language he wants. Such a feature are not ready yet but definitively coming soon in Jupyter Lab.

Updated 28/04/2017 23:49 4 Comments

md-input-container: Allow setting floatPlaceholder globally

angular/material2

Bug, feature request, or proposal:

Allow globally setting the floatPlaceholder option on the md-input-container. Similar to how the ripple can be globally set.

What is the expected behavior?

Globally setting the floatPlaceholder will result in the default action. floatPlaceholder can still be set inline and would take precedence.

What is the current behavior?

floatPlaceholder must be set on each instance or the default ‘auto’ option will be used.

What is the use-case or motivation for changing an existing behavior?

Would like to disable the floating placeholder globally by setting the default value to ‘never’,

Is there anything else we should know?

I have implemented this locally and would be happy to create a PR if there is interest in this feature. Followed the same approach used for the global ripple disable.

Updated 28/04/2017 16:42

[Discussion] Transitive dependencies

fable-compiler/Fable

Continuing the conversation from gitter about transitive dependencies support @alfonsogarciacaro is adding, started in https://github.com/fable-elmish/react/issues/1:

Fable dependencies must be peer to prevent npm from duplicating them in subdirectories if there’re version conflicts. They cannot be dev as they must also be installed in the machine of the final user of your lib. About non-Fable peerDependencies. Fable will just install everything and check if theres an .fsproj file in the root folder of the package. In that case it will add a project reference, the others will be ignored. I’m just trying to define the process, we could also have the convention that all Fable libraries are prefixed with fable- for example. As far as I understand, devDependencies are only installed in the developer machine and not in the library consumer. I guess we could use them as a convention for fable libraries but I don’t see the advantage of forcing the npm semantics, you can also have devDependencies that are not Fable libraries.

I’m assuming the situation is as follows: - fable libs distributed as sources, like anything subject to transpilation has been traditionally a dev dependency. - the guidance for fable libs up to this point, has been “don’t list fable dependencies as either peer or regular, let the user figure it out and install”. - now that we have dotnet fable add we get to examine dependencies of the library being added and potentially trigger installation of its (transitive) dependencies.

Question: should we? Question: if yes, what is the appropriate section dev or peer? Question: what is the predicate for triggering a transitive dependency install? Question: what is the desired behaviour if installed with yarn instead of dotnet fable add?

Updated 29/04/2017 07:45 9 Comments

Configurable mixdepths

AdamISZ/CoinSwapCS

Code currently hardcodes mixdepth 0 as funding depth and mixdepth 1 as destination. It’s nice to have a simple default for easier configuration, but e.g. people with existing joinmarket wallets would like to be able to use different mixdepths for the inbound and outbound.

A very braindead simple first step is to add source_mixdepth and destination_mixdepth in the config so they can be different numbers, even if the model is unchanged. Note that this would have implications for wallet load/sync (currently using 3 in the code).

Related: backout is currently using the same outbound mixdepth, although I originally intended to have it be a third mixdepth (hence the default wallet is 3 mixdepths).

Related: the server may have special considerations here. There might be a good case for having multiple separate mixdepths to serve utxos from, like multiple streams. Not at all sure.

Not currently sure exactly what to do about this, but it should be revisited.

Updated 27/04/2017 13:03

Control System Design Discussion

LakeMaps/boat

As mentioned, for Rev 1.3 we need to come up with a control methodology. Here are some of the basics:

A control system is generally represented as a block diagram where each block is a self-contained series of transformations with inputs, outputs and parameters. image

For us, the system is as follows: - The input in our case is waypoint we want to go to (lat, long). - The Error block is next in line, which computes Error = (waypoint) - (where we are). The result for us should be a vector comprised of distance to waypoint, bearing to waypoint. - The Controller is the block of software we use to turn the input (error) into an output (in our case, a motor speed pair). This can be achieved through one of many types of control methods including PID, Fuzzy, etc. - The Process block is the dynamic model of the system which represents how motor speed translates to position. Not shown in the figure is the so-called Disturbance which will change the way the process effects the output. For us, disturbance includes things like current, wind, and waves. - The Output of the system is where we are as read by the GPS. It is then used as the feedback signal to the Error block.

For Rev 1.3, it is appropriate for us to use PID control, as this is the simplest for us to implement due to its simple mathematical model and familiarity. Interestingly, PID theory was developed by observing helmsmen attempting to keep a vessel on course in varying wind and waves. PID control can be shown as follows: image - P is Proportional control. The error gets multiplied directly by a constant gain, kp. This is used to determine how quickly a system reacts to changes. - I is Integral control. The sum of a constantly shifting set of previous error values (the last x errors) is multiplied by the integral gain, ki. This is used to dampen the oscillations due to P control and eliminate steady-state error. - D is Derivative control. The difference between the current output and the last measured output is multiplied by the derivative gain, kd. This is used to ‘brake’ the system to lessen overshoot and to slow the system reaction.

A few notes: - Our error calculation for bearing is a little non-intuitive. We first determine the bearing between our current position and the setpoint by taking the unit vector of the displacement vector (WPLat-CurrentLat, WPLong-CurrentLong) and then subtract that bearing from our bearing along our current path as stated by the GPS to get our bearing error (in degrees). - We may need to have two separately operating PID systems, one to control speed and the other to control bearing. This should still work if you combine (read: add) the motion values produced by each system before applying it to the motors. - In order for the GPS to accurately read bearing, we need to be moving fast enough such that the apparent ‘motion’ due to variance in position due to GPS accuracy is significantly less than the true change in position due to motion. From my experience, this speed is something >1 m/s. - If bearing proves to be a problem for us, we may need to add a magnetometer to get a reference to magnetic north and then apply the magnetic declination to correct it to true north. - A gyro would enable us to get a more accurate measure of our yaw rate/acceleration (compared with performing subtraction of GPS bearings with each step). This would likely improve our ability to tune the system for achieving the desired bearing and compensate for disturbances.

Updated 30/04/2017 15:06 5 Comments

Adding a top-level examples directory

ioam/holoviews

A major part of improving our docs is to add various examples. The way many libraries structure their examples is in a top-level examples directory (see bokeh, and matplotlib). These examples then usually get built into a gallery (see bokeh, matplotlib, and cartopy).

Adding an examples directory also encourages adding examples when new features are added. I’d even suggest that in future new features should be accompanied by small example notebooks or scripts. We are going to be splitting out the different plotting backends but I’d still strongly argue examples for officially supported backends should live on the core repo, where they are all in one place.

We’ve also had various definitions of examples in the past, what I think it should mean in this context is small self-contained notebooks with at most one or two examples, which are focused on the code, not on telling a story or explaining deeper concepts. That contrasts with quickstart guides, tutorials and the “examples” that are linked to from holoviews.org/Examples, which are really case studies. My suggestion for the different types of notebooks:

  1. Tutorials - Long, detailed notebooks explaining particular concepts in detail, living in doc/Tutorials. New tutorials should be added to holoviews-contrib and can move to the main repo once polished.
  2. Quickstart guides - Shorter notebooks getting the user started on using a particular feature without providing extensive background. Again should start out in holoviews-contrib but once we have a few I’d suggest creating a User Guide (see bokeh) that provides a quick introduction to holoviews.
  3. Examples - These are what this issue is about, they are short and self-contained and generally should just go straight into the main repo since they don’t need detailed explanation.
  4. Case studies - These are what’s currently on holoviews.org/Examples, and basically show how to apply holoviews to a particular domain or problem. I believe these should all live in holoviews-contrib providing a wide-ranging collection of user examples. Keeping them all in one place this way will encourage us to test and update them for each release.

If we agree on these different formats and where they live we should settle the structure of the examples, my suggestion is that each example should be implemented for all backends that support the features used in the example. Then each example links to the equivalent versions for other backends. Each example should contain the following information:

  • Table with links to the example implemented using other backends using unicode tickmarks to show supported and unsupported backends
  • List of requirements, e.g. if the data uses bokeh sample data lists that as a requirement
  • A link to the original source of the example if any
  • (Optional) A list of tags to make the examples more searchable

We also want to structure the examples into sensible subfolders. Here’s some subfolders I can currently imagine:

  • apps - bokeh apps and in future maybe matplotlib webagg based apps
  • elements - All the supported elements split out into individual notebooks
  • plotting - Basic examples showing off specific plotting features
  • streams - Various examples using regular streams and linked streams
Updated 27/04/2017 12:31 6 Comments

Private gitlab Hunter_cache server

ruslo/hunter

I’d like to create a hunter_cache server just for me and my gitlab-ci builders. Currently only the official hunter github server is supported as hunter cache. Where would I need to begin to add any gitlab repo as server?

Updated 28/04/2017 05:15 3 Comments

Missing parts in documetation

bvssvni/path_semantics

Hi! I’m big fan of this work and have read every blog article, docs, etc. I kind of understand the philosophy behind it and the theory.., but what I miss is are REAL LIFE application examples. I mean.., if you could show as some tiny/small useful example (a code) with a real life application (not just theoretical), it would be probably much easier to understand the whole POINT. The example should answer questions like: “What existing problem does’t it solve?” or “What new possibilities it opens?”..

It’s like Physics. The lectures can go on and on, but the real knowlage and interest, in my option, comes from practical examples- when you see the connection- have to apply it to our inner/outer world.

Updated 29/04/2017 09:19 8 Comments

Feature request: "Process window" as a docked tab

gitextensions/gitextensions

I’m not a fan of having too many popup dialog windows. I think it would be nice if the “Process window” (I don’t know what it is officially called) could be docked as a tab.

(With “Process window” I mean the status window that shows the git output when you i.e. do a pull request.) I think that it would work the same way as the output window (that shows for example the build output) in Visual Studio.

Currently the “Process window” is modal so it effectively disables the rest of the GUI. If implementing the tab solution, the GUI will have to be locked down while processes are running.

Maybe a spinner could be displayed in the GUI, while the GUI is locked down?

Also a spinner could be added to the tab title while the process is running? Or should the process tab be focused automatically?

edit 20017-04-28: grammar, formatting

Updated 28/04/2017 08:46

expectSaga test failure on missing assertions

jfairbank/redux-saga-test-plan

Feature request: it’d be wonderful to be able to assert that a given saga yields exactly the specified effects–no more, and (critically for this ticket) no less.

The following example demonstrates the issue: ``` function* mainSaga(x, y) { yield take(‘HELLO’); yield put({ type: ‘ADD’, payload: x + y }); yield take(‘WORLD’); yield put({ type: ‘DONE’ }); }

it(‘PARTIALLY handles dispatching actions’, () => { return expectSaga(mainSaga, 40, 2) .put({ type: ‘DONE’ }) // Put assertion on “ADD” is missing so the test does not break .run(); }); ``` So perhaps a new helper which ensures that all side effects have an assertion would be nice to help developers be sure that their saga is appropriately covered:

it('EXPLICITLY handles dispatching actions', () => {
  return expectSaga(mainSaga, 40, 2)
    .put({ type: 'DONE' })
    .runExactly();
   // Put assertion on "ADD" is missing, test breaks!
});

I’m just making up a crappy API that probably won’t work. Welcome your thoughts!

Updated 28/04/2017 13:06 1 Comments

shadow behaves like reflection

godotengine/godot

previously i’ve noticed strange shadows and investigation lead to skybox render issue https://github.com/godotengine/godot/issues/8050

but now i’ve returned to godot and looked at a big shadow and saw there a reflection of a skybox! this is just a default diffuse material. there is nothing special except added skybox (and directional light with enabled shadows) actually now i think that all that defected shading is caused by skybox being reflected. and skybox itself has that defected gradients (issue above)

Updated 29/04/2017 18:22 1 Comments

no-tzdb should exclude ServiceLoader code from ZoneRulesProvider

ThreeTen/threetenbp

When the timezone DB isn’t included in the JAR, the code to look for it and load it with ServiceLoader should be removed from the static initializer block of ZoneRulesProvider. Apparently ServiceLoader is extremely slow on Android even if there are no implementations loaded (since no-tzdb already handles removing the META-INF entry), and it’s not needed when the code isn’t bundled with a tzdb.

I was trying to figure out some Maven incantation to exclude this version of the class and include an alternate version that removes the static initializer block, but I’ve never used Maven before so I’m lost :)

Updated 28/04/2017 20:09 6 Comments

No notification configure or show in iOS 10.3.1

phonegap/phonegap-plugin-push

Expected Behaviour

Multiple phones iphone 6 and 7 running ios 10.3.1 should configure for and recieve push notifications. User prompted to allow push notifications on app install and show settings in notifications area.

Works in ios 10.2.x and earlier on iphone 6 and iphone5s

Actual Behaviour

User not prompted to allow push notifications App in notifications area is not present (i.e. cant set push settings) No push notifications appear

Reproduce Scenario (including but not limited to)

Update iOS to 10.3.1 Re-install app Push notifications dont prompt user on install Push notifications config dont appear in settings for app Push notifications are not sent

Platform and Version (eg. Android 5.0 or iOS 9.2.1)

iOS 10.3.1

(Android) What device vendor (e.g. Samsung, HTC, Sony…)

Cordova CLI version and cordova platform version

cordova ios 4.3.1

Plugin version

push plugin 1.9.4

Updated 27/04/2017 23:36 2 Comments

[Enhancement] integrate "astyle" into Openscad

openscad/openscad

It would be great to have a menu-entry that would push the scad source though “astyle” with suitable or definable parameters.

Astyle is a source for matter for “C like/ {} block ” languages, astyle -A2 xxx.scad does wonders for readability of scad files, it would good to have a “reformat code” menu-entry.

see: https://github.com/live-clones/astyle/tree/master/AStyle

If its considered to be useful I could have a go at doing it myself and submit a pr, if so which branch should I work against?

Updated 27/04/2017 08:50 3 Comments

ACS: add az acs stop command to stop and deallocate vm's in an acs cluster

Azure/azure-cli

Description - add a helper command to stop/deallocate the acs cluster

Outline the issue here: The az vm stop is not the same as the stop button in the portal. The stop button in the portal also deallocates resources which means that you don’t get charged for the resources after you stop a vm in the portal. In the CLI, you have to explicitly run the deallocate command after the stop command to prevent from getting charged for the resources.

Essentially the code will call the following commands az vm list az vm stop az vm deallocate

Design of the command-

az acs command -n containerServiceName -g resourceGroupName - stops/deallocates all vm’s in the cluster

az acs command -n containerServiceName -g resourceGroupName -vm-names {vm_name1, …} to stop only a specific vm or multiple vm’s

Environment summary

Install Method: How did you install the CLI? (e.g. pip, interactive script, apt-get, Docker, MSI, nightly)
Answer here:pip

CLI Version: What version of the CLI and modules are installed? (Use az --version)
Answer here:dev build

OS Version: What OS and version are you using?
Answer here:mac os

Shell Type: What shell are you using? (e.g. bash, cmd.exe, Bash on Windows)
Answer here:terminal

Updated 27/04/2017 17:17

az vm stop in the CLI stops the VM but Stop in the portal deallocates the resources. need parity between the two?

Azure/azure-cli

Description

Outline the issue here:

az vm stop in the CLI stops the VM but does not deallocate the resources. The customer continues to get charged for the resources. Stop in the portal though deallocates the resources. I think we should have parity between the 2.

Environment summary

Install Method: How did you install the CLI? (e.g. pip, interactive script, apt-get, Docker, MSI, nightly)
Answer here:pip

CLI Version: What version of the CLI and modules are installed? (Use az --version)
Answer here:dev build

OS Version: What OS and version are you using?
Answer here:MACOS

Shell Type: What shell are you using? (e.g. bash, cmd.exe, Bash on Windows)
Answer here:terminal

Updated 27/04/2017 17:20

Working towards 2.0.0 release

dotnet/coreclr

@hqueue @jyoungyun @hseok-oh

I wanted to share some additional data with you all since we forked for release/2.0.0.

We are working towards getting all bugs, identified to be fixed for .NET Core 2.0 Preview2 and RTM release, by 5/10 for CoreCLR, CoreFX and Core-Setup repos. Please plan to get your fixes in the respective master branches by 5/10 EOD PST.

After 5/10, master branch contents will be pushed into respective release/2.0.0branches and master version will become 2.1. Any fixes required for 2.0 release, post 5/10, we will be taking fixes in release/2.0.0 branches but they would be subject to higher bar. For any such fixes that you deem need to be made, I would suggest the following:

1) Make the PR against release/2.0.0 branch and CC @leecow and me. 2) Have the PR description detail the importance of getting the change in.

Likewise, if you have any fixes that need to go into Preview1 (which is what release/2.0.0 branch is versioned as right now), please follow the same process. The timeline for those is EOW.

Please share this with your team as well and do let me know if you have any questions.

CC @leecow @weshaggard @richlander @Petermarcu @shawnro

Updated 28/04/2017 15:02 1 Comments

Give CTOR access to context

AsynkronIT/protoactor-dotnet

In some cases, it might be good to have access to the context already in the CTOR of the actor.

I’m thinking it would be possible with something like this:

var props = Actor.FromProducer(ctx => new MyActor("hello", ctx));
...
class MyActor
{
    private string _id;
    public MyActor(string someArg, IConstructContext ctx)
    {
          //Self, Parent and a few other things could be available upon creation
          _id = ctx.Self.Id; 
    }
}

I’m not sure if this is a good idea and if it promotes doing more than you should in the ctor. But it would be possible technically by adding a new overload on FromProducer and introduce the constructor context.

Updated 27/04/2017 07:00 1 Comments

Better assertion dialogs

Microsoft/visualfsharp

This is more of a discussion for better assertion dialogs, as I find the ones at the minute very difficult to read and have a poor user experience overall. How do people think that we can make the current one better?

As an experiment I’ve redesigned the assertion dialog to use the Task Dialog.aspx) that is available in Windows Vista and later:

image

The above is a screenshot raised from the following code:

Debug.Assert(false, "Example failure here", "Some extra information that I added");

The dialog works by disabling DefaultTraceListener.aspx)’s AssertUiEnabled property, and then registering its own trace listener that displays the improved assertion dialog.

I’m not sure whether we would be happy to have this in the VF# repo, hence me raising an issue before I go through the effort of merging it in 😄

Updated 29/04/2017 12:45 9 Comments

Fork me on GitHub