Is there a way to automatically align function arguments? - rstudio

In RStudio is there a way to automatically align the equal signs in function arguments?
Similar to the following:
objective = obj,
eta = params$eta[i],
gamma = params$gamma[i],
max_depth = params$max_depth[i],
colsample_bytree = params$colsample_bytree[i],
colsample_bylevel = params$colsample_bylevel[i],
lambda = params$lambda[i],
alpha = params$alpha[i],
subsample = params$subsample[i])
I find this much easier to read. If it is not available in RStudio is there a different editor which has this capability?

I found a solution in the AlignAssign RStudio addin: https://github.com/seasmith/AlignAssign

Another option is {remedy}, which is also on CRAN.
That package include addins for aligning equal signs = and assignments <-, plus other addins for working with markdown documents.

Related

Why does `cv2.threshold` only takes grayscale image?

I am working on some projects related to OpenCV and came across cv2.threshold function. Why does this function only take grayscale images only? Can anybody make this clear to me?
UPDATE:
See comments on this question instead of reading it.
I agree with #Cris as he said in the comments "nobody has found it useful to implement it for color images".
There are plenty of functions to achieve the same in much concise way which depend on your use-case.
But it's still a general curiousity question from a newcomer. So one easy approach for the same would be:
def bgr_threshold(src_bgr, thresh_bgr, maxval_bgr, type_bgr):
b, g, r = cv2.split(src_bgr)
thresh_b, thresh_g, thresh_r = thresh_bgr
maxval_b, maxval_g, maxval_r = maxval_bgr
type_b, type_g, type_r = type_bgr
ret_b, thresh_img_b = cv2.threshold(b, thresh_b, maxval_b, type_b)
ret_g, thresh_img_g = cv2.threshold(g, thresh_g, maxval_g, type_g)
ret_r, thresh_img_r = cv2.threshold(r, thresh_r, maxval_r, type_r)
thresh_img_bgr = cv2.merge((thresh_img_b, thresh_img_g, thresh_img_r))
return ((ret_b, ret_g, ret_r), thresh_img_bgr)
ret, th = bgr_threshold(image, (127, )*3, (255, )*3, (cv2.THRESH_BINARY, )*3)
Although this makes it take almost 3 times slower from optimisation point of view.

Terminal dashboard in golang using "termui"

