How do I adjust the left margin on parameters in ReSharper/VS2010? - visual-studio-2010

This is silly, but when I have something like this
SomethingStupid.Whatever(string a, string b, string c);
And then I break them off like this:
SomethingStupid.Whatever(string a,
string b,
string c);
My code cleanup moves them to that position, when I'd like to see them here:
SomethingStupid.Whatever(string a,
string b,
string c);
For the life of me I can't figure out where this setting exists, any ideas?

You need to change the setting at ReSharper -> Options -> C# -> Formatting Style -> Other -> Align Multiline Constructs -> Method Parameters. Enabling the option will line up you multiline method parameters with each other as you want.

Related

Concatenate 2 Enumerated type variable sets

enum sup;
sup=['a','b','c'];
enum sup2;
sup2=['d','e','f'];
enum sup3;
sup3=sup++sup2;
I want to get an new enumerated type sup3 with all a,b,c,d,e,f.Is there any way in minizinc we can do this.
The short answer is no, this is currently not supported. The main issue with the concatenation of enumerated types comes from the fact we are not just concatenating two lists of things, but we are combining types. Take your example:
enum sup = {A, B, C};
enum sup2 = {D, E, F};
enum sup3 = sup ++ sup2;
When I now write E somewhere in an expression, I no longer know if it has type sup2 or sup3. As you might imagine, there is no guarantee that E would have the same value (for the solver) in the two enumerated types, so this can be a big problem.
To shine a glimmer of hope, the MiniZinc team has been working on a similar approach to make this possible (but not yet formally announced). Instead of your syntax, one would write:
enum X = {A, B, C};
enum Y = {D, E, F} ++ F(X);
The idea behind this is that F(X) now gives a constructor for the usage of X in Y. This means that if we see just A, we know it's of type X, but if we see F(A), then it's of type Y. Again, this is not yet possible, but will hopefully end up in the language soon.
More of a comment but here is my example of my need. When doing code coverage and FSM transition analysis I am forced to use exclusion to not analyze some transitions for the return_to_state, in the code below. If instead I could use concatenated types as shown, I would have more control over the tools reporting missing transitions.
type Read_states is (ST1);
type Write_states is (ST2, ST3, ST4);
type SPI_states is (SPI_write);
type All_States is Read_states & Write_states & SPI_states;
I could make return_to_state of type Write_states and FRAM_state of type All_states and then not have to put in exclusions in my FSM analysis.

F# is unable to infer type arguments after annotation

