Modify selection to first element by Selection.SetElementIds - revit-api

I'm having trouble writing a script that lets med select the first element in my selection. This is useful for me because i select my correct Air Terminal from a schedule (where I can see the similar air-flow which I want to use) and use the command Create Similar from the selection. The trouble is that this command does not work when multiple elements are selected. Therefore, I want the first object from the list.
This is the code which I'm trying:
from Autodesk.Revit.UI.Selection.Selection import SetElementIds
from System.Collections.Generic import List
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
selection = [ doc.GetElement( elId ) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ]
sel=[]
for i in selection:
sel.append(i.Id)
uidoc.Selection.SetElementIds(List[ElementId](sel[0]))
That will return the following error message:
Exception : Microsoft.Scripting.ArgumentTypeException: expected int, got ElementId
OK, then I'll try to replace
uidoc.Selection.SetElementIds(List[ElementId](sel[0]))
with
uidoc.Selection.SetElementIds(List[ElementId](sel[0].IntegerValue))
This seems to work, but selection is not modified
I am just starting to write RPS-scripts, but I'm hoping someone will show me what am I doing wrong here even if it is very obvious.
Thank you.
Kyrre
EDIT:
Thank you Jeremy, for solving this for me! The trick was to generate a List, not a python list. .Add method is what I did not get.
Final code if someone is interested:
from Autodesk.Revit.UI.Selection.Selection import SetElementIds
from System.Collections.Generic import List
from Autodesk.Revit.DB import ElementId
uidoc = __revit__.ActiveUIDocument
doc = __revit__.ActiveUIDocument.Document
selection = [ doc.GetElement( elId ) for elId in __revit__.ActiveUIDocument.Selection.GetElementIds() ]
sel=[]
for i in selection:
sel.append(i.Id)
ids=List[ElementId](1)
ids.Add(sel[0])
uidoc.Selection.SetElementIds(ids)

SetElementIds takes a .NET ICollection<ElementId> argument, as you can see from the Revit API documentation.
Your statement calls the .NET List constructor that expects an integrer argument specifying the number N of elements to allovate space for: List[ElementId](N).
sel[0] is an ElementId, not an integer, which causes the first error.
sel[0].IntegerValue is a (very large and semi-arbitrary) integer number, so that causes no error. However, you are still leaving the List empty, unpopulated.
You should initialise the List for one single element and add that:
ids = List[ElementId](1)
ids.Add(sel[0])

Related

How do I autopopulate a tkinter table using a loop

I'm trying to auto-populate a tkinter table with the names of folders in a directory and details about their properties
grpdata_name = listdir(r"PATH")
grpdata_path = r"PATH\{}".format(grpdata_name[0])
grpdata_groupcount = -1
for x in grpdata_name :
grpdata_groupcount = grpdata_groupcount +1
grpdata_groupcurrent = 'grpdata_name{}{}{}'.format('[',grpdata_groupcount,']')
GUI_Table.insert(parent='',index='end',iid=0,text='',
values=('ID',grpdata_groupcurrent,'TIME CREATED','TIME MODIFIED','DEVICES'))
My current method is to change the selected element in a string. This creates a working cycle through each part of the string ( grpdata_name[0] , grpdata_name[1] etc)
I can't figure out how to use the contents of grpdata_groupcurrent as a variable, rather than a string.
This method isn't very efficient overall, so please let me know if there is a better way to do this.

Data appended to multiple dict values instead of one

