code
stringlengths
1
18.2k
def bit_for_bit(model_path, bench_path, config): """ Checks whether the given files have bit for bit solution matches on the given variable list. Args: model_path: absolute path to the model dataset bench_path: absolute path to the benchmark dataset config: the configuration of the set of analyses Returns: A dictionary...
+ " could not be read!") # Begin bit for bit analysis headers = ["Max Error", "Index of Max Error", "RMS Error", "Plot"] stats = LIVVDict() for i, var in enumerate(config["bit_for_bit_vars"]): if var in model_data.variables and var in bench_data.variables: m_vardata = model_data.variables[var][:] b_vardata = bench_data...
def diff_configurations(model_config, bench_config, model_bundle, bench_bundle): """ Description Args: model_config: a dictionary with the model configuration data bench_config: a dictionary with the benchmark configuration data model_bundle: a LIVVkit model bundle object bench_bundle: a LIVVkit model bundle object Ret...
v in model_vars else 'NA' bench_val = bench_data[s][v] if s in bench_sections and v in bench_vars else 'NA' same = True if model_val == bench_val and model_val != 'NA' else False diff_dict[s][v] = (same, model_val, bench_val) return elements.file_diff("Configuration Comparison", diff_dict)
def plot_bit_for_bit(case, var_name, model_data, bench_data, diff_data): """ Create a bit for bit plot """ plot_title = "" plot_name = case + "_" + var_name + ".png" plot_path = os.path.join(os.path.join(livvkit.output_dir, "verification", "imgs")) functions.mkdir_p(plot_path) m_ndim = np.ndim(model_data) b_ndim = np.n...
2) plt.xlabel("Benchmark Data") plt.xticks([]) plt.yticks([]) plt.imshow(bench_data, vmin=_min, vmax=_max, interpolation='nearest', cmap=colormaps.viridis) plt.colorbar() # Plot the difference plt.subplot(1, 3, 3) plt.xlabel("Difference") plt.xticks([]) plt.yticks([]) plt.imshow(diff_data, interpolation='nearest', cmap...
def save(self, *args, **kwargs): """Kicks off celery task to re-save associated special coverages to percolator :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.campaigns.Campaign` """ campaign = super(Campaign, self).save(*args, **kwargs) save_campaign_special_coverage_percolat...
def count_rows_duplicates(self, table, cols='*'): """Get the number of rows that do not contain distinct values.""" return self.count_rows(table, '*') - self.count_rows_distinct(table, cols)
def count_rows(self, table, cols='*'): """Get the number of rows in a particular table.""" query = 'SELECT COUNT({0}) FROM {1}'.format(join_cols(cols), wrap(table)) result = self.fetch(query) return result if result is not None else 0
def count_rows_distinct(self, table, cols='*'): """Get the number distinct of rows in a particular table.""" return self.fetch('SELECT COUNT(DISTINCT {0}) FROM {1}'.format(join_cols(cols), wrap(table)))
def get_unique_column(self, table): """Determine if any of the columns in a table contain exclusively unique values.""" for col in self.get_columns(table): if self.count_rows_duplicates(table, col) == 0: return col
def get_duplicate_vals(self, table, column): """Retrieve duplicate values in a column of a table.""" query = 'SELECT {0} FROM {1} GROUP BY {0} HAVING COUNT(*) > 1'.format(join_cols(column), wrap(table)) return self.fetch(query)
def get_field_info(self, field): """ This method is basically a mirror from rest_framework==3.3.3 We are currently pinned to rest_framework==3.1.1. If we upgrade, this can be refactored and simplified to rely more heavily on rest_framework's built in logic. """ field_info = self.get_attributes(field) field_info["requir...
def maxId(self): """int: current max id of objects""" if len(self.model.db) == 0: return 0 return max(map(lambda obj: obj["id"], self.model.db))
def add(self, obj): """Add a object Args: Object: Object will be added Returns: Object: Object with id Raises: TypeError: If add object is not a dict MultipleInvalid: If input object is invaild """ if not isinstance(obj, dict): raise TypeError("Add object should be a dict object") obj = self.validation(obj) obj["id"] =...
def get(self, id): """Get a object by id Args: id (int): Object id Returns: Object: Object with specified id None: If object not found """ for obj in self.model.db: if obj["id"] == id: return self._cast_model(obj) return None
def remove(self, id): """Remove a object by id Args: id (int): Object's id should be deleted Returns: len(int): affected rows """ before_len = len(self.model.db) self.model.db = [t for t in self.model.db if t["id"] != id] if not self._batch.enable.is_set(): self.model.save_db() return before_len - len(self.model.db)
def removeAll(self): """Remove all objects Returns: len(int): affected rows """ before_len = len(self.model.db) self.model.db = [] if not self._batch.enable.is_set(): self.model.save_db() return before_len - len(self.model.db)
def update(self, id, newObj): """Update a object Args: id (int): Target Object ID newObj (object): New object will be merged into original object Returns: Object: Updated object None: If specified object id is not found MultipleInvalid: If input object is invaild """ newObj = self.validation(newObj) for obj in self.mod...
def set(self, id, newObj): """Set a object Args: id (int): Target Object ID newObj (object): New object will be set Returns: Object: New object None: If specified object id is not found MultipleInvalid: If input object is invaild """ newObj = self.validation(newObj) for index in xrange(0, len(self.model.db)): if self.m...
def getAll(self): """Get all objects Returns: List: list of all objects """ objs = [] for obj in self.model.db: objs.append(self._cast_model(obj)) return objs
def _double_prefix(self): """Grow the given deque by doubling, but don't split the second chunk just because the first one is small. """ new_len = max(len(self._buf[0]) * 2, (len(self._buf[0]) + len(self._buf[1]))) self._merge_prefix(new_len)
def _merge_prefix(self, size): """Replace the first entries in a deque of strings with a single string of up to size bytes. >>> d = collections.deque(['abc', 'de', 'fghi', 'j']) >>> _merge_prefix(d, 5); print(d) deque(['abcde', 'fghi', 'j']) Strings will be split as necessary to reach the desired size. >>> _merge_prefi...
def get_sponsored_special_coverages(): """:returns: Django query for all active special coverages with active campaigns.""" now = timezone.now() qs = SpecialCoverage.objects.filter( tunic_campaign_id__isnull=False, ) return qs.filter( start_date__lte=now, end_date__gt=now ) | qs.filter( start_date__lte=now, end_date__i...
def get_sponsored_special_coverage_query(only_recent=False): """ Reference to all SpecialCovearge queries. :param only_recent: references RECENT_SPONSORED_OFFSET_HOURS from django settings. Used to return sponsored content within a given configuration of hours. :returns: Djes.LazySearch query matching all active speica...
def debug_application(self, environ, start_response): """Run the application and conserve the traceback frames.""" app_iter = None try: app_iter = self.app(environ, start_response) for item in app_iter: yield item if hasattr(app_iter, 'close'): app_iter.close() except Exception: if hasattr(app_iter, 'close'): app_iter....
in streamed ' 'response at a point where response headers were already ' 'sent.\n') else: yield traceback.render_full( evalex=self.evalex, secret=self.secret ).encode('utf-8', 'replace') # This will lead to double logging in case backlash logger is set to DEBUG # but this is actually wanted as some environments, like W...
def display_console(self, request): """Display a standalone shell.""" if 0 not in self.frames: self.frames[0] = _ConsoleFrame(self.console_init_func()) return Response(render_console_html(secret=self.secret), content_type='text/html')
def paste_traceback(self, request, traceback): """Paste the traceback and return a JSON response.""" rv = traceback.paste() return Response(json.dumps(rv), content_type='application/json')
def filter_queryset(self, request, queryset, view): """Apply the relevant behaviors to the view queryset.""" start_value = self.get_start(request) if start_value: queryset = self.apply_published_filter(queryset, "after", start_value) end_value = self.get_end(request) if end_value: # Forces the end_value to be the last ...
def apply_published_filter(self, queryset, operation, value): """ Add the appropriate Published filter to a given elasticsearch query. :param queryset: The DJES queryset object to be filtered. :param operation: The type of filter (before/after). :param value: The date or datetime value being applied to the filter. """ ...
def get_date_datetime_param(self, request, param): """Check the request for the provided query parameter and returns a rounded value. :param request: WSGI request object to retrieve query parameter data. :param param: the name of the query parameter. """ if param in request.GET: param_value = request.GET.get(param, Non...
def create(self, message, mid=None, age=60, force=True): """ create session force if you pass `force = False`, it may raise SessionError due to duplicate message id """ with self.session_lock: if not hasattr(message, "id"): message.__setattr__("id", "event-%s" % (uuid.uuid4().hex,)) if self.session_list.get(message.id,...
def get_all_quiz_submissions(self, quiz_id, course_id, include=None): """ Get all quiz submissions. Get a list of all submissions for this quiz. Users who can view or manage grades for a course will have submissions from multiple users returned. A user who can only submit will have only their own submissions returned. ...
include is not None: self._validate_enum(include, ["submission", "quiz", "user"]) params["include"] = include self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/submissions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "...
def create_quiz_submission_start_quiz_taking_session(self, quiz_id, course_id, access_code=None, preview=None): """ Create the quiz submission (start a quiz-taking session). Start taking a Quiz by creating a QuizSubmission which you can use to answer questions and submit your answers. <b>Responses</b> * <b>200 OK</b> i...
if access_code is not None: data["access_code"] = access_code # OPTIONAL - preview """Whether this should be a preview QuizSubmission and not count towards the user's course record. Teachers only.""" if preview is not None: data["preview"] = preview self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/...
def update_student_question_scores_and_comments(self, id, quiz_id, attempt, course_id, fudge_points=None, questions=None): """ Update student question scores and comments. Update the amount of points a student has scored for questions they've answered, provide comments for the student about their answer(s), or simply f...
- id """ID""" path["id"] = id # REQUIRED - attempt """The attempt number of the quiz submission that should be updated. This attempt MUST be already completed.""" data["attempt"] = attempt # OPTIONAL - fudge_points """Amount of positive or negative points to fudge the total score by.""" if fudge_points is not None: dat...
def complete_quiz_submission_turn_it_in(self, id, quiz_id, attempt, course_id, validation_token, access_code=None): """ Complete the quiz submission (turn it in). Complete the quiz submission by marking it as complete and grading it. When the quiz submission has been marked as complete, no further modifications will be...
- PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - quiz_id """ID""" path["quiz_id"] = quiz_id # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - attempt """The attempt number of the quiz submission that should be completed. Note that this must be the latest attempt index, as earlier...
def parse_args(args=None): """ Handles the parsing of options for LIVVkit's command line interface Args: args: The list of arguments, typically sys.argv[1:] """ parser = argparse.ArgumentParser(description="Main script to run LIVVkit.", formatter_class=argparse.ArgumentDefaultsHelpFormatter, fromfile_prefix_chars='@') ...
figure in', 'the output directory (eps, 600d pi).' ]) ) parser.add_argument('-s', '--serve', nargs='?', type=int, const=8000, help=' '.join(['Start a simple HTTP server for the output website specified', 'by OUT_DIR on port SERVE.' ]) ) parser.add_argument('--version', action='version', version='LIVVkit {}'.format(livv...
def init(options): """ Initialize some defaults """ # Set matlplotlib's backend so LIVVkit can plot to files. import matplotlib matplotlib.use('agg') livvkit.output_dir = os.path.abspath(options.out_dir) livvkit.index_dir = livvkit.output_dir livvkit.verify = True if options.verify is not None else False livvkit.valida...
os.path.basename(livvkit.model_dir) livvkit.bench_bundle = os.path.basename(livvkit.bench_dir) if livvkit.model_bundle in available_bundles: livvkit.numerics_model_config = os.path.join( livvkit.bundle_dir, livvkit.model_bundle, "numerics.json") livvkit.numerics_model_module = importlib.import_module( ".".join(["livvki...
print("") sys.exit(1) return options
def list_group_categories_for_context_accounts(self, account_id): """ List group categories for a context. Returns a list of group categories in a context """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id self.logger.debug("GET /api/v1/accounts/{account_id}/grou...
def list_group_categories_for_context_courses(self, course_id): """ List group categories for a context. Returns a list of group categories in a context """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id self.logger.debug("GET /api/v1/courses/{course_id}/group_categ...
def get_single_group_category(self, group_category_id): """ Get a single group category. Returns the data for a single group category, or a 401 if the caller doesn't have the rights to see it. """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" path["group_category_id"] = group_category_i...
def create_group_category_accounts(self, name, account_id, auto_leader=None, create_group_count=None, group_limit=None, self_signup=None, split_group_count=None): """ Create a Group Category. Create a new group category """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = acc...
are: "first":: the first student to be allocated to a group is the leader "random":: a random student from all members is chosen as the leader""" if auto_leader is not None: self._validate_enum(auto_leader, ["first", "random"]) data["auto_leader"] = auto_leader # OPTIONAL - group_limit """Limit the maximum number of us...
/api/v1/accounts/{account_id}/group_categories with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/group_categories".format(**path), data=data, params=params, single_item=True)
def delete_group_category(self, group_category_id): """ Delete a Group Category. Deletes a group category and all groups under it. Protected group categories can not be deleted, i.e. "communities" and "student_organized". """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" path["group_cat...
def list_groups_in_group_category(self, group_category_id): """ List groups in group category. Returns a list of groups in a group category """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" path["group_category_id"] = group_category_id self.logger.debug("GET /api/v1/group_categories/{gr...
def list_users_in_group_category(self, group_category_id, search_term=None, unassigned=None): """ List users in group category. Returns a list of users in the group category. """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" path["group_category_id"] = group_category_id # OPTIONAL - sea...
def assign_unassigned_members(self, group_category_id, sync=None): """ Assign unassigned members. Assign all unassigned members as evenly as possible among the existing student groups. """ path = {} data = {} params = {} # REQUIRED - PATH - group_category_id """ID""" path["group_category_id"] = group_category_id # OPTI...
def set_client(self, *args, **kwargs): ''' Se você possui informações cadastradas sobre o comprador você pode utilizar este método para enviar estas informações para o PagSeguro. É uma boa prática pois evita que seu cliente tenha que preencher estas informações novamente na página do PagSeguro. Args: name (str): (opcio...
value: self.client[arg] = value client_schema(self.client)
def set_shipping(self, *args, **kwargs): ''' Define os atributos do frete Args: type (int): (opcional) Tipo de frete. Os valores válidos são: 1 para 'Encomenda normal (PAC).', 2 para 'SEDEX' e 3 para 'Tipo de frete não especificado.' cost (float): (opcional) Valor total do frete. Deve ser maior que 0.00 e menor ou igua...
endereço de envio do produto. Apenas o valor 'BRA' é aceito. ''' self.shipping = {} for arg, value in kwargs.iteritems(): self.shipping[arg] = value shipping_schema(self.shipping)
def request(self): ''' Faz a requisição de pagamento ao servidor do PagSeguro. ''' # try: payment_v2_schema(self) # except MultipleInvalid as e: # raise PagSeguroPaymentValidationException(u'Erro na validação dos dados: %s' % e.msg) params = self._build_params() # logger.debug(u'Parametros da requisicao ao PagSeguro: %...
def _build_params(self): ''' método que constrói o dicionario com os parametros que serão usados na requisição HTTP Post ao PagSeguro Returns: Um dicionário com os parametros definidos no objeto Payment. ''' params = {} params['email'] = self.email params['token'] = self.token params['currency'] = self.currency # Atrib...
item['weight'] # Sender if self.client.get('email'): params['senderEmail'] = self.client.get('email') if self.client.get('name'): params['senderName'] = ' '.join(self.client.get('name').split()) if self.client.get('phone_area_code'): params['senderAreaCode'] = self.client.get('phone_area_code') if self.client.get('phon...
def _process_response_xml(self, response_xml): ''' Processa o xml de resposta e caso não existam erros retorna um dicionario com o codigo e data. :return: dictionary ''' result = {} xml = ElementTree.fromstring(response_xml) if xml.tag == 'errors': logger.error( u'Erro no pedido de pagamento ao PagSeguro.' + ' O xml de...
return result
def opensearch(request): """ Return opensearch.xml. """ contact_email = settings.CONTACT_EMAIL short_name = settings.SHORT_NAME description = settings.DESCRIPTION favicon_width = settings.FAVICON_WIDTH favicon_height = settings.FAVICON_HEIGHT favicon_type = settings.FAVICON_TYPE favicon_file = settings.FAVICON_FILE url...
def db_manager(self): """ " Do series of DB operations. """ rc_create = self.create_db() # for first create try: self.load_db() # load existing/factory except Exception as e: _logger.debug("*** %s" % str(e)) try: self.recover_db(self.backup_json_db_path) except Exception: pass else: if rc_create is True: self.db_status...
def create_db(self): """ " Create a db file for model if there is no db. " User need to prepare thier own xxx.json.factory. """ if self.db_type != "json": raise RuntimeError("db_type only supports json now") if os.path.exists(self.json_db_path): return False if os.path.exists(self.factory_json_db_path): with self.db_mu...
def recover_db(self, src_file): """ " Recover DB from xxxxx.backup.json or xxxxx.json.factory to xxxxx.json " [src_file]: copy from src_file to xxxxx.json """ with self.db_mutex: try: shutil.copy2(src_file, self.json_db_path) except IOError as e: _logger.debug("*** NO: %s file." % src_file) raise e
def backup_db(self): """ " Generate a xxxxx.backup.json. """ with self.db_mutex: if os.path.exists(self.json_db_path): try: shutil.copy2(self.json_db_path, self.backup_json_db_path) except (IOError, OSError): _logger.debug("*** No file to copy.")
def load_db(self): """ " Load json db as a dictionary. """ try: with open(self.json_db_path) as fp: self.db = json.load(fp) except Exception as e: _logger.debug("*** Open JSON DB error.") raise e
def save_db(self): """ " Save json db to file system. """ with self.db_mutex: if not isinstance(self.db, dict) and not isinstance(self.db, list): return False try: with open(self.json_db_path, "w") as fp: json.dump(self.db, fp, indent=4) except Exception as e: # disk full or something. _logger.debug("*** Write JSON DB ...
def reserve(self, location=None, force=False, wait_for_up=True, timeout=80): """ Reserve port and optionally wait for port to come up. :param location: port location as 'ip/module/port'. If None, the location will be taken from the configuration. :param force: whether to revoke existing reservation (True) or not (False...
def wait_for_up(self, timeout=40): """ Wait until port is up and running, including all parameters (admin state, oper state, license etc.). :param timeout: max time to wait for port up. """ self.wait_for_states(timeout, 'up') connectionStatus = self.get_attribute('connectionStatus').strip() if connectionStatus.split(':...
def wait_for_states(self, timeout=40, *states): """ Wait until port reaches one of the requested states. :param timeout: max time to wait for requested port states. """ state = self.get_attribute('state') for _ in range(timeout): if state in states: return time.sleep(1) state = self.get_attribute('state') raise TgnErro...
def WGS84toOSGB36(lat, lon): """ Accept latitude and longitude as used in GPS. Return OSGB grid coordinates: eastings and northings. Usage: >>> from latlon_to_bng import WGS84toOSGB36 >>> WGS84toOSGB36(51.4778, -0.0014) (538890.1053365842, 177320.49650700082) >>> WGS84toOSGB36(53.50713, -2.71766) (352500.19520169357, 4...
z_1 = ((1-e2_1)*nu_1 + H)*sin(lat_1) # Perform Helmut transform (to go between GRS80 (_1) and Airy 1830 (_2)) s = 20.4894*10**-6 # The scale factor -1 # The translations along x,y,z axes respectively tx, ty, tz = -446.448, 125.157, -542.060 # The rotations along x,y,z respectively, in seconds rxs, rys, rzs = -0.1502, -...
- (b*b)/(a*a) # The eccentricity of the Airy 1830 ellipsoid p = sqrt(x_2**2 + y_2**2) # Lat is obtained by an iterative proceedure: lat = atan2(z_2, (p*(1-e2))) # Initial value latold = 2*pi while abs(lat - latold) > 10**-16: lat, latold = latold, lat nu = a/sqrt(1-e2*sin(latold)**2) lat = atan2(z_2+e2*nu*sin(latold), ...
# meridional radius of curvature rho = a*F0*(1-e2)*(1-e2*sin(lat)**2)**(-1.5) eta2 = nu*F0/rho-1 M1 = (1 + n + (5/4)*n**2 + (5/4)*n**3) * (lat-lat0) M2 = (3*n + 3*n**2 + (21/8)*n**3) * sin(lat-lat0) * cos(lat+lat0) M3 = ((15/8)*n**2 + (15/8)*n**3) * sin(2*(lat-lat0)) * cos(2*(lat+lat0)) M4 = (35/24)*n**3 * sin(3*(lat-l...
return E, N
def get_form(self, step=None, data=None, files=None): """Instanciate the form for the current step FormAdminView from xadmin expects form to be at self.form_obj """ self.form_obj = super(FormWizardAdminView, self).get_form( step=step, data=data, files=files) return self.form_obj
def render(self, form=None, **kwargs): """Returns the ``HttpResponse`` with the context data""" context = self.get_context(**kwargs) return self.render_to_response(context)
def render_to_response(self, context): """Add django-crispy form helper and draw the template Returns the ``TemplateResponse`` ready to be displayed """ self.setup_forms() return TemplateResponse( self.request, self.form_template, context, current_app=self.admin_site.name)
def get_context(self, **kwargs): """Use this method to built context data for the template Mix django wizard context data with django-xadmin context """ context = self.get_context_data(form=self.form_obj, **kwargs) context.update(super(FormAdminView, self).get_context()) return context
def run(self): """Run merging. """ print("", file=sys.stderr) print("Going to merge/convert RNF-FASTQ files.", file=sys.stderr) print("", file=sys.stderr) print(" mode: ", self.mode, file=sys.stderr) print(" input files: ", ", ".join(self.input_files_fn), file=sys.stderr) print(" output files: ", ", ".join(self.output_...
def is_config_container(v): """ checks whether v is of type list,dict or Config """ cls = type(v) return ( issubclass(cls, list) or issubclass(cls, dict) or issubclass(cls, Config) )
def check(cls, cfg, key_name, path, parent_cfg=None): """ Checks that the config values specified in key name is sane according to config attributes defined as properties on this class """ attr = getattr(cls, key_name, None) if path != "": attr_full_name = "%s.%s" % (path, key_name) else: attr_full_name = key_name if n...
vodka.exceptions.ConfigErrorValue( attr_full_name, attr, value, reason=reason ) elif attr.expected_type != type(value): # attribute type mismatch raise vodka.exceptions.ConfigErrorType( attr_full_name, attr ) if attr.choices and value not in attr.choices: # attribute value not valid according to # available choices rai...
h = getattr(handler, "Configuration", None) #h = getattr(attr.handler(k, value[k]), "Configuration", None) if h: if type(k) == int and type(value[k]) == dict and value[k].get("name"): _path = "%s.%s" % ( attr_full_name, value[k].get("name")) else: _path = "%s.%s" % (attr_full_name, k) _num_crit, _num_warn = h.validate(...
def validate(cls, cfg, path="", nested=0, parent_cfg=None): """ Validates a section of a config dict. Will automatically validate child sections as well if their attribute pointers are instantiated with a handler property """ # number of critical errors found num_crit = 0 # number of non-critical errors found num_warn ...
num_warn += 1 elif inst.level == "critical": vodka.log.error(inst.explanation) num_crit += 1 if type(cfg) in [dict, Config]: keys = list(cfg.keys()) if nested > 0: for _k, _v in cfg.items(): _num_crit, _num_warn = cls.validate( _v, path=("%s.%s" % (path, _k)), nested=nested-1, parent_cfg=cfg ) num_crit += _num_crit num...
def attributes(cls): """ yields tuples for all attributes defined on this handler tuple yielded: name (str), attribute (Attribute) """ for k in dir(cls): v = getattr(cls, k) if isinstance(v, Attribute): yield k,v
def read(self, config_dir=None, clear=False, config_file=None): """ The munge Config's read function only allows to read from a config directory, but we also want to be able to read straight from a config file as well """ if config_file: data_file = os.path.basename(config_file) data_path = os.path.dirname(config_file)...
def remove_group_from_favorites(self, id): """ Remove group from favorites. Remove a group from the current user's favorites. """ path = {} data = {} params = {} # REQUIRED - PATH - id """the ID or SIS ID of the group to remove""" path["id"] = id self.logger.debug("DELETE /api/v1/users/self/favorites/groups/{id} with q...
def reset_course_favorites(self): """ Reset course favorites. Reset the current user's course favorites to the default automatically generated list of enrolled courses """ path = {} data = {} params = {} self.logger.debug("DELETE /api/v1/users/self/favorites/courses with query params: {params} and form data: {data}".fo...
def find_recipients_conversations(self, context=None, exclude=None, from_conversation_id=None, permissions=None, search=None, type=None, user_id=None): """ Find recipients. Find valid recipients (users, courses and groups) that the current user can send messages to. The /api/v1/search/recipients path is the preferred e...
course/group ids prefixed with "course_" or "group_" respectively, e.g. exclude[]=1&exclude[]=2&exclude[]=course_3""" if exclude is not None: params["exclude"] = exclude # OPTIONAL - type """Limit the search just to users or contexts (groups/courses).""" if type is not None: self._validate_enum(type, ["user", "context"...
be returned. This is used to start new side conversations.""" if from_conversation_id is not None: params["from_conversation_id"] = from_conversation_id # OPTIONAL - permissions """Array of permission strings to be checked for each matched context (e.g. "send_messages"). This argument determines which permissions may b...
def list_all_courses(self, open_enrollment_only=None, public_only=None, search=None): """ List all courses. List all courses visible in the public index """ path = {} data = {} params = {} # OPTIONAL - search """Search terms used for matching users/courses/groups (e.g. "bob smith"). If multiple terms are given (separat...
def create_communication_channel(self, user_id, communication_channel_type, communication_channel_address, communication_channel_token=None, skip_confirmation=None): """ Create a communication channel. Creates a new communication channel for the specified user. """ path = {} data = {} params = {} # REQUIRED - PATH - us...