code
stringlengths
1
18.2k
def create_single_poll(self, polls_question, polls_description=None): """ Create a single poll. Create a new poll for the current user """ path = {} data = {} params = {} # REQUIRED - polls[question] """The title of the poll.""" data["polls[question]"] = polls_question # OPTIONAL - polls[description] """A brief descrip...
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT, source_address=None): """Connect to *address* and return the socket object. Convenience function. Connect to *address* (a 2-tuple ``(host, port)``) and return the socket object. Passing the optional *timeout* parameter will set the timeout on the socket in...
= socket(af, socktype, proto) if timeout is not _GLOBAL_DEFAULT_TIMEOUT: sock.settimeout(timeout) if source_address: sock.bind(source_address) sock.connect(sa) return sock except error: err = sys.exc_info()[1] six.exc_clear() if sock is not None: sock.close() if err is not None: raise err else: raise error("getaddrinfo...
def content_deleted(sender, instance=None, **kwargs): """removes content from the ES index when deleted from DB """ if getattr(instance, "_index", True): cls = instance.get_real_instance_class() index = cls.search_objects.mapping.index doc_type = cls.search_objects.mapping.doc_type cls.search_objects.client.delete(inde...
def save(self, *args, **kwargs): """sets the `slug` values as the name :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `super.save()` """ self.slug = slugify(self.name)[:50] return super(Tag, self).save(*args, **kwargs)
def save(self, *args, **kwargs): """sets the `slug` values as the name :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `super.save()` """ if self.slug is None or self.slug == "": self.slug = slugify(self.name) feature_type = super(FeatureType, self).save(*args, **kwargs) if...
def thumbnail(self): """Read-only attribute that provides the value of the thumbnail to display. """ # check if there is a valid thumbnail override if self.thumbnail_override.id is not None: return self.thumbnail_override # otherwise, just try to grab the first image first_image = self.first_image if first_image is not...
def first_image(self): """Ready-only attribute that provides the value of the first non-none image that's not the thumbnail override field. """ # loop through image fields and grab the first non-none one for model_field in self._meta.fields: if isinstance(model_field, ImageField): if model_field.name is not 'thumbnail_...
def get_absolute_url(self): """produces a url to link directly to this instance, given the URL config :return: `str` """ try: url = reverse("content-detail-view", kwargs={"pk": self.pk, "slug": self.slug}) except NoReverseMatch: url = None return url
def is_published(self): """determines if the content is/should be live :return: `bool` """ if self.published: now = timezone.now() if now >= self.published: return True return False
def ordered_tags(self): """gets the related tags :return: `list` of `Tag` instances """ tags = list(self.tags.all()) return sorted( tags, key=lambda tag: ((type(tag) != Tag) * 100000) + tag.count(), reverse=True )
def save(self, *args, **kwargs): """creates the slug, queues up for indexing and saves the instance :param args: inline arguments (optional) :param kwargs: keyword arguments :return: `bulbs.content.Content` """ if not self.slug: self.slug = slugify(self.build_slug())[:self._meta.get_field("slug").max_length] if not sel...
def percolate_special_coverage(self, max_size=10, sponsored_only=False): """gets list of active, sponsored special coverages containing this content via Elasticsearch Percolator (see SpecialCoverage._save_percolator) Sorting: 1) Manually added 2) Most recent start date """ # Elasticsearch v1.4 percolator range query do...
this to work, we need to # sort via scoring_functions, and then manually filter out zero scores. sponsored_filter = { "query": { "function_score": { "functions": [ # Boost Recent Special Coverage # Base score is start time # Note: ES 1.4 sorting granularity is poor for times # within 1 hour of each other. { # v1.4 "fie...
{"_id": "specialcoverage"}, }, }, "weight": 0, }, # Boost Manually Added Content { "filter": { "terms": { "included_ids": [self.id], } }, "weight": MANUALLY_ADDED_BOOST, }, # Penalize Inactive (Zero Score Will be Omitted) { "filter": { "or": [ { "range": { "start_date_epoch": { "gt": now_epoch, }, } }, { "range": { "en...
via scoring function (ex: inactive) if r['_score'] > 0]
def log(self, user, content, message): """creates a new log record :param user: user :param content: content instance :param message: change information """ return self.create( user=user, content_type=ContentType.objects.get_for_model(content), object_id=content.pk, change_message=message )
def save(self, *args, **kwargs): """sets uuid for url :param args: inline arguments (optional) :param kwargs: keyword arguments (optional) :return: `super.save()` """ if not self.id: # this is a totally new instance, create uuid value self.url_uuid = str(uuid.uuid4()).replace("-", "") super(ObfuscatedUrlInfo, self).sav...
def write_playlist_file(self, localdir): """ Check if playlist exists in local directory. """ path = "{0}/playlists".format(localdir) if not os.path.exists(path): os.makedirs(path) filepath = "{0}/{1}".format(path, self.gen_filename()) playlist = open(filepath, "w") for track in self.get_tracks(): playlist.write("{0}/{...
def getmembers(self): """ :return: list of members as name, type tuples :rtype: list """ return filter( lambda m: not m[0].startswith("__") and not inspect.isfunction(m[1]) and not inspect.ismethod(m[1]), inspect.getmembers(self.__class__) )
def _create_instance_attributes(self, arguments): """ Copies class level attribute templates and makes instance placeholders This step is required for direct uses of Model classes. This creates a copy of attribute_names ignores methods and private variables. DataCollection types are deep copied to ignore memory referen...
def get_attribute_keys(self): """ Returns a list of managed attributes for the Model class Implemented for use with data adapters, can be used to quickly make a list of the attribute names in a prestans model """ _attribute_keys = list() for attribute_name, type_instance in self.getmembers(): if isinstance(type_instanc...
def validate(self, value, attribute_filter=None, minified=False): """ :param value: serializable input to validate :type value: dict | None :param attribute_filter: :type: prestans.parser.AttributeFilter | None :param minified: whether or not the input is minified :type minified: bool :return: the validated model :rtyp...
attribute_filter.is_attribute_visible(attribute_name): _model_instance._attributes[attribute_name] = None continue validation_input = None input_value_key = attribute_name # minification support if minified is True: input_value_key = rewrite_map[attribute_name] if input_value_key in value: validation_input = value[inpu...
def attribute_rewrite_map(self): """ Example: long_name -> a_b :return: the rewrite map :rtype: dict """ rewrite_map = dict() token_rewrite_map = self.generate_attribute_token_rewrite_map() for attribute_name, type_instance in self.getmembers(): if isinstance(type_instance, DataType): attribute_tokens = attribute_name....
def as_serializable(self, attribute_filter=None, minified=False): """ Returns a dictionary with attributes and pure python representation of the data instances. If an attribute filter is provided as_serializable will respect the visibility. The response is used by serializers to return data to client :param attribute_f...
= None continue if isinstance(type_instance, DataCollection): sub_attribute_filter = None if isinstance(attribute_filter, (AttributeFilter, AttributeFilterImmutable)) and attribute_name in attribute_filter: sub_attribute_filter = getattr(attribute_filter, attribute_name) model_dictionary[serialized_attribute_name] = se...
def list_enrollments_courses(self, course_id, grading_period_id=None, include=None, role=None, sis_account_id=None, sis_course_id=None, sis_section_id=None, sis_user_id=None, state=None, type=None, user_id=None): """ List enrollments. Depending on the URL given, return either (1) all of the enrollments in a course, (2)...
types to return. Accepted values are 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'DesignerEnrollment', and 'ObserverEnrollment.' If omitted, all enrollment types are returned. This argument is ignored if `role` is given.""" if type is not None: params["type"] = type # OPTIONAL - role """A list of enrollme...
"completed", "inactive"]) params["state"] = state # OPTIONAL - include """Array of additional information to include on the enrollment or user records. "avatar_url" and "group_ids" will be returned on the user record.""" if include is not None: self._validate_enum(include, ["avatar_url", "group_ids", "locked", "observe...
the whole course.""" if grading_period_id is not None: params["grading_period_id"] = grading_period_id # OPTIONAL - sis_account_id """Returns only enrollments for the specified SIS account ID(s). Does not look into subaccounts. May pass in array or string.""" if sis_account_id is not None: params["sis_account_id"] = si...
query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/enrollments".format(**path), data=data, params=params, all_pages=True)
def enroll_user_courses(self, course_id, enrollment_type, enrollment_user_id, enrollment_associated_user_id=None, enrollment_course_section_id=None, enrollment_enrollment_state=None, enrollment_limit_privileges_to_course_section=None, enrollment_notify=None, enrollment_role=None, enrollment_role_id=None, enrollment_sel...
enrollment_role # OPTIONAL - enrollment[role_id] """Assigns a custom course-level role to the user.""" if enrollment_role_id is not None: data["enrollment[role_id]"] = enrollment_role_id # OPTIONAL - enrollment[enrollment_state] """If set to 'active,' student will be immediately enrolled in the course. Otherwise they w...
# OPTIONAL - enrollment[limit_privileges_to_course_section] """If set, the enrollment will only allow the user to see and interact with users enrolled in the section given by course_section_id. * For teachers and TAs, this includes grading privileges. * Section-limited students will not see any users (including teacher...
user can self- enroll as a student in the default section by passing in a valid code. When self-enrolling, the user_id must be 'self'. The enrollment_state will be set to 'active' and all other arguments will be ignored.""" if enrollment_self_enrollment_code is not None: data["enrollment[self_enrollment_code]"] = enrol...
if enrollment_associated_user_id is not None: data["enrollment[associated_user_id]"] = enrollment_associated_user_id self.logger.debug("POST /api/v1/courses/{course_id}/enrollments with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/c...
def conclude_deactivate_or_delete_enrollment(self, id, course_id, task=None): """ Conclude, deactivate, or delete an enrollment. Conclude, deactivate, or delete an enrollment. If the +task+ argument isn't given, the enrollment will be concluded. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID"""...
def filter_ints_based_on_vlan(interfaces, vlan, count=1): """ Filter list of interfaces based on VLAN presence or absence criteria. :param interfaces: list of interfaces to filter. :param vlan: boolean indicating whether to filter interfaces with or without VLAN. :param vlan: number of expected VLANs (note that when vl...
return filtered_interfaces
def _create(self, **attributes): """ Create new interface on IxNetwork. Set enabled and description (==name). :return: interface object reference. """ attributes['enabled'] = True if 'name' in self._data: attributes['description'] = self._data['name'] obj_ref = self.api.add(self.obj_parent(), self.obj_type(), **attribu...
def _constraint_names(self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None): """ Returns all constraint names matching the columns and conditions """ column_names = list(column_names) if column_names else None with self.connection.cursor() as cursor: constraints = get_...
def is_scalar(self): """ :return: :rtype: bool """ return \ isinstance(self._element_template, Boolean) or \ isinstance(self._element_template, Float) or \ isinstance(self._element_template, Integer) or \ isinstance(self._element_template, String)
def validate(self, value, attribute_filter=None, minified=False): """ :param value: :type value: list | None :param attribute_filter: :type attribute_filter: prestans.parser.AttributeFilter :param minified: :type minified: bool :return: """ if not self._required and value is None: return None elif self._required and va...
def login_required(http_method_handler): """ provides a decorator for RESTRequestHandler methods to check for authenticated users RESTRequestHandler subclass must have a auth_context instance, refer to prestans.auth for the parent class definition. If decorator is used and no auth_context is provided the client will be...
self.request raise authentication_error if not self.__provider_config__.authentication.is_authenticated_user(): authentication_error = prestans.exception.AuthenticationError() authentication_error.request = self.request raise authentication_error http_method_handler(self, *args, **kwargs) return secure_http_method_hand...
def role_required(role_name=None): """ Authenticates a HTTP method handler based on a provided role With a little help from Peter Cole's Blog http://mrcoles.com/blog/3-decorator-examples-and-awesome-python/ """ def _role_required(http_method_handler): @wraps(http_method_handler) def secure_http_method_handler(self, *ar...
def access_required(config=None): """ Authenticates a HTTP method handler based on a custom set of arguments """ def _access_required(http_method_handler): def secure_http_method_handler(self, *args, **kwargs): # authentication context must be set if not self.__provider_config__.authentication: _message = "Service avai...
def as_dict(self): """ turns attribute filter object into python dictionary """ output_dictionary = dict() for key, value in iter(self._key_map.items()): if isinstance(value, bool): output_dictionary[key] = value elif isinstance(value, self.__class__): output_dictionary[key] = value.as_dict() return output_dictionary
def gen_cmake_command(config): """ Generate CMake command. """ from autocmake.extract import extract_list s = [] s.append("\n\ndef gen_cmake_command(options, arguments):") s.append(' """') s.append(" Generate CMake command based on options and arguments.") s.append(' """') s.append(" command = []") for env in config['e...
def gen_setup(config, default_build_type, relative_path, setup_script_name): """ Generate setup script. """ from autocmake.extract import extract_list s = [] s.append('#!/usr/bin/env python') s.append('\n{0}'.format(autogenerated_notice())) s.append('\nimport os') s.append('import sys') s.append('assert sys.version_inf...
--help', 'Show this screen.']) s.append(align_options(options)) s.append('"""') s.append(gen_cmake_command(config)) s.append("\n") s.append("# parse command line args") s.append("try:") s.append(" arguments = docopt.docopt(options, argv=None)") s.append("except docopt.DocoptExit:") s.append(r" sys.stderr.write('ERROR: ...
def gen_cmakelists(project_name, project_language, min_cmake_version, default_build_type, relative_path, modules): """ Generate CMakeLists.txt. """ import os s = [] s.append(autogenerated_notice()) s.append('\n# set minimum cmake version') s.append('cmake_minimum_required(VERSION {0} FATAL_ERROR)'.format(min_cmake_vers...
# on windows cmake corrects this so we have to make it wrong again rel_cmake_module_path = rel_cmake_module_path.replace('\\', '/') s.append('set(CMAKE_MODULE_PATH ${{CMAKE_MODULE_PATH}} ${{PROJECT_SOURCE_DIR}}/{0})'.format(rel_cmake_module_path)) if len(modules) > 0: s.append('\n# included cmake modules') for module i...
def align_options(options): """ Indents flags and aligns help texts. """ l = 0 for opt in options: if len(opt[0]) > l: l = len(opt[0]) s = [] for opt in options: s.append(' {0}{1} {2}'.format(opt[0], ' ' * (l - len(opt[0])), opt[1])) return '\n'.join(s)
def format_exception(etype, value, tback, limit=None): """ Python 2 compatible version of traceback.format_exception Accepts negative limits like the Python 3 version """ rtn = ['Traceback (most recent call last):\n'] if limit is None or limit >= 0: rtn.extend(traceback.format_tb(tback, limit)) else: rtn.extend(traceba...
def _import_module(name, path=None): """ Args: name(str): * Full name of object * name can also be an EntryPoint object, name and path will be determined dynamically path(str): Module directory Returns: object: module object or advertised object for EntryPoint Loads a module using importlib catching exceptions If path ...
etype = e.__class__ tback = getattr(e, '__traceback__', sys.exc_info()[2]) # Create traceback starting at module for friendly output start = 0 here = 0 tb_list = traceback.extract_tb(tback) if path: for idx, entry in enumerate(tb_list): # Find index for traceback starting with module we tried to load if os.path.dirname...
friendly=friendly) raise_with_traceback(exception, tback) return mod
def _recursive_import(package): """ Args: package(py:term:`package`): Package to walk Import all modules from a package recursively """ prefix = '%s.' % (package.__name__) path = getattr(package, '__path__', None) if path: for submod in pkgutil.walk_packages(path, prefix=prefix): _import_module(submod[1], submod[0].pat...
def load_modules(self): """ Locate and import modules from locations specified during initialization. Locations include: - Program's standard library (``library``) - `Entry points <Entry point_>`_ (``entry_point``) - Specified modules (``modules``) - Specified paths (``paths``) If a malformed child plugin class is impo...
e), EntryPointWarning) continue # If we have a package, walk it if ismodule(mod): _recursive_import(mod) else: warnings.warn("Entry point '%s' is not a module or package" % epoint.name, EntryPointWarning) # Load auxiliary modules if self.modules: for mod in self.modules: LOGGER.info('Loading plugins from %s', mod) _rec...
def plugins(self): """ Newest version of all plugins in the group filtered by ``blacklist`` Returns: dict: Nested dictionary of plugins accessible through dot-notation. Plugins are returned in a nested dictionary, but can also be accessed through dot-notion. Just as when accessing an undefined dictionary key with index...
def plugins_all(self): """ All resulting versions of all plugins in the group filtered by ``blacklist`` Returns: dict: Nested dictionary of plugins accessible through dot-notation. Similar to :py:attr:`plugins`, but lowest level is a regular dictionary of all unfiltered plugin versions for the given plugin type and nam...
def get_plugin(self, plugin_type, name, version=None): """ Args: plugin_type(str): Parent type name(str): Plugin name version(str): Plugin version Returns: :py:class:`Plugin`: Plugin, or :py:data:`None` if plugin can't be found Retrieve a specific plugin. ``blacklist`` and ``type_filter`` still apply. If ``version`` is...
def insert_uniques(self, table, columns, values): """ Insert multiple rows into a table that do not already exist. If the rows primary key already exists, the rows values will be updated. If the rows primary key does not exists, a new row will be inserted """ # Rows that exist in the table existing_rows = self.select(t...
is not in list of pk values, insert new row if row[pk_index] not in keys: to_insert.append(unique[index]) # Primary key exists, update row rather than insert elif row[pk_index] in keys: to_update.append(unique[index]) # Insert new rows if len(to_insert) > 0: self.insert_many(table, columns, to_insert) # Update existing...
def insert(self, table, columns, values, execute=True): """Insert a single row into a table.""" # TODO: Cant accept lists? # Concatenate statement cols, vals = get_col_val_str(columns) statement = "INSERT INTO {0} ({1}) VALUES ({2})".format(wrap(table), cols, vals) # Execute statement if execute: self._cursor.execute(s...
def insert_many(self, table, columns, values, limit=MAX_ROWS_PER_QUERY, execute=True): """ Insert multiple rows into a table. If only one row is found, self.insert method will be used. """ # Make values a list of lists if it is a flat list if not isinstance(values[0], (list, set, tuple)): values = [] for v in values: i...
def list_quizzes_in_course(self, course_id, search_term=None): """ List quizzes in a course. Returns the list of Quizzes in this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - search_term """The partial title of the quizzes to match and retu...
def create_quiz(self, course_id, quiz_title, quiz_access_code=None, quiz_allowed_attempts=None, quiz_assignment_group_id=None, quiz_cant_go_back=None, quiz_description=None, quiz_due_at=None, quiz_hide_correct_answers_at=None, quiz_hide_results=None, quiz_ip_filter=None, quiz_lock_at=None, quiz_one_question_at_a_time=N...
valid if the quiz is graded, i.e. if quiz_type is "assignment" or "graded_survey".""" if quiz_assignment_group_id is not None: data["quiz[assignment_group_id]"] = quiz_assignment_group_id # OPTIONAL - quiz[time_limit] """Time limit to take this quiz, in minutes. Set to null for no time limit. Defaults to null.""" if qu...
1). Defaults to null.""" if quiz_hide_results is not None: self._validate_enum(quiz_hide_results, ["always", "until_after_last_attempt"]) data["quiz[hide_results]"] = quiz_hide_results # OPTIONAL - quiz[show_correct_answers] """Only valid if hide_results=null If false, hides correct answers from students when quiz resu...
is not None: data["quiz[show_correct_answers_at]"] = quiz_show_correct_answers_at # OPTIONAL - quiz[hide_correct_answers_at] """Only valid if show_correct_answers=true If set, the correct answers will stop being visible once this date has passed. Otherwise, the correct answers will be visible indefinitely.""" if quiz_h...
Defaults to false.""" if quiz_one_question_at_a_time is not None: data["quiz[one_question_at_a_time]"] = quiz_one_question_at_a_time # OPTIONAL - quiz[cant_go_back] """Only valid if one_question_at_a_time=true If true, questions are locked after answering. Defaults to false.""" if quiz_cant_go_back is not None: data["q...
the quiz is due. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_due_at is not None: data["quiz[due_at]"] = quiz_due_at # OPTIONAL - quiz[lock_at] """The day/time the quiz is locked for students. Accepts times in ISO 8601 format, e.g. 2011-10-21T18:48Z.""" if quiz_lock_at is not None: data["quiz[lo...
OPTIONAL - quiz[one_time_results] """Whether students should be prevented from viewing their quiz results past the first time (right after they turn the quiz in.) Only valid if "hide_results" is not set to "always". Defaults to false.""" if quiz_one_time_results is not None: data["quiz[one_time_results]"] = quiz_one_ti...
def validate_quiz_access_code(self, id, course_id, access_code): """ Validate quiz access code. Accepts an access code and returns a boolean indicating whether that access code is correct """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - id """I...
def get(self, block=True, timeout=None): """Remove and return an item from the queue. If optional args 'block' is true and 'timeout' is None (the default), block if necessary until an item is available. If 'timeout' is a positive number, it blocks at most 'timeout' seconds and raises the Empty exception if no item was ...
def run_suite(case, config, summary): """ Run the full suite of validation tests """ m = _load_case_module(case, config) result = m.run(case, config) summary[case] = _summarize_result(m, result) _print_summary(m, case, summary) if result['Type'] == 'Book': for name, page in six.iteritems(result['Data']): functions.crea...
def artifact_already_exists(cli, meta, owner): """ Checks to see whether the built recipe (aka distribution) already exists on the owner/user's binstar account. """ distro_name = '{}/{}.tar.bz2'.format(conda.config.subdir, meta.dist()) try: dist_info = cli.distribution(owner, meta.name(), meta.version(), distro_name) e...
def _add_generate_sub_commands(self): """ Sub commands for generating models for usage by clients. Currently supports Google Closure. """ gen_parser = self._subparsers_handle.add_parser( name="gen", help="generate client side model stubs, filters" ) gen_parser.add_argument( "-t", "--template", choices=['closure.model',...
def _dispatch_gen(self): """ Process the generate subset of commands. """ if not os.path.isdir(self._args.output): raise exception.Base("%s is not a writeable directory" % self._args.output) if not os.path.isfile(self._args.models_definition): if not self.check_package_exists(self._args.models_definition): raise except...
def search(self): """Return a search using the combined query of all associated special coverage objects.""" # Retrieve all Or filters pertinent to the special coverage query. should_filters = [ es_filter.Terms(pk=self.query.get("included_ids", [])), es_filter.Terms(pk=self.query.get("pinned_ids", [])) ] should_filters...
def get_group_filters(self): """Return es OR filters to include all special coverage group conditions.""" group_filters = [] field_map = { "feature-type": "feature_type.slug", "tag": "tags.slug", "content-type": "_type" } for group_set in self.query.get("groups", []): for group in group_set: group_filter = es_filter.Ma...
def query(self): """Group the self.special_coverages queries and memoize them.""" if not self._query: self._query.update({ "excluded_ids": [], "included_ids": [], "pinned_ids": [], "groups": [], }) for special_coverage in self._special_coverages: # Access query at dict level. query = getattr(special_coverage, "query", ...
def set_extensions_for_student_quiz_submissions(self, user_id, course_id, extend_from_end_at=None, extend_from_now=None, extra_attempts=None, extra_time=None, manually_unlocked=None): """ Set extensions for student quiz submissions. <b>Responses</b> * <b>200 OK</b> if the request was successful * <b>403 Forbidden</b> i...
will add to the existing time limit on the submission. This is limited to 10080 minutes (1 week)""" if extra_time is not None: data["extra_time"] = extra_time # OPTIONAL - manually_unlocked """Allow the student to take the quiz even if it's locked for everyone else.""" if manually_unlocked is not None: data["manually_u...
= extend_from_end_at self.logger.debug("POST /api/v1/courses/{course_id}/quiz_extensions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quiz_extensions".format(**path), data=data, params=params, no_data=True)
def sam2rnf(args): """Convert SAM to RNF-based FASTQ with respect to argparse parameters. Args: args (...): Arguments parsed by argparse """ rnftools.mishmash.Source.recode_sam_reads( sam_fn=args.sam_fn, fastq_rnf_fo=args.fq_fo, fai_fo=args.fai_fo, genome_id=args.genome_id, number_of_read_tuples=10**9, simulator_name=a...
def add_sam2rnf_parser(subparsers, subcommand, help, description, simulator_name=None): """Add another parser for a SAM2RNF-like command. Args: subparsers (subparsers): File name of the genome from which read tuples are created (FASTA file). simulator_name (str): Name of the simulator used in comments. """ parser_sam2r...
def create_with_user(self, user_params, **kwargs): """ Creates an affiliate and corresponding affiliate user :param user_params: kwargs for user creation :param kwargs: :return: affiliate instance """ affiliate = self.create(**kwargs) self.api.affiliate_users.create(affiliate_id=affiliate.id, **user_params) return affi...
def list_roles(self, account_id, show_inherited=None, state=None): """ List roles. List the roles available to an account. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """The id of the account to retrieve roles for.""" path["account_id"] = account_id # OPTIONAL - state """Filter by role state. If ...
def get_single_role(self, id, role_id, account_id, role=None): """ Get a single role. Retrieve information about a single role """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - account_id """The id of the account containing the role""" path["account_id"] = account_i...
def execute_script(self, sql_script=None, commands=None, split_algo='sql_split', prep_statements=False, dump_fails=True, execute_fails=True, ignored_commands=('DROP', 'UNLOCK', 'LOCK')): """Wrapper method for SQLScript class.""" ss = Execute(sql_script, split_algo, prep_statements, dump_fails, self) ss.execute(commands...
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
def authorize_url(self, scope: list, state: str = None) -> tuple: """ Returns the URL to which the user can be redirected to authorize your application to access his/her account. It will also return the state which can be used for CSRF protection. A state is generated if not passed to this method. Example: >>> auth = O...
def obtain_token(self, redirect_url: str, state: str) -> str: """ Exchange the code that was obtained using `authorize_url` for an authorization token. The code is extracted from the URL that redirected the user back to your site. Example: >>> auth = OAuthAuthentication('https://example.com/oauth/moneybird/', 'your_id'...
[state] != url_data['state']: logger.warning("OAuth CSRF attack detected: the state in the provided URL does not equal the given state") raise ValueError("CSRF attack detected: the state in the provided URL does not equal the given state") try: response = requests.post( url=urljoin(self.base_url, self.token_url), data=...
obtaining a token: no access token") self.real_auth.set_token(response['access_token']) logger.debug("Obtained authentication token for state %s: %s" % (state, self.real_auth.auth_token)) return response['access_token']