code stringlengths 1 18.2k |
|---|
2012'" )) |
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in parallel in an asynchronous way. ''' result_futures = [self.executor_pool.submit(resp_generator, req, *args, **kwargs) for req in requests] resp = [res_future.result() for res_future in result_futures] ret... |
def execute(self, requests, resp_generator, *args, **kwargs): ''' Calls the resp_generator for all the requests in sequential order. ''' return [resp_generator(request) for request in requests] |
def setup_logging(args): """ Sets up basic logging :param args: ArgParse arguments :return: nothing. sets logger up globally """ loglevel = logging.WARNING if args.verbose: loglevel = logging.INFO if args.debug: loglevel = logging.DEBUG console = logging.StreamHandler() logging.getLogger('').setLevel(loglevel) console.... |
def get_ip(self, address): """ Get an IPAddress object with the IP address (string) from the API. e.g manager.get_ip('80.69.175.210') """ res = self.get_request('/ip_address/' + address) return IPAddress(cloud_manager=self, **res['ip_address']) |
def get_ips(self): """ Get all IPAddress objects from the API. """ res = self.get_request('/ip_address') IPs = IPAddress._create_ip_address_objs(res['ip_addresses'], cloud_manager=self) return IPs |
def attach_ip(self, server, family='IPv4'): """ Attach a new (random) IPAddress to the given server (object or UUID). """ body = { 'ip_address': { 'server': str(server), 'family': family } } res = self.request('POST', '/ip_address', body) return IPAddress(cloud_manager=self, **res['ip_address']) |
def modify_ip(self, ip_addr, ptr_record): """ Modify an IP address' ptr-record (Reverse DNS). Accepts an IPAddress instance (object) or its address (string). """ body = { 'ip_address': { 'ptr_record': ptr_record } } res = self.request('PUT', '/ip_address/' + str(ip_addr), body) return IPAddress(cloud_manager=self, **re... |
def new(self, user, name, description=None): """ Creates a new Feed object :param user: feed username :param name: feed name :param description: feed description :return: dict """ uri = self.client.remote + '/users/{0}/feeds'.format(user) data = { 'feed': { 'name': name, 'description': description } } resp = self.clien... |
def delete(self, user, name): """ Removes a feed :param user: feed username :param name: feed name :return: true/false """ uri = self.client.remote + '/users/{}/feeds/{}'.format(user, name) resp = self.client.session.delete(uri) return resp.status_code |
def index(self, user): """ Returns a list of Feeds from the API :param user: feed username :return: list Example: ret = feed.index('csirtgadgets') """ uri = self.client.remote + '/users/{0}/feeds'.format(user) return self.client.get(uri) |
def show(self, user, name, limit=None, lasttime=None): """ Returns a specific Feed from the API :param user: feed username :param name: feed name :param limit: limit the results :param lasttime: only show >= lasttime :return: dict Example: ret = feed.show('csirtgadgets', 'port-scanners', limit=5) """ uri = self.client.... |
def codenerix(request): ''' Codenerix CONTEXT ''' # Get values DEBUG = getattr(settings, 'DEBUG', False) VERSION = getattr(settings, 'VERSION', _('WARNING: No version set to this code, add VERSION contant to your configuration')) # Set environment return { 'DEBUG': DEBUG, 'VERSION': VERSION, 'CODENERIX_VERSION': __vers... |
def build_object(self, obj): """Override django-bakery to skip profiles that raise 404""" try: build_path = self.get_build_path(obj) self.request = self.create_request(build_path) self.request.user = AnonymousUser() self.set_kwargs(obj) self.build_file(build_path, self.get_content()) except Http404: # cleanup directory... |
def make_schedule_row(schedule_day, slot, seen_items): """Create a row for the schedule table.""" row = ScheduleRow(schedule_day, slot) skip = {} expanding = {} all_items = list(slot.scheduleitem_set .select_related('talk', 'page', 'venue') .all()) for item in all_items: if item in seen_items: # Inc rowspan seen_items[... |
1} row.items[item.venue] = scheditem seen_items[item] = scheditem if item.expand: expanding[item.venue] = [] empty = [] expanding_right = None skipping = 0 skip_item = None for venue in schedule_day.venues: if venue in skip: # We need to skip all the venues this item spans over skipping = 1 skip_item = skip[venue] cont... |
+= 1 empty = [] expanding_right = item elif venue in row.items: empty = [] expanding_right = None elif expanding_right: expanding_right['colspan'] += 1 elif skipping > 0 and skipping < skip_item['colspan']: skipping += 1 else: skipping = 0 empty.append(venue) row.items[venue] = {'item': None, 'rowspan': 1, 'colspan': 1... |
def generate_schedule(today=None): """Helper function which creates an ordered list of schedule days""" # We create a list of slots and schedule items schedule_days = {} seen_items = {} for slot in Slot.objects.all().order_by('end_time', 'start_time', 'day'): day = slot.get_day() if today and day != today: # Restrict o... |
make_schedule_row(schedule_day, slot, seen_items) schedule_day.rows.append(row) return sorted(schedule_days.values(), key=lambda x: x.day.date) |
def get_context_data(self, **kwargs): """Allow adding a 'render_description' parameter""" context = super(ScheduleXmlView, self).get_context_data(**kwargs) if self.request.GET.get('render_description', None) == '1': context['render_description'] = True else: context['render_description'] = False return context |
def get(self, request): """Create a iCal file from the schedule""" # Heavily inspired by https://djangosnippets.org/snippets/2223/ and # the icalendar documentation calendar = Calendar() site = get_current_site(request) calendar.add('prodid', '-//%s Schedule//%s//' % (site.name, site.domain)) calendar.add('version', '2... |
sched_event.add('location', item.venue.name) sched_event.add('dtstart', item.get_start_datetime()) sched_event.add('duration', datetime.timedelta(minutes=item.get_duration_minutes())) sched_event.add('class', 'PUBLIC') sched_event.add('uid', '%s@%s' % (item.pk, site.domain)) calendar.add_component(sched_event) response... |
def slug(request, url): """Look up a page by url (which is a tree of slugs)""" page = None if url: for slug in url.split('/'): if not slug: continue try: page = Page.objects.get(slug=slug, parent=page) except Page.DoesNotExist: raise Http404 else: try: page = Page.objects.get(slug='index', parent=None) except Page.Does... |
if not request.user.has_perm('pages.change_page'): raise PermissionDenied return ComparePage.as_view()(request, pk=page.id) return ShowPage.as_view()(request, pk=page.id) |
def build_object(self, obj): """Override django-bakery to skip pages marked exclude_from_static""" if not obj.exclude_from_static: super(ShowPage, self).build_object(obj) |
def build_object(self, obj): """Override django-bakery to skip talks that raise 403""" try: super(TalkView, self).build_object(obj) except PermissionDenied: # We cleanup the directory created self.unbuild_object(obj) |
def get_object(self, *args, **kwargs): '''Only talk owners can see talks, unless they've been accepted''' object_ = super(TalkView, self).get_object(*args, **kwargs) if not object_.can_view(self.request.user): raise PermissionDenied return object_ |
def render_to_response(self, *args, **kwargs): '''Canonicalize the URL if the slug changed''' if self.request.path != self.object.get_absolute_url(): return HttpResponseRedirect(self.object.get_absolute_url()) return super(TalkView, self).render_to_response(*args, **kwargs) |
def delete(self, request, *args, **kwargs): """Override delete to only withdraw""" talk = self.get_object() talk.status = WITHDRAWN talk.save() revisions.set_user(self.request.user) revisions.set_comment("Talk Withdrawn") return HttpResponseRedirect(self.success_url) |
def order_results_by(*fields): """A decorator that applies an ordering to the QuerySet returned by a function. """ def decorator(f): @functools.wraps(f) def wrapper(*args, **kw): result = f(*args, **kw) return result.order_by(*fields) return wrapper return decorator |
def cache_result(cache_key, timeout): """A decorator for caching the result of a function.""" def decorator(f): cache_name = settings.WAFER_CACHE @functools.wraps(f) def wrapper(*args, **kw): cache = caches[cache_name] result = cache.get(cache_key) if result is None: result = f(*args, **kw) cache.set(cache_key, result,... |
def build_queryset(self): """Override django-bakery's build logic to fake pagination.""" paths = [(os.path.join(self.build_prefix, 'index.html'), {})] self.request = None queryset = self.get_queryset() paginator = self.get_paginator(queryset, self.get_paginate_by(queryset)) for page in paginator.page_range: paths.appen... |
= kwargs self.prep_directory(build_path) target_path = os.path.join(settings.BUILD_DIR, build_path) self.build_file(target_path, self.get_content()) |
def get_groups(self, gs=None, processed=[], initial=True): ''' <--------------------------------------- 12 columns ------------------------------------> <--- 6 columns ---> <--- 6 columns ---> ------------------------------------------ ------------------------------------------ | Info | | Personal | |==================... |
6 -> <- 6 -> | | | <--- 8 columns ---> <-4 col-> | | | [.....] [.....] | | | | | | | | <- 6 -> <- 6 -> | ----------------- | | Address | | ----------------- | | [.....................................] | ------------------------------------------ | <--- 12 columns ---> | | [..] number | | <--- 12 columns ---> | | | |
------------------------------------------ group = [ (_('Info'),(6,'#8a6d3b','#fcf8e3','center'), (_('Identification'),6, ["cid",6], ["country",6], ), (None,6, ["name",None,6], ["surname",None,6,False], ), ), (_('Personal'),6, ["phone",None,8], ["zipcode",None,4], ["address",None,12], ["number",None,12, True], ), ] Gro... |
None: default of 6 will be used <Attributes>: it can be an integer that represent the size in columns it can be a tuple with several attributes where each element represents: (<Size in columns>,'#<Font color>','#<Background color>','<Alignment>') <Element>: it can be a Group it can be a Field Examples: ('Info', 6, ["na... |
each with name and surname inputs ('Info', (6,None,'#fcf8e3','center'), ["name",6], ["surname",6]) -> Info panel using 6 columns with a yellow brackground in centered title, 2 boxes, 6 columns for each with name and surname inputs ('Info', 12, ('Name', 6, ["name",12]), ('Surname',6, ["surname",12])) -> Info panel using... |
an input "name" and "surname" where it belongs. Field: must be a list with at least 1 element in it: Grammar: [<Name of field>, <Size in columns>, <Label>] <Name of field>: This must be filled always It is the input's name inside the form Must exists as a form element or as a grouped form element <Size in columns>: Siz... |
columns If it is not defined or if it is defined as None: default of 6 will be used <Label>: It it is defined as False: the label for this field will not be shown If it is not defined or if it is defined as None: default of True will be used (default input's label will be shown) If it is a string: |
this string will be shown as a label Examples: ['age'] Input 'age' will be shown with 6 columns and its default label ['age',8] Input 'age' will be shown with 8 columns and its default label ['age', None, False] Input 'age' will be shown with 6 columns and NO LABEL ['age',8,False] Input 'age' will be shown with 8 colum... |
Input 'age' will be shown with 8 columns and translated label text "Age in days" to user's language ['age',8,_("Age in days"), True] Input 'age' will be shown with 8 columns and translated label text "Age in days" to user's language, and input inline with label ['age',6, None, None, None, None, None, ["ng-click=functio... |
filter ONLY DETAILS ['age',6, {'color': 'red'} Input 'age' will be shown with red title ''' # Check if language is set if not self.__language: raise IOError("ERROR: No language suplied!") # Initialize the list if initial: processed = [] # Where to look for fields if 'list_fields' in dir(self): list_fields = self.list_f... |
for fields attributes = [ ('columns', 6), ('color', None), ('bgcolor', None), ('textalign', None), ('inline', False), # input in line with label ('label', True), ('extra', None), ('extra_div', None), ('foreign_info', {}), ] labels = [x[0] for x in attributes] # Get groups if none was given if gs is None: gs = self.__gr... |
None focus_must = None # html helper for groups and fields html_helper = self.html_helper() # Start processing for g in gs: token = {} token['name'] = g[0] if token['name'] in html_helper: if 'pre' in html_helper[token['name']]: token["html_helper_pre"] = html_helper[token['name']]['pre'] if 'post' in html_helper[token... |
= g[1][1] if len(styles) >= 3: token['bgcolor'] = g[1][2] if len(styles) >= 4: token['textalign'] = g[1][3] if len(styles) >= 5: token['inline'] = g[1][4] if len(styles) >= 7: token['extra'] = g[1][5] if len(styles) >= 8: token['extra_div'] = g[1][6] else: token['columns'] = g[1] fs = g[2:] fields = [] for f in fs: # F... |
not if type(f) == tuple: # Recursive fields += self.get_groups([list(f)], processed, False) else: try: list_type = [str, unicode, ] except NameError: list_type = [str, ] # Check if it is a list if type(f) == list: # This is a field with attributes, get the name field = f[0] if html_helper and token['name'] in html_help... |
'pre' in html_helper[token['name']]['items'][field]: atr["html_helper_pre"] = html_helper[token['name']]['items'][field]['pre'] if 'post' in html_helper[token['name']]['items'][field]: atr["html_helper_post"] = html_helper[token['name']]['items'][field]['post'] # Process each attribute (if any) dictionary = False for i... |
is not None: atr[attributes[idx][0]] = element else: raise IOError("We already processed a dicionary element in this list of fields, you can not add anoother type of elements to it, you must keep going with dictionaries") elif type(f) in list_type: field = f else: raise IOError("Uknown element type '{0}' inside group '... |
list_fields: if infield.__dict__[check_system] == field: found = infield break if found: # Get attributes (required and original attributes) wrequired = found.field.widget.is_required wattrs = found.field.widget.attrs # Fill base attributes atr['name'] = found.html_name atr['input'] = found atr['focus'] = False # Set f... |
self.Meta.autofill.get(found.html_name, None) atr['autofill'] = autofill if autofill: # Check format of the request autokind = autofill[0] if type(autokind) == str: # Using new format if autokind == 'select': # If autofill is True for this field set the DynamicSelect widget found.field.widget = DynamicSelect(wattrs) el... |
== 'input': # If autofill is True for this field set the DynamicSelect widget found.field.widget = DynamicInput(wattrs) else: raise IOError("Autofill filled using new format but autokind is '{}' and I only know 'input' or 'select'".format(autokind)) # Configure the field found.field.widget.is_required = wrequired found... |
OLD VERSION] # If autofill is True for this field set the DynamicSelect widget found.field.widget = DynamicSelect(wattrs) found.field.widget.is_required = wrequired found.field.widget.form_name = self.form_name found.field.widget.field_name = infield.html_name found.field.widget.autofill_deepness = autofill[0] found.fi... |
and not isinstance(found.field.widget, DynamicSelect): if not isinstance(found.field.widget, MultiStaticSelect): found.field.widget = StaticSelect(wattrs) found.field.widget.choices = found.field.choices found.field.widget.is_required = wrequired found.field.widget.form_name = self.form_name found.field.widget.field_na... |
"set_language", None) if flang: flang(self.__language) # Attach the element fields.append(atr) # Remember we have processed it processed.append(found.__dict__[check_system]) else: raise IOError("Unknown field '{0}' specified in group '{1}'".format(f, token['name'])) token['fields'] = fields groups.append(token) # Add t... |
infield.field.widget.attrs wrequired = infield.field.widget.is_required # Prepare attr atr = {} # Fill base attributes atr['name'] = infield.html_name atr['input'] = infield atr['focus'] = False # Set focus if focus_must is None: if focus_first is None: focus_first = atr if wrequired: focus_must = atr # Autocomplete if... |
= autofill[0] if type(autokind) == str: # Get old information # Using new format if autokind == 'select': # If autofill is True for this field set the DynamicSelect widget infield.field.widget = DynamicSelect(wattrs) elif autokind == 'multiselect': # If autofill is True for this field set the DynamicSelect widget infie... |
set the DynamicSelect widget infield.field.widget = DynamicInput(wattrs) else: raise IOError("Autofill filled using new format but autokind is '{}' and I only know 'input' or 'select'".format(autokind)) # Configure the field infield.field.widget.is_required = wrequired infield.field.widget.form_name = self.form_name in... |
set the DynamicSelect widget infield.field.widget = DynamicSelect(wattrs) infield.field.widget.is_required = wrequired infield.field.widget.form_name = self.form_name infield.field.widget.field_name = infield.html_name infield.field.widget.autofill_deepness = autofill[0] infield.field.widget.autofill_url = autofill[1] ... |
elif not isinstance(infield.field.widget, MultiStaticSelect): infield.field.widget = StaticSelect(wattrs) if hasattr(infield.field.widget, 'choices') and hasattr(infield.field, 'choices'): infield.field.widget.choices = infield.field.choices infield.field.widget.is_required = wrequired infield.field.widget.form_name = ... |
= getattr(infield.field.widget, "set_language", None) if flang: flang(self.__language) # Attach the attribute fields.append(atr) # Save the new elements if fields: groups.append({'name': None, 'columns': 12, 'fields': fields}) # Set focus if focus_must: focus_must['focus'] = True elif focus_first is not None: focus_fir... |
def site_info(request): '''Expose the site's info to templates''' site = get_current_site(request) context = { 'WAFER_CONFERENCE_NAME': site.name, 'WAFER_CONFERENCE_DOMAIN': site.domain, } return context |
def navigation_info(request): '''Expose whether to display the navigation header and footer''' if request.GET.get('wafer_hide_navigation') == "1": nav_class = "wafer-invisible" else: nav_class = "wafer-visible" context = { 'WAFER_NAVIGATION_VISIBILITY': nav_class, } return context |
def registration_settings(request): '''Expose selected settings to templates''' context = {} for setting in ( 'WAFER_SSO', 'WAFER_HIDE_LOGIN', 'WAFER_REGISTRATION_OPEN', 'WAFER_REGISTRATION_MODE', 'WAFER_TALKS_OPEN', 'WAFER_VIDEO_LICENSE', ): context[setting] = getattr(settings, setting, None) return context |
def profiles(self): ''' return the rolls this people is related with ''' limit = [] if self.is_admin(): limit.append(_("Administrator")) limit.sort() return limit |
def matern_function(Xi, Xj, *args): r"""Matern covariance function of arbitrary dimension, for use with :py:class:`ArbitraryKernel`. The Matern kernel has the following hyperparameters, always referenced in the order listed: = ===== ==================================== 0 sigma prefactor 1 nu order of kernel 2 l1 length... |
k_M = \sigma^2 \frac{2^{1-\nu}}{\Gamma(\nu)} \left (\sqrt{2\nu \sum_i\left (\frac{\tau_i^2}{l_i^2}\right )}\right )^\nu K_\nu\left(\sqrt{2\nu \sum_i\left(\frac{\tau_i^2}{l_i^2}\right)}\right) Parameters ---------- Xi, Xj : :py:class:`Array`, :py:class:`mpf`, tuple or scalar float Points to evaluate the covariance betwe... |
if isinstance(Xi, scipy.matrix): Xi = scipy.asarray(Xi, dtype=float) Xj = scipy.asarray(Xj, dtype=float) tau = scipy.asarray(Xi - Xj, dtype=float) l_mat = scipy.tile(args[-num_dim:], (tau.shape[0], 1)) r2l2 = scipy.sum((tau / l_mat)**2, axis=1) y = scipy.sqrt(2.0 * nu * r2l2) k = 2.0**(1 - nu) / scipy.special.gamma(nu)... |
Xj)] except TypeError: tau = Xi - Xj try: r2l2 = sum([(t / l)**2 for t, l in zip(tau, args[2:])]) except TypeError: r2l2 = (tau / args[2])**2 y = mpmath.sqrt(2.0 * nu * r2l2) k = 2.0**(1 - nu) / mpmath.gamma(nu) * y**nu * mpmath.besselk(nu, y) k *= args[0]**2.0 return k |
def _compute_k(self, tau): r"""Evaluate the kernel directly at the given values of `tau`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. Returns ------- k : :py:class:`Array`, (`M`,) :math:`k(\tau)` (less the :math:`\sigma^2` prefactor). """ y, r2l2 = self._compute_y(tau, retu... |
def _compute_y(self, tau, return_r2l2=False): r"""Covert tau to :math:`y=2\nu\sum_i(\tau_i^2/l_i^2)`. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. return_r2l2 : bool, optional Set to True to return a tuple of (`y`, `r2l2`). Default is False (only return `y`). Returns -------... |
r2l2 = self._compute_r2l2(tau) y = 2.0 * self.nu * r2l2 if return_r2l2: return (y, r2l2) else: return y |
def _compute_y_wrapper(self, *args): r"""Convert tau to :math:`y=\sqrt{2\nu\sum_i(\tau_i^2/l_i^2)}`. Takes `tau` as an argument list for compatibility with :py:func:`mpmath.diff`. Parameters ---------- tau[0] : scalar float First element of `tau`. tau[1] : And so on... Returns ------- y : scalar float Inner part of Mat... |
def _compute_dk_dy(self, y, n): r"""Evaluate the derivative of the outer form of the Matern kernel. Uses the general Leibniz rule to compute the n-th derivative of: .. math:: f(y) = \frac{2^{1-\nu}}{\Gamma(\nu)} y^{\nu/2} K_\nu(y^{1/2}) Parameters ---------- y : :py:class:`Array`, (`M`,) `M` inputs to evaluate at. n : ... |
locations. """ return 2.0**(1 - self.nu) / (scipy.special.gamma(self.nu)) * yn2Kn2Der(self.nu, y, n=n) |
def _compute_dy_dtau(self, tau, b, r2l2): r"""Evaluate the derivative of the inner argument of the Matern kernel. Take the derivative of .. math:: y = 2 \nu \sum_i(\tau_i^2 / l_i^2) Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`) `M` inputs with dimension `D`. b : :py:class:`Array`, (`P`,) Block specifying d... |
Specified derivative at specified locations. """ if len(b) == 0: return self._compute_y(tau) elif len(b) == 1: return 4.0 * self.nu * tau[:, b[0]] / (self.params[2 + b[0]])**2.0 elif (len(b) == 2) and (b[0] == b[1]): return 4.0 * self.nu / (self.params[2 + b[0]])**2.0 else: return scipy.zeros_like(r2l2) |
def _compute_dk_dtau_on_partition(self, tau, p): """Evaluate the term inside the sum of Faa di Bruno's formula for the given partition. Overrides the version from :py:class:`gptools.kernel.core.ChainRuleKernel` in order to get the correct behavior at the origin. Parameters ---------- tau : :py:class:`Matrix`, (`M`, `D`... |
use. Returns ------- dk_dtau : :py:class:`Array`, (`M`,) The specified derivatives over the given partition at the specified locations. """ # Find the derivative order: n = len(p) y, r2l2 = self._compute_y(tau, return_r2l2=True) # Keep track of how many times a given variable has a block of length 1: n1 = 0 # Build the... |
p: # If the partial derivative is exactly zero there is no sense in # continuing the computation: if (len(b) > 2) or ((len(b) == 2) and (b[0] != b[1])): return scipy.zeros_like(y) dy_dtau_factor *= self._compute_dy_dtau(tau, b, r2l2) # Count the number of blocks of length 1: if len(b) == 1: n1 += 1.0 # Compute d^(|pi|)... |
0: mask = (y == 0.0) tau_pow = 2 * (self.nu - n) + n1 if tau_pow == 0: # In this case the limit does not exist, so it is set to NaN: dk_dy[mask] = scipy.nan elif tau_pow > 0: dk_dy[mask] = 0.0 return dk_dy * dy_dtau_factor |
def add_logging_parser(main_parser): "Build an argparse argument parser to parse the command line." main_parser.set_defaults(setup_logging=set_logging_level) verbosity_group = main_parser.add_mutually_exclusive_group(required=False) verbosity_group.add_argument( '--verbose', '-v', action='count', help='Output more verb... |
def set_logging_level(args): "Computes and sets the logging level from the parsed arguments." root_logger = logging.getLogger() level = logging.INFO logging.getLogger('requests.packages.urllib3').setLevel(logging.WARNING) if "verbose" in args and args.verbose is not None: logging.getLogger('requests.packages.urllib3').... |
is not None: if args.quiet > 1: level = logging.ERROR elif args.quiet > 0: level = logging.WARNING else: logging.critical("quiet is an unexpected value. (%s) exiting.", args.quiet) if level is not None: root_logger.setLevel(level) if args.silence_urllib3: # See: https://urllib3.readthedocs.org/en/latest/security.html r... |
def check_auth(user): ''' Check if the user should or shouldn't be inside the system: - If the user is staff or superuser: LOGIN GRANTED - If the user has a Person and it is not "disabled": LOGIN GRANTED - Elsewhere: LOGIN DENIED ''' # Initialize authentication auth = None person = None # Check if there is an user if u... |
that Django accepted the user and it is active if user.is_staff or user.is_superuser: # This is an administrator, let it in auth = user else: # It is a normal user, check if there is a person behind person = getattr(user, "person", None) if not person: # Check if there is related one person_related = getattr(user, "peo... |
one if person_related.count() == 1: person = person_related.get() if person and ((person.disabled is None) or (person.disabled > timezone.now())): # There is a person, no disabled found or the found one is fine to log in auth = user # Return back the final decision return auth |
def debug(self, msg): ''' Handle the debugging to a file ''' # If debug is not disabled if self.__debug is not False: # If never was set, try to set it up if self.__debug is None: # Check what do we have inside settings debug_filename = getattr(settings, "AD_DEBUG_FILE", None) if debug_filename: # Open the debug file p... |
debuging forever self.__debug = False if self.__debug: # Debug the given message self.__debug.write("{}\n".format(msg)) self.__debug.flush() |
def authenticate(self, *args, **kwargs): ''' Authenticate the user agains LDAP ''' # Get config username = kwargs.get("username", None) password = kwargs.get("password", None) # Check user in Active Directory (authorization == None if can not connect to Active Directory Server) authorization = self.ldap_link(username, ... |
the new user if user: # If the user has been properly validated user.is_active = True user.save() else: # Locate user in our system user = User.objects.filter(username=username).first() if user and not user.is_staff: # If access was denied if authorization is False or getattr(settings, "AD_LOCK_UNAUTHORIZED", False): #... |
Return the final decision return user |
def get_or_create_user(self, username, password): ''' Get or create the given user ''' # Get the groups for this user info = self.get_ad_info(username, password) self.debug("INFO found: {}".format(info)) # Find the user try: user = User.objects.get(username=username) except User.DoesNotExist: user = User(username=usern... |
is_admin = False for domain in info['groups']: if 'Domain Admins' in info['groups'][domain]: is_admin = True break # Set the user permissions user.is_staff = is_admin user.is_superuser = is_admin # Refresh the password user.set_password(password) # Validate the selected user and gotten information user = self.validate(... |
didn't pass validation!") # Finally return user return user |
def synchronize(self, user, info): ''' It tries to do a group synchronization if possible This methods should be redeclared by the developer ''' self.debug("Synchronize!") # Remove all groups from this user user.groups.clear() # For all domains found for this user for domain in info['groups']: # For all groups he is fo... |
# If found, add the user to that group user.groups.add(group) |
def set_hyperparams(self, new_params): """Sets the free hyperparameters to the new parameter values in new_params. Parameters ---------- new_params : :py:class:`Array` or other Array-like, (len(:py:attr:`self.free_params`),) New parameter values, ordered as dictated by the docstring for the class. """ new_params = scip... |
new_params[idx] = bound[0] elif bound[1] is not None and new_param > bound[1]: new_params[idx] = bound[1] self.params[~self.fixed_params] = new_params else: raise ValueError("Length of new_params must be %s!" % (len(self.free_params),)) |
def _compute_r2l2(self, tau, return_l=False): r"""Compute the anisotropic :math:`r^2/l^2` term for the given `tau`. Here, :math:`\tau=X_i-X_j` is the difference vector. Computes .. math:: \frac{r^2}{l^2} = \sum_i\frac{\tau_i^2}{l_{i}^{2}} Assumes that the length parameters are the last `num_dim` elements of :py:attr:`s... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.