How do I align multiple views across multiple axes in SwiftUI? - layout

How do I lay out the following in SwiftUI?
The two circles are centre aligned horizontally along the blue line, and the top circle is vertically aligned with its rectangle along the green line, with the bottom circle vertically aligned with the bottom rectangle along the red line.
There’s no nested HStack/VStack structure that can describe this. We think the solution has something to do with custom alignment guides, but all of the examples we could find stop short of this level of complexity.

It feels like your best bet in this situation would be to use a LazyVGrid. There's a tendency to think of grids being used for collections where we might have long lists of items, but they also work for a known, finite number of children, so I think they'd work here.
In essence, you have two columns of items – both can be flexible to a degree, but it sounds like your column of rectangles needs to expand more. So you could start off by trying something like:
let columns = [
GridItem(.flexible(maximum: 120)),
GridItem(.flexible())
]
var body: some View {
LazyVGrid(columns: columns) {
// row 1, column 1
RoundedRectangle(cornerRadius: 10)
.frame(width: 100, height: 160)
// row 1, column 2
Text("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque tincidunt enim in iaculis tincidunt. Nunc vitae imperdiet dolor")
// row 2, column 1
Circle()
.frame(height: 100)
// row 2, column 2
Text("Integer vitae volutpat urna. Morbi vel pharetra dolor. Interdum et malesuada fames ac ante ipsum primis in faucibus. Mauris ornare a augue id cursus")
}
}
The code above gives you something like:
I've not had the opportunity to use grids in this way myself yet, so haven't played around with all the customisation they offer, but it does feel like this might be the best way to get you what you want without worrying about alignment guides or preferences.

Related

Apache POI: autoSizeColumn() with text rotation and wrap text

I'm using a prepared .xlsx file and edit it programatically. This is the original:
In my code, I autosize the column:
XSSFSheet sheet = workbook.getSheetAt(0);
sheet.getColumnStyle(COLUMN_H).setWrapText(true);
System.out.println("COL " + sheet.getColumnStyle(COLUMN_H).getWrapText()); // it's 'true'
sheet.autoSizeColumn(COLUMN_H);
The end result looks like this:
I hoped the column would shrink just enough to show all the lines of the text.
I'm using version 5.2.2 of the POI library.
Is this not what autosize does? Is there a way to calculate the prefered width of the column and set it explicitely?
When I double click on the border right of column H, the width is set as expected.
Yes, this is how Sheet.autoSizeColumn works up to now. It cannot do the same as Excel's GUI can do, simply because it does not have the same resources and possibilities. Excel's GUI runs as desktop application and so has access to the full memory and graphical system. Apache POI only has access to the memory which the Java JRE got and the data which is stored in the Excel file. That's not enough to do the same things, the Excel GUI can do.
To be able to auto-size the width of Excel cells the program must know the font metrics and the text content in rich text format for each cell in the column to calculate the needed width for the text. This is what Apache POI tries up to now. And this is expensive enough when you see how much time Sheet.autoSizeColumn consumes only for a little amount of rows. In addition, this needs access to fonts and GUI-classes such as Java AWT for example. This is currently already causing problems in some server-systems.
To be able additional considering the wrap-text case without having explicit line breaks in the text or when text is rotated too, the row heights for each row in the column also needs to be known. Apache POI does not take this into account until now. That's why Sheet.autoSizeColumn can only work correctly when there are explicit line breaks in the text and when the text is not rotated.
The following complete example shows this.
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.util.SheetUtil;
public class ExcelAutoSizeColumn {
public static void main(String args[]) throws Exception {
//String testString = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.";
String testString =
"Lorem ipsum dolor sit amet,\n"
+"consetetur sadipscing elitr,\n"
+"sed diam nonumy eirmod tempor \n"
+"invidunt ut labore et dolore \n"
+"magna aliquyam erat,\n"
+"sed diam voluptua. At vero eos \n"
+"et accusam et justo duo dolores \n"
+"et ea rebum. Stet clita kasd gubergren,\n"
+"no sea takimata sanctus est Lorem\n"
+"ipsum dolor sit amet.";
String filePath = "./Excel.xlsx";
String fontName = "Calibri";
short fontSize = 11;
//short rotation = 0;
//short rowHeight = -1; //-1 for auto height
short rotation = 90;
short rowHeight = 180*20;
boolean italic = false;
boolean bold = false;
try ( Workbook workbook = new XSSFWorkbook();
java.io.FileOutputStream out = new java.io.FileOutputStream(filePath)) {
Font font = workbook.createFont();
font.setFontHeightInPoints(fontSize);
font.setFontName(fontName);
font.setItalic(italic);
font.setBold(bold);
CellStyle style = workbook.createCellStyle();
style.setFont(font);
style.setWrapText(true);
style.setRotation(rotation);
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(0);
row.setHeight(rowHeight);
Cell cell = row.createCell(0);
cell.setCellValue(testString);
cell.setCellStyle(style);
double width = SheetUtil.getColumnWidth(sheet, 0, true);
System.out.println(width);
sheet.autoSizeColumn(0, true);
workbook.write(out);
}
}
}
You could file a bug report about this in https://bz.apache.org/bugzilla/buglist.cgi?list_id=201224&product=POI. But I doubt it will be fixed soon, because it will increase the time consuming of that method very much.

