(Groovy) Finding all Confluence spaces with a certain user group in it - groovy

as the title states, I want to be able to iterate through my Confluence System and find all spaces, in which a certain user group is in.
I am able to find a user group in a single space with the code below, but I can not seem to find an answer how to do this with ALL spaces.
import com.atlassian.confluence.spaces.SpaceManager
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.confluence.security.SpacePermissionManager
import com.atlassian.confluence.security.SpacePermission
import com.atlassian.user.GroupManager
import com.atlassian.confluence.core.ContentPermissionManager
import com.atlassian.confluence.internal.security.SpacePermissionContext
def spaceManager = ComponentLocator.getComponent(SpaceManager)
def spacePermissionManager = ComponentLocator.getComponent(SpacePermissionManager)
def groupManager = ComponentLocator.getComponent(GroupManager)
def targetSpace = spaceManager.getSpace("NameOfSpace")
def targetGroup = groupManager.getGroup("UserGroup")
if (spacePermissionManager.getGroupsWithPermissions(targetSpace).contains(targetGroup)) {
//do something (in my case, remove User Group)
}
I tried it with "def allSpaces = spaceManager.getAllSpaces()" and substituted it into the getGroupsWithPermissions() method with no success.
Thanks!

Have you tried SpacePermissionManager#getAllPermissionsForGroup? I haven't tested this with Groovy, but at least in Java, it returns a list of the space permissions attached with the user group.
Not all SpacePermissions will be attached to actual spaces so you will most likely need to loop through the list and filter results where getSpace() is not null.

Related

Three strings of code repeat in three different view-functios

