Python pptx: how to find and delete the empty or unpopulated placeholders - python-2.7

I have created a presentation using python-pptx. However, some slides have the empty placeholders with default text click to add title/text that looks like the one below.
So basically, there are non-empty placeholder with text Some texts here and other two are empty placeholders. How can I find and delete them? Also, there are same empty placeholders for images. How can I find them as well. Thanks

Finding them is fairly easy; something roughly like this should do the trick:
for placeholder in slide.shapes.placeholders:
if placeholder.has_text_frame and placeholder.text_frame.text == "":
print("found one %s" % placeholder)
Deleting it is harder, because there is no direct API support for deleting shapes. However, in this simple case of text placeholders, this should work:
sp = placeholder._sp
sp.getparent().remove(sp)
The ._sp attribute is the lxml etree._Element object representing the actual shape XML element (a placeholder <p:sp> element in this case). .getparent() and .remove() are methods on etree._Element and calling these manipulates the underlying XML directly. This can be dangerous, like if you tried this with a chart shape you'd probably get a repair error when you tried to load the presentation, but in this case it's safe enough.

Related

How can I dynamically create multi-level hierarchical forms in Django?

I'm building an advanced search page for a scientific database using Django. The goal is to be able to allow some dynamically created sophisticated searches, joining groups of search terms with and & or.
I got part-way there by following this example, which allows multiple terms anded together. It's basically a single group of search terms, dynamically created, that I can either and-together or or-together. E.g.
<field1|field2> <is|is not|contains|doesn't contain> <search term> <->
<+>
...where <-> will remove a search term row and <+> will add a new row.
But I would like the user to be able to either add another search term row, or add an and-group and an or-group, so that I'd have something like:
<and-group|or-group> <->
<field1|field2> <is|is not|contains|doesn't contain> <search term> <->
<+term|+and-group|_or-group>
A user could then add terms or groups. The result search might end up like:
and-group
compound is lysine
or-group
tissue is brain
tissue is spleen
feeding status is not fasted
Thus the resulting filter would be like the following.
Data.objects.filter(Q(compound="lysine") & (Q(tissue=brain) | Q(tissue="spleen")) & ~Q(feeding_status="fasted"))
Note - I'm not necessarily asking how to get the filter expression below correct - it's just the dynamic hierarchical construction component that I'm trying to figure out. Please excuse me if I got the Q and/or filter syntax wrong. I've made these queries before, but I'm still new to Django, so getting it right off the top of my head here is pretty much guaranteed to be zero-chance. I also skipped the model relationships I spanned here, so let's assume these are all fields in the same model, for simplicity.
I'm not sure how I would dynamically add parentheses to the filter expression, but my current code could easily join individual Q expressions with and or or.
I'm also not sure how I could dynamically create a hierarchal form to create the sub-groups. I'm guessing any such solution would have to be a hack and that there are not established mechanisms for doing something like this...
Here's a screenshot example of what I've currently got working:
UPDATE:
I got really far following this example I found. I forked that fiddle and got this proof of concept working before incorporating it into my Django project:
http://jsfiddle.net/hepcat72/d42k38j1/18/
The console spits out exactly the object I want. And there are no errors. Clicking the search button works for form validation. Any fields I leave empty causes a prompt to fill in the field. Here's a demo gif:
Now I need to process the POST input to construct the query (which I think I can handle) and restore the form above the results - which I'm not quite sure how to accomplish - perhaps a recursive function in a custom tag?
Although, is there a way to snapshot the form and restore it when the results load below it? Or maybe have the results load in a different frame?
I don't know if I'm teaching a grandmother to suck eggs, but in case not, one of the features of the Python language may be useful.
foo( bar = 27, baz = None)
can instead be coded
args = {}
a1, a2 = 'bar', 'baz'
d[a1] = 27
d[a2] = None
foo( **args )
so an arbitrary Q object specified by runtime keys and values can be constructed q1 = Q(**args)
IIRC q1 & q2 and q1 | q2 are themselves Q objects so you can build up a filter of arbitrary complexity.
I'll also include a mention of Django-filter which is usually my answer to filtering questions like this one, but I suspect in this case you are after greater power than it easily provides. Basically, it will "and" together a list of filter conditions specified by the user. The built-in ones are simple .filter( key=value), but by adding code you can create custom filters with complex Q expressions related to a user-supplied value.
As for the forms, a Django form is a linear construct, and a formset is a list of similar forms. I think I might resort to JavaScript to build some sort of tree representing a complex query in the browser, and have the submit button encode it as JSON and return it through a single text field (or just pick it out of request.POST without using a form). There may be some Javascript out there already written to do this, but I'm not aware of it. You'd need to be sure that malicious submission of field names and values you weren't expecting doesn't result in security issues. For a pure filtering operation, this basically amounts to being sure that the user is entitled to get all data in database table in any case.
There's a form JSONField in the Django PostgreSQL extensions, which validates that user-supplied (or Javascript-generated) text is indeed JSON, and supplies it to you as Python dicts and lists.

