Is it possible to configure resharper to chop all methods in a method chain
e.g.
var query = list.Where(x => true).Select(x => x);
becomes
var query = list
.Where(x => true)
.Select(x => x);
If not, then is it possible to configure resharper to ignore method chains when formatting? So I can chop the text manually without having to worry about resharper re-formatting it.
Unfortunately, there is no way to align .Where under list.
As for chopping, there is an option in ReSharper | Options -> Code Editing | C# | Formatting Style | Line Breaks and Wrapping -> Line Wrapping called Wrap chained method calls. If you set it to Chop always, it would chop, but it uses a slightly different formatting:
var query = list.Where(x => true)
.Select(x => x);
If you leave it to Chop if long (default value), then it wouldn't re-chop your code unless it would be very long (more than Right margin option, which is in the same option group mentioned above).
Related
Using ControlFlow in try_fold seems better than Option in this case where one need to use any value.
But it's not very pleasant to use ControlFlow in try_fold because this irrefutable pattern shown below:
let (Break(value) | Continue(value)) =
values
.iter()
.try_fold(0, |previous, ¤t| match (previous) {
0 => Continue(1),
1 => Continue(2),
_ => Break(3),
});
Is there a way to get rid of this irrefutable pattern while using ControlFlow and retrieving the value?
I have a NodeJS test in Jest which compares very long strings with lots of lines. In my real example this results from pretty-printed JSON but the simple example below illustrates the problem:
describe('Stuff', () => {
it('should make it clear where the diff is but does not', () => {
const str1 = 'Hellox\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nx\nworldx\nx\nx\nx\nx\nx\nx\nx\nx\nx\n'
const str2 = 'Hellox\nx\nx\nx\nx\nx\n123\nx\nx\nx\nx\nx\nx\nworldx\nx\nx\nx\nx\nx\nx\nx\nx\nx\n'
expect(str1).toEqual(str2)
})
})
When I run it, I get this:
● Stuff › should make it clear where the diff is but does not
expect(received).toEqual(expected) // deep equality
- Expected - 1
+ Received + 0
## -2,11 +2,10 ##
x
x
x
x
x
- 123
x
x
x
x
x
There's so many similar or identical lines either side of the diff that it's very difficult to figure out where the problem is. Is there a way I can control or expand the context or is it hard-coded as a 5-before, 5-after rule?
Not cleanly. There are options in jest-diff to set this:
https://github.com/facebook/jest/tree/main/packages/jest-diff#options
However, at the time of writing, these are not passed through from the jest config - there's an open feature request for that:
https://github.com/facebook/jest/issues/12576
Hence, there's no clean way to configure this. It is possible to simply edit the value in node_modules/jest-diff/build/normalizeDiffOptions.js which works but is nasty for obvious reasons.
I might be missing something but recently I came across a task to get last symbols according to some condition. For example I have a string: "this_is_separated_values_5". Now I want to extract 5 as Int.
Note: number of parts separated by _ is not defined.
If I would have a method takeRightWhile(f: Char => Boolean) on a string it would be trivial: takeRightWhile(ch => ch != '_'). Moreover it would be efficient: a straightforward implementation would actually involve finding the last index of _ and taking a substring while the use of this method would save first step and provide better average time complexity.
UPDATE: Guys, all the variations of str.reverse.takeWhile(_!='_').reverse are quite inefficient as you actually use additional O(n) space. If you want to implement method takeRightWhile efficiently you could iterate starting from the right, accumulating result in string builder of whatever else, and returning the result. I am asking about this kind of method, not implementation which was already described and declined in the question itself.
Question: Does this kind of method exist in scala standard library? If no, is there method combination from the standard library to achieve the same in minimum amount of lines?
Thanks in advance.
Possible solution:
str.reverse.takeWhile(_!='_').reverse
Update
You can go from right to left with following expression using foldRight:
str.toList.foldRight(List.empty[Char]) {
case (item, acc) => item::acc
}
Here you need to check condition and stop adding items after condition met. For this you can pass a flag to accumulated value:
val (_, list) = str.toList.foldRight((false, List.empty[Char])) {
case (item, (false, list)) if item!='_' => (false, item::list)
case (_, (_, list)) => (true, list)
}
val res = list.mkString.toInt
This solution is even more inefficient then solution with double reverse:
Implementation of foldRight uses combination of List reverse and foldLeft
You cannot break foldRight execution, so you need flag to skip all items after condition met
I'd go with this:
val s = "string_with_following_number_42"
s.split("_").reverse.head
// res:String = 42
This is a naive attempt and by no means optimized. What it does is splitting the String into an Array of Strings, reverses it and takes the first element. Note that, because the reversing happens after the splitting, the order of the characters is correct.
I am not exactly sure about the problem you are facing. My understanding is that you want have a string of format xxx_xxx_xx_...._xxx_123 and you want to extract the part at the end as Int.
import scala.util.Try
val yourStr = "xxx_xxx_xxx_xx...x_xxxxx_123"
val yourInt = yourStr.split('_').last.toInt
// But remember that the above is unsafe so you may want to take it as Option
val yourIntOpt = Try(yourStr.split('_').last.toInt).toOption
Or... lets say your requirement is to collect a right-suffix till some boolean condition remains true.
import scala.util.Try
val yourStr = "xxx_xxx_xxx_xx...x_xxxxx_123"
val rightSuffix = yourStr.reverse.takeWhile(c => c != '_').reverse
val yourInt = rightSuffix.toInt
// but above is unsafe so
val yourIntOpt = Try(righSuffix.toInt).toOption
Comment if your requirement is different from this.
You can use StringBuilder and lastIndexWhere.
val str = "this_is_separated_values_5"
val sb = new StringBuilder(str)
val lastIdx = sb.lastIndexWhere(ch => ch != '_')
val lastCh = str.charAt(lastIdx)
I'm writing a pretty-printer for a simple white-space sensitive language.
I like the Leijen pretty-printer library more than I like the Wadler library, but the Leijen library has one problem in my domain: any line break I insert may be overridden by the group construct, which may compress any line, which might change the semantics of the output.
I don't think I can implement an ungroupable line in the wl-pprint (although I'd love to be wrong).
Looking a bit at the wl-pprint-extras package, I don't think that even the exposed internal interface allows me to create a line which will not be squashed by group.
Do I just have to rely on the fact that I never use group, or do I have some better option?
Given that you want to be able to group and you also need to be able to ensure some lines aren't uninserted,
why don't we use the fact that the library designers encoded the semantics in the data type,
instead of in code. This fabulous decision makes it eminently re-engineerable.
The Doc data type encodes a line break using the constructor Line :: Bool -> Doc.
The Bool represents whether to omit a space when removing a line. (Lines indent when they're there.)
Let's replace the Bool:
data LineBehaviour = OmitSpace | AddSpace | Keep
data Doc = ...
...
Line !LineBehaviour -- not Bool any more
The beautiful thing about the semantics-as-data design is that if we replace
this Bool data with LineBehaviour data, functions that didn't use it but
passed it on unchanged don't need editing. Functions that look inside at what
the Bool is break with the change - we'll rewrite exactly the parts of the code
that need changing to support the new semantics by changing the data type where
the old semantics resided. The program won't compile until we've made all the
changes we should, while we won't need to touch a line of code that doesn't
depend on line break semantics. Hooray!
For example, renderPretty uses the Line constructor, but in the pattern Line _,
so we can leave that alone.
First, we need to replace Line True with Line OmitSpace, and Line False with Line AddSpace,
line = Line AddSpace
linebreak = Line OmitSpace
but perhaps we should add our own
hardline :: Doc
hardline = Line Keep
and we could perhaps do with a binary operator that uses it
infixr 5 <->
(<->) :: Doc -> Doc -> Doc
x <-> y = x <> hardline <> y
and the equvalent of the vertical seperator, which I can't think of a better name than very vertical separator:
vvsep,vvcat :: [Doc] -> Doc
vvsep = fold (<->)
vvcat = fold (<->)
The actual removing of lines happens in the group function. Everything can stay the same except:
flatten (Line break) = if break then Empty else Text 1 " "
should be changed to
flatten (Line OmitSpace) = Empty
flatten (Line AddSpace) = Text 1 " "
flatten (Line Keep) = Line Keep
That's it: I can't find anything else to change!
You do need to avoid group, yes. The library's designed to facilitate wrapping or not wrapping based on the width of the output that you specify.
Dependent on the syntax of language you're implementing, you should also be cautious about softline and softbreak and the </> and <//> operators that use them. There's no reason I can see that you can't use <$> and <$$> instead.
sep, fillSep, cat and fillCat all use group directly or indirectly (and have the indeterminate semantics/width-dependent line breaks you want to avoid). However, given the your purpose, I don't think you need them:
Use vsep or hsep instead of sep or fillSep.
Use hcat or vcat instead of cat or fillCat.
You could use a line like
import Text.PrettyPrint.Leijen hiding (group,softline,softbreak,
(</>),(<//>),
sep,fillSep,cat,fillCat)
to make sure you don't call these functions.
I can't think of a way to ensure that functions you do use don't call group somewhere along the line, but I think those are the ones to avoid.
I want to subscribe to an observable, but only run an action once until a different IObservable fires. Each time the other IObservable fires, I'd like to be resubscribed and run my action once. The following code should accomplish that:
Action<object> act = null;
act = _ => {
DoThis();
obj.Observable1.SkipUntil(obj.CompletedObservable).Take(1).Subscribe(act);
};
obj.Observable1.Take(1).Subscribe(act);
Is there a more proper way to do this with the Rx framework? If not, how could I wrap this pattern into an extension?
It seems that you want something like this:
first -----1------------2-------------3--4--------->
| | | |
second ---------A--B----------C-D-E-----------F---G->
| | |
final ---------A-------------C---------------F----- >
For this, a combination of SelectMany, Take, and TakeUntil should work. I would say:
var final = from f in first
from s in second.Take(1).TakeUntil(first)
select s;
The .Take(1) ensures that you only get the first item after the first (for 1, 2, and 4). The .TakeUntil(first) covers 3, so that F only gets passed once (to 4). If you have a nice name for this operation, it would be easy to wrap into a method taking the two observables as parameters.
I think I've got it:
obj
.CompletedObservable
.StartWith(/* value of suitable type for CompletedObservable */)
.Select(x => obj.Observable1.Take(1))
.Switch()
.Subscribe(x => DoThis());
Have you tried the following:
obj.CompletedObservable
.Select(_ => obj.Observable1.Next().First())
.Subscribe(_ => DoThis());