I am working on drawing graphs on the terminal itself from inside a go code.I found this (https://github.com/gizak/termui) in golang. And used this(https://github.com/gizak/termui/blob/master/_example/gauge.go) to draw graph in my code.
Problem is this , as we can see in the code( https://github.com/gizak/termui/blob/master/_example/gauge.go ), they are passing g0,g1,g2,g3 all together in the end "termui.Render(g0, g1, g2, g3, g4)".
In my case I don't know how many gauges to draw before hand so I used a list to store gauge objects and then tried to pass list to render.
termui.Render(chartList...)
But it creates only one gauge.
This is how I am appending elements in the list.
for i := 0; i < 5; i++ {
g0 := termui.NewGauge()
g0.Percent = i
g0.Width = 50
g0.Height = 3
g0.BorderLabel = "Slim Gauge"
chartList = append(chartList, g0)
}
what I am getting is a gauge for i=4 only. when I am doing termui.Render(chartList...)
Am I doing something wrong?
PS - I have modified question based on the answer I got in this question.
Here is a good read on Variadic Functions
Take a look at the function signature of Render, https://github.com/gizak/termui/blob/master/render.go#L161
func Render(bs ...Bufferer) {
All you need to do is
termui.Render(chatList...)
assuming chartList is a []Bufferer
Edit
You are only seeing one because they are stacking on top of one-another. To see this add
g0.Height = 3
g0.Y = i * g0.Height // <-- add this line
g0.BorderLabel = "Slim Gauge"
From a quick review of the project, it appears there are ways for auto-arranging that have to do with creating rows (and probably columns). So you might want to explore that, or you will need to manually position your elements.

How to get the entire Visual Studio active document... with formatting

I know how to use VS Extensibility to get the entire active document's text. Unfortunately, that only gets me the text and doesn't give me the formatting, and I want that too.
I can, for example, get an IWpfTextView but once I get it, I'm not sure what to do with it. Are there examples of actually getting all the formatting from it? I'm only really interested in text foreground/background color, that's it.
Note: I need the formatted text on every edit, so unfortunately doing cut-and-paste using the clipboard is not an option.
Possibly the simplest method is to select all of the text and copy it to the clipboard. VS puts the rich text into the clipboard, so when you paste, elsewhere, you'll get the colors (assuming you handle rich text in your destination).
Here's my not-the-simplest solution. TL;DR: you can jump to the code at https://github.com/jimmylewis/GetVSTextViewFormattedTextSample.
The VS editor uses "classifications" to show segments of text which have special meaning. These classifications can then be formatted differently according to the language and user settings.
There's an API for getting the classifications in a document, but it didn't work for me. Or other people, apparently. But we can still get the classifications through an ITagAggregator<IClassificationTag>, as described in the preceding link, or right here:
[Import]
IViewTagAggregatorFactoryService tagAggregatorFactory = null;
// in some method...
var classificationAggregator = tagAggregatorFactory.CreateTagAggregator<IClassificationTag>(textView);
var wholeBufferSpan = new SnapshotSpan(textBuffer.CurrentSnapshot, 0, textBuffer.CurrentSnapshot.Length);
var tags = classificationAggregator.GetTags(wholeBufferSpan);
Armed with these, we can rebuild the document. It's important to note that some text is not classified, so you have to piece everything together in chunks.
It's also notable that at this point, we have no idea how any of these tags are formatted - i.e. the colors used during rendering. If you want to, you can define your own mapping from IClassificationType to a color of your choice. Or, we can ask VS for what it would do using an IClassificationFormatMap. Again, remember, this is affected by user settings, Light vs. Dark theme, etc.
Either way, it could look something like this:
// Magic sauce pt1: See the example repo for an RTFStringBuilder I threw together.
RTFStringBuilder sb = new RTFStringBuilder();
var wholeBufferSpan = new SnapshotSpan(textBuffer.CurrentSnapshot, 0, textBuffer.CurrentSnapshot.Length);
// Magic sauce pt2: see the example repo, but it's basically just
// mapping the spans from the snippet above with the formatting settings
// from the IClassificationFormatMap.
var textSpans = GetTextSpansWithFormatting(textBuffer);
int currentPos = 0;
var formattedSpanEnumerator = textSpans.GetEnumerator();
while (currentPos < wholeBufferSpan.Length && formattedSpanEnumerator.MoveNext())
{
var spanToFormat = formattedSpanEnumerator.Current;
if (currentPos < spanToFormat.Span.Start)
{
int unformattedLength = spanToFormat.Span.Start - currentPos;
SnapshotSpan unformattedSpan = new SnapshotSpan(textBuffer.CurrentSnapshot, currentPos, unformattedLength);
sb.AppendText(unformattedSpan.GetText(), System.Drawing.Color.Black);
}
System.Drawing.Color textColor = GetTextColor(spanToFormat.Formatting.ForegroundBrush);
sb.AppendText(spanToFormat.Span.GetText(), textColor);
currentPos = spanToFormat.Span.End;
}
if (currentPos < wholeBufferSpan.Length)
{
// append any remaining unformatted text
SnapshotSpan unformattedSpan = new SnapshotSpan(textBuffer.CurrentSnapshot, currentPos, wholeBufferSpan.Length - currentPos);
sb.AppendText(unformattedSpan.GetText(), System.Drawing.Color.Black);
}
return sb.ToString();
Hope this helps with whatever you're doing. The example repo will ask if you you want the formatted text in the clipboard after each edit, but that was just a dirty way that I could test and see that it worked. It's annoying, but it was just a PoC.

How to visualize charts in Visual Studio and Azure ML through R script?

I have seen on various examples (even in Azure ML) that you are able to create appealing charts using R in Visual Studio (not R Studio!), but I have no clue how they did it. I am experienced with R, but if someone could point me in the right direction of how to visualize data sets in Visual Studio and Azure ML; I would really appreciate it.
Here is an example I would like to duplicate (in both Azure ML and Visual Studio): Visual studio chart
Image source: https://regmedia.co.uk/2016/03/09/r_vis_studio_plot.jpg?x=648&y=348&crop=1
You can install ggplot2 in your solution in the Visual Studio extension Open R (https://www.visualstudio.com/en-us/features/rtvs-vs.aspx) through this line of code and visualize it within the R Plot window in Visual Studio after creating your R-project:
install.packages('ggplot2', dep = TRUE)
library(ggplot2)
The reason I have «library(ggplot2)» is to check if the package got successfully installed, else you would get an error like this: Error in library(ggplot2) : there is no package called ‘ggplot2’
So if you don’t get that error; you should be good to go.
For your question about how to output charts; you simply have to populate the ggplot2 charts from a datasource, like in my example below (csv-file):
dataset1 <- read.csv("Adult Census Income Binary Classification dataset.csv", header = TRUE, sep = ",", quote = "", fill = TRUE, comment.char = "")
head(dataset1)
install.packages('ggplot2', dep = TRUE)
library(ggplot2)
names(dataset1) <- sub(pattern = ',', replacement = '.', x = names(dataset1))
foo = qplot(age, data = dataset1, geom = "histogram", fill = income, position = "dodge");
print(foo)
bar = qplot(age, data = dataset1, geom = "density", alpha = 1, fill = income);
print(bar)
Here you can see that I create two charts, one histogram and one density-chart.
In Azure ML, the same charts (this time I included a histogram for Relationships as well), would look like this:
// Map 1-based optional input ports to variables
dataset1 <- maml.mapInputPort(1) # class: data.frame
library(ggplot2)
library(data.table)
names(dataset1) <- sub(pattern=',', replacement='.', x=names(dataset1))
// This time we need to specify the X to be sex; which we didn’t need in Visual Studio
foo = qplot(x=sex, data=dataset1, geom="histogram", fill=income, position="dodge");
print(foo)
foo = qplot(x=relationship, data=dataset1, geom="histogram", fill=income, position="dodge");
print(foo)
foo = qplot(x=age, data=dataset1, geom="density", alpha=0.5, fill=income);
print(foo)
// Select data.frame to be sent to the output Dataset port maml.mapOutputPort("dataset1");
Remember to put all of this in a “Execute R Script module” in order to run it correctly. After that, you can right lick the module and visualize the result.
I believe you're referring to the R Tools for Visual Studio. These provide a means to develop and debug R code in the Visual Studio IDE, and can produce plots like the one you shared.
However, that plot looks like a pretty standard chart from the CRAN ggplot2 package, which means it could have been just as easily produced from R code running in the R console or RStudio.
This posting on the R-bloggers site should help get you started with ggplot2.
http://www.r-bloggers.com/basic-introduction-to-ggplot2/
Good luck, and enjoy!
jmp

MATLAB date selection popup calendar for gui

Does anyone know of a method to display a popup date selection calendar in a MATLAB gui? I know the financial toolbox has a uicalendar function, but unfortunately I don't have that toolbox.
I have a hunch I'm going to have to use some Java or some other language for this one, which I know nothing about.
I'm looking for something similar to this:
(source: welie.com)
which would return a date string after the user selects the date.
Here are two approaches that would give you a professional-looking calendar component in Matlab without too much programming work:
Use a Java calendar component (for example, one of these or these). Once you download the relevant Java class or Jar-file, add it to your static Java classpath (use the edit('classpath.txt') command from the Matlab Command Prompt). Finally, use the built-in javacomponent function to place the component in your Matlab figure window.
If you are using a Windows OS, you can embed any Active-X calendar control that is available. Use the built-in actxcontrolselect function to choose your favorite calendar control (for example, Microsoft Office's "Calendar Control 11.0" - MSCAL.Calendar.7 - which is automatically installed with Office 2003; or "Microsoft Date and Time Picker Control 6.0" - MSComCtl2.DTPicker.2, or ...). Then use the actxcontrol function to place the component in your Matlab figure window.
Matlab has some pretty useful built-in calendar (date-selection) controls - I posted an article about them today
I don't have much time for a more complete answer, unfortunately, but I'd try uitable to create a table and to define the CellSelectionCallback to get the date.
Here's a bit to get you started:
dates = calendar;
dates(~any(dates,2),:) = [];
fh = figure;
uh = uitable('parent',fh,'data',dates,'ColumnWidth',repmat({20},1,7),...
'ColumnName',{'S','M','T','W','T','F','S'});
I'd start with the calendar() function which outputs a matrix containing the calendar for any month. I assume you could combine this with a user-clickable interface to retrieve a specific date?
The following code is really ugly, but could help you get started...
WINDOW_WIDTH = 300;
WINDOW_HEIGHT = 200;
f= figure('Position',[300 300 WINDOW_WIDTH WINDOW_HEIGHT]);
NB_ROWS = 6;
NB_COLS = 7;
width = round(WINDOW_WIDTH/NB_COLS);
height = round(WINDOW_HEIGHT/NB_ROWS);
buttons = nan(NB_ROWS,NB_COLS);
dates = calendar();
for row = 1:NB_ROWS
for col = 1:NB_COLS
if dates(row,col) == 0
mydate = '';
else
mydate = sprintf('%i', dates(row,col));
end
buttons(row,col) = uicontrol('Style', 'PushButton', ...
'String', mydate, ...
'Position', [(col-1)*width (NB_ROWS - row)*height width height]);
end
end

Resources