How to delete duplicate constructed objects in a list while preserving order and returning a List in dart?

I have a list of constructed objects called RecentCard which is basically an object with user id, pic, and name. I have created a list arranged in order of most recent interaction based on timestamp. However i need to get rid of the second occurence and onwards of any duplicated object. I am comparing just the ids since users may have the same name or photo, and i cannot remove duplicates from a simple list of uids because then i could lose the order of corresponding photos and names.
For example the list would look something like this :
List<RecentCard> recentCards= [RecentCard(uid:as721dn18j2,name:mike,photourl:https://sadadasd1d1),RecentCard(.....]
I have searched for solutions but all of them are dealing with like primitive types like simple lists of strings and the solutions didn't work for me. For example this post: How to delete duplicates in a dart List? list.distinct()? Read below
The first answer's link is no longer available, the next answer with sets is something i tried but it simply doesnt work i have no idea why maybe because its not a primitive type. The next answer with the queries package didn't work because i was using the list to build a listview.builder and so when i called list.length it said i couldnt call that on an iterable or something. The final solution wouldn't work because it said String is not a subtype of RecentCard.
I tried using two forloops with the second just comparing first value to the next couple but that doesnt work because if a duplicate is found, the object is removed and the length is messed up so some elements get skipped.
Any ideas? I feel like its very simple but im not sure how to do it.
You have to use Set to store seen cards and then filter away those ones that are already in the set.
final seenCards = Set<String>();
final uniqueCards = recentCards.where((card) => seenCards.add(card.uid)).toList();

Predicting the placeholder for a dynamic placeholder

I am using the Dynamic Placeholders from Fortis, but need to setup a page template where the Dynamic Placeholders contains renderings. I am setting the page template up, by setting layout detail on the standard values of the page template.
I have been unable to succeed in this, since the dynamic placeholder is postfixed by a GUID which is generated. Is there a way to predict this GUID? According to the documentation, the GUID is generated using the following logic:
Dynamic Placeholders simply use the rendering ID to create a unique placeholder name. If more than one dynamic placeholder with the same name is in a rendering it will also append on an incrementing number
I tried another approach, by using a home brewed dynamic placeholder library, which just prepended the dynamic placeholder with a sequential number, e.g. row1, row2, row3. But this approach makes the content editors unable to move rows in the experience editor, since the content inside the row is tied to a fixed number, which changes when the rows are moved.
As this question have been answered on sitecore.stackexchange.com, I want to bring the answer here as well. Big credit to Richard Seal and Thomas D.
Thomas D:
You can try to open the standard values item with the Experience Editor and add the renderings you like.
Richard Seal:
This is an alternative to the method mentioned by Thomas D.
The Fortis solution uses the UID for the rendering attached to the placeholder key that you enter. You can get this by changing to Raw Values view and copying the xml out of the renderings or final renderings field.
Find the rendering that contains your placeholder. There will be an xml element like this:
<r id="{CA76EB6F-2934-4B8A-BB6A-508A8E44A7C5}"
ph="body"
uid="{0FD41EBD-43CF-4647-8A0F-F1F1D2E00CCD}" />
There may be other fields too. The 2 that are important are id, which is the item id of your rendering item and uid, this is the unique rendering id that is added to your placeholder key.
The key is built like this: string.Format("{0}_{1}", placeholderName, renderingId);
So if you have a placeholder key called title, the key for the above xml snippet would be: title_{0FD41EBD-43CF-4647-8A0F-F1F1D2E00CCD}

Writing value on the current textbox - Selenium

Well I'm facing an issue here:
I use Selenium to automate test on my application, and I use the following code to fill a textbox:
driver.find_element_by_id("form_widget_serial_number").send_keys("example", u'\u0009')
All the textboxes have the same id (form_widget_serial_number) so it's impossible to select a specific textbox by using selection by id (the code above selects the first textbox and u'\u0009' changes the cursor position to the next textbox).
Anyway, how can I send values to the "current" textbox without using find_element_by_id or another selector, given that the cursor is in the current textbox?
There are several selectors available to you - Xpath and css in particular are very powerful.
Xpath can even select by the text of an element and then access its second sibling1:
elem = driver.find_element(:xpath, "//div[contains(text(), 'match this text')]/following-sibling::*[2]")
If you need to find the current element that has focus:
focused_elem = driver.switch_to.active_element
And then to find the next one:
elem_sibling = focused_elem.find_element(:xpath, "following-sibling::*")
Using this example, you could easily traverse any sequence of sequential elements, which would appear to solve your problem.
Take a close look at the structure of the page and then see how you would navigate to the element you need from a reference you can get to. There is probably an Xpath or css selector that can make the traversal across the document.
1 FYI, I'm using an old version of Selenium in Ruby, in case your version's syntax is different
My approach would be:
Get a list of all contemplable elements by the known id
Loop over them until you find a focused element
Use send_keys to write into that element
To get the focused element something like
get_element_index('dom=document.activeElement')
might work. See this question for more information.
Edit: If the list you get from 1. is accidently sorted properly the index of an element in this list might even represent the number of u'\u0009' you have to send to reach that specific element.
Use ActionChains utility to do that. Use following code:
from selenium.webdriver.common.action_chains import ActionChains
ActionChains(driver).send_keys("Hello").perform()

sifr menu list problems, height of object calculated wrong

I am using Drupal and have sifr set on list items, and also a, a:hover are set via Drupal so that the links hover. I looked at the sifr3-rules.js file drupal's render module creates and it looks good. and in fact my other sifr items look fine... But the list item ones are goofing for some reason... There is extra space below the list,
so if i have a list item, and inside of that, I have a unordered list with more list items, the Flash Object made in the 1st li (which will cover the rest of the sublist items too), is too bid so you see space under the children until the next parent li comes up. (so looks like extra bottom padding on that portion of the list in IE8... in FF almost similar but each subitem has space at bottom... with javascript turned off, you see the list items look fine by themselves)....
Also if the parent list item is shorter than the sub list items text, the width for the flash object is set only as long as the first list item, and therefore cuts off the rest the sublist item's text.
Any idea how to resolve any of these?
Only unusual thing i see i am doing is setting forceSingleLine and preventWrap (which dont make a difference if taken off).
****Edit, I may just try to figure out how to get Drupal's menu-block module to output a around my hyperlinks in the list items... then i can target the div's with my rule (and the a,a:hover rules will apply), so each menu item gets its own sifr object instead of sifr3 trying to figure out how to do the lists and sublists.
Very useful to me is anyone knows a way to target a hyperlink (<a> tag) and also allow a:hover rules. I know how to do it with pretend another tag that includes hyperlinks, like if i had <h2><a>sometitle</a></h2>, i could have a rule for h2, but then use the a, a:hover rules in the sifr3-rules.js file to target that. so i would need a way to target the hyperlink in the list, but also apply a :hover to it (not sure if this can be done since its not underneith for example the h2 tag).
I just overrode theme_menu_item
to return ''. $link ."". $menu ."\n"; (so added a div class). and used a sifr rule to target '.mymenu .menu_item'. then a sifr flash object is created for each list item hyperlink but won't try to wrap the whole list (and its sublists) like before. Seemed to fix both problems :)