Connecting a function to a pyqt5 QTextEdit that was created and added to a QTableWidget inside a loop

I am currently creating an application that helps analyse chat logs that have two participants. A bot and a customer.
My goal is to add a QTableWidget that has QTextEdit elements in it to my application's main window. The user can then select the text inside those QTextEdits. Once selected, the text background color of the selected text should be changed.
example:
Suspendisse suscipit, tellus ut varius aliquam, tortor enim placerat sem, sit amet porta eros tellus ultrices risus.
The user double clicks and selects "tellus ut varius" from the above text. The background color is now changed. If they select those words again, the change is reverted.
I am using this solution to add the QTextEdits to the QTableWidget:
How to put a TextEdit inside a cell in QTableWidget - Pyqt5?
The table is populated inside the following loop:
def populate_chat(self):
self.chat.setColumnCount(1)
self.chat.setRowCount(len(example_chat_list))
for idx, message in enumerate(example_chat_list):
oname1, oname2 = 'chat_bubble_bot', 'chat_bubble_customer'
if idx % 2 == 0:
combo = TextEdit(self, objectName=oname1)
else:
combo = TextEdit(self, objectName=oname2)
self.chat.setCellWidget(idx, 0, combo)
combo.setText(message)
combo.cursorPositionChanged.connect(self.test)
combo.textChanged.connect(
lambda idx=idx: self.chat.resizeRowToContents(idx))
self.chat.installEventFilter(self)
The goal is to have this function change the text background:
def test(self):
cursor = self.exampleelement.textCursor()
current_color = cursor.charFormat().background().color().rgb()
format = QTextCharFormat()
if cursor.hasSelection() and current_color != 4294901760:
format.setBackground(Qt.red)
else:
format.setBackground(QColor(70, 70, 70))
cursor.setCharFormat(format)
I am having trouble referring to the QTextEdit element (exampleelement in the code block) when calling the test function.
The chat bubbles for the participants are styled differently in a separate stylesheet where they are referred to by name. That is why I have kept the names of the objects different for the participants. I have also tried enumerating the names like chat_bubble_customer0. chat_bubble_customer1 and so on, but was still unsuccessful in transferring the name of the element over to the test function.

Dynamically create animation for showing text

I'm currently trying to dynamically create an animation and playing it to show text based on the length of the text and the set speed of characters per second.
What I'm trying to recreate in code is this animation:
So an animation with a property track on the label's property visible_characters with update mode on continuous and interpolation mode on linear
Structure of the scene is:
The script behind the DialogBox node:
extends Control
export(String, MULTILINE) var Text = ""
export(int) var CharactersPerSecond = 100
func _ready():
$Panel/Label.set_text(Text)
print($Panel/Label.get_text())
createAnimation()
$AnimationPlayer.play("show-text")
print("is playing " + str($AnimationPlayer.is_playing()))
print("current animation " + $AnimationPlayer.current_animation)
func createAnimation():
var animationLength = Text.length() / (CharactersPerSecond as float)
print(animationLength)
var animation = $AnimationPlayer.get_animation("show-text")
animation.clear()
var trackIdx = animation.add_track(Animation.TYPE_VALUE)
animation.track_set_path(trackIdx, "Panel/Label:visible_characters")
animation.track_set_interpolation_type(trackIdx,Animation.INTERPOLATION_LINEAR)
animation.value_track_set_update_mode(trackIdx, Animation.UPDATE_CONTINUOUS)
animation.track_insert_key(trackIdx, 0, 0)
animation.track_insert_key(trackIdx, animationLength, Text.length())
For testing purposes the text is being set in the editor using the exported Text variable and is some lorem ipsum.
What happens when I run the scene is that the Panel and Label get shown but no text is shown in the Label, it stays empty, but according the print statements the show-text animation is playing
The printed data in the output window is:
** Debug Process Started **
Godot Engine v3.1.2.stable.mono.official - https://godotengine.org
OpenGL ES 3.0 Renderer: AMD Radeon R7 200 Series
label text: Magnam consequatur vel alias earum accusantium. Nobis voluptatem voluptatem quaerat adipisci voluptas. Numquam id error earum consectetur veniam. Quaerat quibusdam quas sunt alias et blanditiis corporis. Cupiditate rem ut natus est molestiae quidem. Magnam consequatur vel alias earum accusantium. Nobis voluptatem voluptatem quaerat adipisci voluptas. Numquam id error earum consectetur veniam. Quaerat quibusdam quas sunt alias et blanditiis
animationlength: 4.44
is playing: True
current animation: show-text
** Debug Process Stopped **
so the problem was that i still needed to set the length of the animation
just inserting the keys wasn't enough
adding the following line after animation.clear() fixed it:
animation.set_length(animationLength)