So I have some json response content represented as string and I want to get its property names.
What I am doing
let properties = Newtonsoft.Json.Linq.JObject.Parse(responseContent).Properties()
let propertyNames, (jprop: JProperty) = properties.Select(jprop => jprop.Name);
According to this answer I needed to annotate the call to the extension method, however, I still get the error.
A unique overload for method 'Select' could not be determined based on type information prior to this program point. A type annotation may be needed. Candidates: (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,'TResult>) : Collections.Generic.IEnumerable<'TResult>, (extension) Collections.Generic.IEnumerable.Select<'TSource,'TResult>(selector: Func<'TSource,int,'TResult>) : Collections.Generic.IEnumerable<'TResult>
Am I doing something wrong?
First, the syntax x => y you're trying to use is C# syntax for lambda expressions, not F# syntax. In F#, the correct syntax for lambda-expressions is fun x -> y.
Second, the syntax let a, b = c means "destructure the pair". For example:
let pair = (42, "foo")
let a, b = pair // Here, a = 42 and b = "foo"
You can provide a type annotation for one of the pair elements:
let a, (b: string) = pair
But this won't have any effect on pair the way you apparently expect it to work.
In order to provide type annotation for the argument of a lambda expression, just annotate the argument, what could be simpler?
fun (x: string) -> y
So, putting all of the above together, this is how your line should look:
let propertyNames = properties.Select(fun (jprop: JProperty) -> jprop.Name)
(also, note the absence of semicolon at the end. F# doesn't require semicolons)
If you have this level of difficulty with basic syntax, I suggest you read up on F# and work your way through a few examples before trying to implement something complex.

How do I concisely write a || b where a and b are Optional values?

I'm happy with an answer in any language, but I ultimately want an answer in Java. (Java 8+ is fine. Not limited to Java 8. I've tried to fix the tags.)
If I have two Optional<Integer> values, how do I concisely compute the equivalent of a || b, meaning: a, if it's defined; otherwise b, if it's defined; otherwise empty()?
Optional<Integer> a = ...;
Optional<Integer> b = ...;
Optional<Integer> aOrB = a || b; // How to write this in Java 8+?
I know that I can write a.orElse(12), but what if the default "value" is also Optional?
Evidently, in C#, the operator ?? does what I want.
In java-9 you can follow any of these :
✓ Simply chain it using the or as :-
Optional<Integer> a, b, c, d; // initialized
Optional<Integer> opOr = a.or(() -> b).or(() -> c).or(() -> d);
implementation documented as -
If a value is present, returns an Optional describing the value,
otherwise returns an Optional produced by the supplying function.
✓ Alternatively as pointed out by #Holger, use the stream as:-
Optional<Integer> opOr = Stream.of(a, b, c, d).flatMap(Optional::stream).findFirst();
implementation documented as -
If a value is present, returns a sequential Stream containing only
that value, otherwise returns an empty Stream.
Optional<Integer> aOrB = a.isPresent() ? a : b;
In java-8 we don't have any solution to easy chain Optional objects, but you can try with:
Stream.of(a, b)
.filter(op -> op.isPresent())
.map(op -> op.get())
.findFirst();
In java9 you can do:
Optional<Integer> result = a.or(() -> b);
In java-8 if you want something close to the Optional::stream mechanic, you could do
Stream.of(a, b)
.flatMap(x ->
x.map(Stream::of)
.orElse(Stream.empty())
)
.findFirst()
Hi you can do something like this.
a.orElse(b.orElse(null));

c++ pointer assignment confusion

Consider this MCV example
class A
{
class B
{
public:
B();
~B();
};
public:
B* a, b, c;
A();
~A();
void foo();
};
A::foo()
{
a = b = c;
}
yields the following compilation error in Visual Studio 2015
Severity Code Description Project File Line Suppression State
Error C2679 binary '=': no operator found which takes a right-hand operand of type 'A::B *' (or there is no acceptable conversion)
Strangely if I declare a, b, and c as follows
B* a; B* b, B* c;
There is no compilation issue. Because the pointers are class type, am I required to provide an appropriate B operator=(B& poo) for the original declaration to work? Certainly I can do the following int x, y, z so why is the above generating a compiler error?
The correct answer here is, don't declare multiple variables on one line. It's a pointless character saving that saves nothing on semantics whatsoever and merely leads to confusion. Don't use the std::add_pointer_t thing and don't just add more stars.
This is an anachronism from C; the pointer asterisk (*) binds to the name, and not the type, yielding:
B* a;
B b;
B c;
A better, less error prone way to declare multiple raw pointers is this:
std::add_pointer_t<B> a, b, c;
If you only have access to C++11, you need to use the more verbose std::add_pointer<B>::type instead.
In some codebases you might also find named typedefs for commonly used pointer types, like so:
typedef B* BPtr;
BPtr a, b, c;
Which yields what you'd expect. You can still use that, mixing and matching with using and std::add_pointer.
Alternatively, you can put a star in front of every name. That's why some people write this as:
B *a, *b, *c;
I'd personally discourage that. As mentioned before, it's not really readable and quite error-prone.
However, this assumes that your variables should actually be of the same type, which isn't coincidental. An example of such coincidence could be two numeric values happening to be int-s, but with no relationship between them. This is more of a design decision, though, and I assume that if you're asking about a single-type, multiple-name declaration, you understand what it entails.
In the original declaration, a is of type B*, but b and c are of type B.
To make it work as a single declaration it should be
B* a, *b, *c;
IMHO I'd leave it as separate declarations if only to avoid the entire issue.

When to use Hold / ReleaseHold in Mathematica?

Example and background ( note the usage of Hold, ReleaseHold ):
The following code represents a static factory method to create a scenegraph object ( from an XML file ). The (output-)field is an instance of CScenegraph ( an OO-System class ).
new[imp_]:= Module[{
ret,
type = "TG",
record ={{0,0,0},"Root TG"}
},
ret = MathNew[
"CScenegraph",
2,
MathNew["CTransformationgroup",1,{type,record},0,0,0,0,Null]];
ret#setTree[ret];
ret#getRoot[]#setColref[ret];
csp = loadClass["CSphere"];
spheres = Cases[imp, XMLElement["sphere", _, __], Infinity];
codesp = Cases[spheres, XMLElement["sphere",
{"point" -> point_, "radius" -> rad_, "hue" -> hue_}, {}] -> Hold[csp#new[ToExpression[point], ToExpression[rad], ToExpression[hue]]]];
ret#addAschild[ret#getRoot[],ReleaseHold[codesp]];
ret
];
My question is about the following:
spheres = Cases[imp, XMLElement[\sphere\, _, __], Infinity];
codesp = Cases[spheres, XMLElement[\sphere\,
{\point\ -> point_, \radius\ -> rad_, \"hue\" -> hue_}, {}] -> Hold[csp#new[ToExpression[point], ToExpression[rad], ToExpression[hue]]]];
ret#addAschild[ret#getRoot[],ReleaseHold[codesp]];
where
addAschild
adds ( a list of ) geometries to a ( root ) transformationgroup and has the signature
addAsChild[parent MathObject, child MathObject], or
addAsChild[parent MathObject, Children List{MathObject, ...}]
and the XML element representing a sphere looks as follows:
<sphere point='{0., 1., 3.}'
radius='1'
hue='0.55' />
If I do NOT USE Hold[] , ReleaseHold[] I end up with objectdata like
{"GE", {"SP", {CScenegraph`point, CScenegraph`rad}}, {CScenegraph`hue}}
while I would have expected
{"GE", {"SP", {{4., 3., -4.}, 3.}}, {0.45}}
(The above code with Hold[], ReleaseHold[] yields the correct data.)
Questions
1. Why is Hold necessary in this case? ( In fact, is it? Is there a way to code this without Hold[], ReleaseHold[]? ) ( I got it right by trial and error! Don't really understand why. )
2. As a learning point: What is the prototypical example / case for the usage of Hold / ReleaseHold?
EDIT:
Summary of Leonid's answer. Change this code
codesp = Cases[spheres, XMLElement["sphere",
{"point" -> point_, "radius" -> rad_, "hue" -> hue_}, {}] -> Hold[csp#new[ToExpression[point], ToExpression[rad], ToExpression[hue]]]];
ret#addAschild[ret#getRoot[],ReleaseHold[codesp]];
to:
codesp = Cases[spheres, XMLElement["sphere",
{"point" -> point_, "radius" -> rad_, "hue" -> hue_}, {}] :> csp#new[ToExpression[point], ToExpression[rad], ToExpression[hue]]];
ret#addAschild[ret#getRoot[],codesp];
The short answer for the first question is that you probably should have used RuleDelayed rather than Rule, and then you don't need Hold-ReleaseHold.
It is hard to be sure what is going on since your code sample is not self-contained. One thing to be sure is that OO-System performs non-trivial manipulations with contexts, since it uses contexts as an encapsulation mechanism (which makes sense). Normally, Rule and RuleDelayed inject the matched expressions in the r.h.s., so it is not clear how this could happen. Here is one possible scenario (you may execute this in a notebook):
BeginPackage["Test`"]
f[{a_Symbol, b_Symbol}] := {c, d};
fn[input_] := Cases[input, XMLElement[{"a" -> a_, "b" -> b_}, {}, {}] -> f[{a, b}]];
fn1[input_] := Cases[input, XMLElement[{"a" -> a_, "b" -> b_}, {}, {}] :> f[{a, b}]];
EndPackage[];
$ContextPath = DeleteCases[$ContextPath, "Test`"]
Now,
In[71]:= Test`fn[{XMLElement[{"a"->1,"b"->2},{},{}],{"a"->3,"b"->4},{"a"->5,"b"->6}}]
Out[71]= {{Test`c,Test`d}}
What happened is that, since we used Rule in XMLElement[...]->rhs, the r.h.s. evaluates before the substitution takes place - in this case the function f evaluates. Now,
In[78]:= Test`fn1[{XMLElement[{"a" -> 1, "b" -> 2}, {}, {}],
{"a" ->3, "b" -> 4}, {"a" -> 5, "b" -> 6}}]
Out[78]= {Test`f[{1, 2}]}
The result is different here since the idiom XMLElement[...] :> rhs was used in implementation of fn1, involving RuleDelayed this time. Therefore, f[{a,b}] was not evaluated until a and b were substituted by the matching numbers from the l.h.s. And since f does not have a rule for the argument of the form of list of 2 numbers, it is returned.
The reason why your method with Hold-ReleaseHold worked is that this prevented the r.h.s. (function f in my example, and the call to new in your original one) from evaluation until the values for pattern variables have been substituted into it. As a side note, you may find it useful to add better error-checking to your constructor (if OO-System allows that), so that problems like this would be better diagnosed at run-time.
So, the bottom line: use RuleDelayed, not Rule.
To answer the second question, the combination ReleaseHold-Hold is generally useful when you want to manipulate the held code before you allow it to evaluate. For example:
In[82]:=
{a,b,c}={1,2,3};
ReleaseHold[Replace[Hold[{a,b,c}],s_Symbol:>Print[s^2],{2}]]
During evaluation of In[82]:= 1
During evaluation of In[82]:= 4
During evaluation of In[82]:= 9
Out[83]= {Null,Null,Null}
One can probably come up with more sensible examples. This is especially useful for things like code-generation - one less trivial example can be found here. The specific case at hand, as I already mentioned, does not really fall into the category of cases where Hold-ReleaseHold are beneficial - they are here just a workaround, which is not really necessary when you use delayed rules.

Resources