driver_data_form = {
'forc_day_off':[],
'pref_day_off':[],
'pref_shift':{"day"+str(i):None for i in range(1,15)},
'route_data':[]
}
So I am creating the dict driver_data (seen below) by using driver_data_form (seen above)
driver_data = {str(i):driver_data_form for i in range(1,12)}
and accordingly populating it :
loop_list = [str(i) for i in range(1,13)]
1 for specific_driver in loop_list:
2 for driver in forced_day_off_data:
3 for day in driver:
4 if driver[day]=='1' and day != "driverid":
5 driver_data[specific_driver]['forc_day_off'].append(day)
forced_day_off_data looks like:
But for some reason, after the above loop is executed once (lines 2-5), and by placing a break point in line 2, I am getting all 11 values of my driver_data[forc_day_off] dictionary populated, instead of only the first one. It appears that the values of the first key are copied to all the rest of the values:
I debugged this piece of code many times and this behavior makes no sence to me? What could be causing this and how can I fix it?
The problem with your code is that python is using references to dicts and lists. When you do this
driver_data = {str(i):driver_data_form for i in range(1,12)}
It basically sets the same dict reference for all your keys so when you change one value you actually update for all the other keys since it's the same dict
For your code to work you need to do this:
driver_data = {str(i):{
'forc_day_off':[],
'pref_day_off':[],
'pref_shift':{"day"+str(j):None for j in range(1,15)},
'route_data':[]
} for i in range(1,12)}
This way you create a new dict for each element and you will update only the specific dict.
See this this link to better understand the difference.

Excel crash when typing open parenthesis