Vertical alignment in kableextra

I am having some trouble aligning results in Kableextra.
---
title: "Report test 1"
author: "Adam"
date: "May 9, 2019"
output: pdf_document
---
COLLEGE: College of Education
DEPARTMENT: Office of Assessment and Accreditation
SEMESTER: Fall 2018
SECTION 1: Please provide the mean and frequency distribution of the two required questions for all Traditional Delivery Courses. NOTE: The MEAN and N is required. The Frequency is optional.
x<-c(45,2,8,10,32,33)
y<-c(2,3,3,3,3,3)
EDLP_D.1<-cbind(x,y)
colnames(EDLP_D.1)<- c("Sheet", "Please indicate your level of satisfaction with the availability of the instructor outside the classroom. (In selecting your rating, consider the instructor's availability via established office hours, appointments, and opportunities for face-to-face interaction as well and as via telephones, e-mail, fax, and other means")
#function to compute values needed for table
vec_fun4 <- function(x,y){
Vec <-c(colnames(x[,y]),round(mean(x[[y]]),2),length(which(!is.na(x[,y]==F))),length(which(x[,y]==1)),length(which(x[,y]==2)),length(which(x[,y]==3)),length(which(x[,y]==4)))
return(Vec)
}
#Switch from long format to wide format
item2.1 <- as.data.frame(t(as.matrix(vec_fun4(EDLP_D.1,1))))
#Make table
library(kableExtra)
kable(item2.1,"latex" ,booktabs=T, align = "lcccccc", col.names=linebreak(c(' ','Mean','\\textit{N}' ,'Strongly\n Disagree','Disagree','Agree','Strongly\n Agree')),row.names = F,escape=F) %>%
column_spec(1, width = "20em" )
I would like to have the numeric values centered horizontally and vertically within their cells.
I have attached a copy of the table here
I don't have enough points to leave a comment. I am having the same issue, did you ever figure this out?
You can try this function to center the text:
centerText <- function(text){
paste0("\\multirow{1}{*}[0pt]{", text, "}")
}
However, this may mess up your formatting such as column width and text wrap like it did mine. Please let me know if you found a better solution.
My solution is replace few latex script
example:
```{r results='asis'}
library(kableExtra)
library(dplyr)
library(stringr)
kable(
data.frame(
'x1' = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit voluptates ut quam delectus perferendis tempora, voluptas fuga deleniti asperiores ipsam ipsum nam animi sequi, nisi dicta, minus pariatur atque, nemo.',
'x2' = 11,
'x3' = 22,
'x4' = 33
),
# align = 'lccr',
# booktabs = T
col.names = c(' ','X2','X3' ,'X4'),
format = "latex"
) %>%
# column_spec(1, width = "20em") %>%
# column_spec(2:4, width = "5em") %>%
str_replace(
'(?<=\\\\begin\\{tabular\\}).+',
'{ >{\\\\raggedright\\\\arraybackslash}m{20em} >{\\\\centering\\\\arraybackslash}m{5em} >{\\\\centering\\\\arraybackslash}m{5em} >{\\\\raggedleft\\\\arraybackslash}m{5em} }'
) %>%
cat
```
ref: https://es.overleaf.com/learn/latex/Tables

GNUplot concatenate 2 macros in an xlabel

Is there a way to concatenate two string macros, each with a different font into a single xlabel?
xLabel1="Lorem ipsum dolor sit amet, consectetur adipiscing elit."
style1=" offset 0,2 font \"Gill Sans,12\""
xLabel2="\"A\" font \"Moon Phases,28\" offset 0,2"
label1="xLabel1 #style1"
label2="xLabel2"
bothLabels="#label1 #label2"
Both label1 and label2 work when used alone for the xlabel.
It's the last line that I cannot figure out; perhaps this cannot be done?
"A" in that font displays a full moon symbol.
I don't have any problem nesting more than one macro inside a string.
set macro
SET='set '
LABEL='label 1 #WHAT #WHERE'
WHAT="'bar' "
WHERE="at 0,1 front"
ALL=SET.LABEL
#ALL
show label
However, at this point, I would also recommend using eval and sprintf.

Resources