Search is not available for this dataset
text
stringlengths
75
104k
def post(self, request, customer_uuid): """ Handle POST request - handle form submissions. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpResponse...
def delete(self, request, customer_uuid): """ Handle DELETE request - handle unlinking learner. Arguments: request (django.http.request.HttpRequest): Request instance customer_uuid (str): Enterprise Customer UUID Returns: django.http.response.HttpRes...
def proxied_get(self, *args, **kwargs): """ Perform the query and returns a single object matching the given keyword arguments. This customizes the queryset to return an instance of ``ProxyDataSharingConsent`` when the searched-for ``DataSharingConsent`` instance does not exist. ...
def from_children(cls, program_uuid, *children): """ Build a ProxyDataSharingConsent using the details of the received consent records. """ if not children or any(child is None for child in children): return None granted = all((child.granted for child in children)) ...
def commit(self): """ Commit a real ``DataSharingConsent`` object to the database, mirroring current field settings. :return: A ``DataSharingConsent`` object if validation is successful, otherwise ``None``. """ if self._child_consents: consents = [] for ...
def send_xapi_statements(self, lrs_configuration, days): """ Send xAPI analytics data of the enterprise learners to the given LRS. Arguments: lrs_configuration (XAPILRSConfiguration): Configuration object containing LRS configurations of the LRS where to send xAPI l...
def get_course_completions(self, enterprise_customer, days): """ Get course completions via PersistentCourseGrade for all the learners of given enterprise customer. Arguments: enterprise_customer (EnterpriseCustomer): Include Course enrollments for learners of this e...
def prefetch_users(persistent_course_grades): """ Prefetch Users from the list of user_ids present in the persistent_course_grades. Arguments: persistent_course_grades (list): A list of PersistentCourseGrade. Returns: (dict): A dictionary containing user_id to u...
def create_roles(apps, schema_editor): """Create the enterprise roles if they do not already exist.""" EnterpriseFeatureRole = apps.get_model('enterprise', 'EnterpriseFeatureRole') EnterpriseFeatureRole.objects.update_or_create(name=ENTERPRISE_CATALOG_ADMIN_ROLE) EnterpriseFeatureRole.objects.update_or_...
def delete_roles(apps, schema_editor): """Delete the enterprise roles.""" EnterpriseFeatureRole = apps.get_model('enterprise', 'EnterpriseFeatureRole') EnterpriseFeatureRole.objects.filter( name__in=[ENTERPRISE_CATALOG_ADMIN_ROLE, ENTERPRISE_DASHBOARD_ADMIN_ROLE, ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE...
def get_identity_provider(provider_id): """ Get Identity Provider with given id. Return: Instance of ProviderConfig or None. """ try: from third_party_auth.provider import Registry # pylint: disable=redefined-outer-name except ImportError as exception: LOGGER.warning("...
def get_idp_choices(): """ Get a list of identity providers choices for enterprise customer. Return: A list of choices of all identity providers, None if it can not get any available identity provider. """ try: from third_party_auth.provider import Registry # pylint: disable=redef...
def get_catalog_admin_url_template(mode='change'): """ Get template of catalog admin url. URL template will contain a placeholder '{catalog_id}' for catalog id. Arguments: mode e.g. change/add. Returns: A string containing template for catalog url. Example: >>> get_cat...
def build_notification_message(template_context, template_configuration=None): """ Create HTML and plaintext message bodies for a notification. We receive a context with data we can use to render, as well as an optional site template configration - if we don't get a template configuration, we'll use th...
def get_notification_subject_line(course_name, template_configuration=None): """ Get a subject line for a notification email. The method is designed to fail in a "smart" way; if we can't render a database-backed subject line template, then we'll fall back to a template saved in the Django settings;...
def send_email_notification_message(user, enrolled_in, enterprise_customer, email_connection=None): """ Send an email notifying a user about their enrollment in a course. Arguments: user: Either a User object or a PendingEnterpriseCustomerUser that we can use to get details for the emai...
def get_enterprise_customer(uuid): """ Get the ``EnterpriseCustomer`` instance associated with ``uuid``. :param uuid: The universally unique ID of the enterprise customer. :return: The ``EnterpriseCustomer`` instance, or ``None`` if it doesn't exist. """ EnterpriseCustomer = apps.get_model('ent...
def get_enterprise_customer_for_user(auth_user): """ Return enterprise customer instance for given user. Some users are associated with an enterprise customer via `EnterpriseCustomerUser` model, 1. if given user is associated with any enterprise customer, return enterprise customer. 2. othe...
def get_enterprise_customer_user(user_id, enterprise_uuid): """ Return the object for EnterpriseCustomerUser. Arguments: user_id (str): user identifier enterprise_uuid (UUID): Universally unique identifier for the enterprise customer. Returns: (EnterpriseCustomerUser): enterpri...
def get_course_track_selection_url(course_run, query_parameters): """ Return track selection url for the given course. Arguments: course_run (dict): A dictionary containing course run metadata. query_parameters (dict): A dictionary containing query parameters to be added to course selection...
def update_query_parameters(url, query_parameters): """ Return url with updated query parameters. Arguments: url (str): Original url whose query parameters need to be updated. query_parameters (dict): A dictionary containing query parameters to be added to course selection url. Returns...
def filter_audit_course_modes(enterprise_customer, course_modes): """ Filter audit course modes out if the enterprise customer has not enabled the 'Enable audit enrollment' flag. Arguments: enterprise_customer: The EnterpriseCustomer that the enrollment was created using. course_modes: iter...
def get_enterprise_customer_or_404(enterprise_uuid): """ Given an EnterpriseCustomer UUID, return the corresponding EnterpriseCustomer or raise a 404. Arguments: enterprise_uuid (str): The UUID (in string form) of the EnterpriseCustomer to fetch. Returns: (EnterpriseCustomer): The Ente...
def get_cache_key(**kwargs): """ Get MD5 encoded cache key for given arguments. Here is the format of key before MD5 encryption. key1:value1__key2:value2 ... Example: >>> get_cache_key(site_domain="example.com", resource="enterprise") # Here is key format for above call ...
def traverse_pagination(response, endpoint): """ Traverse a paginated API response. Extracts and concatenates "results" (list of dict) returned by DRF-powered APIs. Arguments: response (Dict): Current response dict from service API endpoint (slumber Resource object): slumber Resour...
def ungettext_min_max(singular, plural, range_text, min_val, max_val): """ Return grammatically correct, translated text based off of a minimum and maximum value. Example: min = 1, max = 1, singular = '{} hour required for this course', plural = '{} hours required for this course' output = ...
def format_price(price, currency='$'): """ Format the price to have the appropriate currency and digits.. :param price: The price amount. :param currency: The currency for the price. :return: A formatted price string, i.e. '$10', '$10.52'. """ if int(price) == price: return '{}{}'.f...
def get_configuration_value_for_site(site, key, default=None): """ Get the site configuration value for a key, unless a site configuration does not exist for that site. Useful for testing when no Site Configuration exists in edx-enterprise or if a site in LMS doesn't have a configuration tied to it. ...
def get_configuration_value(val_name, default=None, **kwargs): """ Get a configuration value, or fall back to ``default`` if it doesn't exist. Also takes a `type` argument to guide which particular upstream method to use when trying to retrieve a value. Current types include: - `url` to specifi...
def get_request_value(request, key, default=None): """ Get the value in the request, either through query parameters or posted data, from a key. :param request: The request from which the value should be gotten. :param key: The key to use to get the desired value. :param default: The backup value t...
def track_event(user_id, event_name, properties): """ Emit a track event to segment (and forwarded to GA) for some parts of the Enterprise workflows. """ # Only call the endpoint if the import was successful. if segment: segment.track(user_id, event_name, properties)
def track_enrollment(pathway, user_id, course_run_id, url_path=None): """ Emit a track event for enterprise course enrollment. """ track_event(user_id, 'edx.bi.user.enterprise.onboarding', { 'pathway': pathway, 'url_path': url_path, 'course_run_id': course_run_id, })
def is_course_run_enrollable(course_run): """ Return true if the course run is enrollable, false otherwise. We look for the following criteria: - end is greater than now OR null - enrollment_start is less than now OR null - enrollment_end is greater than now OR null """ now = datetime.d...
def is_course_run_upgradeable(course_run): """ Return true if the course run has a verified seat with an unexpired upgrade deadline, false otherwise. """ now = datetime.datetime.now(pytz.UTC) for seat in course_run.get('seats', []): if seat.get('type') == 'verified': upgrade_dead...
def get_closest_course_run(course_runs): """ Return course run with start date closest to now. """ if len(course_runs) == 1: return course_runs[0] now = datetime.datetime.now(pytz.UTC) # course runs with no start date should be considered last. never = now - datetime.timedelta(days=...
def get_active_course_runs(course, users_all_enrolled_courses): """ Return active course runs (user is enrolled in) of the given course. This function will return the course_runs of 'course' which have active enrollment by looking into 'users_all_enrolled_courses' """ # User's all course_run id...
def get_current_course_run(course, users_active_course_runs): """ Return the current course run on the following conditions. - If user has active course runs (already enrolled) then return course run with closest start date Otherwise it will check the following logic: - Course run is enrollable (se...
def strip_html_tags(text, allowed_tags=None): """ Strip all tags from a string except those tags provided in `allowed_tags` parameter. Args: text (str): string to strip html tags from allowed_tags (list): allowed list of html tags Returns: a string without html tags """ if text...
def parse_course_key(course_identifier): """ Return the serialized course key given either a course run ID or course key. """ try: course_run_key = CourseKey.from_string(course_identifier) except InvalidKeyError: # Assume we already have a course key. return course_identifier...
def create_roles(apps, schema_editor): """Create the enterprise roles if they do not already exist.""" SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole') SystemWideEnterpriseRole.objects.update_or_create(name=ENTERPRISE_OPERATOR_ROLE)
def delete_roles(apps, schema_editor): """Delete the enterprise roles.""" SystemWideEnterpriseRole = apps.get_model('enterprise', 'SystemWideEnterpriseRole') SystemWideEnterpriseRole.objects.filter( name__in=[ENTERPRISE_OPERATOR_ROLE] ).delete()
def lrs(self): """ LRS client instance to be used for sending statements. """ return RemoteLRS( version=self.lrs_configuration.version, endpoint=self.lrs_configuration.endpoint, auth=self.lrs_configuration.authorization_header, )
def save_statement(self, statement): """ Save xAPI statement. Arguments: statement (EnterpriseStatement): xAPI Statement to send to the LRS. Raises: ClientError: If xAPI statement fails to save. """ response = self.lrs.save_statement(statement) ...
def get_learner_data_records(self, enterprise_enrollment, completed_date=None, grade=None, is_passing=False): """ Return a SapSuccessFactorsLearnerDataTransmissionAudit with the given enrollment and course completion data. If completed_date is None and the learner isn't passing, then course com...
def unlink_learners(self): """ Iterate over each learner and unlink inactive SAP channel learners. This method iterates over each enterprise learner and unlink learner from the enterprise if the learner is marked inactive in the related integrated channel. """ sa...
def has_implicit_access_to_dashboard(user, obj): # pylint: disable=unused-argument """ Check that if request user has implicit access to `ENTERPRISE_DASHBOARD_ADMIN_ROLE` feature role. Returns: boolean: whether the request user has access or not """ request = get_request_or_stub() deco...
def has_implicit_access_to_catalog(user, obj): # pylint: disable=unused-argument """ Check that if request user has implicit access to `ENTERPRISE_CATALOG_ADMIN_ROLE` feature role. Returns: boolean: whether the request user has access or not """ request = get_request_or_stub() decoded_...
def has_implicit_access_to_enrollment_api(user, obj): # pylint: disable=unused-argument """ Check that if request user has implicit access to `ENTERPRISE_ENROLLMENT_API_ADMIN_ROLE` feature role. Returns: boolean: whether the request user has access or not """ request = get_request_or_stub(...
def transform_language_code(code): """ Transform ISO language code (e.g. en-us) to the language name expected by SAPSF. """ if code is None: return 'English' components = code.split('-', 2) language_code = components[0] try: country_code = components[1] except IndexError...
def ecommerce_coupon_url(self, instance): """ Instance is EnterpriseCustomer. Return e-commerce coupon urls. """ if not instance.entitlement_id: return "N/A" return format_html( '<a href="{base_url}/coupons/{id}" target="_blank">View coupon "{id}" details...
def dropHistoricalTable(apps, schema_editor): """ Drops the historical sap_success_factors table named herein. """ table_name = 'sap_success_factors_historicalsapsuccessfactorsenterprisecus80ad' if table_name in connection.introspection.table_names(): migrations.DeleteModel( name...
def handle(self, *args, **options): """ Transmit the learner data for the EnterpriseCustomer(s) to the active integration channels. """ # Ensure that we were given an api_user name, and that User exists. api_username = options['api_user'] try: User.objects.get...
def export_as_csv_action(description="Export selected objects as CSV file", fields=None, header=True): """ Return an export csv action. Arguments: description (string): action description fields ([string]): list of model fields to include header (bool): whether or not to output the ...
def get_clear_catalog_id_action(description=None): """ Return the action method to clear the catalog ID for a EnterpriseCustomer. """ description = description or _("Unlink selected objects from existing course catalogs") def clear_catalog_id(modeladmin, request, queryset): # pylint: disable=unuse...
def _login(self, email, password): """ Login to pybotvac account using provided email and password. :param email: email for pybotvac account :param password: Password for pybotvac account :return: """ response = requests.post(urljoin(self.ENDPOINT, 'sessions'), ...
def refresh_maps(self): """ Get information about maps of the robots. :return: """ for robot in self.robots: resp2 = ( requests.get(urljoin(self.ENDPOINT, 'users/me/robots/{}/maps'.format(robot.serial)), headers=self._head...
def refresh_robots(self): """ Get information about robots connected to account. :return: """ resp = requests.get(urljoin(self.ENDPOINT, 'dashboard'), headers=self._headers) resp.raise_for_status() for robot in resp.json()['robots']: ...
def get_map_image(url, dest_path=None): """ Return a requested map from a robot. :return: """ image = requests.get(url, stream=True, timeout=10) if dest_path: image_url = url.rsplit('/', 2)[1] + '-' + url.rsplit('/', 1)[1] image_filename = image_...
def refresh_persistent_maps(self): """ Get information about persistent maps of the robots. :return: """ for robot in self._robots: resp2 = (requests.get(urljoin( self.ENDPOINT, 'users/me/robots/{}/persistent_maps'.format(robot.serial)...
def _message(self, json): """ Sends message to robot with data from parameter 'json' :param json: dict containing data to send :return: server response """ cert_path = os.path.join(os.path.dirname(__file__), 'cert', 'neatocloud.com.crt') response = requests.post(...
def add_edge_lengths(g): """Add add the edge lengths as a :any:`DiGraph<networkx.DiGraph>` for the graph. Uses the ``pos`` vertex property to get the location of each vertex. These are then used to calculate the length of an edge between two vertices. Parameters ---------- g : :any:`ne...
def _prepare_graph(g, g_colors, q_cls, q_arg, adjust_graph): """Prepares a graph for use in :class:`.QueueNetwork`. This function is called by ``__init__`` in the :class:`.QueueNetwork` class. It creates the :class:`.QueueServer` instances that sit on the edges, and sets various edge and node prope...
def desired_destination(self, network, edge): """Returns the agents next destination given their current location on the network. An ``Agent`` chooses one of the out edges at random. The probability that the ``Agent`` will travel along a specific edge is specified in the :class:...
def desired_destination(self, network, edge): """Returns the agents next destination given their current location on the network. ``GreedyAgents`` choose their next destination with-in the network by picking the adjacent queue with the fewest number of :class:`Agents<.Agent>` in...
def _calculate_distance(latlon1, latlon2): """Calculates the distance between two points on earth. """ lat1, lon1 = latlon1 lat2, lon2 = latlon2 dlon = lon2 - lon1 dlat = lat2 - lat1 R = 6371 # radius of the earth in kilometers a = np.sin(dlat / 2)**2 + np.cos(lat1) * np.cos(lat2) * (np...
def graph2dict(g, return_dict_of_dict=True): """Takes a graph and returns an adjacency list. Parameters ---------- g : :any:`networkx.DiGraph`, :any:`networkx.Graph`, etc. Any object that networkx can turn into a :any:`DiGraph<networkx.DiGraph>`. return_dict_of_dict : bool (optional...
def _matrix2dict(matrix, etype=False): """Takes an adjacency matrix and returns an adjacency list.""" n = len(matrix) adj = {k: {} for k in range(n)} for k in range(n): for j in range(n): if matrix[k, j] != 0: adj[k][j] = {} if not etype else matrix[k, j] return ...
def _dict2dict(adj_dict): """Takes a dictionary based representation of an adjacency list and returns a dict of dicts based representation. """ item = adj_dict.popitem() adj_dict[item[0]] = item[1] if not isinstance(item[1], dict): new_dict = {} for key, value in adj_dict.items()...
def _adjacency_adjust(adjacency, adjust, is_directed): """Takes an adjacency list and returns a (possibly) modified adjacency list. """ for v, adj in adjacency.items(): for properties in adj.values(): if properties.get('edge_type') is None: properties['edge_type'] = ...
def adjacency2graph(adjacency, edge_type=None, adjust=1, **kwargs): """Takes an adjacency list, dict, or matrix and returns a graph. The purpose of this function is take an adjacency list (or matrix) and return a :class:`.QueueNetworkDiGraph` that can be used with a :class:`.QueueNetwork` instance. The...
def get_edge_type(self, edge_type): """Returns all edges with the specified edge type. Parameters ---------- edge_type : int An integer specifying what type of edges to return. Returns ------- out : list of 2-tuples A list of 2-tuples rep...
def draw_graph(self, line_kwargs=None, scatter_kwargs=None, **kwargs): """Draws the graph. Uses matplotlib, specifically :class:`~matplotlib.collections.LineCollection` and :meth:`~matplotlib.axes.Axes.scatter`. Gets the default keyword arguments for both methods by calling ...
def lines_scatter_args(self, line_kwargs=None, scatter_kwargs=None, pos=None): """Returns the arguments used when plotting. Takes any keyword arguments for :class:`~matplotlib.collections.LineCollection` and :meth:`~matplotlib.axes.Axes.scatter` and returns two dictionaries with...
def poisson_random_measure(t, rate, rate_max): """A function that returns the arrival time of the next arrival for a Poisson random measure. Parameters ---------- t : float The start time from which to simulate the next arrival time. rate : function The *intensity function* for ...
def clear(self): """Clears out the queue. Removes all arrivals, departures, and queued agents from the :class:`.QueueServer`, resets ``num_arrivals``, ``num_departures``, ``num_system``, and the clock to zero. It also clears any stored ``data`` and the server is then set to inact...
def _current_color(self, which=0): """Returns a color for the queue. Parameters ---------- which : int (optional, default: ``0``) Specifies the type of color to return. Returns ------- color : list Returns a RGBA color that is represented...
def delay_service(self, t=None): """Adds an extra service time to the next departing :class:`Agent's<.Agent>` service time. Parameters ---------- t : float (optional) Specifies the departing time for the agent scheduled to depart next. If ``t`` is not giv...
def fetch_data(self, return_header=False): """Fetches data from the queue. Parameters ---------- return_header : bool (optonal, default: ``False``) Determines whether the column headers are returned. Returns ------- data : :class:`~numpy.ndarray` ...
def next_event(self): """Simulates the queue forward one event. Use :meth:`.simulate` instead. Returns ------- out : :class:`.Agent` (sometimes) If the next event is a departure then the departing agent is returned, otherwise nothing is returned. ...
def next_event_description(self): """Returns an integer representing whether the next event is an arrival, a departure, or nothing. Returns ------- out : int An integer representing whether the next event is an arrival or a departure: ``1`` corresponds to...
def set_num_servers(self, n): """Change the number of servers in the queue to ``n``. Parameters ---------- n : int or :const:`numpy.infty` A positive integer (or ``numpy.infty``) to set the number of queues in the system to. Raises ------ ...
def simulate(self, n=1, t=None, nA=None, nD=None): """This method simulates the queue forward for a specified amount of simulation time, or for a specific number of events. Parameters ---------- n : int (optional, default: ``1``) The number of events to simul...
def _get_queues(g, queues, edge, edge_type): """Used to specify edge indices from different types of arguments.""" INT = numbers.Integral if isinstance(queues, INT): queues = [queues] elif queues is None: if edge is not None: if isinstance(edge, tuple): if is...
def animate(self, out=None, t=None, line_kwargs=None, scatter_kwargs=None, **kwargs): """Animates the network as it's simulating. The animations can be saved to disk or viewed in interactive mode. Closing the window ends the animation if viewed in interactive mode. This ...
def clear(self): """Resets the queue to its initial state. The attributes ``t``, ``num_events``, ``num_agents`` are set to zero, :meth:`.reset_colors` is called, and the :meth:`.QueueServer.clear` method is called for each queue in the network. Notes ----- ...
def clear_data(self, queues=None, edge=None, edge_type=None): """Clears data from all queues. If none of the parameters are given then every queue's data is cleared. Parameters ---------- queues : int or an iterable of int (optional) The edge index (or an it...
def copy(self): """Returns a deep copy of itself.""" net = QueueNetwork(None) net.g = self.g.copy() net.max_agents = copy.deepcopy(self.max_agents) net.nV = copy.deepcopy(self.nV) net.nE = copy.deepcopy(self.nE) net.num_agents = copy.deepcopy(self.num_agents) ...
def draw(self, update_colors=True, line_kwargs=None, scatter_kwargs=None, **kwargs): """Draws the network. The coloring of the network corresponds to the number of agents at each queue. Parameters ---------- update_colors : ``bool`` (optional, default: ``True``). ...
def get_agent_data(self, queues=None, edge=None, edge_type=None, return_header=False): """Gets data from queues and organizes it by agent. If none of the parameters are given then data from every :class:`.QueueServer` is retrieved. Parameters ---------- queues : int or ...
def get_queue_data(self, queues=None, edge=None, edge_type=None, return_header=False): """Gets data from all the queues. If none of the parameters are given then data from every :class:`.QueueServer` is retrieved. Parameters ---------- queues : int or an *array_like* of...
def initialize(self, nActive=1, queues=None, edges=None, edge_type=None): """Prepares the ``QueueNetwork`` for simulation. Each :class:`.QueueServer` in the network starts inactive, which means they do not accept arrivals from outside the network, and they have no agents in their system...
def next_event_description(self): """Returns whether the next event is an arrival or a departure and the queue the event is accuring at. Returns ------- des : str Indicates whether the next event is an arrival, a departure, or nothing; returns ``'Arrival'...
def reset_colors(self): """Resets all edge and vertex colors to their default values.""" for k, e in enumerate(self.g.edges()): self.g.set_ep(e, 'edge_color', self.edge2queue[k].colors['edge_color']) for v in self.g.nodes(): self.g.set_vp(v, 'vertex_fill_color', self.colo...
def set_transitions(self, mat): """Change the routing transitions probabilities for the network. Parameters ---------- mat : dict or :class:`~numpy.ndarray` A transition routing matrix or transition dictionary. If passed a dictionary, the keys are source ...
def show_active(self, **kwargs): """Draws the network, highlighting active queues. The colored vertices represent vertices that have at least one queue on an in-edge that is active. Dark edges represent queues that are active, light edges represent queues that are inactive. ...
def show_type(self, edge_type, **kwargs): """Draws the network, highlighting queues of a certain type. The colored vertices represent self loops of type ``edge_type``. Dark edges represent queues of type ``edge_type``. Parameters ---------- edge_type : int T...
def simulate(self, n=1, t=None): """Simulates the network forward. Simulates either a specific number of events or for a specified amount of simulation time. Parameters ---------- n : int (optional, default: 1) The number of events to simulate. If ``t`` is n...
def start_collecting_data(self, queues=None, edge=None, edge_type=None): """Tells the queues to collect data on agents' arrival, service start, and departure times. If none of the parameters are given then every :class:`.QueueServer` will start collecting data. Parameters ...
def stop_collecting_data(self, queues=None, edge=None, edge_type=None): """Tells the queues to stop collecting data on agents. If none of the parameters are given then every :class:`.QueueServer` will stop collecting data. Parameters ---------- queues : int, *array_like...
def transitions(self, return_matrix=True): """Returns the routing probabilities for each vertex in the graph. Parameters ---------- return_matrix : bool (optional, the default is ``True``) Specifies whether an :class:`~numpy.ndarray` is returned. If ``Fal...