Create an Array from list of objects in MaxScript and add them to a new layer - select

I'm super new to Maxscript and want to automate a process, I've been looking at some tutorials, but I'm running into a issue with selection. What I'm trying to do, is I have a list of strings (that I might have to add to) that represent objects in the max file that I want to select (if they exist in that file) and then add to a new layer.
for instance:
/* I have a big long list of objects I want to mass select, this has to be hardcoded because its a similar list that exists in a ton of max files */
rObj1 = "testObj1"
rObj2 = "sampleObj2"
""
rObj99 = "newObj90"
/*I want to then add it to an array
removeList = #(rObj***)
/* Then run through each entry in the array to make sure it exists and then add it to my selection
for i in removeList do
(
if i != undefined then select (i)
)
/*Then Add what I have selected to a new layer
newLayer = LayerManager.newLayerFromName "removed_list"
for obj in selection do newLayer.addNode obj
I keep getting an error when it comes to selection, being new to Max I'm not sure what to do.

You are trying to select string where you should be selecting (or adding to the layer) an object:
newLayer = LayerManager.newLayerFromName "removed_list"
for objName in removeList where isValidNode (getNodeByName objName) do
newLayer.addNode (getNodeByName objName)

Related

How can I create a function that automatically takes data from Google Sheets and replaces the tags in a Slides template?

I am new to Google Apps Script and coding in general and wasn't entirely sure how to do this. I want to create code that allows me to create a new set of Google Slides based on a Slides template using the relevant rows from a Google Sheets document.
function generateNewSlides() {
var wsID = "would insert worksheet URL ID here";
var ws = SpreadsheetApp.openById(wsID).getSheetByName("Data");
var data = ws.getRange(2, 1, ws.getLastRow()-1, 5).getValues();
>the above should get the relevant table from the sheet
data.forEach(function(info){
if(info[0]){
var firstname = info[0];
var surname = info[1];
var email = info[2];
var phone = info[3];
var image = info[4];
var presName = info[5];
>the above are columns where the different pieces of data would be taken from for the placeholders in the Slides template
var slidesTemplateID = "would insert slides template URL ID here";
var slidesTemplate = SlidesApp.openById(slidesTemplateID);
var template = slidesTemplate.getSlides();
var folderID = "would insert desired folder ID for saving in here";
>the above should get me the Slides template
template.makeCopy(presName,DriveApp.getFolderById(folderID)); **>line where error occurred**
var newPresentation = DriveApp.getFilesByName(presName).next().getUrl();
var Presentation = SlidesApp.openByUrl(newPresentation);
>the above should create a copy and then open it
var shapes = (Presentation.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{firstname}}',firstname);
shape.getText().replaceAllText('{{surname}}',surname);
shape.getText().replaceAllText('{{email}}',email);
shape.getText().replaceAllText('{{phone}}',phone);
shape.getText().replaceAllText('{{presname}}', presName)
});
>the above should replace all the placeholder tags in the template with the row data
}
});
}
Above is the code I have so far. The worksheet I am extracting data from has columns: first name, surname, email address, phone number, image (URL), and presentation name. When I try to run it I encounter an error on line 37 where it says template.makeCopy is not a function, however I am certain .makeCopy should be able to create a copy for it, no?
My main questions are:
1) What should I change to make it work, generating a new set slides for each row in the worksheet?
2) How can I add images to it replacing placeholder tags I've added in squares (not textboxes) in the template?
Thanks in advance!
Issue 1. makeCopy:
makeCopy(name, destination) is a method of the class File, which belongs to the Drive Service, not to the Slides Service. In your code, template is a list of Slides (you retrieve it by calling the method getSlides() from a Presentation). makeCopy cannot work here.
In order to make a copy of a Presentation, you should be using the Drive Service instead. You should replace these lines:
var slidesTemplate = SlidesApp.openById(slidesTemplateID);
var template = slidesTemplate.getSlides();
With this one:
var template = DriveApp.getFileById(slidesTemplateID);
Issue 2. Iterating through all shapes:
Next, you want to iterate through all shapes in your Presentation, and replace all placeholder tags with your desired text. In order to do that, you are using Presentation.getShapes(), which cannot work, since getShapes() is not a method of Presentation, but of Slide.
You should first iterate through all Slides in the Presentation, and for each Slide, iterate through all Shapes. You should replace these lines:
var shapes = (Presentation.getShapes());
shapes.forEach(function(shape){
// Replacing text lines
});
With these ones:
Presentation.getSlides().forEach(function(slide) {
slide.getShapes().forEach(function(shape) {
// Replacing text lines
})
});
Note:
In order to retrieve the copied presentation, you are currently doing this:
template.makeCopy(presName,DriveApp.getFolderById(folderID));
var newPresentation = DriveApp.getFilesByName(presName).next().getUrl();
var Presentation = SlidesApp.openByUrl(newPresentation);
There is no need to do this, you can just retrieve the ID of the created template, and open by ID, like this:
var copiedTemplate = template.makeCopy(presName,DriveApp.getFolderById(folderID));
var Presentation = SlidesApp.openById(copiedTemplate.getId());
Reference:
Slides Service
Drive Service

Get all outging connectors from a shape programmatically

I want to rename a connector after a shape has been dropped.
Lets say I have a shape1 and I dropped a shape2 connected with shape1.
I want the connector shape between shape1 and shape2 so that I can rename it.
I guess it depends on what stage you intercept the drop. If it's immediately, you might make some assumptions about how many connectors might be involved, but if if some time after the drop then you might want to determine how many connections are involved.
As an example, with the following shapes:
...you could approach this in a number of ways:
Use the GluedShapes method working back from ShapeTwo
Use the GluedShapes method including the 'from' shape
Iterate through the Connects collection of the Page
Iterate over the Connect objects in on your target shape (ShapeOne)
I would definitely try and use the GluedShapes method (which came into Visio in 2010) over the Connect objects, but I'm adding them here as they can be useful depending on what you're trying to achieve.
Here's an example using LINQPad:
void Main()
{
var vApp = MyExtensions.GetRunningVisio();
var vPag = vApp.ActivePage;
//For demo purposes I'm assuming the following shape IDs
//but in reality you'd get a reference by other methods
//such as Window.Selection, Page index or ID
var shpOne = vPag.Shapes.ItemFromID[1];
var shpTwo = vPag.Shapes.ItemFromID[2];
Array gluedIds;
Console.WriteLine("1) using GluedShapes with the 'to' shape only");
gluedIds = shpTwo.GluedShapes(Visio.VisGluedShapesFlags.visGluedShapesIncoming1D,"");
IterateByIds(vPag, gluedIds);
Console.WriteLine("\n2) using GluedShapes with the 'to' and 'from' shapes");
gluedIds = shpTwo.GluedShapes(Visio.VisGluedShapesFlags.visGluedShapesIncoming1D, "", shpOne);
IterateByIds(vPag, gluedIds);
Console.WriteLine("\n3) using the Connects collection on Page");
var pageConns = from c in vPag.Connects.Cast<Visio.Connect>()
where c.FromSheet.OneD != 0
group c by c.FromSheet into connectPair
where connectPair.Any(p => p.ToSheet.ID == shpOne.ID) && connectPair.Any(p => p.ToSheet.ID == shpTwo.ID)
select connectPair.Key.Text;
pageConns.Dump();
Console.WriteLine("\n4) using FromConnects and Linq to navigate from shpOne to shpTwo finding the connector in the middle");
var shpConns = from c in shpOne.FromConnects.Cast<Visio.Connect>()
where c.FromSheet.OneD != 0
let targetConnector = c.FromSheet
from c2 in targetConnector.Connects.Cast<Visio.Connect>()
where c2.ToSheet.Equals(shpTwo)
select targetConnector.Text;
shpConns.Dump();
}
private void IterateByIds(Visio.Page hostPage, Array shpIds)
{
if (shpIds.Length > 0)
{
for (int i = 0; i < shpIds.Length; i++)
{
//Report on the shape text (or change it as required)
Console.WriteLine(hostPage.Shapes.ItemFromID[(int)shpIds.GetValue(i)].Text);
}
}
}
Running the above will result in this output:
It's worth bearing in mind that the Connects code (3 and 4) makes the assumption that connector shape (1D) are being connected to the flowchart shapes (2D) and not the other way round (which is possible).
You can think of the connect objects as being analgous to connection points, so in the diagram, the three connector shapes generate six connect objects:
Anyway, hope that gets you unstuck.
UPDATE - Just to be clear (and to answer the original question properly), the code to get all outgoing connectors from ShapeOne would be:
Console.WriteLine("using GluedShapes to report outgoing connectors");
gluedIds = shpOne.GluedShapes(Visio.VisGluedShapesFlags.visGluedShapesOutgoing1D, "");
IterateByIds(vPag, gluedIds);

Set object properties after setting the object

I've created a class with various properties in VB6.
The properties are
PiccoId
OrderId
UserId
StockCode
Quantity
At the top of the class I have declared 2 instances of classes I'm using.
Dim stkLine As CSOPSLine ' This is the class where the properties are declared and read
Private SOPSLines As cSLine ' This class creates the new objects and sets the property values
When the user enters the order number on a handheld barcode scanner, I'm creating an object to associate with this particular scanner like so:
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
In the next stage of the process, the user needs to enter their user ID so it can be seen which user scanned in the item.
I need to update the property of this same object, but I'm not sure how - Currently I am trying to do it within my getSOPSLine function, like this:
Dim line As New CSOPSLine
Dim bFound As Boolean
bFound = False
For Each line In SOPSLines.Items
If line.PiccoId = ID Then
line.OrderId = OrderId
line.Quantity = Qty
line.StockCode = stock
line.UserId = UserId
Set getSOPSLine = line
bFound = True
Exit For
End If
Next
If bFound = False Then
Set line = SOPSLines.Add(ID, OrderId, UserId, stock, Qty)
Set getSOPSLine = line
End If
Set line = Nothing
However, as I'm not storing sOrder at class level (Due to the fact multiple users can be using barcode scanners, the order ID can't be kept at class level as other users will just overwrite it),
I'm not sure how once I've got the next variable (In this case, userID, and the other variables after this stage) I can update the same object as I've just created.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
How can I update the properties of stkLine without constantly creating new objects?
EDIT
To clarify:
When the application receives data from the handheld barcode scanner, a select case is entered, with one case for each of the variables being entered (E.g. Order ID, user ID, stock code etc.)
The first case sets the order ID.
The code here is
Case FRAME_ORDER_SELECTION
On Error Resume Next
Dim sOrder As Long
sOrder = Picco.GetData(ID, 50)
If sOrder = 0 Then
Call Picco.Send(ID, FRAME_ORDER_SELECTION)
Exit Sub
Else
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== User ID =====")
Call .Text(ID, LINE_2, "")
Call .NewField(ID, 60, 5, FLD_LINE + SND_ENTER)
Call .Send(ID, FRAME_LINE_ADD)
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
End With
End If
frameid = FRAME_LINE_ADD
m_iLastFrameId = FRAME_ORDER_SELECTION
On Error GoTo Picco_DataArrived_Err
This is where the object is created.
The next case is after the user enters their user ID into the scanner.
Case FRAME_LINE_ADD
On Error Resume Next
Dim pUser As String
pUser = ""
pUser = Picco.GetData(ID, 60)
If pUser = "" Then
Exit Sub
End If
On Error GoTo Picco_DataArrived_Err
With Picco
Call .ClearForm(ID)
Call .Text(ID, LINE_1, "===== Add Line =====")
Call .Text(ID, LINE_2, "")
Call .Text(ID, LINE_7, "Scan or type code")
Call .NewField(ID, FIELD_POS, 18, FLD_LINE + FLD_READER + SND_ENTER)
Call .Send(ID, FRAME_LINE_QTY)
End With
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
frameid = FRAME_LINE_QTY
m_iLastFrameId = FRAME_LINE_ADD
Then there will be 2 or 3 more cases when populating the rest of the required values.
What I need to do, is in the second case (And all other following cases) update the properties of the object created in the first case.
I'm using the getSOPSLine function as this gets the object with the matching barcode scanner ID (As multiple users may be accessing different orders, they need to be kept separate in this way), but I'm not sure how to update the object where the scanner ID matches.
When you call getSOPSLine in each Case, enter some temporary values for the variables that you're not setting.
Example;
In the UserID case: stkLine = getSOPSLine(ID, 0, pUser, "", 0)
Then, in the getSOPSLine() function, change it so that instead of setting the values automatically, it instead only updates them if they don't equal 0, or "", or whichever temporary variables you use.
That way you're updating the same object, but aren't storing data that may get overwritten.
I'm not sure what you're confused about; I think that you must have some misunderstanding of what objects, variables, and properties are that is preventing you from asking this in a way that I understand. I'm not sure how your code lines up with your questions. But I'll give this a shot:
Private SOPSLines As cSLine
Set SOPSLines = New cSLine
Set SOPSLines = getSOPSLine(ID, sOrder, "", "", 0)
This declares a class-level variable, that can hold a cSLine object. That seems reasonable. Then you create a new instance of cSLine to put in that variable. But I don't know why, because you then point the variable to a different instance entirely, which is the instance returned from your getSOPSLine function. That middle line doesn't seem to be doing anything, and I'm not sure what you're trying to do with it.
I've tried to do something like
Set stkLine = getSOPSLine(ID, stkLine.OrderId, pUser, "", 0)
but it errors saying
object or with block variable has not been set
Well, then it sounds like stkLine isn't set to an object. I don't see any code that's trying to set stkLine other than that line. So when you try to get stkLine.OrderId, there isn't an object to get the OrderID property of, so it gives you an error.
I need to update the property of this same object, but I'm not sure how
Well, if there's an object you care about, you probably have it in a variable somewhere. You use variable.property = value syntax to assign value to the property of the object currently stored in variable.
But again, I'm not sure where your confusion is, since you're clearly assigning properties of objects in your code already.
If you're not understanding how objects work in VB, I'd recommend reading through the Working with Objects chapter of the documentation.
And if your confusion lies elsewhere, perhaps you could put together a more specific question about what you're trying to do?

Adding columns to a Web2py table in a form

In my web2py application, in the controller I read from an external DB the names of students I want to take a register for. I loop through the resulting list adding the list elements to a new list.
for student in pupils_query:
attendance_list.insert(counter, [student[0], student[1], student[2], student[3]])
counter += 1
counter = 0
Then for each student I read their attendance codes for the day so far from another table, and append them to attendance_list:
for attendance_code in attendance_result:
attendance_list[counter].append(attendance_code)
Now, I'm going to want to make a form from all this, using a table which will show each students' attendance code in a text input (so they can be updated if wrong), then have a dropdown for input of the current lesson code.
I'm using a FORM and TABLE helper to create the table in the form:
form=FORM(TABLE(*[TR(*rows) for rows in attendance_list]))
but can't seem to be able to add a new 'row' form item with something like:
select = "SELECT("+ main_reg_list +")"
attendance_list[counter].append(select)
where main_reg_list is dictionary of acceptable attendance codes (or of course, any other form input element).
In summary, I'm stuck adding new TDs to a table made with a TABLE helper from a list of lists. I bet I'm not the first person to overcome this problem.
I am still not clear about what you want. I think you want table of student information and in one column you want dropdown. Something similat to following image
Above form is created from following code.
I hope following code will help you:
# controller/default.py
def index():
# Dummy attendance list, list after appending attendance code
attendance_list = [['stud_id_1', 'first_name_1', 'last_name_1', 'attendance_code_1'],
['stud_id_2', 'first_name_2', 'last_name_2', 'attendance_code_2'],
['stud_id_3', 'first_name_3', 'last_name_3', 'attendance_code_5'],
['stud_id_4', 'first_name_4', 'last_name_4', 'attendance_code_4']]
possible_att_code = ['attendance_code_1', 'attendance_code_2', 'attendance_code_3', 'attendance_code_4', 'attendance_code_5']
# initialise form_rows with Table heading
form_rows = [THEAD(TR(TH('ID'), TH('First Name'), TH('Last Name'), TH('Attendence Code')))]
for attendance in attendance_list:
attendance_code_dropdown = _get_dropdown(attendance[0], attendance[3], possible_att_code)
td_list = [TD(attendance[0]), TD(attendance[1]), TD(attendance[2]),
TD(attendance_code_dropdown)]
table_row = TR(td_list, _id='row_' + attendance[0])
form_rows.append(table_row)
# Form submit button
form_rows.append(TR(INPUT(_type='submit')))
form = FORM(TABLE(*form_rows), _name='student_attendance',
_id='student_attendance')
if form.accepts(request, session):
# Write code to update record
pass
return dict(form=form)
def _get_dropdown(stud_id, att_code, possible_att_code):
option_list = []
for pac in possible_att_code:
if pac == att_code:
option_list.append(OPTION(pac, _value=pac, _selected='selected'))
else:
option_list.append(OPTION(pac, _value=pac))
return SELECT(*option_list, _name=stud_id)
<!-- views/default/index.html -->
{{extend 'layout.html'}}
{{=form}}
Are my assumptions correct? or you want any thing else? Comment if didn't understood code.

OpenXml: Copy OpenXmlElement between documents

I have two Word documents (WordprocessingDocument), and I want to replace the contents of an element in the first with the contents in the body of the second one.
This is what I'm doing right now:
var docA = WordprocessingDocument.Open(docAPath, true);
var docB = WordprocessingDocument.Open(docBPath, true);
var containerElement = docA.MainDocumentPart.Document.Body
.Descendants<SdtBlock>()
.FirstOrDefault(sdt => sdt.SdtProperties.Descendants<SdtAlias>().Any(alias => alias.Val == containerElementName))
.SdtContentBlock;
var elementsToCopy = docB.MainDocument.Part.Document.Body.ChildElements.Where(e => e.LocalName != "sectPr"));
containerElement.RemoveAllChildren();
containerElement.Append(elementsToCopy);
Basically I get the container (an SdtBlock) from the first document using its alias to identify it, then get all the children of the second element (removing the SectionProperties which I don't want to copy) and then try to add those to the container element.
The problem is that I'm getting this exception:
Cannot insert the OpenXmlElement "newChild" because it is part of a tree.
When I invoke the last line on that code (the Append).
Any ideas on how can I achieve what I want?
You need to clone the element to copy containerElement.Append(elementsToCopy.CloneNode(true));
The elementsToCopy is still attached to it's original tree. So you would have to remove it's parents or copy them( to keep the original intact). I think there exists a removeParent() method.