Here's one I don't understand.
Given this class module (stripped down to the bare minimum necessary to reproduce the crash):
VERSION 1.0 CLASS
BEGIN
MultiUse = -1 'True
END
Attribute VB_Name = "TestCrashClass"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False
Option Explicit
Public Function Init() As TestCrashClass
Attribute Init.VB_UserMemId = 0
Dim tcc As New TestCrashClass
Set Init = tcc
End Function
Public Property Get Data() As String
Data = "test data"
End Property
Can anyone tell me why Excel totally craps out when I type in this code:
Sub MakeExcelCrash()
With TestCrashClass(
At this point, I this lovely message:
Even if I type in a full procedure without the offending parentheses and then try to add them later, I get the same crash.
The only way I can get Excel not to crash is to copy/paste a set of () from somewhere else to this line of code.
Sub MakeExcelCrash()
With TestCrashClass()
Debug.Print .Data
End With
End Sub
If the Init() method has a parameter—even an optional one—it won't crash when the opening paren is typed.
I'm more curious about why this happens than ways around it; it doesn't actually come up that often in my code and when it does I can fix it with a change in approach, but I'm really frustrated that I don't know what's causing these crashes. So maybe someone who knows more about the inner working of VBA can explain it to me?
You don't even need the With block. Any attempt to type ( after the class name takes Excel down.
The problem is that you have the VB_PredeclaredId set to true and the default member is trying to return itself. When you attach a debugger to the dying Excel instance, you can see that the underlying issue is a stack overflow:
Unhandled exception at 0x0F06EC84 (VBE7.DLL) in EXCEL.EXE: 0xC00000FD:
Stack overflow (parameters: 0x00000001, 0x00212FFC).
When you type With TestCrashClass(, what happens is that VBA starts looking for an indexer on the default property, because Init() doesn't have any properties. For example, consider a Collection. You can use the default property's (Item) indexer like this:
Dim x As Collection
Set x = New Collection
x.Add 42
Debug.Print x(1) '<--indexed access via default member.
This is exactly equivalent to Debug.Print x.Items(1). This is where you start running into problems. Init() doesn't have parameters, so VBA starts drilling down through the default members to find the first one that has an indexer so IntelliSense can display the parameter list. It starts doing this:
x.[default].[default].[default].[default].[default]...
In your case, it's creating an infinite loop because [default] returns x. The same thing happens in the Collection code above (except it finds one):
Throw in the fact that you have a default instance, and the end result is something like this:
Private Sub Class_Initialize()
Class_Initialize
End Sub
As #TimWilliams points out, having a default member that returns an instance of the same class (or a class loop eg. ParentClass.ChildClass.ParentClass.ChildClass... where ParentClass and ChildClass both have default members), and when used in certain syntax cases, such as a With block, will cause VBE to try and resolve the default member.
The first parenthesis makes VBE assume there must be a method, indexed get or array index that will take an argument, so it sets off to resolve the ultimate target member.
So the incomplete line, with a cursor located after the parenthesis:
With TestCrashClass(
Is effectively the same as:
With TestCrashClass.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init.Init '....You're inquisitive scrolling this far over, but you get the point.
At some point, your system or VBE runs out of resources and exits with the grace and poise of a thermonuclear group-hug.
+1 for improvising with a copy/pasta of a parentheses pair.
Sounds like some sort of corruption. I've had Excel behave irrationally like this before, normally in large projects, and the only way to get around it is to drag all of your classes etc into a new project.
I suspect it happens because Excel doesn't truly delete classes, modules, worksheets etc that have been removed. You can tell this because of the file size.
There is no Compact and Repair functionality, as in Access, as far as i'm aware

Filtering Haystack (SOLR) results by django_id

With Django/Haystack/SOLR, I'd like to be able to restrict the result of a search to those records within a particular range of django_ids. Getting these IDs is not a problem, but trying to filter by them produces some unexpected effects. The code looks like this (extraneous code trimmed for clarity):
def view_results(request,arg):
# django_ids list is first calculated using arg...
sqs = SearchQuerySet().facet('example_facet') # STEP_1
sqs = sqs.filter(django_id__in=django_ids) # STEP_2
view = search_view_factory(
view_class=SearchView,
template='search/search-results.html',
searchqueryset=sqs,
form_class=FacetedSearchForm
)
return view(request)
At the point marked STEP_1 I get all the database records. At STEP_2 the records are successfully narrowed down to the number I'd expect for that list of django_ids. The problem comes when the search results are displayed in cases where the user has specified a search term in the form. Rather than returning all records from STEP_2 which match the term, I get all records from STEP_2 plus all from STEP_1 which match the term.
Presumably, therefore, I need to override one/some of the methods in for SearchView in haystack/views.py, but what? Can anyone suggest a means of achieving what is required here?
After a bit more thought, I found a way around this. In the code above, the problem was occurring in the view = search_view_factory... line, so I needed to create my own SearchView class and override the get_results(self) method in order to apply the filtering after the search has been run with the user's search terms. The result is code along these lines:
class MySearchView(SearchView):
def get_results(self):
search = self.form.search()
# The ID I need for the database search is at the end of the URL,
# but this may have some search parameters on and need cleaning up.
view_id = self.request.path.split("/")[-1]
view_query = MyView.objects.filter(id=view_id.split("&")[0])
# At this point the django_ids of the required objects can be found.
if len(view_query) > 0:
view_item = view_query.__getitem__(0)
django_ids = []
for thing in view_item.things.all():
django_ids.append(thing.id)
search = search.filter_and(django_id__in=django_ids)
return search
Using search.filter_and rather than search.filter at the end was another thing which turned out to be essential, but which didn't do what I needed when the filtering was being performed before getting to the SearchView.

Create a collection of item ids Revit API in Python

So I am trying to use a list of input strings to isolate them in a view using Revit API. I got this far, but I am getting stuck where I am trying to create a set that takes all elements in a view and removes ones that are created from input IDs. I am doing this to end up with a set of all elements except ones that i want to isolate.
dataEnteringNode = IN0
view = IN0
str_ids = IN1
doc = __doc__
collector = FilteredElementCollector(doc, view.Id)
for i in str_ids:
int_id = int(i)
id = ElementId(int_id)
element = doc.GetElement(id)
element_set = ElementSet()
element_set.Insert(element)
elements_to_hide = collector.WhereElementIsNotElementType().Excluding(element_set).ToElements()
#Assign your output to the OUT variable
OUT = elements_to_hide
I would greatly appreciate a help in solving this error. I am getting that "expected ICollection[ElementId], got set". I am guessing the problem lies in a Excluding filter where i need to create a collection of Ids to exclude but I dont know how. Thank you in advance. Thank you for help in advance!
The reason your code doesn't work is that ElementSet in the Revit API does not implement the ICollection<T> interface - just the IEnumerable<T>. So, to get your code working, you will need to create an ICollection<T> object from your set.
Try something like this:
# ...
from System.Collections.Generic import List
element_collection = List[ElementId](element_set)
elements_to_hide = collector.WhereElementIsNotElementType().Excluding(element_collection).ToElements()

Resources