I have three view-functions in views.py in django project that using a same three arguments in them:
paginator = Paginator(post_list, settings.POSTS_LIMIT)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
How can I put em in a single function (make an utility) to use one string of code in my view-functions, instead of repeat using three?
Thats my first question here, thank you :)
As you note, you can create a single function to handle this, taking the info it needs as arguments. You can include this as a helper function in your views.py or separate it out into a utils.py and then import it. Assuming the latter, for tidiness and future-proofing
utils.py
from django.core.paginator import Paginator
from django.conf.settings import POSTS_LIMITS #you may have another place for your settings
from .utils import make_pagination #utils.py file in same directory
def make_pagination(request, thing_to_paginate, num_per_page=POSTS_LIMITS)
paginator = Paginator(thing_to_paginate, num_per_page)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
return page_obj
views.py
from .utils import make_pagination
def records(request):
...
#we'll use the provided settings-based default for num_per_page
page_obj = make_pagination(request, post_list)
return render(request, 'template.html', {'page_obj': page_obj})
If you wanted more than just the page_obj for some reason, you can return more than the one value, eg,
utils.py
...
return page_obj, paginator
views py
...
page_obj, paginator = make_pagination(request, post_list)
I've gotten the page number in the function itself, but you can also do that either in the view itself, or even in the function call in the view eg,
make_pagination(request.GET.get('page') or 1, post_list)
(If you go this path, don't forget to change the function to accommodate the different argument)

simple question on how to put a value on a group picker field - Scriptrunner for Jira Cloud

I'm having difficulties in proceeding with a script.
I scripted it with scriptrunner to improve the runtime of this automation. Basically what I need is for the script to do a check on a cascading jira cloud field and depending on option 1 AND option 2, I need the script to define a third field with one of the available options. This third field is a group picker field in jira cloud
My difficulty is in line 18, on the put function, so far what i have is this:
import groovy.json.JsonSlurper
import java.util.logging.Logger
def key = issue.key
def epics = get("/rest/api/2/search").queryString('jql', "key = '${key}'").asObject(Map).body
def requests_brasil = epics["issues"]["fields"]["customfield_10830"]["value"]
def requests_child = epics["issues"]["fields"]["customfield_10830"]["child"]["value"][0]
def solver_group = ""
logger.info(requests_brasil)
logger.info(requests_child)
if (requests_brasil == "Active Directory Group" && request_child == "Create New Active Directory Group") {
solver_group = "ServiceDesk-N1"
}
#from here is where i am finding it difficult to continue
def result = put("/rest/api/2/issue/${issue.key}")
.header('Content-Type', 'application/json')
.body({
fields: [
"customfield_10583": solver_group
]
})
.asString()
I don't have a knowledge of advancing in scriptrunner, so I believe my code is very simple in complexity, I'm open to suggestions for improvements too
I would like to know how I can make this put function work on this group picker field
Thanks for the support guys

Get Discord username and discriminator through a mention

I have tried reading the docs, but I don't understand what is going on here and how to fix it. I am trying to map a mention to its proper Name#NNNN form, but alas, it is proving to be a fruitless endeavor for me.
import discord
from discord.ext import commands
from collections import defaultdict
client = commands.Bot(command_prefix=">")
#client.event
async def on_ready():
print('Ready!')
jobz = {}
'''PART 1 v v v'''
#client.event
if message.content.startswith('>jobsched'):
author = message.author
jobz[author].append(...)
await channel.send(jobz[author])
'''PART 2 v v v'''
if message.content.startswith('>when '):
channel = message.channel
worker = list(filter(None, message.content[6:].split(' ')))[0]
uname = message.mentions[0].mention
await channel.send(jobz[uname])
PART 1:
I run this first, the send works as expected as seen below:
>jobsched 'a'
>jobsched 'b'
As seen in the last line, this spits out ['1a', '2b']
PART 2:
Here is where I have my issue.
>when #Name
I expected this to spit out ['1a', '2b'] because I expected it to look up or translate the mentioned name, find its respective name and discriminator. I thought this should happen since, in the above piece, that is how the name gets written into the dictionary is i.e. Name#1234: ['1a','2b']
Printing out .keys() shows that the key has the name and discriminator i.e. Name#1234 in the 'jobz' dictionary.
However, I can't seem to get the mention to give me the Name and Discriminator. I have tried doing mentions[0].mention from what I have seen here on stackoverflow, but it doesn't result in a Member class for me, just a string, presumably just '#Name'. If I leave it alone, as shown in my 'worker' variable, it passes an empty list. It should pull the list because when I override it to jobz['Name#1234'] it gives me the list I expect.
Can anyone please help?
just cast the member object to string to get the name and discriminator as it says in the discord.py docs. To mention someone, put the internal representation like this: f'<#{member.id}>'. To stop problems like this, use client.command() it's way easier to put in parameters, and easier to access info. So, here would be the code:
#client.command()
async def when(ctx, member: discord.Member):
await ctx.send(jobz[str(member)])
Also, if your worker variable is returning None, you're not passing a parameter at all
mentions is a list of Member objects, so when you do mentions[0] you are referencing a Member. Thus, mentions[0].mention is the formatted mention string for the first-mentioned (element 0) Member.
You probably want mentions[0].name and mentions[0].discriminator
See: https://discordpy.readthedocs.io/en/latest/api.html#discord.Message.mentions

Problem: Can only check multiple checkbuttons together?

I would like to generate checkbuttons for multiple items. Due to the repetition, I used a loop to initialize the widget and the default state, saving the BooleanVar() and widgets in separate lists. But by doing so, I can only check either check or uncheck all of them together.
I already tried to set different value to the BooleanVar in the list from within the loop, but to no avail.
ckbtnVarList = [tk.BooleanVar()]*len(ckbtnDict["Tag"])
ckbtnWdtList = [None]*len(ckbtnDict["Tag"])
for idx in range(len(ckbtnDict["Tag"])):
ckbtnVarList[idx].set(1)
ckbtnWdtList[idx]=ttk.Checkbutton(mainfrm, text=ckbtnDict["Text"][idx], variable=ckbtnVarList[idx]).pack()
As specified in the comments above, you need to create your list of BooleanVar's with a list comprehension or a list. The below code shows how to do this.
Since you didn't provide a complete code example, I've had to make some assumptions about your input data.
import tkinter as tk
ckbtnDict = {}
ckbtnDict['Tag'] = ["Tag1","Tag2","Tag3"]
ckbtnDict["Text"] = ["Txt1","Txt2","Txt3"]
mainfrm = tk.Tk()
ckbtnVarList = [tk.BooleanVar() for i in range(len(ckbtnDict["Tag"]))]
ckbtnWdtList = [None for i in range(len(ckbtnDict["Tag"]))]
for idx in range(len(ckbtnDict["Tag"])):
ckbtnVarList[idx].set(1)
ckbtnWdtList[idx]=tk.Checkbutton(mainfrm, text=ckbtnDict["Text"][idx], variable=ckbtnVarList[idx])
ckbrnWdtList[idx].pack()
mainfrm.mainloop()

Django haystack, how to match parts of words?

I'm using haystack 1.2.7 + whoosh 2.4.0 in Django 1.4 (Python is 2.7)
Example: Search query "sear" should match items containing "search" and "sear" and "searching" (etc).
my settings:
HAYSTACK_SITECONF = 'verticalsoftware.search.search_sites'
HAYSTACK_SEARCH_ENGINE = 'whoosh'
HAYSTACK_WHOOSH_PATH = 'C:/whoosh/prodeo_index'
HAYSTACK_INCLUDE_SPELLING = True
search index:
class GalleryIndex(SearchIndex):
text = indexes.CharField(document=True, use_template=True)
content_auto = indexes.NgramField(model_attr='title')
def index_queryset(self):
"""Used when the entire index for model is updated."""
return Gallery.objects.filter(date_added__lte=datetime.datetime.now())
also tried with EdgeNgramField and/or RealTimeSearchIndex
custom urlCONF:
from django.conf.urls.defaults import *
from verticalsoftware.search.views import SearchWithRequest
urlpatterns = patterns('haystack.views',
url(r'^$', SearchWithRequest(), name='haystack_search'),
)
custom view:
from haystack.views import SearchView
import operator
from haystack.query import SearchQuerySet, SQ
class SearchWithRequest(SearchView):
__name__ = 'SearchWithRequest'
def build_form(self, form_kwargs=None):
if form_kwargs is None:
form_kwargs = {}
if self.searchqueryset is None:
sqs = SearchQuerySet().filter(reduce(operator.__or__, [SQ(text=word.strip()) for word in self.request.GET.get("q").split(' ')]))
form_kwargs['searchqueryset'] = sqs
return super(SearchWithRequest, self).build_form(form_kwargs)
for sqs I've tried everything imaginable, using filter and autocomplete as seen in the docs and every relevant forum post I could find; using __startswith and __contains in combination with my content_auto or text field didn't help at all (the latter would not match anything at all; while the former only matched 1 character or the complete string)
the variant pasted above at least has the benefit of returning results for strings with spaces (each word still has to fully match the corresponding database entry, ergo the need for this post)
any help will be IMMENSELY appreciated
late to the party, but suggesting to change your main document field (text) to an EdgeNgramField or NgramField, otherwise the searched index is not capable of matching word fragments, only complete word matching is possible with the CharField.
also, playing in the django shell is sometimes usefull, when debugging haystack:
./manage.py shell
from haystack.query import SearchQuerySet
s = SearchQuerySet()
s.auto_query('sear')
s.auto_query('sear').count()
...

Resources