repository_name
stringlengths
5
67
func_path_in_repository
stringlengths
4
234
func_name
stringlengths
0
314
whole_func_string
stringlengths
52
3.87M
language
stringclasses
6 values
func_code_string
stringlengths
52
3.87M
func_code_tokens
listlengths
15
672k
func_documentation_string
stringlengths
1
47.2k
func_documentation_tokens
listlengths
1
3.92k
split_name
stringclasses
1 value
func_code_url
stringlengths
85
339
arcturial/clickatell-python
clickatell/http/__init__.py
Http.getMessageCharge
def getMessageCharge(self, apiMsgId): """ See parent method for documentation """ content = self.parseLegacy(self.request('http/getmsgcharge', {'apimsgid': apiMsgId})) return { 'id': apiMsgId, 'status': content['status'], 'description': self.getStatus(content['status']), 'charge': float(content['charge']) }
python
def getMessageCharge(self, apiMsgId): """ See parent method for documentation """ content = self.parseLegacy(self.request('http/getmsgcharge', {'apimsgid': apiMsgId})) return { 'id': apiMsgId, 'status': content['status'], 'description': self.getStatus(content['status']), 'charge': float(content['charge']) }
[ "def", "getMessageCharge", "(", "self", ",", "apiMsgId", ")", ":", "content", "=", "self", ".", "parseLegacy", "(", "self", ".", "request", "(", "'http/getmsgcharge'", ",", "{", "'apimsgid'", ":", "apiMsgId", "}", ")", ")", "return", "{", "'id'", ":", "a...
See parent method for documentation
[ "See", "parent", "method", "for", "documentation" ]
train
https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/http/__init__.py#L96-L107
arcturial/clickatell-python
clickatell/http/__init__.py
Http.routeCoverage
def routeCoverage(self, msisdn): """ If the route coverage lookup encounters an error, we will treat it as "not covered". """ try: content = self.parseLegacy(self.request('utils/routeCoverage', {'msisdn': msisdn})) return { 'routable': True, 'destination': msisdn, 'charge': float(content['Charge']) } except Exception: # If we encounter any error, we will treat it like it's "not covered" # TODO perhaps catch different types of exceptions so we can isolate certain global exceptions # like authentication return { 'routable': False, 'destination': msisdn, 'charge': 0 }
python
def routeCoverage(self, msisdn): """ If the route coverage lookup encounters an error, we will treat it as "not covered". """ try: content = self.parseLegacy(self.request('utils/routeCoverage', {'msisdn': msisdn})) return { 'routable': True, 'destination': msisdn, 'charge': float(content['Charge']) } except Exception: # If we encounter any error, we will treat it like it's "not covered" # TODO perhaps catch different types of exceptions so we can isolate certain global exceptions # like authentication return { 'routable': False, 'destination': msisdn, 'charge': 0 }
[ "def", "routeCoverage", "(", "self", ",", "msisdn", ")", ":", "try", ":", "content", "=", "self", ".", "parseLegacy", "(", "self", ".", "request", "(", "'utils/routeCoverage'", ",", "{", "'msisdn'", ":", "msisdn", "}", ")", ")", "return", "{", "'routable...
If the route coverage lookup encounters an error, we will treat it as "not covered".
[ "If", "the", "route", "coverage", "lookup", "encounters", "an", "error", "we", "will", "treat", "it", "as", "not", "covered", "." ]
train
https://github.com/arcturial/clickatell-python/blob/4a554c28edaf2e5d0d9e81b4c9415241bfd61d00/clickatell/http/__init__.py#L109-L129
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.clean_publish_dates
def clean_publish_dates(self): """ If an end_date value is provided, the start_date must be less. """ if self.end_date: if not self.start_date: raise ValidationError("""The End Date requires a Start Date value.""") elif self.end_date <= self.start_date: raise ValidationError("""The End Date must not precede the Start Date.""")
python
def clean_publish_dates(self): """ If an end_date value is provided, the start_date must be less. """ if self.end_date: if not self.start_date: raise ValidationError("""The End Date requires a Start Date value.""") elif self.end_date <= self.start_date: raise ValidationError("""The End Date must not precede the Start Date.""")
[ "def", "clean_publish_dates", "(", "self", ")", ":", "if", "self", ".", "end_date", ":", "if", "not", "self", ".", "start_date", ":", "raise", "ValidationError", "(", "\"\"\"The End Date requires a Start Date value.\"\"\"", ")", "elif", "self", ".", "end_date", "<...
If an end_date value is provided, the start_date must be less.
[ "If", "an", "end_date", "value", "is", "provided", "the", "start_date", "must", "be", "less", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L55-L63
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.clean_videos
def clean_videos(self): """ Validates that all values in the video list are integer ids and removes all None values. """ if self.videos: self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
python
def clean_videos(self): """ Validates that all values in the video list are integer ids and removes all None values. """ if self.videos: self.videos = [int(v) for v in self.videos if v is not None and is_valid_digit(v)]
[ "def", "clean_videos", "(", "self", ")", ":", "if", "self", ".", "videos", ":", "self", ".", "videos", "=", "[", "int", "(", "v", ")", "for", "v", "in", "self", ".", "videos", "if", "v", "is", "not", "None", "and", "is_valid_digit", "(", "v", ")"...
Validates that all values in the video list are integer ids and removes all None values.
[ "Validates", "that", "all", "values", "in", "the", "video", "list", "are", "integer", "ids", "and", "removes", "all", "None", "values", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L74-L79
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.clean_super_features
def clean_super_features(self): """ Removes any null & non-integer values from the super feature list """ if self.super_features: self.super_features = [int(sf) for sf in self.super_features if sf is not None and is_valid_digit(sf)]
python
def clean_super_features(self): """ Removes any null & non-integer values from the super feature list """ if self.super_features: self.super_features = [int(sf) for sf in self.super_features if sf is not None and is_valid_digit(sf)]
[ "def", "clean_super_features", "(", "self", ")", ":", "if", "self", ".", "super_features", ":", "self", ".", "super_features", "=", "[", "int", "(", "sf", ")", "for", "sf", "in", "self", ".", "super_features", "if", "sf", "is", "not", "None", "and", "i...
Removes any null & non-integer values from the super feature list
[ "Removes", "any", "null", "&", "non", "-", "integer", "values", "from", "the", "super", "feature", "list" ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L81-L87
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.save
def save(self, *args, **kwargs): """Saving ensures that the slug, if not set, is set to the slugified name.""" self.clean() if not self.slug: self.slug = slugify(self.name) super(SpecialCoverage, self).save(*args, **kwargs) if self.query and self.query != {}: # Always save and require client to filter active date range self._save_percolator()
python
def save(self, *args, **kwargs): """Saving ensures that the slug, if not set, is set to the slugified name.""" self.clean() if not self.slug: self.slug = slugify(self.name) super(SpecialCoverage, self).save(*args, **kwargs) if self.query and self.query != {}: # Always save and require client to filter active date range self._save_percolator()
[ "def", "save", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "self", ".", "clean", "(", ")", "if", "not", "self", ".", "slug", ":", "self", ".", "slug", "=", "slugify", "(", "self", ".", "name", ")", "super", "(", "SpecialCo...
Saving ensures that the slug, if not set, is set to the slugified name.
[ "Saving", "ensures", "that", "the", "slug", "if", "not", "set", "is", "set", "to", "the", "slugified", "name", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L89-L100
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage._save_percolator
def _save_percolator(self): """ Saves the query field as an elasticsearch percolator """ index = Content.search_objects.mapping.index query_filter = self.get_content(published=False).to_dict() q = {} if "query" in query_filter: q = {"query": query_filter.get("query", {})} else: # We don't know how to save this return # We'll need this data, to decide which special coverage section to use q["sponsored"] = bool(self.tunic_campaign_id) # Elasticsearch v1.4 percolator "field_value_factor" does not # support missing fields, so always need to include q["start_date"] = self.start_date # NOTE: set end_date to datetime.max if special coverage has no end date # (i.e. is a neverending special coverage) q["end_date"] = self.end_date if self.end_date else datetime.max.replace(tzinfo=pytz.UTC) # Elasticsearch v1.4 percolator range query does not support DateTime range queries # (PercolateContext.nowInMillisImpl is not implemented). if q["start_date"]: q['start_date_epoch'] = datetime_to_epoch_seconds(q["start_date"]) if q["end_date"]: q['end_date_epoch'] = datetime_to_epoch_seconds(q["end_date"]) # Store manually included IDs for percolator retrieval scoring (boost # manually included content). if self.query: q['included_ids'] = self.query.get('included_ids', []) es.index( index=index, doc_type=".percolator", body=q, id=self.es_id )
python
def _save_percolator(self): """ Saves the query field as an elasticsearch percolator """ index = Content.search_objects.mapping.index query_filter = self.get_content(published=False).to_dict() q = {} if "query" in query_filter: q = {"query": query_filter.get("query", {})} else: # We don't know how to save this return # We'll need this data, to decide which special coverage section to use q["sponsored"] = bool(self.tunic_campaign_id) # Elasticsearch v1.4 percolator "field_value_factor" does not # support missing fields, so always need to include q["start_date"] = self.start_date # NOTE: set end_date to datetime.max if special coverage has no end date # (i.e. is a neverending special coverage) q["end_date"] = self.end_date if self.end_date else datetime.max.replace(tzinfo=pytz.UTC) # Elasticsearch v1.4 percolator range query does not support DateTime range queries # (PercolateContext.nowInMillisImpl is not implemented). if q["start_date"]: q['start_date_epoch'] = datetime_to_epoch_seconds(q["start_date"]) if q["end_date"]: q['end_date_epoch'] = datetime_to_epoch_seconds(q["end_date"]) # Store manually included IDs for percolator retrieval scoring (boost # manually included content). if self.query: q['included_ids'] = self.query.get('included_ids', []) es.index( index=index, doc_type=".percolator", body=q, id=self.es_id )
[ "def", "_save_percolator", "(", "self", ")", ":", "index", "=", "Content", ".", "search_objects", ".", "mapping", ".", "index", "query_filter", "=", "self", ".", "get_content", "(", "published", "=", "False", ")", ".", "to_dict", "(", ")", "q", "=", "{",...
Saves the query field as an elasticsearch percolator
[ "Saves", "the", "query", "field", "as", "an", "elasticsearch", "percolator" ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L102-L144
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.contents
def contents(self): """performs .get_content() and caches it in a ._content property """ if not hasattr(self, "_content"): self._content = self.get_content() return self._content
python
def contents(self): """performs .get_content() and caches it in a ._content property """ if not hasattr(self, "_content"): self._content = self.get_content() return self._content
[ "def", "contents", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "\"_content\"", ")", ":", "self", ".", "_content", "=", "self", ".", "get_content", "(", ")", "return", "self", ".", "_content" ]
performs .get_content() and caches it in a ._content property
[ "performs", ".", "get_content", "()", "and", "caches", "it", "in", "a", ".", "_content", "property" ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L179-L184
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.has_pinned_content
def has_pinned_content(self): """determines if the there is a pinned object in the search """ if "query" in self.query: q = self.query["query"] else: q = self.query if "pinned_ids" in q: return bool(len(q.get("pinned_ids", []))) return False
python
def has_pinned_content(self): """determines if the there is a pinned object in the search """ if "query" in self.query: q = self.query["query"] else: q = self.query if "pinned_ids" in q: return bool(len(q.get("pinned_ids", []))) return False
[ "def", "has_pinned_content", "(", "self", ")", ":", "if", "\"query\"", "in", "self", ".", "query", ":", "q", "=", "self", ".", "query", "[", "\"query\"", "]", "else", ":", "q", "=", "self", ".", "query", "if", "\"pinned_ids\"", "in", "q", ":", "retur...
determines if the there is a pinned object in the search
[ "determines", "if", "the", "there", "is", "a", "pinned", "object", "in", "the", "search" ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L191-L200
theonion/django-bulbs
bulbs/special_coverage/models.py
SpecialCoverage.custom_template_name
def custom_template_name(self): """ Returns the path for the custom special coverage template we want. """ base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom") if base_path is None: base_path = "" return "{0}/{1}_custom.html".format( base_path, self.slug.replace("-", "_") ).lstrip("/")
python
def custom_template_name(self): """ Returns the path for the custom special coverage template we want. """ base_path = getattr(settings, "CUSTOM_SPECIAL_COVERAGE_PATH", "special_coverage/custom") if base_path is None: base_path = "" return "{0}/{1}_custom.html".format( base_path, self.slug.replace("-", "_") ).lstrip("/")
[ "def", "custom_template_name", "(", "self", ")", ":", "base_path", "=", "getattr", "(", "settings", ",", "\"CUSTOM_SPECIAL_COVERAGE_PATH\"", ",", "\"special_coverage/custom\"", ")", "if", "base_path", "is", "None", ":", "base_path", "=", "\"\"", "return", "\"{0}/{1}...
Returns the path for the custom special coverage template we want.
[ "Returns", "the", "path", "for", "the", "custom", "special", "coverage", "template", "we", "want", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/special_coverage/models.py#L203-L212
anentropic/django-exclusivebooleanfield
exclusivebooleanfield/fields.py
ExclusiveBooleanField.deconstruct
def deconstruct(self): """ to support Django 1.7 migrations, see also the add_introspection_rules section at bottom of this file for South + earlier Django versions """ name, path, args, kwargs = super( ExclusiveBooleanField, self).deconstruct() if self._on_fields: kwargs['on'] = self._on_fields return name, path, args, kwargs
python
def deconstruct(self): """ to support Django 1.7 migrations, see also the add_introspection_rules section at bottom of this file for South + earlier Django versions """ name, path, args, kwargs = super( ExclusiveBooleanField, self).deconstruct() if self._on_fields: kwargs['on'] = self._on_fields return name, path, args, kwargs
[ "def", "deconstruct", "(", "self", ")", ":", "name", ",", "path", ",", "args", ",", "kwargs", "=", "super", "(", "ExclusiveBooleanField", ",", "self", ")", ".", "deconstruct", "(", ")", "if", "self", ".", "_on_fields", ":", "kwargs", "[", "'on'", "]", ...
to support Django 1.7 migrations, see also the add_introspection_rules section at bottom of this file for South + earlier Django versions
[ "to", "support", "Django", "1", ".", "7", "migrations", "see", "also", "the", "add_introspection_rules", "section", "at", "bottom", "of", "this", "file", "for", "South", "+", "earlier", "Django", "versions" ]
train
https://github.com/anentropic/django-exclusivebooleanfield/blob/e94cdc0312ee9e41758126e440fee8df7ab50049/exclusivebooleanfield/fields.py#L39-L48
hickeroar/simplebayes
simplebayes/category.py
BayesCategory.train_token
def train_token(self, word, count): """ Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in self.tokens: self.tokens[word] = 0 self.tokens[word] += count self.tally += count
python
def train_token(self, word, count): """ Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in self.tokens: self.tokens[word] = 0 self.tokens[word] += count self.tally += count
[ "def", "train_token", "(", "self", ",", "word", ",", "count", ")", ":", "if", "word", "not", "in", "self", ".", "tokens", ":", "self", ".", "tokens", "[", "word", "]", "=", "0", "self", ".", "tokens", "[", "word", "]", "+=", "count", "self", ".",...
Trains a particular token (increases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int
[ "Trains", "a", "particular", "token", "(", "increases", "the", "weight", "/", "count", "of", "it", ")" ]
train
https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/category.py#L40-L53
hickeroar/simplebayes
simplebayes/category.py
BayesCategory.untrain_token
def untrain_token(self, word, count): """ Untrains a particular token (decreases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in self.tokens: return # If we're trying to untrain more tokens than we have, we end at 0 count = min(count, self.tokens[word]) self.tokens[word] -= count self.tally -= count
python
def untrain_token(self, word, count): """ Untrains a particular token (decreases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int """ if word not in self.tokens: return # If we're trying to untrain more tokens than we have, we end at 0 count = min(count, self.tokens[word]) self.tokens[word] -= count self.tally -= count
[ "def", "untrain_token", "(", "self", ",", "word", ",", "count", ")", ":", "if", "word", "not", "in", "self", ".", "tokens", ":", "return", "# If we're trying to untrain more tokens than we have, we end at 0", "count", "=", "min", "(", "count", ",", "self", ".", ...
Untrains a particular token (decreases the weight/count of it) :param word: the token we're going to train :type word: str :param count: the number of occurances in the sample :type count: int
[ "Untrains", "a", "particular", "token", "(", "decreases", "the", "weight", "/", "count", "of", "it", ")" ]
train
https://github.com/hickeroar/simplebayes/blob/b8da72c50d20b6f8c0df2c2f39620715b08ddd32/simplebayes/category.py#L55-L71
damoti/django-postgres-schema
postgres_schema/management/commands/migrate.py
Command.sync_apps
def sync_apps(self, connection, app_labels): "Runs the old syncdb-style operation on a list of app_labels." cursor = connection.cursor() try: # Get a list of already installed *models* so that references work right. tables = connection.introspection.table_names(cursor) created_models = set() # Build the manifest of apps and models that are to be synchronized all_models = [ (app_config.label, router.get_migratable_models(app_config, connection.alias, include_auto_created=False)) for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config.label in app_labels ] def model_installed(model): opts = model._meta converter = connection.introspection.table_name_converter # Note that if a model is unmanaged we short-circuit and never try to install it return not ( (converter(opts.db_table) in tables) or (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables) ) manifest = OrderedDict( (app_name, list(filter(model_installed, model_list))) for app_name, model_list in all_models ) # Create the tables for each model if self.verbosity >= 1: self.stdout.write(" Creating tables...\n") with transaction.atomic(using=connection.alias, savepoint=connection.features.can_rollback_ddl): with connection.schema_editor() as editor: editor.execute("CREATE SCHEMA {}".format(settings.POSTGRES_TEMPLATE_SCHEMA)) statements = editor.connection.ops.prepare_sql_script(CLONE_SCHEMA) for statement in statements: editor.execute(statement, params=None) schema_deferred_sql = {} with connection.schema_editor() as editor: schema_model = apps.get_model(settings.POSTGRES_SCHEMA_MODEL) editor.create_model(schema_model, verbosity=self.verbosity) schema_deferred_sql.update(editor.schema_deferred_sql) editor.schema_deferred_sql = {} created_models.add(schema_model) for app_name, model_list in manifest.items(): for model in model_list: if not model._meta.can_migrate(connection): continue if model in created_models: continue # probably schema model if self.verbosity >= 3: self.stdout.write( " Processing %s.%s model\n" % (app_name, model._meta.object_name) ) with connection.schema_editor() as editor: editor.schema_deferred_sql.update(schema_deferred_sql) editor.create_model(model, verbosity=self.verbosity) schema_deferred_sql.update(editor.schema_deferred_sql) editor.schema_deferred_sql = {} created_models.add(model) if self.verbosity >= 1: self.stdout.write("\n Running deferred SQL...\n") with connection.schema_editor() as editor: editor.schema_deferred_sql = schema_deferred_sql finally: cursor.close() return created_models
python
def sync_apps(self, connection, app_labels): "Runs the old syncdb-style operation on a list of app_labels." cursor = connection.cursor() try: # Get a list of already installed *models* so that references work right. tables = connection.introspection.table_names(cursor) created_models = set() # Build the manifest of apps and models that are to be synchronized all_models = [ (app_config.label, router.get_migratable_models(app_config, connection.alias, include_auto_created=False)) for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config.label in app_labels ] def model_installed(model): opts = model._meta converter = connection.introspection.table_name_converter # Note that if a model is unmanaged we short-circuit and never try to install it return not ( (converter(opts.db_table) in tables) or (opts.auto_created and converter(opts.auto_created._meta.db_table) in tables) ) manifest = OrderedDict( (app_name, list(filter(model_installed, model_list))) for app_name, model_list in all_models ) # Create the tables for each model if self.verbosity >= 1: self.stdout.write(" Creating tables...\n") with transaction.atomic(using=connection.alias, savepoint=connection.features.can_rollback_ddl): with connection.schema_editor() as editor: editor.execute("CREATE SCHEMA {}".format(settings.POSTGRES_TEMPLATE_SCHEMA)) statements = editor.connection.ops.prepare_sql_script(CLONE_SCHEMA) for statement in statements: editor.execute(statement, params=None) schema_deferred_sql = {} with connection.schema_editor() as editor: schema_model = apps.get_model(settings.POSTGRES_SCHEMA_MODEL) editor.create_model(schema_model, verbosity=self.verbosity) schema_deferred_sql.update(editor.schema_deferred_sql) editor.schema_deferred_sql = {} created_models.add(schema_model) for app_name, model_list in manifest.items(): for model in model_list: if not model._meta.can_migrate(connection): continue if model in created_models: continue # probably schema model if self.verbosity >= 3: self.stdout.write( " Processing %s.%s model\n" % (app_name, model._meta.object_name) ) with connection.schema_editor() as editor: editor.schema_deferred_sql.update(schema_deferred_sql) editor.create_model(model, verbosity=self.verbosity) schema_deferred_sql.update(editor.schema_deferred_sql) editor.schema_deferred_sql = {} created_models.add(model) if self.verbosity >= 1: self.stdout.write("\n Running deferred SQL...\n") with connection.schema_editor() as editor: editor.schema_deferred_sql = schema_deferred_sql finally: cursor.close() return created_models
[ "def", "sync_apps", "(", "self", ",", "connection", ",", "app_labels", ")", ":", "cursor", "=", "connection", ".", "cursor", "(", ")", "try", ":", "# Get a list of already installed *models* so that references work right.", "tables", "=", "connection", ".", "introspec...
Runs the old syncdb-style operation on a list of app_labels.
[ "Runs", "the", "old", "syncdb", "-", "style", "operation", "on", "a", "list", "of", "app_labels", "." ]
train
https://github.com/damoti/django-postgres-schema/blob/49b7e721abaacc10ec281289df8a67bf8e8b50e0/postgres_schema/management/commands/migrate.py#L17-L94
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneData.get_database_rows
def get_database_rows(self, tables=None, database=None): """Retrieve a dictionary of table keys and list of rows values for every table.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables # Get database select queries commands = self._get_select_commands(source, tables) # Execute select commands return self._execute_select_commands(source, commands)
python
def get_database_rows(self, tables=None, database=None): """Retrieve a dictionary of table keys and list of rows values for every table.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables # Get database select queries commands = self._get_select_commands(source, tables) # Execute select commands return self._execute_select_commands(source, commands)
[ "def", "get_database_rows", "(", "self", ",", "tables", "=", "None", ",", "database", "=", "None", ")", ":", "# Get table data and columns from source database", "source", "=", "database", "if", "database", "else", "self", ".", "database", "tables", "=", "tables",...
Retrieve a dictionary of table keys and list of rows values for every table.
[ "Retrieve", "a", "dictionary", "of", "table", "keys", "and", "list", "of", "rows", "values", "for", "every", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L10-L20
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneData._get_select_commands
def _get_select_commands(self, source, tables): """ Create select queries for all of the tables from a source database. :param source: Source database name :param tables: Iterable of table names :return: Dictionary of table keys, command values """ # Create dictionary of select queries row_queries = {tbl: self.select_all(tbl, execute=False) for tbl in tqdm(tables, total=len(tables), desc='Getting {0} select queries'.format(source))} # Convert command strings into lists of commands for tbl, command in row_queries.items(): if isinstance(command, str): row_queries[tbl] = [command] # Pack commands into list of tuples return [(tbl, cmd) for tbl, cmds in row_queries.items() for cmd in cmds]
python
def _get_select_commands(self, source, tables): """ Create select queries for all of the tables from a source database. :param source: Source database name :param tables: Iterable of table names :return: Dictionary of table keys, command values """ # Create dictionary of select queries row_queries = {tbl: self.select_all(tbl, execute=False) for tbl in tqdm(tables, total=len(tables), desc='Getting {0} select queries'.format(source))} # Convert command strings into lists of commands for tbl, command in row_queries.items(): if isinstance(command, str): row_queries[tbl] = [command] # Pack commands into list of tuples return [(tbl, cmd) for tbl, cmds in row_queries.items() for cmd in cmds]
[ "def", "_get_select_commands", "(", "self", ",", "source", ",", "tables", ")", ":", "# Create dictionary of select queries", "row_queries", "=", "{", "tbl", ":", "self", ".", "select_all", "(", "tbl", ",", "execute", "=", "False", ")", "for", "tbl", "in", "t...
Create select queries for all of the tables from a source database. :param source: Source database name :param tables: Iterable of table names :return: Dictionary of table keys, command values
[ "Create", "select", "queries", "for", "all", "of", "the", "tables", "from", "a", "source", "database", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L22-L40
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneData._execute_select_commands
def _execute_select_commands(self, source, commands): """Execute select queries for all of the tables from a source database.""" rows = {} for tbl, command in tqdm(commands, total=len(commands), desc='Executing {0} select queries'.format(source)): # Add key to dictionary if tbl not in rows: rows[tbl] = [] rows[tbl].extend(self.fetch(command, commit=True)) self._commit() return rows
python
def _execute_select_commands(self, source, commands): """Execute select queries for all of the tables from a source database.""" rows = {} for tbl, command in tqdm(commands, total=len(commands), desc='Executing {0} select queries'.format(source)): # Add key to dictionary if tbl not in rows: rows[tbl] = [] rows[tbl].extend(self.fetch(command, commit=True)) self._commit() return rows
[ "def", "_execute_select_commands", "(", "self", ",", "source", ",", "commands", ")", ":", "rows", "=", "{", "}", "for", "tbl", ",", "command", "in", "tqdm", "(", "commands", ",", "total", "=", "len", "(", "commands", ")", ",", "desc", "=", "'Executing ...
Execute select queries for all of the tables from a source database.
[ "Execute", "select", "queries", "for", "all", "of", "the", "tables", "from", "a", "source", "database", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L42-L51
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneData.get_database_columns
def get_database_columns(self, tables=None, database=None): """Retrieve a dictionary of columns.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables return {tbl: self.get_columns(tbl) for tbl in tqdm(tables, total=len(tables), desc='Getting {0} columns'.format(source))}
python
def get_database_columns(self, tables=None, database=None): """Retrieve a dictionary of columns.""" # Get table data and columns from source database source = database if database else self.database tables = tables if tables else self.tables return {tbl: self.get_columns(tbl) for tbl in tqdm(tables, total=len(tables), desc='Getting {0} columns'.format(source))}
[ "def", "get_database_columns", "(", "self", ",", "tables", "=", "None", ",", "database", "=", "None", ")", ":", "# Get table data and columns from source database", "source", "=", "database", "if", "database", "else", "self", ".", "database", "tables", "=", "table...
Retrieve a dictionary of columns.
[ "Retrieve", "a", "dictionary", "of", "columns", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L53-L59
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneData._get_insert_commands
def _get_insert_commands(self, rows, cols): """Retrieve dictionary of insert statements to be executed.""" # Get insert queries insert_queries = {} for table in tqdm(list(rows.keys()), total=len(list(rows.keys())), desc='Getting insert rows queries'): insert_queries[table] = {} _rows = rows.pop(table) _cols = cols.pop(table) if len(_rows) > 1: insert_queries[table]['insert_many'] = self.insert_many(table, _cols, _rows, execute=False) elif len(_rows) == 1: insert_queries[table]['insert'] = self.insert(table, _cols, _rows, execute=False) return insert_queries
python
def _get_insert_commands(self, rows, cols): """Retrieve dictionary of insert statements to be executed.""" # Get insert queries insert_queries = {} for table in tqdm(list(rows.keys()), total=len(list(rows.keys())), desc='Getting insert rows queries'): insert_queries[table] = {} _rows = rows.pop(table) _cols = cols.pop(table) if len(_rows) > 1: insert_queries[table]['insert_many'] = self.insert_many(table, _cols, _rows, execute=False) elif len(_rows) == 1: insert_queries[table]['insert'] = self.insert(table, _cols, _rows, execute=False) return insert_queries
[ "def", "_get_insert_commands", "(", "self", ",", "rows", ",", "cols", ")", ":", "# Get insert queries", "insert_queries", "=", "{", "}", "for", "table", "in", "tqdm", "(", "list", "(", "rows", ".", "keys", "(", ")", ")", ",", "total", "=", "len", "(", ...
Retrieve dictionary of insert statements to be executed.
[ "Retrieve", "dictionary", "of", "insert", "statements", "to", "be", "executed", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L61-L74
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneDatabase.copy_database_structure
def copy_database_structure(self, source, destination, tables=None): """Copy multiple tables from one database to another.""" # Change database to source self.change_db(source) if tables is None: tables = self.tables # Change database to destination self.change_db(destination) for t in tqdm(tables, total=len(tables), desc='Copying {0} table structure'.format(source)): self.copy_table_structure(source, destination, t)
python
def copy_database_structure(self, source, destination, tables=None): """Copy multiple tables from one database to another.""" # Change database to source self.change_db(source) if tables is None: tables = self.tables # Change database to destination self.change_db(destination) for t in tqdm(tables, total=len(tables), desc='Copying {0} table structure'.format(source)): self.copy_table_structure(source, destination, t)
[ "def", "copy_database_structure", "(", "self", ",", "source", ",", "destination", ",", "tables", "=", "None", ")", ":", "# Change database to source", "self", ".", "change_db", "(", "source", ")", "if", "tables", "is", "None", ":", "tables", "=", "self", "."...
Copy multiple tables from one database to another.
[ "Copy", "multiple", "tables", "from", "one", "database", "to", "another", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L90-L101
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneDatabase.copy_table_structure
def copy_table_structure(self, source, destination, table): """ Copy a table from one database to another. :param source: Source database :param destination: Destination database :param table: Table name """ self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source))
python
def copy_table_structure(self, source, destination, table): """ Copy a table from one database to another. :param source: Source database :param destination: Destination database :param table: Table name """ self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source))
[ "def", "copy_table_structure", "(", "self", ",", "source", ",", "destination", ",", "table", ")", ":", "self", ".", "execute", "(", "'CREATE TABLE {0}.{1} LIKE {2}.{1}'", ".", "format", "(", "destination", ",", "wrap", "(", "table", ")", ",", "source", ")", ...
Copy a table from one database to another. :param source: Source database :param destination: Destination database :param table: Table name
[ "Copy", "a", "table", "from", "one", "database", "to", "another", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L103-L111
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneDatabase.copy_database_data
def copy_database_data(self, source, destination, optimized=False): """ Copy the data from one database to another. Retrieve existing data from the source database and insert that data into the destination database. """ # Change database to source self.enable_printing = False self.change_db(source) tables = self.tables # Copy database data by executing INSERT and SELECT commands in a single query if optimized: self._copy_database_data_serverside(source, destination, tables) # Generate and execute SELECT and INSERT commands else: self._copy_database_data_clientside(tables, source, destination) self.enable_printing = True
python
def copy_database_data(self, source, destination, optimized=False): """ Copy the data from one database to another. Retrieve existing data from the source database and insert that data into the destination database. """ # Change database to source self.enable_printing = False self.change_db(source) tables = self.tables # Copy database data by executing INSERT and SELECT commands in a single query if optimized: self._copy_database_data_serverside(source, destination, tables) # Generate and execute SELECT and INSERT commands else: self._copy_database_data_clientside(tables, source, destination) self.enable_printing = True
[ "def", "copy_database_data", "(", "self", ",", "source", ",", "destination", ",", "optimized", "=", "False", ")", ":", "# Change database to source", "self", ".", "enable_printing", "=", "False", "self", ".", "change_db", "(", "source", ")", "tables", "=", "se...
Copy the data from one database to another. Retrieve existing data from the source database and insert that data into the destination database.
[ "Copy", "the", "data", "from", "one", "database", "to", "another", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L113-L132
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneDatabase._copy_database_data_serverside
def _copy_database_data_serverside(self, source, destination, tables): """Select rows from a source database and insert them into a destination db in one query""" for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'): self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source))
python
def _copy_database_data_serverside(self, source, destination, tables): """Select rows from a source database and insert them into a destination db in one query""" for table in tqdm(tables, total=len(tables), desc='Copying table data (optimized)'): self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source))
[ "def", "_copy_database_data_serverside", "(", "self", ",", "source", ",", "destination", ",", "tables", ")", ":", "for", "table", "in", "tqdm", "(", "tables", ",", "total", "=", "len", "(", "tables", ")", ",", "desc", "=", "'Copying table data (optimized)'", ...
Select rows from a source database and insert them into a destination db in one query
[ "Select", "rows", "from", "a", "source", "database", "and", "insert", "them", "into", "a", "destination", "db", "in", "one", "query" ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L134-L137
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
CloneDatabase._copy_database_data_clientside
def _copy_database_data_clientside(self, tables, source, destination): """Copy the data from a table into another table.""" # Retrieve database rows rows = self.get_database_rows(tables, source) # Retrieve database columns cols = self.get_database_columns(tables, source) # Validate rows and columns for r in list(rows.keys()): assert r in tables for c in list(cols.keys()): assert c in tables # Change database to destination self.change_db(destination) # Get insert queries insert_queries = self._get_insert_commands(rows, cols) # Execute insert queries self._execute_insert_commands(insert_queries)
python
def _copy_database_data_clientside(self, tables, source, destination): """Copy the data from a table into another table.""" # Retrieve database rows rows = self.get_database_rows(tables, source) # Retrieve database columns cols = self.get_database_columns(tables, source) # Validate rows and columns for r in list(rows.keys()): assert r in tables for c in list(cols.keys()): assert c in tables # Change database to destination self.change_db(destination) # Get insert queries insert_queries = self._get_insert_commands(rows, cols) # Execute insert queries self._execute_insert_commands(insert_queries)
[ "def", "_copy_database_data_clientside", "(", "self", ",", "tables", ",", "source", ",", "destination", ")", ":", "# Retrieve database rows", "rows", "=", "self", ".", "get_database_rows", "(", "tables", ",", "source", ")", "# Retrieve database columns", "cols", "="...
Copy the data from a table into another table.
[ "Copy", "the", "data", "from", "a", "table", "into", "another", "table", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L139-L160
mrstephenneal/mysql-toolkit
mysql/toolkit/components/operations/clone.py
Clone.copy_database
def copy_database(self, source, destination): """ Copy a database's content and structure. SMALL Database speed improvements (DB size < 5mb) Using optimized is about 178% faster Using one_query is about 200% faster LARGE Database speed improvements (DB size > 5mb) Using optimized is about 900% faster Using one_query is about 2600% faster :param source: Source database :param destination: Destination database """ print('\tCopying database {0} structure and data to database {1}'.format(source, destination)) with Timer('\nSuccess! Copied database {0} to {1} in '.format(source, destination)): # Create destination database if it does not exist if destination in self.databases: self.truncate_database(destination) # Truncate database if it does exist else: self.create_database(destination) # Copy database structure and data self.change_db(source) tables = self.tables # Change database to destination self.change_db(destination) print('\n') _enable_printing = self.enable_printing self.enable_printing = False # Copy tables structure for table in tqdm(tables, total=len(tables), desc='Copying {0} table structures'.format(source)): self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source)) # Copy tables data for table in tqdm(tables, total=len(tables), desc='Copying {0} table data'.format(source)): self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source)) self.enable_printing = _enable_printing
python
def copy_database(self, source, destination): """ Copy a database's content and structure. SMALL Database speed improvements (DB size < 5mb) Using optimized is about 178% faster Using one_query is about 200% faster LARGE Database speed improvements (DB size > 5mb) Using optimized is about 900% faster Using one_query is about 2600% faster :param source: Source database :param destination: Destination database """ print('\tCopying database {0} structure and data to database {1}'.format(source, destination)) with Timer('\nSuccess! Copied database {0} to {1} in '.format(source, destination)): # Create destination database if it does not exist if destination in self.databases: self.truncate_database(destination) # Truncate database if it does exist else: self.create_database(destination) # Copy database structure and data self.change_db(source) tables = self.tables # Change database to destination self.change_db(destination) print('\n') _enable_printing = self.enable_printing self.enable_printing = False # Copy tables structure for table in tqdm(tables, total=len(tables), desc='Copying {0} table structures'.format(source)): self.execute('CREATE TABLE {0}.{1} LIKE {2}.{1}'.format(destination, wrap(table), source)) # Copy tables data for table in tqdm(tables, total=len(tables), desc='Copying {0} table data'.format(source)): self.execute('INSERT INTO {0}.{1} SELECT * FROM {2}.{1}'.format(destination, wrap(table), source)) self.enable_printing = _enable_printing
[ "def", "copy_database", "(", "self", ",", "source", ",", "destination", ")", ":", "print", "(", "'\\tCopying database {0} structure and data to database {1}'", ".", "format", "(", "source", ",", "destination", ")", ")", "with", "Timer", "(", "'\\nSuccess! Copied datab...
Copy a database's content and structure. SMALL Database speed improvements (DB size < 5mb) Using optimized is about 178% faster Using one_query is about 200% faster LARGE Database speed improvements (DB size > 5mb) Using optimized is about 900% faster Using one_query is about 2600% faster :param source: Source database :param destination: Destination database
[ "Copy", "a", "database", "s", "content", "and", "structure", "." ]
train
https://github.com/mrstephenneal/mysql-toolkit/blob/6964f718f4b72eb30f2259adfcfaf3090526c53d/mysql/toolkit/components/operations/clone.py#L164-L205
karel-brinda/rnftools
rnftools/mishmash/CuReSim.py
CuReSim.recode_curesim_reads
def recode_curesim_reads( curesim_fastq_fo, rnf_fastq_fo, fai_fo, genome_id, number_of_read_tuples=10**9, recode_random=False, ): """Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file. Args: curesim_fastq_fo (file object): File object of CuReSim FASTQ file. fastq_rnf_fo (file object): File object of RNF FASTQ. fai_fo (file object): File object for FAI file of the reference genome. genome_id (int): RNF genome ID to be used. number_of_read_tuples (int): Expected number of read tuples (to estimate number of digits in RNF). recode_random (bool): Recode random reads. Raises: ValueError """ curesim_pattern = re.compile('@(.*)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)') """ CuReSim read name format @<#1>_<#2>_<#3>_<#4>_<#5>_<#6>_<#7>_<#8> 1: contig name 2: original position 3: strand (0=forward;1=reverse) 4: random read (0=non-random;1=random) 5: number of insertions 6: number of deletions 7: number of substitution 8: read number (unique within a genome) """ max_seq_len = 0 fai_index = rnftools.utils.FaIdx(fai_fo=fai_fo) read_tuple_id_width = len(format(number_of_read_tuples, 'x')) fq_creator = rnftools.rnfformat.FqCreator( fastq_fo=rnf_fastq_fo, read_tuple_id_width=read_tuple_id_width, genome_id_width=2, chr_id_width=fai_index.chr_id_width, coor_width=fai_index.coor_width, info_reads_in_tuple=True, info_simulator="curesim", ) # parsing FQ file read_tuple_id = 0 i = 0 for line in curesim_fastq_fo: if i % 4 == 0: m = curesim_pattern.search(line) if m is None: rnftools.utils.error( "Read '{}' was not generated by CuReSim.".format(line[1:]), program="RNFtools", subprogram="MIShmash", exception=ValueError ) contig_name = m.group(1) start_pos = int(m.group(2)) direction = "R" if int(m.group(3)) else "F" random = bool(m.group(4)) ins_nb = int(m.group(5)) del_nb = int(m.group(6)) subst_nb = int(m.group(7)) rd_id = int(m.group(8)) end_pos = start_pos - 1 - ins_nb + del_nb chr_id = 0 random = contig_name[:4] == "rand" # TODO: uncomment when the chromosome naming bug in curesim is corrected # chr_id = self.dict_chr_ids[contig_name] if self.dict_chr_ids!={} else "0" elif i % 4 == 1: bases = line.strip() end_pos += len(bases) if recode_random: left = 0 right = 0 else: left = start_pos + 1 right = end_pos segment = rnftools.rnfformat.Segment( genome_id=genome_id, chr_id=chr_id, direction=direction, left=left, right=right, ) elif i % 4 == 2: pass elif i % 4 == 3: qualities = line.strip() if random == recode_random: fq_creator.add_read( read_tuple_id=read_tuple_id, bases=bases, qualities=qualities, segments=[segment], ) read_tuple_id += 1 i += 1 fq_creator.flush_read_tuple()
python
def recode_curesim_reads( curesim_fastq_fo, rnf_fastq_fo, fai_fo, genome_id, number_of_read_tuples=10**9, recode_random=False, ): """Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file. Args: curesim_fastq_fo (file object): File object of CuReSim FASTQ file. fastq_rnf_fo (file object): File object of RNF FASTQ. fai_fo (file object): File object for FAI file of the reference genome. genome_id (int): RNF genome ID to be used. number_of_read_tuples (int): Expected number of read tuples (to estimate number of digits in RNF). recode_random (bool): Recode random reads. Raises: ValueError """ curesim_pattern = re.compile('@(.*)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)') """ CuReSim read name format @<#1>_<#2>_<#3>_<#4>_<#5>_<#6>_<#7>_<#8> 1: contig name 2: original position 3: strand (0=forward;1=reverse) 4: random read (0=non-random;1=random) 5: number of insertions 6: number of deletions 7: number of substitution 8: read number (unique within a genome) """ max_seq_len = 0 fai_index = rnftools.utils.FaIdx(fai_fo=fai_fo) read_tuple_id_width = len(format(number_of_read_tuples, 'x')) fq_creator = rnftools.rnfformat.FqCreator( fastq_fo=rnf_fastq_fo, read_tuple_id_width=read_tuple_id_width, genome_id_width=2, chr_id_width=fai_index.chr_id_width, coor_width=fai_index.coor_width, info_reads_in_tuple=True, info_simulator="curesim", ) # parsing FQ file read_tuple_id = 0 i = 0 for line in curesim_fastq_fo: if i % 4 == 0: m = curesim_pattern.search(line) if m is None: rnftools.utils.error( "Read '{}' was not generated by CuReSim.".format(line[1:]), program="RNFtools", subprogram="MIShmash", exception=ValueError ) contig_name = m.group(1) start_pos = int(m.group(2)) direction = "R" if int(m.group(3)) else "F" random = bool(m.group(4)) ins_nb = int(m.group(5)) del_nb = int(m.group(6)) subst_nb = int(m.group(7)) rd_id = int(m.group(8)) end_pos = start_pos - 1 - ins_nb + del_nb chr_id = 0 random = contig_name[:4] == "rand" # TODO: uncomment when the chromosome naming bug in curesim is corrected # chr_id = self.dict_chr_ids[contig_name] if self.dict_chr_ids!={} else "0" elif i % 4 == 1: bases = line.strip() end_pos += len(bases) if recode_random: left = 0 right = 0 else: left = start_pos + 1 right = end_pos segment = rnftools.rnfformat.Segment( genome_id=genome_id, chr_id=chr_id, direction=direction, left=left, right=right, ) elif i % 4 == 2: pass elif i % 4 == 3: qualities = line.strip() if random == recode_random: fq_creator.add_read( read_tuple_id=read_tuple_id, bases=bases, qualities=qualities, segments=[segment], ) read_tuple_id += 1 i += 1 fq_creator.flush_read_tuple()
[ "def", "recode_curesim_reads", "(", "curesim_fastq_fo", ",", "rnf_fastq_fo", ",", "fai_fo", ",", "genome_id", ",", "number_of_read_tuples", "=", "10", "**", "9", ",", "recode_random", "=", "False", ",", ")", ":", "curesim_pattern", "=", "re", ".", "compile", "...
Recode CuReSim output FASTQ file to the RNF-compatible output FASTQ file. Args: curesim_fastq_fo (file object): File object of CuReSim FASTQ file. fastq_rnf_fo (file object): File object of RNF FASTQ. fai_fo (file object): File object for FAI file of the reference genome. genome_id (int): RNF genome ID to be used. number_of_read_tuples (int): Expected number of read tuples (to estimate number of digits in RNF). recode_random (bool): Recode random reads. Raises: ValueError
[ "Recode", "CuReSim", "output", "FASTQ", "file", "to", "the", "RNF", "-", "compatible", "output", "FASTQ", "file", "." ]
train
https://github.com/karel-brinda/rnftools/blob/25510798606fbc803a622a1abfcecf06d00d47a9/rnftools/mishmash/CuReSim.py#L157-L278
bharadwaj-raju/libdesktop
libdesktop/directories.py
get_config_dir
def get_config_dir(program='', system_wide=False): '''Get the configuration directory. Get the configuration directories, optionally for a specific program. Args: program (str) : The name of the program whose configuration directories have to be found. system_wide (bool): Gets the system-wide configuration directories. Returns: list: A list of all matching configuration directories found. ''' config_homes = [] if system_wide: if os.name == 'nt': config_homes.append( winreg.ExpandEnvironmentStrings('%PROGRAMDATA%')) else: config_homes.append('/etc') config_homes.append('/etc/xdg') if os.name == 'darwin': config_homes.append('/Library') else: if os.name == 'nt': import winreg config_homes.append( winreg.ExpandEnvironmentStrings('%LOCALAPPDATA%')) config_homes.append( os.path.join( winreg.ExpandEnvironmentStrings('%APPDATA%'), 'Roaming')) else: if os.getenv('XDG_CONFIG_HOME'): config_homes.append(os.getenv('XDG_CONFIG_HOME')) else: try: from xdg import BaseDirectory config_homes.append(BaseDirectory.xdg_config_home) except ImportError: config_homes.append(os.path.expanduser('~/.config')) config_homes.append(os.path.expanduser('~')) if os.name == 'darwin': config_homes.append(os.path.expanduser('~/Library')) if program: def __find_homes(app, dirs): homes = [] for home in dirs: if os.path.isdir(os.path.join(home, app)): homes.append(os.path.join(home, app)) if os.path.isdir(os.path.join(home, '.' + app)): homes.append(os.path.join(home, '.' + app)) if os.path.isdir(os.path.join(home, app + '.d')): homes.append(os.path.join(home, app + '.d')) return homes app_homes = __find_homes(program, config_homes) # Special Cases if program == 'vim': app_homes.extend(__find_homes('vimfiles', config_homes)) elif program == 'chrome': app_homes.extend(__find_homes('google-chrome', config_homes)) elif program in ['firefox', 'thunderbird']: app_homes.extend( __find_homes( program, [ os.path.expanduser('~/.mozilla')])) return app_homes return config_homes
python
def get_config_dir(program='', system_wide=False): '''Get the configuration directory. Get the configuration directories, optionally for a specific program. Args: program (str) : The name of the program whose configuration directories have to be found. system_wide (bool): Gets the system-wide configuration directories. Returns: list: A list of all matching configuration directories found. ''' config_homes = [] if system_wide: if os.name == 'nt': config_homes.append( winreg.ExpandEnvironmentStrings('%PROGRAMDATA%')) else: config_homes.append('/etc') config_homes.append('/etc/xdg') if os.name == 'darwin': config_homes.append('/Library') else: if os.name == 'nt': import winreg config_homes.append( winreg.ExpandEnvironmentStrings('%LOCALAPPDATA%')) config_homes.append( os.path.join( winreg.ExpandEnvironmentStrings('%APPDATA%'), 'Roaming')) else: if os.getenv('XDG_CONFIG_HOME'): config_homes.append(os.getenv('XDG_CONFIG_HOME')) else: try: from xdg import BaseDirectory config_homes.append(BaseDirectory.xdg_config_home) except ImportError: config_homes.append(os.path.expanduser('~/.config')) config_homes.append(os.path.expanduser('~')) if os.name == 'darwin': config_homes.append(os.path.expanduser('~/Library')) if program: def __find_homes(app, dirs): homes = [] for home in dirs: if os.path.isdir(os.path.join(home, app)): homes.append(os.path.join(home, app)) if os.path.isdir(os.path.join(home, '.' + app)): homes.append(os.path.join(home, '.' + app)) if os.path.isdir(os.path.join(home, app + '.d')): homes.append(os.path.join(home, app + '.d')) return homes app_homes = __find_homes(program, config_homes) # Special Cases if program == 'vim': app_homes.extend(__find_homes('vimfiles', config_homes)) elif program == 'chrome': app_homes.extend(__find_homes('google-chrome', config_homes)) elif program in ['firefox', 'thunderbird']: app_homes.extend( __find_homes( program, [ os.path.expanduser('~/.mozilla')])) return app_homes return config_homes
[ "def", "get_config_dir", "(", "program", "=", "''", ",", "system_wide", "=", "False", ")", ":", "config_homes", "=", "[", "]", "if", "system_wide", ":", "if", "os", ".", "name", "==", "'nt'", ":", "config_homes", ".", "append", "(", "winreg", ".", "Exp...
Get the configuration directory. Get the configuration directories, optionally for a specific program. Args: program (str) : The name of the program whose configuration directories have to be found. system_wide (bool): Gets the system-wide configuration directories. Returns: list: A list of all matching configuration directories found.
[ "Get", "the", "configuration", "directory", "." ]
train
https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/directories.py#L180-L266
bharadwaj-raju/libdesktop
libdesktop/directories.py
get_config_file
def get_config_file(program, system_wide=False): '''Get the configuration file for a program. Gets the configuration file for a given program, assuming it stores it in a standard location. See also :func:`get_config_dir()`. Args: program (str): The program for which to get the configuration file. system_wide (bool):Whether to get the system-wide file for the program. Returns: list: A list of all matching configuration files found. ''' program_config_homes = get_config_dir(program, system_wide) config_homes = get_config_dir(system_wide=system_wide) config_files = [] for home in config_homes: for sub in os.listdir(home): if os.path.isfile(os.path.join(home, sub)): if sub.startswith(program): config_files.append(os.path.join(home, sub)) if not program.startswith('.'): config_files.extend(get_config_file('.' + program, system_wide)) for home in program_config_homes: for sub in os.listdir(home): if os.path.isfile(os.path.join(home, sub) ) and sub.startswith(program): config_files.append(os.path.join(home, sub)) return config_files
python
def get_config_file(program, system_wide=False): '''Get the configuration file for a program. Gets the configuration file for a given program, assuming it stores it in a standard location. See also :func:`get_config_dir()`. Args: program (str): The program for which to get the configuration file. system_wide (bool):Whether to get the system-wide file for the program. Returns: list: A list of all matching configuration files found. ''' program_config_homes = get_config_dir(program, system_wide) config_homes = get_config_dir(system_wide=system_wide) config_files = [] for home in config_homes: for sub in os.listdir(home): if os.path.isfile(os.path.join(home, sub)): if sub.startswith(program): config_files.append(os.path.join(home, sub)) if not program.startswith('.'): config_files.extend(get_config_file('.' + program, system_wide)) for home in program_config_homes: for sub in os.listdir(home): if os.path.isfile(os.path.join(home, sub) ) and sub.startswith(program): config_files.append(os.path.join(home, sub)) return config_files
[ "def", "get_config_file", "(", "program", ",", "system_wide", "=", "False", ")", ":", "program_config_homes", "=", "get_config_dir", "(", "program", ",", "system_wide", ")", "config_homes", "=", "get_config_dir", "(", "system_wide", "=", "system_wide", ")", "confi...
Get the configuration file for a program. Gets the configuration file for a given program, assuming it stores it in a standard location. See also :func:`get_config_dir()`. Args: program (str): The program for which to get the configuration file. system_wide (bool):Whether to get the system-wide file for the program. Returns: list: A list of all matching configuration files found.
[ "Get", "the", "configuration", "file", "for", "a", "program", "." ]
train
https://github.com/bharadwaj-raju/libdesktop/blob/4d6b815755c76660b6ef4d2db6f54beff38c0db7/libdesktop/directories.py#L269-L302
coddingtonbear/taskwarrior-capsules
taskwarrior_capsules/capsule.py
CommandCapsule.get_tasks_changed_since
def get_tasks_changed_since(self, since): """ Returns a list of tasks that were changed recently.""" changed_tasks = [] for task in self.client.filter_tasks({'status': 'pending'}): if task.get( 'modified', task.get( 'entry', datetime.datetime(2000, 1, 1).replace(tzinfo=pytz.utc) ) ) >= since: changed_tasks.append(task) return changed_tasks
python
def get_tasks_changed_since(self, since): """ Returns a list of tasks that were changed recently.""" changed_tasks = [] for task in self.client.filter_tasks({'status': 'pending'}): if task.get( 'modified', task.get( 'entry', datetime.datetime(2000, 1, 1).replace(tzinfo=pytz.utc) ) ) >= since: changed_tasks.append(task) return changed_tasks
[ "def", "get_tasks_changed_since", "(", "self", ",", "since", ")", ":", "changed_tasks", "=", "[", "]", "for", "task", "in", "self", ".", "client", ".", "filter_tasks", "(", "{", "'status'", ":", "'pending'", "}", ")", ":", "if", "task", ".", "get", "("...
Returns a list of tasks that were changed recently.
[ "Returns", "a", "list", "of", "tasks", "that", "were", "changed", "recently", "." ]
train
https://github.com/coddingtonbear/taskwarrior-capsules/blob/63f4b7cd801d13db31760fa32def26d3168f3c69/taskwarrior_capsules/capsule.py#L140-L154
theonion/django-bulbs
bulbs/content/managers.py
ContentManager.evergreen
def evergreen(self, included_channel_ids=None, excluded_channel_ids=None, **kwargs): """ Search containing any evergreen piece of Content. :included_channel_ids list: Contains ids for channel ids relevant to the query. :excluded_channel_ids list: Contains ids for channel ids excluded from the query. """ eqs = self.search(**kwargs) eqs = eqs.filter(Evergreen()) if included_channel_ids: eqs = eqs.filter(VideohubChannel(included_ids=included_channel_ids)) if excluded_channel_ids: eqs = eqs.filter(VideohubChannel(excluded_ids=excluded_channel_ids)) return eqs
python
def evergreen(self, included_channel_ids=None, excluded_channel_ids=None, **kwargs): """ Search containing any evergreen piece of Content. :included_channel_ids list: Contains ids for channel ids relevant to the query. :excluded_channel_ids list: Contains ids for channel ids excluded from the query. """ eqs = self.search(**kwargs) eqs = eqs.filter(Evergreen()) if included_channel_ids: eqs = eqs.filter(VideohubChannel(included_ids=included_channel_ids)) if excluded_channel_ids: eqs = eqs.filter(VideohubChannel(excluded_ids=excluded_channel_ids)) return eqs
[ "def", "evergreen", "(", "self", ",", "included_channel_ids", "=", "None", ",", "excluded_channel_ids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "eqs", "=", "self", ".", "search", "(", "*", "*", "kwargs", ")", "eqs", "=", "eqs", ".", "filter", ...
Search containing any evergreen piece of Content. :included_channel_ids list: Contains ids for channel ids relevant to the query. :excluded_channel_ids list: Contains ids for channel ids excluded from the query.
[ "Search", "containing", "any", "evergreen", "piece", "of", "Content", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/managers.py#L18-L31
theonion/django-bulbs
bulbs/content/managers.py
ContentManager.evergreen_video
def evergreen_video(self, **kwargs): """Filter evergreen content to exclusively video content.""" eqs = self.evergreen(**kwargs) eqs = eqs.filter(VideohubVideo()) return eqs
python
def evergreen_video(self, **kwargs): """Filter evergreen content to exclusively video content.""" eqs = self.evergreen(**kwargs) eqs = eqs.filter(VideohubVideo()) return eqs
[ "def", "evergreen_video", "(", "self", ",", "*", "*", "kwargs", ")", ":", "eqs", "=", "self", ".", "evergreen", "(", "*", "*", "kwargs", ")", "eqs", "=", "eqs", ".", "filter", "(", "VideohubVideo", "(", ")", ")", "return", "eqs" ]
Filter evergreen content to exclusively video content.
[ "Filter", "evergreen", "content", "to", "exclusively", "video", "content", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/managers.py#L33-L37
theonion/django-bulbs
bulbs/content/managers.py
ContentManager.instant_articles
def instant_articles(self, **kwargs): """ QuerySet including all published content approved for instant articles. Instant articles are configured via FeatureType. FeatureType.instant_article = True. """ eqs = self.search(**kwargs).sort('-last_modified', '-published') return eqs.filter(InstantArticle())
python
def instant_articles(self, **kwargs): """ QuerySet including all published content approved for instant articles. Instant articles are configured via FeatureType. FeatureType.instant_article = True. """ eqs = self.search(**kwargs).sort('-last_modified', '-published') return eqs.filter(InstantArticle())
[ "def", "instant_articles", "(", "self", ",", "*", "*", "kwargs", ")", ":", "eqs", "=", "self", ".", "search", "(", "*", "*", "kwargs", ")", ".", "sort", "(", "'-last_modified'", ",", "'-published'", ")", "return", "eqs", ".", "filter", "(", "InstantArt...
QuerySet including all published content approved for instant articles. Instant articles are configured via FeatureType. FeatureType.instant_article = True.
[ "QuerySet", "including", "all", "published", "content", "approved", "for", "instant", "articles", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/managers.py#L44-L51
theonion/django-bulbs
bulbs/content/managers.py
ContentManager.sponsored
def sponsored(self, **kwargs): """Search containing any sponsored pieces of Content.""" eqs = self.search(**kwargs) eqs = eqs.filter(AllSponsored()) published_offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", None) if published_offset: now = timezone.now() eqs = eqs.filter( Published( after=now - timezone.timedelta(hours=published_offset), before=now ) ) return eqs
python
def sponsored(self, **kwargs): """Search containing any sponsored pieces of Content.""" eqs = self.search(**kwargs) eqs = eqs.filter(AllSponsored()) published_offset = getattr(settings, "RECENT_SPONSORED_OFFSET_HOURS", None) if published_offset: now = timezone.now() eqs = eqs.filter( Published( after=now - timezone.timedelta(hours=published_offset), before=now ) ) return eqs
[ "def", "sponsored", "(", "self", ",", "*", "*", "kwargs", ")", ":", "eqs", "=", "self", ".", "search", "(", "*", "*", "kwargs", ")", "eqs", "=", "eqs", ".", "filter", "(", "AllSponsored", "(", ")", ")", "published_offset", "=", "getattr", "(", "set...
Search containing any sponsored pieces of Content.
[ "Search", "containing", "any", "sponsored", "pieces", "of", "Content", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/managers.py#L53-L66
theonion/django-bulbs
bulbs/content/managers.py
ContentManager.search
def search(self, **kwargs): """ Query using ElasticSearch, returning an elasticsearch queryset. :param kwargs: keyword arguments (optional) * query : ES Query spec * tags : content tags * types : content types * feature_types : featured types * published : date range """ search_query = super(ContentManager, self).search() if "query" in kwargs: search_query = search_query.query("match", _all=kwargs.get("query")) else: search_query = search_query.sort('-published', '-last_modified') # Right now we have "Before", "After" (datetimes), # and "published" (a boolean). Should simplify this in the future. if "before" in kwargs or "after" in kwargs: published_filter = Published(before=kwargs.get("before"), after=kwargs.get("after")) search_query = search_query.filter(published_filter) else: # TODO: kill this "published" param. it sucks if kwargs.get("published", True) and "status" not in kwargs: published_filter = Published() search_query = search_query.filter(published_filter) if "status" in kwargs: search_query = search_query.filter(Status(kwargs["status"])) if "excluded_ids" in kwargs: exclusion_filter = ~es_filter.Ids(values=kwargs.get("excluded_ids", [])) search_query = search_query.filter(exclusion_filter) tag_filter = Tags(kwargs.get("tags", [])) search_query = search_query.filter(tag_filter) author_filter = Authors(kwargs.get("authors", [])) search_query = search_query.filter(author_filter) feature_type_filter = FeatureTypes(kwargs.get("feature_types", [])) search_query = search_query.filter(feature_type_filter) # Is this good enough? Are we even using this feature at all? types = kwargs.pop("types", []) if types: search_query._doc_type = types return search_query
python
def search(self, **kwargs): """ Query using ElasticSearch, returning an elasticsearch queryset. :param kwargs: keyword arguments (optional) * query : ES Query spec * tags : content tags * types : content types * feature_types : featured types * published : date range """ search_query = super(ContentManager, self).search() if "query" in kwargs: search_query = search_query.query("match", _all=kwargs.get("query")) else: search_query = search_query.sort('-published', '-last_modified') # Right now we have "Before", "After" (datetimes), # and "published" (a boolean). Should simplify this in the future. if "before" in kwargs or "after" in kwargs: published_filter = Published(before=kwargs.get("before"), after=kwargs.get("after")) search_query = search_query.filter(published_filter) else: # TODO: kill this "published" param. it sucks if kwargs.get("published", True) and "status" not in kwargs: published_filter = Published() search_query = search_query.filter(published_filter) if "status" in kwargs: search_query = search_query.filter(Status(kwargs["status"])) if "excluded_ids" in kwargs: exclusion_filter = ~es_filter.Ids(values=kwargs.get("excluded_ids", [])) search_query = search_query.filter(exclusion_filter) tag_filter = Tags(kwargs.get("tags", [])) search_query = search_query.filter(tag_filter) author_filter = Authors(kwargs.get("authors", [])) search_query = search_query.filter(author_filter) feature_type_filter = FeatureTypes(kwargs.get("feature_types", [])) search_query = search_query.filter(feature_type_filter) # Is this good enough? Are we even using this feature at all? types = kwargs.pop("types", []) if types: search_query._doc_type = types return search_query
[ "def", "search", "(", "self", ",", "*", "*", "kwargs", ")", ":", "search_query", "=", "super", "(", "ContentManager", ",", "self", ")", ".", "search", "(", ")", "if", "\"query\"", "in", "kwargs", ":", "search_query", "=", "search_query", ".", "query", ...
Query using ElasticSearch, returning an elasticsearch queryset. :param kwargs: keyword arguments (optional) * query : ES Query spec * tags : content tags * types : content types * feature_types : featured types * published : date range
[ "Query", "using", "ElasticSearch", "returning", "an", "elasticsearch", "queryset", "." ]
train
https://github.com/theonion/django-bulbs/blob/0c0e6e3127a7dc487b96677fab95cacd2b3806da/bulbs/content/managers.py#L68-L117
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_obj_class
def get_obj_class(self, obj_type): """ Returns the object class based on parent and object types. In most cases the object class can be derived from object type alone but sometimes the same object type name is used for different object types so the parent (or even grandparent) type is required in order to determine the exact object type. For example, interface object type can be child of vport or router (ospf etc.). In the first case the required class is IxnInterface while in the later case it is IxnObject. :param obj_type: IXN object type. :return: object class if specific class else IxnObject. """ if obj_type in IxnObject.str_2_class: if type(IxnObject.str_2_class[obj_type]) is dict: if self.obj_type() in IxnObject.str_2_class[obj_type]: return IxnObject.str_2_class[obj_type][self.obj_type()] elif self.obj_parent().obj_type() in IxnObject.str_2_class[obj_type]: return IxnObject.str_2_class[obj_type][self.obj_parent().obj_type()] else: return IxnObject.str_2_class[obj_type] return IxnObject
python
def get_obj_class(self, obj_type): """ Returns the object class based on parent and object types. In most cases the object class can be derived from object type alone but sometimes the same object type name is used for different object types so the parent (or even grandparent) type is required in order to determine the exact object type. For example, interface object type can be child of vport or router (ospf etc.). In the first case the required class is IxnInterface while in the later case it is IxnObject. :param obj_type: IXN object type. :return: object class if specific class else IxnObject. """ if obj_type in IxnObject.str_2_class: if type(IxnObject.str_2_class[obj_type]) is dict: if self.obj_type() in IxnObject.str_2_class[obj_type]: return IxnObject.str_2_class[obj_type][self.obj_type()] elif self.obj_parent().obj_type() in IxnObject.str_2_class[obj_type]: return IxnObject.str_2_class[obj_type][self.obj_parent().obj_type()] else: return IxnObject.str_2_class[obj_type] return IxnObject
[ "def", "get_obj_class", "(", "self", ",", "obj_type", ")", ":", "if", "obj_type", "in", "IxnObject", ".", "str_2_class", ":", "if", "type", "(", "IxnObject", ".", "str_2_class", "[", "obj_type", "]", ")", "is", "dict", ":", "if", "self", ".", "obj_type",...
Returns the object class based on parent and object types. In most cases the object class can be derived from object type alone but sometimes the same object type name is used for different object types so the parent (or even grandparent) type is required in order to determine the exact object type. For example, interface object type can be child of vport or router (ospf etc.). In the first case the required class is IxnInterface while in the later case it is IxnObject. :param obj_type: IXN object type. :return: object class if specific class else IxnObject.
[ "Returns", "the", "object", "class", "based", "on", "parent", "and", "object", "types", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L28-L49
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_attribute
def get_attribute(self, attribute): """ :param attribute: requested attributes. :return: attribute value. :raise TgnError: if invalid attribute. """ value = self.api.getAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if value == '::ixNet::OK': raise TgnError(self.ref + ' does not have attribute ' + attribute) return str(value)
python
def get_attribute(self, attribute): """ :param attribute: requested attributes. :return: attribute value. :raise TgnError: if invalid attribute. """ value = self.api.getAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if value == '::ixNet::OK': raise TgnError(self.ref + ' does not have attribute ' + attribute) return str(value)
[ "def", "get_attribute", "(", "self", ",", "attribute", ")", ":", "value", "=", "self", ".", "api", ".", "getAttribute", "(", "self", ".", "obj_ref", "(", ")", ",", "attribute", ")", "# IXN returns '::ixNet::OK' for invalid attributes. We want error.", "if", "value...
:param attribute: requested attributes. :return: attribute value. :raise TgnError: if invalid attribute.
[ ":", "param", "attribute", ":", "requested", "attributes", ".", ":", "return", ":", "attribute", "value", ".", ":", "raise", "TgnError", ":", "if", "invalid", "attribute", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L71-L81
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_list_attribute
def get_list_attribute(self, attribute): """ :return: attribute value as Python list. """ list_attribute = self.api.getListAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if list_attribute == ['::ixNet::OK']: raise TgnError(self.ref + ' does not have attribute ' + attribute) return list_attribute
python
def get_list_attribute(self, attribute): """ :return: attribute value as Python list. """ list_attribute = self.api.getListAttribute(self.obj_ref(), attribute) # IXN returns '::ixNet::OK' for invalid attributes. We want error. if list_attribute == ['::ixNet::OK']: raise TgnError(self.ref + ' does not have attribute ' + attribute) return list_attribute
[ "def", "get_list_attribute", "(", "self", ",", "attribute", ")", ":", "list_attribute", "=", "self", ".", "api", ".", "getListAttribute", "(", "self", ".", "obj_ref", "(", ")", ",", "attribute", ")", "# IXN returns '::ixNet::OK' for invalid attributes. We want error."...
:return: attribute value as Python list.
[ ":", "return", ":", "attribute", "value", "as", "Python", "list", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L83-L91
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_children
def get_children(self, *types): """ Read (getList) children from IXN. Use this method to align with current IXN configuration. :param types: list of requested children. :return: list of all children objects of the requested types. """ children_objs = OrderedDict() if not types: types = self.get_all_child_types(self.obj_ref()) for child_type in types: children_list = self.api.getList(self.obj_ref(), child_type) children_objs.update(self._build_children_objs(child_type, children_list)) return list(children_objs.values())
python
def get_children(self, *types): """ Read (getList) children from IXN. Use this method to align with current IXN configuration. :param types: list of requested children. :return: list of all children objects of the requested types. """ children_objs = OrderedDict() if not types: types = self.get_all_child_types(self.obj_ref()) for child_type in types: children_list = self.api.getList(self.obj_ref(), child_type) children_objs.update(self._build_children_objs(child_type, children_list)) return list(children_objs.values())
[ "def", "get_children", "(", "self", ",", "*", "types", ")", ":", "children_objs", "=", "OrderedDict", "(", ")", "if", "not", "types", ":", "types", "=", "self", ".", "get_all_child_types", "(", "self", ".", "obj_ref", "(", ")", ")", "for", "child_type", ...
Read (getList) children from IXN. Use this method to align with current IXN configuration. :param types: list of requested children. :return: list of all children objects of the requested types.
[ "Read", "(", "getList", ")", "children", "from", "IXN", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L93-L108
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_child_static
def get_child_static(self, objType, seq_number=None): """ Returns IxnObject representing the requested child without reading it from the IXN. Statically build the child object reference based on the requested object type and sequence number and build the IxnObject with this calculated object reference. Ideally we would prefer to never use this function and always read the child dynamically but this has huge impact on performance so we use the static approach wherever possible. """ child_obj_ref = self.obj_ref() + '/' + objType if seq_number: child_obj_ref += ':' + str(seq_number) child_obj = self.get_object_by_ref(child_obj_ref) child_obj_type = self.get_obj_class(objType) return child_obj if child_obj else child_obj_type(parent=self, objType=objType, objRef=child_obj_ref)
python
def get_child_static(self, objType, seq_number=None): """ Returns IxnObject representing the requested child without reading it from the IXN. Statically build the child object reference based on the requested object type and sequence number and build the IxnObject with this calculated object reference. Ideally we would prefer to never use this function and always read the child dynamically but this has huge impact on performance so we use the static approach wherever possible. """ child_obj_ref = self.obj_ref() + '/' + objType if seq_number: child_obj_ref += ':' + str(seq_number) child_obj = self.get_object_by_ref(child_obj_ref) child_obj_type = self.get_obj_class(objType) return child_obj if child_obj else child_obj_type(parent=self, objType=objType, objRef=child_obj_ref)
[ "def", "get_child_static", "(", "self", ",", "objType", ",", "seq_number", "=", "None", ")", ":", "child_obj_ref", "=", "self", ".", "obj_ref", "(", ")", "+", "'/'", "+", "objType", "if", "seq_number", ":", "child_obj_ref", "+=", "':'", "+", "str", "(", ...
Returns IxnObject representing the requested child without reading it from the IXN. Statically build the child object reference based on the requested object type and sequence number and build the IxnObject with this calculated object reference. Ideally we would prefer to never use this function and always read the child dynamically but this has huge impact on performance so we use the static approach wherever possible.
[ "Returns", "IxnObject", "representing", "the", "requested", "child", "without", "reading", "it", "from", "the", "IXN", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L110-L123
shmir/PyIxNetwork
ixnetwork/ixn_object.py
IxnObject.get_ref_indices
def get_ref_indices(self): """ :return: list of all indices in object reference. """ ixn_obj = self ref_indices = [] while ixn_obj != ixn_obj.root: ref_indices.append(ixn_obj.ref.split(':')[-1]) ixn_obj = ixn_obj.parent return ref_indices[::-1]
python
def get_ref_indices(self): """ :return: list of all indices in object reference. """ ixn_obj = self ref_indices = [] while ixn_obj != ixn_obj.root: ref_indices.append(ixn_obj.ref.split(':')[-1]) ixn_obj = ixn_obj.parent return ref_indices[::-1]
[ "def", "get_ref_indices", "(", "self", ")", ":", "ixn_obj", "=", "self", "ref_indices", "=", "[", "]", "while", "ixn_obj", "!=", "ixn_obj", ".", "root", ":", "ref_indices", ".", "append", "(", "ixn_obj", ".", "ref", ".", "split", "(", "':'", ")", "[", ...
:return: list of all indices in object reference.
[ ":", "return", ":", "list", "of", "all", "indices", "in", "object", "reference", "." ]
train
https://github.com/shmir/PyIxNetwork/blob/e7d7a89c08a5d3a1382b4dcfd915bbfc7eedd33f/ixnetwork/ixn_object.py#L166-L176
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.list_conversations
def list_conversations(self, filter=None, filter_mode=None, include=None, include_all_conversation_ids=None, interleave_submissions=None, scope=None): """ List conversations. Returns the list of conversations for the current user, most recent ones first. """ path = {} data = {} params = {} # OPTIONAL - scope """When set, only return conversations of the specified type. For example, set to "unread" to return only conversations that haven't been read. The default behavior is to return all non-archived conversations (i.e. read and unread).""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) params["scope"] = scope # OPTIONAL - filter """When set, only return conversations for the specified courses, groups or users. The id should be prefixed with its type, e.g. "user_123" or "course_456". Can be an array (by setting "filter[]") or single value (by setting "filter")""" if filter is not None: params["filter"] = filter # OPTIONAL - filter_mode """When filter[] contains multiple filters, combine them with this mode, filtering conversations that at have at least all of the contexts ("and") or at least one of the contexts ("or")""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) params["filter_mode"] = filter_mode # OPTIONAL - interleave_submissions """(Obsolete) Submissions are no longer linked to conversations. This parameter is ignored.""" if interleave_submissions is not None: params["interleave_submissions"] = interleave_submissions # OPTIONAL - include_all_conversation_ids """Default is false. If true, the top-level element of the response will be an object rather than an array, and will have the keys "conversations" which will contain the paged conversation data, and "conversation_ids" which will contain the ids of all conversations under this scope/filter in the same order.""" if include_all_conversation_ids is not None: params["include_all_conversation_ids"] = include_all_conversation_ids # OPTIONAL - include """"participant_avatars":: Optionally include an "avatar_url" key for each user participanting in the conversation""" if include is not None: self._validate_enum(include, ["participant_avatars"]) params["include"] = include self.logger.debug("GET /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/conversations".format(**path), data=data, params=params, all_pages=True)
python
def list_conversations(self, filter=None, filter_mode=None, include=None, include_all_conversation_ids=None, interleave_submissions=None, scope=None): """ List conversations. Returns the list of conversations for the current user, most recent ones first. """ path = {} data = {} params = {} # OPTIONAL - scope """When set, only return conversations of the specified type. For example, set to "unread" to return only conversations that haven't been read. The default behavior is to return all non-archived conversations (i.e. read and unread).""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) params["scope"] = scope # OPTIONAL - filter """When set, only return conversations for the specified courses, groups or users. The id should be prefixed with its type, e.g. "user_123" or "course_456". Can be an array (by setting "filter[]") or single value (by setting "filter")""" if filter is not None: params["filter"] = filter # OPTIONAL - filter_mode """When filter[] contains multiple filters, combine them with this mode, filtering conversations that at have at least all of the contexts ("and") or at least one of the contexts ("or")""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) params["filter_mode"] = filter_mode # OPTIONAL - interleave_submissions """(Obsolete) Submissions are no longer linked to conversations. This parameter is ignored.""" if interleave_submissions is not None: params["interleave_submissions"] = interleave_submissions # OPTIONAL - include_all_conversation_ids """Default is false. If true, the top-level element of the response will be an object rather than an array, and will have the keys "conversations" which will contain the paged conversation data, and "conversation_ids" which will contain the ids of all conversations under this scope/filter in the same order.""" if include_all_conversation_ids is not None: params["include_all_conversation_ids"] = include_all_conversation_ids # OPTIONAL - include """"participant_avatars":: Optionally include an "avatar_url" key for each user participanting in the conversation""" if include is not None: self._validate_enum(include, ["participant_avatars"]) params["include"] = include self.logger.debug("GET /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/conversations".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_conversations", "(", "self", ",", "filter", "=", "None", ",", "filter_mode", "=", "None", ",", "include", "=", "None", ",", "include_all_conversation_ids", "=", "None", ",", "interleave_submissions", "=", "None", ",", "scope", "=", "None", ")", ...
List conversations. Returns the list of conversations for the current user, most recent ones first.
[ "List", "conversations", ".", "Returns", "the", "list", "of", "conversations", "for", "the", "current", "user", "most", "recent", "ones", "first", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L19-L76
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.create_conversation
def create_conversation(self, body, recipients, attachment_ids=None, context_code=None, filter=None, filter_mode=None, group_conversation=None, media_comment_id=None, media_comment_type=None, mode=None, scope=None, subject=None, user_note=None): """ Create a conversation. Create a new conversation with one or more recipients. If there is already an existing private conversation with the given recipients, it will be reused. """ path = {} data = {} params = {} # REQUIRED - recipients """An array of recipient ids. These may be user ids or course/group ids prefixed with "course_" or "group_" respectively, e.g. recipients[]=1&recipients[]=2&recipients[]=course_3""" data["recipients"] = recipients # OPTIONAL - subject """The subject of the conversation. This is ignored when reusing a conversation. Maximum length is 255 characters.""" if subject is not None: data["subject"] = subject # REQUIRED - body """The message to be sent""" data["body"] = body # OPTIONAL - group_conversation """Defaults to false. If true, this will be a group conversation (i.e. all recipients may see all messages and replies). If false, individual private conversations will be started with each recipient. Must be set false if the number of recipients is over the set maximum (default is 100).""" if group_conversation is not None: data["group_conversation"] = group_conversation # OPTIONAL - attachment_ids """An array of attachments ids. These must be files that have been previously uploaded to the sender's "conversation attachments" folder.""" if attachment_ids is not None: data["attachment_ids"] = attachment_ids # OPTIONAL - media_comment_id """Media comment id of an audio of video file to be associated with this message.""" if media_comment_id is not None: data["media_comment_id"] = media_comment_id # OPTIONAL - media_comment_type """Type of the associated media file""" if media_comment_type is not None: self._validate_enum(media_comment_type, ["audio", "video"]) data["media_comment_type"] = media_comment_type # OPTIONAL - user_note """Will add a faculty journal entry for each recipient as long as the user making the api call has permission, the recipient is a student and faculty journals are enabled in the account.""" if user_note is not None: data["user_note"] = user_note # OPTIONAL - mode """Determines whether the messages will be created/sent synchronously or asynchronously. Defaults to sync, and this option is ignored if this is a group conversation or there is just one recipient (i.e. it must be a bulk private message). When sent async, the response will be an empty array (batch status can be queried via the {api:ConversationsController#batches batches API})""" if mode is not None: self._validate_enum(mode, ["sync", "async"]) data["mode"] = mode # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) data["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: data["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) data["filter_mode"] = filter_mode # OPTIONAL - context_code """The course or group that is the context for this conversation. Same format as courses or groups in the recipients argument.""" if context_code is not None: data["context_code"] = context_code self.logger.debug("POST /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations".format(**path), data=data, params=params, no_data=True)
python
def create_conversation(self, body, recipients, attachment_ids=None, context_code=None, filter=None, filter_mode=None, group_conversation=None, media_comment_id=None, media_comment_type=None, mode=None, scope=None, subject=None, user_note=None): """ Create a conversation. Create a new conversation with one or more recipients. If there is already an existing private conversation with the given recipients, it will be reused. """ path = {} data = {} params = {} # REQUIRED - recipients """An array of recipient ids. These may be user ids or course/group ids prefixed with "course_" or "group_" respectively, e.g. recipients[]=1&recipients[]=2&recipients[]=course_3""" data["recipients"] = recipients # OPTIONAL - subject """The subject of the conversation. This is ignored when reusing a conversation. Maximum length is 255 characters.""" if subject is not None: data["subject"] = subject # REQUIRED - body """The message to be sent""" data["body"] = body # OPTIONAL - group_conversation """Defaults to false. If true, this will be a group conversation (i.e. all recipients may see all messages and replies). If false, individual private conversations will be started with each recipient. Must be set false if the number of recipients is over the set maximum (default is 100).""" if group_conversation is not None: data["group_conversation"] = group_conversation # OPTIONAL - attachment_ids """An array of attachments ids. These must be files that have been previously uploaded to the sender's "conversation attachments" folder.""" if attachment_ids is not None: data["attachment_ids"] = attachment_ids # OPTIONAL - media_comment_id """Media comment id of an audio of video file to be associated with this message.""" if media_comment_id is not None: data["media_comment_id"] = media_comment_id # OPTIONAL - media_comment_type """Type of the associated media file""" if media_comment_type is not None: self._validate_enum(media_comment_type, ["audio", "video"]) data["media_comment_type"] = media_comment_type # OPTIONAL - user_note """Will add a faculty journal entry for each recipient as long as the user making the api call has permission, the recipient is a student and faculty journals are enabled in the account.""" if user_note is not None: data["user_note"] = user_note # OPTIONAL - mode """Determines whether the messages will be created/sent synchronously or asynchronously. Defaults to sync, and this option is ignored if this is a group conversation or there is just one recipient (i.e. it must be a bulk private message). When sent async, the response will be an empty array (batch status can be queried via the {api:ConversationsController#batches batches API})""" if mode is not None: self._validate_enum(mode, ["sync", "async"]) data["mode"] = mode # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) data["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: data["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) data["filter_mode"] = filter_mode # OPTIONAL - context_code """The course or group that is the context for this conversation. Same format as courses or groups in the recipients argument.""" if context_code is not None: data["context_code"] = context_code self.logger.debug("POST /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations".format(**path), data=data, params=params, no_data=True)
[ "def", "create_conversation", "(", "self", ",", "body", ",", "recipients", ",", "attachment_ids", "=", "None", ",", "context_code", "=", "None", ",", "filter", "=", "None", ",", "filter_mode", "=", "None", ",", "group_conversation", "=", "None", ",", "media_...
Create a conversation. Create a new conversation with one or more recipients. If there is already an existing private conversation with the given recipients, it will be reused.
[ "Create", "a", "conversation", ".", "Create", "a", "new", "conversation", "with", "one", "or", "more", "recipients", ".", "If", "there", "is", "already", "an", "existing", "private", "conversation", "with", "the", "given", "recipients", "it", "will", "be", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L78-L176
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.get_single_conversation
def get_single_conversation(self, id, auto_mark_as_read=None, filter=None, filter_mode=None, interleave_submissions=None, scope=None): """ Get a single conversation. Returns information for a single conversation for the current user. Response includes all fields that are present in the list/index action as well as messages and extended participant information. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - interleave_submissions """(Obsolete) Submissions are no longer linked to conversations. This parameter is ignored.""" if interleave_submissions is not None: params["interleave_submissions"] = interleave_submissions # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) params["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: params["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) params["filter_mode"] = filter_mode # OPTIONAL - auto_mark_as_read """Default true. If true, unread conversations will be automatically marked as read. This will default to false in a future API release, so clients should explicitly send true if that is the desired behavior.""" if auto_mark_as_read is not None: params["auto_mark_as_read"] = auto_mark_as_read self.logger.debug("GET /api/v1/conversations/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/conversations/{id}".format(**path), data=data, params=params, no_data=True)
python
def get_single_conversation(self, id, auto_mark_as_read=None, filter=None, filter_mode=None, interleave_submissions=None, scope=None): """ Get a single conversation. Returns information for a single conversation for the current user. Response includes all fields that are present in the list/index action as well as messages and extended participant information. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - interleave_submissions """(Obsolete) Submissions are no longer linked to conversations. This parameter is ignored.""" if interleave_submissions is not None: params["interleave_submissions"] = interleave_submissions # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) params["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: params["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) params["filter_mode"] = filter_mode # OPTIONAL - auto_mark_as_read """Default true. If true, unread conversations will be automatically marked as read. This will default to false in a future API release, so clients should explicitly send true if that is the desired behavior.""" if auto_mark_as_read is not None: params["auto_mark_as_read"] = auto_mark_as_read self.logger.debug("GET /api/v1/conversations/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/conversations/{id}".format(**path), data=data, params=params, no_data=True)
[ "def", "get_single_conversation", "(", "self", ",", "id", ",", "auto_mark_as_read", "=", "None", ",", "filter", "=", "None", ",", "filter_mode", "=", "None", ",", "interleave_submissions", "=", "None", ",", "scope", "=", "None", ")", ":", "path", "=", "{",...
Get a single conversation. Returns information for a single conversation for the current user. Response includes all fields that are present in the list/index action as well as messages and extended participant information.
[ "Get", "a", "single", "conversation", ".", "Returns", "information", "for", "a", "single", "conversation", "for", "the", "current", "user", ".", "Response", "includes", "all", "fields", "that", "are", "present", "in", "the", "list", "/", "index", "action", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L193-L244
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.edit_conversation
def edit_conversation(self, id, conversation_starred=None, conversation_subscribed=None, conversation_workflow_state=None, filter=None, filter_mode=None, scope=None): """ Edit a conversation. Updates attributes for a single conversation. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - conversation[workflow_state] """Change the state of this conversation""" if conversation_workflow_state is not None: self._validate_enum(conversation_workflow_state, ["read", "unread", "archived"]) data["conversation[workflow_state]"] = conversation_workflow_state # OPTIONAL - conversation[subscribed] """Toggle the current user's subscription to the conversation (only valid for group conversations). If unsubscribed, the user will still have access to the latest messages, but the conversation won't be automatically flagged as unread, nor will it jump to the top of the inbox.""" if conversation_subscribed is not None: data["conversation[subscribed]"] = conversation_subscribed # OPTIONAL - conversation[starred] """Toggle the starred state of the current user's view of the conversation.""" if conversation_starred is not None: data["conversation[starred]"] = conversation_starred # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) data["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: data["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) data["filter_mode"] = filter_mode self.logger.debug("PUT /api/v1/conversations/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/conversations/{id}".format(**path), data=data, params=params, no_data=True)
python
def edit_conversation(self, id, conversation_starred=None, conversation_subscribed=None, conversation_workflow_state=None, filter=None, filter_mode=None, scope=None): """ Edit a conversation. Updates attributes for a single conversation. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - conversation[workflow_state] """Change the state of this conversation""" if conversation_workflow_state is not None: self._validate_enum(conversation_workflow_state, ["read", "unread", "archived"]) data["conversation[workflow_state]"] = conversation_workflow_state # OPTIONAL - conversation[subscribed] """Toggle the current user's subscription to the conversation (only valid for group conversations). If unsubscribed, the user will still have access to the latest messages, but the conversation won't be automatically flagged as unread, nor will it jump to the top of the inbox.""" if conversation_subscribed is not None: data["conversation[subscribed]"] = conversation_subscribed # OPTIONAL - conversation[starred] """Toggle the starred state of the current user's view of the conversation.""" if conversation_starred is not None: data["conversation[starred]"] = conversation_starred # OPTIONAL - scope """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if scope is not None: self._validate_enum(scope, ["unread", "starred", "archived"]) data["scope"] = scope # OPTIONAL - filter """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter is not None: data["filter"] = filter # OPTIONAL - filter_mode """Used when generating "visible" in the API response. See the explanation under the {api:ConversationsController#index index API action}""" if filter_mode is not None: self._validate_enum(filter_mode, ["and", "or", "default or"]) data["filter_mode"] = filter_mode self.logger.debug("PUT /api/v1/conversations/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/conversations/{id}".format(**path), data=data, params=params, no_data=True)
[ "def", "edit_conversation", "(", "self", ",", "id", ",", "conversation_starred", "=", "None", ",", "conversation_subscribed", "=", "None", ",", "conversation_workflow_state", "=", "None", ",", "filter", "=", "None", ",", "filter_mode", "=", "None", ",", "scope",...
Edit a conversation. Updates attributes for a single conversation.
[ "Edit", "a", "conversation", ".", "Updates", "attributes", "for", "a", "single", "conversation", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L246-L300
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.add_recipients
def add_recipients(self, id, recipients): """ Add recipients. Add recipients to an existing group conversation. Response is similar to the GET/show action, except that only includes the latest message (e.g. "joe was added to the conversation by bob") """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - recipients """An array of recipient ids. These may be user ids or course/group ids prefixed with "course_" or "group_" respectively, e.g. recipients[]=1&recipients[]=2&recipients[]=course_3""" data["recipients"] = recipients self.logger.debug("POST /api/v1/conversations/{id}/add_recipients with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/add_recipients".format(**path), data=data, params=params, no_data=True)
python
def add_recipients(self, id, recipients): """ Add recipients. Add recipients to an existing group conversation. Response is similar to the GET/show action, except that only includes the latest message (e.g. "joe was added to the conversation by bob") """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - recipients """An array of recipient ids. These may be user ids or course/group ids prefixed with "course_" or "group_" respectively, e.g. recipients[]=1&recipients[]=2&recipients[]=course_3""" data["recipients"] = recipients self.logger.debug("POST /api/v1/conversations/{id}/add_recipients with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/add_recipients".format(**path), data=data, params=params, no_data=True)
[ "def", "add_recipients", "(", "self", ",", "id", ",", "recipients", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - recipien...
Add recipients. Add recipients to an existing group conversation. Response is similar to the GET/show action, except that only includes the latest message (e.g. "joe was added to the conversation by bob")
[ "Add", "recipients", ".", "Add", "recipients", "to", "an", "existing", "group", "conversation", ".", "Response", "is", "similar", "to", "the", "GET", "/", "show", "action", "except", "that", "only", "includes", "the", "latest", "message", "(", "e", ".", "g...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L335-L358
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.add_message
def add_message(self, id, body, attachment_ids=None, included_messages=None, media_comment_id=None, media_comment_type=None, recipients=None, user_note=None): """ Add a message. Add a message to an existing conversation. Response is similar to the GET/show action, except that only includes the latest message (i.e. what we just sent) An array of user ids. Defaults to all of the current conversation recipients. To explicitly send a message to no other recipients, this array should consist of the logged-in user id. An array of message ids from this conversation to send to recipients of the new message. Recipients who already had a copy of included messages will not be affected. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - body """The message to be sent.""" data["body"] = body # OPTIONAL - attachment_ids """An array of attachments ids. These must be files that have been previously uploaded to the sender's "conversation attachments" folder.""" if attachment_ids is not None: data["attachment_ids"] = attachment_ids # OPTIONAL - media_comment_id """Media comment id of an audio of video file to be associated with this message.""" if media_comment_id is not None: data["media_comment_id"] = media_comment_id # OPTIONAL - media_comment_type """Type of the associated media file.""" if media_comment_type is not None: self._validate_enum(media_comment_type, ["audio", "video"]) data["media_comment_type"] = media_comment_type # OPTIONAL - recipients """no description""" if recipients is not None: data["recipients"] = recipients # OPTIONAL - included_messages """no description""" if included_messages is not None: data["included_messages"] = included_messages # OPTIONAL - user_note """Will add a faculty journal entry for each recipient as long as the user making the api call has permission, the recipient is a student and faculty journals are enabled in the account.""" if user_note is not None: data["user_note"] = user_note self.logger.debug("POST /api/v1/conversations/{id}/add_message with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/add_message".format(**path), data=data, params=params, no_data=True)
python
def add_message(self, id, body, attachment_ids=None, included_messages=None, media_comment_id=None, media_comment_type=None, recipients=None, user_note=None): """ Add a message. Add a message to an existing conversation. Response is similar to the GET/show action, except that only includes the latest message (i.e. what we just sent) An array of user ids. Defaults to all of the current conversation recipients. To explicitly send a message to no other recipients, this array should consist of the logged-in user id. An array of message ids from this conversation to send to recipients of the new message. Recipients who already had a copy of included messages will not be affected. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - body """The message to be sent.""" data["body"] = body # OPTIONAL - attachment_ids """An array of attachments ids. These must be files that have been previously uploaded to the sender's "conversation attachments" folder.""" if attachment_ids is not None: data["attachment_ids"] = attachment_ids # OPTIONAL - media_comment_id """Media comment id of an audio of video file to be associated with this message.""" if media_comment_id is not None: data["media_comment_id"] = media_comment_id # OPTIONAL - media_comment_type """Type of the associated media file.""" if media_comment_type is not None: self._validate_enum(media_comment_type, ["audio", "video"]) data["media_comment_type"] = media_comment_type # OPTIONAL - recipients """no description""" if recipients is not None: data["recipients"] = recipients # OPTIONAL - included_messages """no description""" if included_messages is not None: data["included_messages"] = included_messages # OPTIONAL - user_note """Will add a faculty journal entry for each recipient as long as the user making the api call has permission, the recipient is a student and faculty journals are enabled in the account.""" if user_note is not None: data["user_note"] = user_note self.logger.debug("POST /api/v1/conversations/{id}/add_message with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/add_message".format(**path), data=data, params=params, no_data=True)
[ "def", "add_message", "(", "self", ",", "id", ",", "body", ",", "attachment_ids", "=", "None", ",", "included_messages", "=", "None", ",", "media_comment_id", "=", "None", ",", "media_comment_type", "=", "None", ",", "recipients", "=", "None", ",", "user_not...
Add a message. Add a message to an existing conversation. Response is similar to the GET/show action, except that only includes the latest message (i.e. what we just sent) An array of user ids. Defaults to all of the current conversation recipients. To explicitly send a message to no other recipients, this array should consist of the logged-in user id. An array of message ids from this conversation to send to recipients of the new message. Recipients who already had a copy of included messages will not be affected.
[ "Add", "a", "message", ".", "Add", "a", "message", "to", "an", "existing", "conversation", ".", "Response", "is", "similar", "to", "the", "GET", "/", "show", "action", "except", "that", "only", "includes", "the", "latest", "message", "(", "i", ".", "e", ...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L360-L424
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.delete_message
def delete_message(self, id, remove): """ Delete a message. Delete messages from this conversation. Note that this only affects this user's view of the conversation. If all messages are deleted, the conversation will be as well (equivalent to DELETE) """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - remove """Array of message ids to be deleted""" data["remove"] = remove self.logger.debug("POST /api/v1/conversations/{id}/remove_messages with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/remove_messages".format(**path), data=data, params=params, no_data=True)
python
def delete_message(self, id, remove): """ Delete a message. Delete messages from this conversation. Note that this only affects this user's view of the conversation. If all messages are deleted, the conversation will be as well (equivalent to DELETE) """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - remove """Array of message ids to be deleted""" data["remove"] = remove self.logger.debug("POST /api/v1/conversations/{id}/remove_messages with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/conversations/{id}/remove_messages".format(**path), data=data, params=params, no_data=True)
[ "def", "delete_message", "(", "self", ",", "id", ",", "remove", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - remove\r", ...
Delete a message. Delete messages from this conversation. Note that this only affects this user's view of the conversation. If all messages are deleted, the conversation will be as well (equivalent to DELETE)
[ "Delete", "a", "message", ".", "Delete", "messages", "from", "this", "conversation", ".", "Note", "that", "this", "only", "affects", "this", "user", "s", "view", "of", "the", "conversation", ".", "If", "all", "messages", "are", "deleted", "the", "conversatio...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L426-L447
PGower/PyCanvas
pycanvas/apis/conversations.py
ConversationsAPI.batch_update_conversations
def batch_update_conversations(self, event, conversation_ids): """ Batch update conversations. Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. """ path = {} data = {} params = {} # REQUIRED - conversation_ids """List of conversations to update. Limited to 500 conversations.""" data["conversation_ids"] = conversation_ids # REQUIRED - event """The action to take on each conversation.""" self._validate_enum(event, ["mark_as_read", "mark_as_unread", "star", "unstar", "archive", "destroy"]) data["event"] = event self.logger.debug("PUT /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/conversations".format(**path), data=data, params=params, single_item=True)
python
def batch_update_conversations(self, event, conversation_ids): """ Batch update conversations. Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. """ path = {} data = {} params = {} # REQUIRED - conversation_ids """List of conversations to update. Limited to 500 conversations.""" data["conversation_ids"] = conversation_ids # REQUIRED - event """The action to take on each conversation.""" self._validate_enum(event, ["mark_as_read", "mark_as_unread", "star", "unstar", "archive", "destroy"]) data["event"] = event self.logger.debug("PUT /api/v1/conversations with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/conversations".format(**path), data=data, params=params, single_item=True)
[ "def", "batch_update_conversations", "(", "self", ",", "event", ",", "conversation_ids", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - conversation_ids\r", "\"\"\"List of conversations to update. Limited to 500 conversati...
Batch update conversations. Perform a change on a set of conversations. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation.
[ "Batch", "update", "conversations", ".", "Perform", "a", "change", "on", "a", "set", "of", "conversations", ".", "Operates", "asynchronously", ";", "use", "the", "{", "api", ":", "ProgressController#show", "progress", "endpoint", "}", "to", "query", "the", "st...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/conversations.py#L449-L470
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
list_preferences_communication_channel_id
def list_preferences_communication_channel_id(self, user_id, communication_channel_id): """ List preferences. Fetch all preferences for the given communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences".format(**path), data=data, params=params, all_pages=True)
python
def list_preferences_communication_channel_id(self, user_id, communication_channel_id): """ List preferences. Fetch all preferences for the given communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_preferences_communication_channel_id", "(", "self", ",", "user_id", ",", "communication_channel_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"us...
List preferences. Fetch all preferences for the given communication channel
[ "List", "preferences", ".", "Fetch", "all", "preferences", "for", "the", "given", "communication", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L19-L38
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
list_preferences_type
def list_preferences_type(self, type, user_id, address): """ List preferences. Fetch all preferences for the given communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences".format(**path), data=data, params=params, all_pages=True)
python
def list_preferences_type(self, type, user_id, address): """ List preferences. Fetch all preferences for the given communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_preferences_type", "(", "self", ",", "type", ",", "user_id", ",", "address", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "...
List preferences. Fetch all preferences for the given communication channel
[ "List", "preferences", ".", "Fetch", "all", "preferences", "for", "the", "given", "communication", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L40-L63
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
get_preference_communication_channel_id
def get_preference_communication_channel_id(self, user_id, notification, communication_channel_id): """ Get a preference. Fetch the preference for the given notification for the given communicaiton channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - notification """ID""" path["notification"] = notification self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification}".format(**path), data=data, params=params, single_item=True)
python
def get_preference_communication_channel_id(self, user_id, notification, communication_channel_id): """ Get a preference. Fetch the preference for the given notification for the given communicaiton channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - notification """ID""" path["notification"] = notification self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{communication_channel_id}/notification_preferences/{notification}".format(**path), data=data, params=params, single_item=True)
[ "def", "get_preference_communication_channel_id", "(", "self", ",", "user_id", ",", "notification", ",", "communication_channel_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", ...
Get a preference. Fetch the preference for the given notification for the given communicaiton channel
[ "Get", "a", "preference", ".", "Fetch", "the", "preference", "for", "the", "given", "notification", "for", "the", "given", "communicaiton", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L86-L109
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
get_preference_type
def get_preference_type(self, type, user_id, address, notification): """ Get a preference. Fetch the preference for the given notification for the given communicaiton channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address # REQUIRED - PATH - notification """ID""" path["notification"] = notification self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification}".format(**path), data=data, params=params, single_item=True)
python
def get_preference_type(self, type, user_id, address, notification): """ Get a preference. Fetch the preference for the given notification for the given communicaiton channel """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address # REQUIRED - PATH - notification """ID""" path["notification"] = notification self.logger.debug("GET /api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/communication_channels/{type}/{address}/notification_preferences/{notification}".format(**path), data=data, params=params, single_item=True)
[ "def", "get_preference_type", "(", "self", ",", "type", ",", "user_id", ",", "address", ",", "notification", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\...
Get a preference. Fetch the preference for the given notification for the given communicaiton channel
[ "Get", "a", "preference", ".", "Fetch", "the", "preference", "for", "the", "given", "notification", "for", "the", "given", "communicaiton", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L111-L138
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
update_preference_communication_channel_id
def update_preference_communication_channel_id(self, notification, communication_channel_id, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - notification """ID""" path["notification"] = notification # REQUIRED - notification_preferences[frequency] """The desired frequency for this notification""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification}".format(**path), data=data, params=params, no_data=True)
python
def update_preference_communication_channel_id(self, notification, communication_channel_id, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - notification """ID""" path["notification"] = notification # REQUIRED - notification_preferences[frequency] """The desired frequency for this notification""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{communication_channel_id}/notification_preferences/{notification}".format(**path), data=data, params=params, no_data=True)
[ "def", "update_preference_communication_channel_id", "(", "self", ",", "notification", ",", "communication_channel_id", ",", "notification_preferences_frequency", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - com...
Update a preference. Change the preference for a single notification for a single communication channel
[ "Update", "a", "preference", ".", "Change", "the", "preference", "for", "a", "single", "notification", "for", "a", "single", "communication", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L140-L163
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
update_preference_type
def update_preference_type(self, type, address, notification, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address # REQUIRED - PATH - notification """ID""" path["notification"] = notification # REQUIRED - notification_preferences[frequency] """The desired frequency for this notification""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{type}/{address}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{type}/{address}/notification_preferences/{notification}".format(**path), data=data, params=params, no_data=True)
python
def update_preference_type(self, type, address, notification, notification_preferences_frequency): """ Update a preference. Change the preference for a single notification for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - type """ID""" path["type"] = type # REQUIRED - PATH - address """ID""" path["address"] = address # REQUIRED - PATH - notification """ID""" path["notification"] = notification # REQUIRED - notification_preferences[frequency] """The desired frequency for this notification""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{type}/{address}/notification_preferences/{notification} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{type}/{address}/notification_preferences/{notification}".format(**path), data=data, params=params, no_data=True)
[ "def", "update_preference_type", "(", "self", ",", "type", ",", "address", ",", "notification", ",", "notification_preferences_frequency", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - type\r", "\"\"\"ID\"\...
Update a preference. Change the preference for a single notification for a single communication channel
[ "Update", "a", "preference", ".", "Change", "the", "preference", "for", "a", "single", "notification", "for", "a", "single", "communication", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L165-L192
PGower/PyCanvas
pycanvas/apis/notification_preferences.py
update_preferences_by_category
def update_preferences_by_category(self, category, communication_channel_id, notification_preferences_frequency): """ Update preferences by category. Change the preferences for multiple notifications based on the category for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - category """The name of the category. Must be parameterized (e.g. The category "Course Content" should be "course_content")""" path["category"] = category # REQUIRED - notification_preferences[frequency] """The desired frequency for each notification in the category""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category}".format(**path), data=data, params=params, no_data=True)
python
def update_preferences_by_category(self, category, communication_channel_id, notification_preferences_frequency): """ Update preferences by category. Change the preferences for multiple notifications based on the category for a single communication channel """ path = {} data = {} params = {} # REQUIRED - PATH - communication_channel_id """ID""" path["communication_channel_id"] = communication_channel_id # REQUIRED - PATH - category """The name of the category. Must be parameterized (e.g. The category "Course Content" should be "course_content")""" path["category"] = category # REQUIRED - notification_preferences[frequency] """The desired frequency for each notification in the category""" data["notification_preferences[frequency]"] = notification_preferences_frequency self.logger.debug("PUT /api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/communication_channels/{communication_channel_id}/notification_preference_categories/{category}".format(**path), data=data, params=params, no_data=True)
[ "def", "update_preferences_by_category", "(", "self", ",", "category", ",", "communication_channel_id", ",", "notification_preferences_frequency", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - communication_chann...
Update preferences by category. Change the preferences for multiple notifications based on the category for a single communication channel
[ "Update", "preferences", "by", "category", ".", "Change", "the", "preferences", "for", "multiple", "notifications", "based", "on", "the", "category", "for", "a", "single", "communication", "channel" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/notification_preferences.py#L194-L217
LIVVkit/LIVVkit
livvkit/__main__.py
main
def main(cl_args=None): """ Direct execution. """ if cl_args is None and len(sys.argv) > 1: cl_args = sys.argv[1:] args = options.parse_args(cl_args) print("-------------------------------------------------------------------") print(" __ _____ ___ ____ _ __ ") print(" / / / _/ | / / | / / /__ (_) /_ ") print(" / /___/ / | |/ /| |/ / '_// / __/ ") print(" /____/___/ |___/ |___/_/\_\/_/\__/ ") print("") print(" Land Ice Verification & Validation ") print("-------------------------------------------------------------------") print("") print(" Current run: " + livvkit.timestamp) print(" User: " + livvkit.user) print(" OS Type: " + livvkit.os_type) print(" Machine: " + livvkit.machine) print(" " + livvkit.comment) from livvkit.components import numerics from livvkit.components import verification from livvkit.components import performance from livvkit.components import validation from livvkit import scheduler from livvkit.util import functions from livvkit.util import elements summary_elements = [] if livvkit.verify or livvkit.validate: functions.setup_output() if livvkit.verify: summary_elements.append(scheduler.run("numerics", numerics, functions.read_json(livvkit.numerics_model_config))) summary_elements.append(scheduler.run("verification", verification, functions.read_json(livvkit.verification_model_config))) summary_elements.append(scheduler.run("performance", performance, functions.read_json(livvkit.performance_model_config))) if livvkit.validate: print(" -----------------------------------------------------------------") print(" Beginning the validation test suite ") print(" -----------------------------------------------------------------") print("") validation_config = {} for conf in livvkit.validation_model_configs: validation_config = functions.merge_dicts(validation_config, functions.read_json(conf)) summary_elements.extend(scheduler.run_quiet(validation, validation_config, group=False)) print(" -----------------------------------------------------------------") print(" Validation test suite complete ") print(" -----------------------------------------------------------------") print("") if livvkit.verify or livvkit.validate: result = elements.page("Summary", "", element_list=summary_elements) functions.write_json(result, livvkit.output_dir, "index.json") print("-------------------------------------------------------------------") print(" Done! Results can be seen in a web browser at:") print(" " + os.path.join(livvkit.output_dir, 'index.html')) print("-------------------------------------------------------------------") if args.serve: try: # Python 3 import http.server as server import socketserver as socket except ImportError: # Python 2 # noinspection PyPep8Naming import SimpleHTTPServer as server # noinspection PyPep8Naming import SocketServer as socket httpd = socket.TCPServer(('', args.serve), server.SimpleHTTPRequestHandler) sa = httpd.socket.getsockname() print('\nServing HTTP on {host} port {port} (http://{host}:{port}/)'.format(host=sa[0], port=sa[1])) print('\nView the generated website by navigating to:') print('\n http://{host}:{port}/{path}/index.html'.format(host=sa[0], port=sa[1], path=os.path.relpath(livvkit.output_dir) )) print('\nExit by pressing `ctrl+c` to send a keyboard interrupt.\n') try: httpd.serve_forever() except KeyboardInterrupt: print('\nKeyboard interrupt received, exiting.\n') sys.exit(0)
python
def main(cl_args=None): """ Direct execution. """ if cl_args is None and len(sys.argv) > 1: cl_args = sys.argv[1:] args = options.parse_args(cl_args) print("-------------------------------------------------------------------") print(" __ _____ ___ ____ _ __ ") print(" / / / _/ | / / | / / /__ (_) /_ ") print(" / /___/ / | |/ /| |/ / '_// / __/ ") print(" /____/___/ |___/ |___/_/\_\/_/\__/ ") print("") print(" Land Ice Verification & Validation ") print("-------------------------------------------------------------------") print("") print(" Current run: " + livvkit.timestamp) print(" User: " + livvkit.user) print(" OS Type: " + livvkit.os_type) print(" Machine: " + livvkit.machine) print(" " + livvkit.comment) from livvkit.components import numerics from livvkit.components import verification from livvkit.components import performance from livvkit.components import validation from livvkit import scheduler from livvkit.util import functions from livvkit.util import elements summary_elements = [] if livvkit.verify or livvkit.validate: functions.setup_output() if livvkit.verify: summary_elements.append(scheduler.run("numerics", numerics, functions.read_json(livvkit.numerics_model_config))) summary_elements.append(scheduler.run("verification", verification, functions.read_json(livvkit.verification_model_config))) summary_elements.append(scheduler.run("performance", performance, functions.read_json(livvkit.performance_model_config))) if livvkit.validate: print(" -----------------------------------------------------------------") print(" Beginning the validation test suite ") print(" -----------------------------------------------------------------") print("") validation_config = {} for conf in livvkit.validation_model_configs: validation_config = functions.merge_dicts(validation_config, functions.read_json(conf)) summary_elements.extend(scheduler.run_quiet(validation, validation_config, group=False)) print(" -----------------------------------------------------------------") print(" Validation test suite complete ") print(" -----------------------------------------------------------------") print("") if livvkit.verify or livvkit.validate: result = elements.page("Summary", "", element_list=summary_elements) functions.write_json(result, livvkit.output_dir, "index.json") print("-------------------------------------------------------------------") print(" Done! Results can be seen in a web browser at:") print(" " + os.path.join(livvkit.output_dir, 'index.html')) print("-------------------------------------------------------------------") if args.serve: try: # Python 3 import http.server as server import socketserver as socket except ImportError: # Python 2 # noinspection PyPep8Naming import SimpleHTTPServer as server # noinspection PyPep8Naming import SocketServer as socket httpd = socket.TCPServer(('', args.serve), server.SimpleHTTPRequestHandler) sa = httpd.socket.getsockname() print('\nServing HTTP on {host} port {port} (http://{host}:{port}/)'.format(host=sa[0], port=sa[1])) print('\nView the generated website by navigating to:') print('\n http://{host}:{port}/{path}/index.html'.format(host=sa[0], port=sa[1], path=os.path.relpath(livvkit.output_dir) )) print('\nExit by pressing `ctrl+c` to send a keyboard interrupt.\n') try: httpd.serve_forever() except KeyboardInterrupt: print('\nKeyboard interrupt received, exiting.\n') sys.exit(0)
[ "def", "main", "(", "cl_args", "=", "None", ")", ":", "if", "cl_args", "is", "None", "and", "len", "(", "sys", ".", "argv", ")", ">", "1", ":", "cl_args", "=", "sys", ".", "argv", "[", "1", ":", "]", "args", "=", "options", ".", "parse_args", "...
Direct execution.
[ "Direct", "execution", "." ]
train
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/__main__.py#L43-L134
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.list_users_in_account
def list_users_in_account(self, account_id, search_term=None): """ List users in account. Retrieve the list of users associated with this account. @example_request curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \ -X GET \ -H 'Authorization: Bearer <token>' """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - search_term """The partial name or full ID of the users to match and return in the results list. Must be at least 3 characters. Note that the API will prefer matching on canonical user ID if the ID has a numeric form. It will only search against other fields if non-numeric in form, or if the numeric value doesn't yield any matches. Queries by administrative users will search on SIS ID, name, or email address; non- administrative queries will only be compared against name.""" if search_term is not None: params["search_term"] = search_term self.logger.debug("GET /api/v1/accounts/{account_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/users".format(**path), data=data, params=params, all_pages=True)
python
def list_users_in_account(self, account_id, search_term=None): """ List users in account. Retrieve the list of users associated with this account. @example_request curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \ -X GET \ -H 'Authorization: Bearer <token>' """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - search_term """The partial name or full ID of the users to match and return in the results list. Must be at least 3 characters. Note that the API will prefer matching on canonical user ID if the ID has a numeric form. It will only search against other fields if non-numeric in form, or if the numeric value doesn't yield any matches. Queries by administrative users will search on SIS ID, name, or email address; non- administrative queries will only be compared against name.""" if search_term is not None: params["search_term"] = search_term self.logger.debug("GET /api/v1/accounts/{account_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/users".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_users_in_account", "(", "self", ",", "account_id", ",", "search_term", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"account_id\"...
List users in account. Retrieve the list of users associated with this account. @example_request curl https://<canvas>/api/v1/accounts/self/users?search_term=<search value> \ -X GET \ -H 'Authorization: Bearer <token>'
[ "List", "users", "in", "account", ".", "Retrieve", "the", "list", "of", "users", "associated", "with", "this", "account", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L19-L51
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.create_user
def create_user(self, account_id, pseudonym_unique_id, communication_channel_address=None, communication_channel_confirmation_url=None, communication_channel_skip_confirmation=None, communication_channel_type=None, enable_sis_reactivation=None, force_validations=None, pseudonym_authentication_provider_id=None, pseudonym_force_self_registration=None, pseudonym_integration_id=None, pseudonym_password=None, pseudonym_send_confirmation=None, pseudonym_sis_user_id=None, user_birthdate=None, user_locale=None, user_name=None, user_short_name=None, user_skip_registration=None, user_sortable_name=None, user_terms_of_use=None, user_time_zone=None): """ Create a user. Create and return a new user and pseudonym for an account. If you don't have the "Modify login details for users" permission, but self-registration is enabled on the account, you can still use this endpoint to register new users. Certain fields will be required, and others will be ignored (see below). """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - user[name] """The full name of the user. This name will be used by teacher for grading. Required if this is a self-registration.""" if user_name is not None: data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[birthdate] """The user's birth date.""" if user_birthdate is not None: data["user[birthdate]"] = user_birthdate # OPTIONAL - user[terms_of_use] """Whether the user accepts the terms of use. Required if this is a self-registration and this canvas instance requires users to accept the terms (on by default). If this is true, it will mark the user as having accepted the terms of use.""" if user_terms_of_use is not None: data["user[terms_of_use]"] = user_terms_of_use # OPTIONAL - user[skip_registration] """Automatically mark the user as registered. If this is true, it is recommended to set <tt>"pseudonym[send_confirmation]"</tt> to true as well. Otherwise, the user will not receive any messages about their account creation. The users communication channel confirmation can be skipped by setting <tt>"communication_channel[skip_confirmation]"</tt> to true as well.""" if user_skip_registration is not None: data["user[skip_registration]"] = user_skip_registration # REQUIRED - pseudonym[unique_id] """User's login ID. If this is a self-registration, it must be a valid email address.""" data["pseudonym[unique_id]"] = pseudonym_unique_id # OPTIONAL - pseudonym[password] """User's password. Cannot be set during self-registration.""" if pseudonym_password is not None: data["pseudonym[password]"] = pseudonym_password # OPTIONAL - pseudonym[sis_user_id] """SIS ID for the user's account. To set this parameter, the caller must be able to manage SIS permissions.""" if pseudonym_sis_user_id is not None: data["pseudonym[sis_user_id]"] = pseudonym_sis_user_id # OPTIONAL - pseudonym[integration_id] """Integration ID for the login. To set this parameter, the caller must be able to manage SIS permissions. The Integration ID is a secondary identifier useful for more complex SIS integrations.""" if pseudonym_integration_id is not None: data["pseudonym[integration_id]"] = pseudonym_integration_id # OPTIONAL - pseudonym[send_confirmation] """Send user notification of account creation if true. Automatically set to true during self-registration.""" if pseudonym_send_confirmation is not None: data["pseudonym[send_confirmation]"] = pseudonym_send_confirmation # OPTIONAL - pseudonym[force_self_registration] """Send user a self-registration style email if true. Setting it means the users will get a notification asking them to "complete the registration process" by clicking it, setting a password, and letting them in. Will only be executed on if the user does not need admin approval. Defaults to false unless explicitly provided.""" if pseudonym_force_self_registration is not None: data["pseudonym[force_self_registration]"] = pseudonym_force_self_registration # OPTIONAL - pseudonym[authentication_provider_id] """The authentication provider this login is associated with. Logins associated with a specific provider can only be used with that provider. Legacy providers (LDAP, CAS, SAML) will search for logins associated with them, or unassociated logins. New providers will only search for logins explicitly associated with them. This can be the integer ID of the provider, or the type of the provider (in which case, it will find the first matching provider).""" if pseudonym_authentication_provider_id is not None: data["pseudonym[authentication_provider_id]"] = pseudonym_authentication_provider_id # OPTIONAL - communication_channel[type] """The communication channel type, e.g. 'email' or 'sms'.""" if communication_channel_type is not None: data["communication_channel[type]"] = communication_channel_type # OPTIONAL - communication_channel[address] """The communication channel address, e.g. the user's email address.""" if communication_channel_address is not None: data["communication_channel[address]"] = communication_channel_address # OPTIONAL - communication_channel[confirmation_url] """Only valid for account admins. If true, returns the new user account confirmation URL in the response.""" if communication_channel_confirmation_url is not None: data["communication_channel[confirmation_url]"] = communication_channel_confirmation_url # OPTIONAL - communication_channel[skip_confirmation] """Only valid for site admins and account admins making requests; If true, the channel is automatically validated and no confirmation email or SMS is sent. Otherwise, the user must respond to a confirmation message to confirm the channel. If this is true, it is recommended to set <tt>"pseudonym[send_confirmation]"</tt> to true as well. Otherwise, the user will not receive any messages about their account creation.""" if communication_channel_skip_confirmation is not None: data["communication_channel[skip_confirmation]"] = communication_channel_skip_confirmation # OPTIONAL - force_validations """If true, validations are performed on the newly created user (and their associated pseudonym) even if the request is made by a privileged user like an admin. When set to false, or not included in the request parameters, any newly created users are subject to validations unless the request is made by a user with a 'manage_user_logins' right. In which case, certain validations such as 'require_acceptance_of_terms' and 'require_presence_of_name' are not enforced. Use this parameter to return helpful json errors while building users with an admin request.""" if force_validations is not None: data["force_validations"] = force_validations # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted user with matching sis_user_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/accounts/{account_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/users".format(**path), data=data, params=params, single_item=True)
python
def create_user(self, account_id, pseudonym_unique_id, communication_channel_address=None, communication_channel_confirmation_url=None, communication_channel_skip_confirmation=None, communication_channel_type=None, enable_sis_reactivation=None, force_validations=None, pseudonym_authentication_provider_id=None, pseudonym_force_self_registration=None, pseudonym_integration_id=None, pseudonym_password=None, pseudonym_send_confirmation=None, pseudonym_sis_user_id=None, user_birthdate=None, user_locale=None, user_name=None, user_short_name=None, user_skip_registration=None, user_sortable_name=None, user_terms_of_use=None, user_time_zone=None): """ Create a user. Create and return a new user and pseudonym for an account. If you don't have the "Modify login details for users" permission, but self-registration is enabled on the account, you can still use this endpoint to register new users. Certain fields will be required, and others will be ignored (see below). """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - user[name] """The full name of the user. This name will be used by teacher for grading. Required if this is a self-registration.""" if user_name is not None: data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[birthdate] """The user's birth date.""" if user_birthdate is not None: data["user[birthdate]"] = user_birthdate # OPTIONAL - user[terms_of_use] """Whether the user accepts the terms of use. Required if this is a self-registration and this canvas instance requires users to accept the terms (on by default). If this is true, it will mark the user as having accepted the terms of use.""" if user_terms_of_use is not None: data["user[terms_of_use]"] = user_terms_of_use # OPTIONAL - user[skip_registration] """Automatically mark the user as registered. If this is true, it is recommended to set <tt>"pseudonym[send_confirmation]"</tt> to true as well. Otherwise, the user will not receive any messages about their account creation. The users communication channel confirmation can be skipped by setting <tt>"communication_channel[skip_confirmation]"</tt> to true as well.""" if user_skip_registration is not None: data["user[skip_registration]"] = user_skip_registration # REQUIRED - pseudonym[unique_id] """User's login ID. If this is a self-registration, it must be a valid email address.""" data["pseudonym[unique_id]"] = pseudonym_unique_id # OPTIONAL - pseudonym[password] """User's password. Cannot be set during self-registration.""" if pseudonym_password is not None: data["pseudonym[password]"] = pseudonym_password # OPTIONAL - pseudonym[sis_user_id] """SIS ID for the user's account. To set this parameter, the caller must be able to manage SIS permissions.""" if pseudonym_sis_user_id is not None: data["pseudonym[sis_user_id]"] = pseudonym_sis_user_id # OPTIONAL - pseudonym[integration_id] """Integration ID for the login. To set this parameter, the caller must be able to manage SIS permissions. The Integration ID is a secondary identifier useful for more complex SIS integrations.""" if pseudonym_integration_id is not None: data["pseudonym[integration_id]"] = pseudonym_integration_id # OPTIONAL - pseudonym[send_confirmation] """Send user notification of account creation if true. Automatically set to true during self-registration.""" if pseudonym_send_confirmation is not None: data["pseudonym[send_confirmation]"] = pseudonym_send_confirmation # OPTIONAL - pseudonym[force_self_registration] """Send user a self-registration style email if true. Setting it means the users will get a notification asking them to "complete the registration process" by clicking it, setting a password, and letting them in. Will only be executed on if the user does not need admin approval. Defaults to false unless explicitly provided.""" if pseudonym_force_self_registration is not None: data["pseudonym[force_self_registration]"] = pseudonym_force_self_registration # OPTIONAL - pseudonym[authentication_provider_id] """The authentication provider this login is associated with. Logins associated with a specific provider can only be used with that provider. Legacy providers (LDAP, CAS, SAML) will search for logins associated with them, or unassociated logins. New providers will only search for logins explicitly associated with them. This can be the integer ID of the provider, or the type of the provider (in which case, it will find the first matching provider).""" if pseudonym_authentication_provider_id is not None: data["pseudonym[authentication_provider_id]"] = pseudonym_authentication_provider_id # OPTIONAL - communication_channel[type] """The communication channel type, e.g. 'email' or 'sms'.""" if communication_channel_type is not None: data["communication_channel[type]"] = communication_channel_type # OPTIONAL - communication_channel[address] """The communication channel address, e.g. the user's email address.""" if communication_channel_address is not None: data["communication_channel[address]"] = communication_channel_address # OPTIONAL - communication_channel[confirmation_url] """Only valid for account admins. If true, returns the new user account confirmation URL in the response.""" if communication_channel_confirmation_url is not None: data["communication_channel[confirmation_url]"] = communication_channel_confirmation_url # OPTIONAL - communication_channel[skip_confirmation] """Only valid for site admins and account admins making requests; If true, the channel is automatically validated and no confirmation email or SMS is sent. Otherwise, the user must respond to a confirmation message to confirm the channel. If this is true, it is recommended to set <tt>"pseudonym[send_confirmation]"</tt> to true as well. Otherwise, the user will not receive any messages about their account creation.""" if communication_channel_skip_confirmation is not None: data["communication_channel[skip_confirmation]"] = communication_channel_skip_confirmation # OPTIONAL - force_validations """If true, validations are performed on the newly created user (and their associated pseudonym) even if the request is made by a privileged user like an admin. When set to false, or not included in the request parameters, any newly created users are subject to validations unless the request is made by a user with a 'manage_user_logins' right. In which case, certain validations such as 'require_acceptance_of_terms' and 'require_presence_of_name' are not enforced. Use this parameter to return helpful json errors while building users with an admin request.""" if force_validations is not None: data["force_validations"] = force_validations # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted user with matching sis_user_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/accounts/{account_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/users".format(**path), data=data, params=params, single_item=True)
[ "def", "create_user", "(", "self", ",", "account_id", ",", "pseudonym_unique_id", ",", "communication_channel_address", "=", "None", ",", "communication_channel_confirmation_url", "=", "None", ",", "communication_channel_skip_confirmation", "=", "None", ",", "communication_...
Create a user. Create and return a new user and pseudonym for an account. If you don't have the "Modify login details for users" permission, but self-registration is enabled on the account, you can still use this endpoint to register new users. Certain fields will be required, and others will be ignored (see below).
[ "Create", "a", "user", ".", "Create", "and", "return", "a", "new", "user", "and", "pseudonym", "for", "an", "account", ".", "If", "you", "don", "t", "have", "the", "Modify", "login", "details", "for", "users", "permission", "but", "self", "-", "registrat...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L429-L596
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.self_register_user
def self_register_user(self, user_name, account_id, user_terms_of_use, pseudonym_unique_id, communication_channel_address=None, communication_channel_type=None, user_birthdate=None, user_locale=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): """ Self register a user. Self register and return a new user and pseudonym for an account. If self-registration is enabled on the account, you can use this endpoint to self register new users. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - user[name] """The full name of the user. This name will be used by teacher for grading.""" data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[birthdate] """The user's birth date.""" if user_birthdate is not None: data["user[birthdate]"] = user_birthdate # REQUIRED - user[terms_of_use] """Whether the user accepts the terms of use.""" data["user[terms_of_use]"] = user_terms_of_use # REQUIRED - pseudonym[unique_id] """User's login ID. Must be a valid email address.""" data["pseudonym[unique_id]"] = pseudonym_unique_id # OPTIONAL - communication_channel[type] """The communication channel type, e.g. 'email' or 'sms'.""" if communication_channel_type is not None: data["communication_channel[type]"] = communication_channel_type # OPTIONAL - communication_channel[address] """The communication channel address, e.g. the user's email address.""" if communication_channel_address is not None: data["communication_channel[address]"] = communication_channel_address self.logger.debug("POST /api/v1/accounts/{account_id}/self_registration with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/self_registration".format(**path), data=data, params=params, single_item=True)
python
def self_register_user(self, user_name, account_id, user_terms_of_use, pseudonym_unique_id, communication_channel_address=None, communication_channel_type=None, user_birthdate=None, user_locale=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): """ Self register a user. Self register and return a new user and pseudonym for an account. If self-registration is enabled on the account, you can use this endpoint to self register new users. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - user[name] """The full name of the user. This name will be used by teacher for grading.""" data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[birthdate] """The user's birth date.""" if user_birthdate is not None: data["user[birthdate]"] = user_birthdate # REQUIRED - user[terms_of_use] """Whether the user accepts the terms of use.""" data["user[terms_of_use]"] = user_terms_of_use # REQUIRED - pseudonym[unique_id] """User's login ID. Must be a valid email address.""" data["pseudonym[unique_id]"] = pseudonym_unique_id # OPTIONAL - communication_channel[type] """The communication channel type, e.g. 'email' or 'sms'.""" if communication_channel_type is not None: data["communication_channel[type]"] = communication_channel_type # OPTIONAL - communication_channel[address] """The communication channel address, e.g. the user's email address.""" if communication_channel_address is not None: data["communication_channel[address]"] = communication_channel_address self.logger.debug("POST /api/v1/accounts/{account_id}/self_registration with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/self_registration".format(**path), data=data, params=params, single_item=True)
[ "def", "self_register_user", "(", "self", ",", "user_name", ",", "account_id", ",", "user_terms_of_use", ",", "pseudonym_unique_id", ",", "communication_channel_address", "=", "None", ",", "communication_channel_type", "=", "None", ",", "user_birthdate", "=", "None", ...
Self register a user. Self register and return a new user and pseudonym for an account. If self-registration is enabled on the account, you can use this endpoint to self register new users.
[ "Self", "register", "a", "user", ".", "Self", "register", "and", "return", "a", "new", "user", "and", "pseudonym", "for", "an", "account", ".", "If", "self", "-", "registration", "is", "enabled", "on", "the", "account", "you", "can", "use", "this", "endp...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L598-L666
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.update_user_settings
def update_user_settings(self, id, collapse_global_nav=None, manual_mark_as_read=None): """ Update user settings. Update an existing user's settings. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - manual_mark_as_read """If true, require user to manually mark discussion posts as read (don't auto-mark as read).""" if manual_mark_as_read is not None: params["manual_mark_as_read"] = manual_mark_as_read # OPTIONAL - collapse_global_nav """If true, the user's page loads with the global navigation collapsed""" if collapse_global_nav is not None: params["collapse_global_nav"] = collapse_global_nav self.logger.debug("GET /api/v1/users/{id}/settings with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{id}/settings".format(**path), data=data, params=params, no_data=True)
python
def update_user_settings(self, id, collapse_global_nav=None, manual_mark_as_read=None): """ Update user settings. Update an existing user's settings. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - manual_mark_as_read """If true, require user to manually mark discussion posts as read (don't auto-mark as read).""" if manual_mark_as_read is not None: params["manual_mark_as_read"] = manual_mark_as_read # OPTIONAL - collapse_global_nav """If true, the user's page loads with the global navigation collapsed""" if collapse_global_nav is not None: params["collapse_global_nav"] = collapse_global_nav self.logger.debug("GET /api/v1/users/{id}/settings with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{id}/settings".format(**path), data=data, params=params, no_data=True)
[ "def", "update_user_settings", "(", "self", ",", "id", ",", "collapse_global_nav", "=", "None", ",", "manual_mark_as_read", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\...
Update user settings. Update an existing user's settings.
[ "Update", "user", "settings", ".", "Update", "an", "existing", "user", "s", "settings", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L668-L694
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.get_custom_color
def get_custom_color(self, id, asset_string): """ Get custom color. Returns the custom colors that have been saved for a user for a given context. The asset_string parameter should be in the format 'context_id', for example 'course_42'. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - asset_string """ID""" path["asset_string"] = asset_string self.logger.debug("GET /api/v1/users/{id}/colors/{asset_string} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{id}/colors/{asset_string}".format(**path), data=data, params=params, no_data=True)
python
def get_custom_color(self, id, asset_string): """ Get custom color. Returns the custom colors that have been saved for a user for a given context. The asset_string parameter should be in the format 'context_id', for example 'course_42'. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - asset_string """ID""" path["asset_string"] = asset_string self.logger.debug("GET /api/v1/users/{id}/colors/{asset_string} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{id}/colors/{asset_string}".format(**path), data=data, params=params, no_data=True)
[ "def", "get_custom_color", "(", "self", ",", "id", ",", "asset_string", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - PATH...
Get custom color. Returns the custom colors that have been saved for a user for a given context. The asset_string parameter should be in the format 'context_id', for example 'course_42'.
[ "Get", "custom", "color", ".", "Returns", "the", "custom", "colors", "that", "have", "been", "saved", "for", "a", "user", "for", "a", "given", "context", ".", "The", "asset_string", "parameter", "should", "be", "in", "the", "format", "context_id", "for", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L713-L735
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.edit_user
def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): """ Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - user[name] """The full name of the user. This name will be used by teacher for grading.""" if user_name is not None: data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[email] """The default email address of the user.""" if user_email is not None: data["user[email]"] = user_email # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[avatar][token] """A unique representation of the avatar record to assign as the user's current avatar. This token can be obtained from the user avatars endpoint. This supersedes the user [avatar] [url] argument, and if both are included the url will be ignored. Note: this is an internal representation and is subject to change without notice. It should be consumed with this api endpoint and used in the user update endpoint, and should not be constructed by the client.""" if user_avatar_token is not None: data["user[avatar][token]"] = user_avatar_token # OPTIONAL - user[avatar][url] """To set the user's avatar to point to an external url, do not include a token and instead pass the url here. Warning: For maximum compatibility, please use 128 px square images.""" if user_avatar_url is not None: data["user[avatar][url]"] = user_avatar_url self.logger.debug("PUT /api/v1/users/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{id}".format(**path), data=data, params=params, single_item=True)
python
def edit_user(self, id, user_avatar_token=None, user_avatar_url=None, user_email=None, user_locale=None, user_name=None, user_short_name=None, user_sortable_name=None, user_time_zone=None): """ Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - user[name] """The full name of the user. This name will be used by teacher for grading.""" if user_name is not None: data["user[name]"] = user_name # OPTIONAL - user[short_name] """User's name as it will be displayed in discussions, messages, and comments.""" if user_short_name is not None: data["user[short_name]"] = user_short_name # OPTIONAL - user[sortable_name] """User's name as used to sort alphabetically in lists.""" if user_sortable_name is not None: data["user[sortable_name]"] = user_sortable_name # OPTIONAL - user[time_zone] """The time zone for the user. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if user_time_zone is not None: data["user[time_zone]"] = user_time_zone # OPTIONAL - user[email] """The default email address of the user.""" if user_email is not None: data["user[email]"] = user_email # OPTIONAL - user[locale] """The user's preferred language, from the list of languages Canvas supports. This is in RFC-5646 format.""" if user_locale is not None: data["user[locale]"] = user_locale # OPTIONAL - user[avatar][token] """A unique representation of the avatar record to assign as the user's current avatar. This token can be obtained from the user avatars endpoint. This supersedes the user [avatar] [url] argument, and if both are included the url will be ignored. Note: this is an internal representation and is subject to change without notice. It should be consumed with this api endpoint and used in the user update endpoint, and should not be constructed by the client.""" if user_avatar_token is not None: data["user[avatar][token]"] = user_avatar_token # OPTIONAL - user[avatar][url] """To set the user's avatar to point to an external url, do not include a token and instead pass the url here. Warning: For maximum compatibility, please use 128 px square images.""" if user_avatar_url is not None: data["user[avatar][url]"] = user_avatar_url self.logger.debug("PUT /api/v1/users/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{id}".format(**path), data=data, params=params, single_item=True)
[ "def", "edit_user", "(", "self", ",", "id", ",", "user_avatar_token", "=", "None", ",", "user_avatar_url", "=", "None", ",", "user_email", "=", "None", ",", "user_locale", "=", "None", ",", "user_name", "=", "None", ",", "user_short_name", "=", "None", ","...
Edit a user. Modify an existing user. To modify a user's login, see the documentation for logins.
[ "Edit", "a", "user", ".", "Modify", "an", "existing", "user", ".", "To", "modify", "a", "user", "s", "login", "see", "the", "documentation", "for", "logins", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L808-L874
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.merge_user_into_another_user_destination_user_id
def merge_user_into_another_user_destination_user_id(self, id, destination_user_id): """ Merge user into another user. Merge a user into another user. To merge users, the caller must have permissions to manage both users. This should be considered irreversible. This will delete the user and move all the data into the destination user. When finding users by SIS ids in different accounts the destination_account_id is required. The account can also be identified by passing the domain in destination_account_id. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - destination_user_id """ID""" path["destination_user_id"] = destination_user_id self.logger.debug("PUT /api/v1/users/{id}/merge_into/{destination_user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{id}/merge_into/{destination_user_id}".format(**path), data=data, params=params, single_item=True)
python
def merge_user_into_another_user_destination_user_id(self, id, destination_user_id): """ Merge user into another user. Merge a user into another user. To merge users, the caller must have permissions to manage both users. This should be considered irreversible. This will delete the user and move all the data into the destination user. When finding users by SIS ids in different accounts the destination_account_id is required. The account can also be identified by passing the domain in destination_account_id. """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - PATH - destination_user_id """ID""" path["destination_user_id"] = destination_user_id self.logger.debug("PUT /api/v1/users/{id}/merge_into/{destination_user_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{id}/merge_into/{destination_user_id}".format(**path), data=data, params=params, single_item=True)
[ "def", "merge_user_into_another_user_destination_user_id", "(", "self", ",", "id", ",", "destination_user_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "...
Merge user into another user. Merge a user into another user. To merge users, the caller must have permissions to manage both users. This should be considered irreversible. This will delete the user and move all the data into the destination user. When finding users by SIS ids in different accounts the destination_account_id is required. The account can also be identified by passing the domain in destination_account_id.
[ "Merge", "user", "into", "another", "user", ".", "Merge", "a", "user", "into", "another", "user", ".", "To", "merge", "users", "the", "caller", "must", "have", "permissions", "to", "manage", "both", "users", ".", "This", "should", "be", "considered", "irre...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L876-L903
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.get_user_profile
def get_user_profile(self, user_id): """ Get user profile. Returns user profile data, including user id, name, and profile pic. When requesting the profile for the user accessing the API, the user's calendar feed URL will be returned as well. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id self.logger.debug("GET /api/v1/users/{user_id}/profile with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/profile".format(**path), data=data, params=params, single_item=True)
python
def get_user_profile(self, user_id): """ Get user profile. Returns user profile data, including user id, name, and profile pic. When requesting the profile for the user accessing the API, the user's calendar feed URL will be returned as well. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id self.logger.debug("GET /api/v1/users/{user_id}/profile with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/profile".format(**path), data=data, params=params, single_item=True)
[ "def", "get_user_profile", "(", "self", ",", "user_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "=", "user_id", "self", ".", "logge...
Get user profile. Returns user profile data, including user id, name, and profile pic. When requesting the profile for the user accessing the API, the user's calendar feed URL will be returned as well.
[ "Get", "user", "profile", ".", "Returns", "user", "profile", "data", "including", "user", "id", "name", "and", "profile", "pic", ".", "When", "requesting", "the", "profile", "for", "the", "user", "accessing", "the", "API", "the", "user", "s", "calendar", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L966-L984
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.list_user_page_views
def list_user_page_views(self, user_id, end_time=None, start_time=None): """ List user page views. Return the user's page view history in json format, similar to the available CSV download. Pagination is used as described in API basics section. Page views are returned in descending order, newest to oldest. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - start_time """The beginning of the time range from which you want page views.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want page views.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/users/{user_id}/page_views with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/page_views".format(**path), data=data, params=params, all_pages=True)
python
def list_user_page_views(self, user_id, end_time=None, start_time=None): """ List user page views. Return the user's page view history in json format, similar to the available CSV download. Pagination is used as described in API basics section. Page views are returned in descending order, newest to oldest. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - start_time """The beginning of the time range from which you want page views.""" if start_time is not None: params["start_time"] = start_time # OPTIONAL - end_time """The end of the time range from which you want page views.""" if end_time is not None: params["end_time"] = end_time self.logger.debug("GET /api/v1/users/{user_id}/page_views with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/page_views".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_user_page_views", "(", "self", ",", "user_id", ",", "end_time", "=", "None", ",", "start_time", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "p...
List user page views. Return the user's page view history in json format, similar to the available CSV download. Pagination is used as described in API basics section. Page views are returned in descending order, newest to oldest.
[ "List", "user", "page", "views", ".", "Return", "the", "user", "s", "page", "view", "history", "in", "json", "format", "similar", "to", "the", "available", "CSV", "download", ".", "Pagination", "is", "used", "as", "described", "in", "API", "basics", "secti...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L1011-L1038
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.store_custom_data
def store_custom_data(self, ns, data, user_id): """ Store custom data. Store arbitrary user data as JSON. Arbitrary JSON data can be stored for a User. A typical scenario would be an external site/service that registers users in Canvas and wants to capture additional info about them. The part of the URL that follows +/custom_data/+ defines the scope of the request, and it reflects the structure of the JSON data to be stored or retrieved. The value +self+ may be used for +user_id+ to store data associated with the calling user. In order to access another user's custom data, you must be an account administrator with permission to manage users. A namespace parameter, +ns+, is used to prevent custom_data collisions between different apps. This parameter is required for all custom_data requests. A request with Content-Type multipart/form-data or Content-Type application/x-www-form-urlencoded can only be used to store strings. Example PUT with multipart/form-data data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/telephone' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data=555-1234' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "555-1234" } Subscopes (or, generated scopes) can also be specified by passing values to +data+[+subscope+]. Example PUT specifying subscopes: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data[waist]=32in' \ -F 'data[inseam]=34in' \ -F 'data[chest]=40in' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "chest": "40in", "waist": "32in", "inseam": "34in" } } Following such a request, subsets of the stored data to be retrieved directly from a subscope. Example {api:UsersController#get_custom_data GET} from a generated scope curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements/chest' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "40in" } If you want to store more than just strings (i.e. numbers, arrays, hashes, true, false, and/or null), you must make a request with Content-Type application/json as in the following example. Example PUT with JSON data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data' \ -H 'Content-Type: application/json' \ -X PUT \ -d '{ "ns": "com.my-organization.canvas-app", "data": { "a-number": 6.02e23, "a-bool": true, "a-string": "true", "a-hash": {"a": {"b": "ohai"}}, "an-array": [1, "two", null, false] } }' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "a-number": 6.02e+23, "a-bool": true, "a-string": "true", "a-hash": { "a": { "b": "ohai" } }, "an-array": [1, "two", null, false] } } If the data is an Object (as it is in the above example), then subsets of the data can be accessed by including the object's (possibly nested) keys in the scope of a GET request. Example {api:UsersController#get_custom_data GET} with a generated scope: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/a-hash/a/b' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "ohai" } On success, this endpoint returns an object containing the data that was stored. Responds with status code 200 if the scope already contained data, and it was overwritten by the data specified in the request. Responds with status code 201 if the scope was previously empty, and the data specified in the request was successfully stored there. Responds with status code 400 if the namespace parameter, +ns+, is missing or invalid, or if the +data+ parameter is missing. Responds with status code 409 if the requested scope caused a conflict and data was not stored. This happens when storing data at the requested scope would cause data at an outer scope to be lost. e.g., if +/custom_data+ was +{"fashion_app": {"hair": "blonde"}}+, but you tried to +`PUT /custom_data/fashion_app/hair/style -F data=buzz`+, then for the request to succeed,the value of +/custom_data/fashion_app/hair+ would have to become a hash, and its old string value would be lost. In this situation, an error object is returned with the following format: !!!javascript { "message": "write conflict for custom_data hash", "conflict_scope": "fashion_app/hair", "type_at_conflict": "String", "value_at_conflict": "blonde" } """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - ns """The namespace under which to store the data. This should be something other Canvas API apps aren't likely to use, such as a reverse DNS for your organization.""" data["ns"] = ns # REQUIRED - data """The data you want to store for the user, at the specified scope. If the data is composed of (possibly nested) JSON objects, scopes will be generated for the (nested) keys (see examples).""" data["data"] = data self.logger.debug("PUT /api/v1/users/{user_id}/custom_data with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{user_id}/custom_data".format(**path), data=data, params=params, no_data=True)
python
def store_custom_data(self, ns, data, user_id): """ Store custom data. Store arbitrary user data as JSON. Arbitrary JSON data can be stored for a User. A typical scenario would be an external site/service that registers users in Canvas and wants to capture additional info about them. The part of the URL that follows +/custom_data/+ defines the scope of the request, and it reflects the structure of the JSON data to be stored or retrieved. The value +self+ may be used for +user_id+ to store data associated with the calling user. In order to access another user's custom data, you must be an account administrator with permission to manage users. A namespace parameter, +ns+, is used to prevent custom_data collisions between different apps. This parameter is required for all custom_data requests. A request with Content-Type multipart/form-data or Content-Type application/x-www-form-urlencoded can only be used to store strings. Example PUT with multipart/form-data data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/telephone' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data=555-1234' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "555-1234" } Subscopes (or, generated scopes) can also be specified by passing values to +data+[+subscope+]. Example PUT specifying subscopes: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data[waist]=32in' \ -F 'data[inseam]=34in' \ -F 'data[chest]=40in' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "chest": "40in", "waist": "32in", "inseam": "34in" } } Following such a request, subsets of the stored data to be retrieved directly from a subscope. Example {api:UsersController#get_custom_data GET} from a generated scope curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements/chest' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "40in" } If you want to store more than just strings (i.e. numbers, arrays, hashes, true, false, and/or null), you must make a request with Content-Type application/json as in the following example. Example PUT with JSON data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data' \ -H 'Content-Type: application/json' \ -X PUT \ -d '{ "ns": "com.my-organization.canvas-app", "data": { "a-number": 6.02e23, "a-bool": true, "a-string": "true", "a-hash": {"a": {"b": "ohai"}}, "an-array": [1, "two", null, false] } }' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "a-number": 6.02e+23, "a-bool": true, "a-string": "true", "a-hash": { "a": { "b": "ohai" } }, "an-array": [1, "two", null, false] } } If the data is an Object (as it is in the above example), then subsets of the data can be accessed by including the object's (possibly nested) keys in the scope of a GET request. Example {api:UsersController#get_custom_data GET} with a generated scope: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/a-hash/a/b' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "ohai" } On success, this endpoint returns an object containing the data that was stored. Responds with status code 200 if the scope already contained data, and it was overwritten by the data specified in the request. Responds with status code 201 if the scope was previously empty, and the data specified in the request was successfully stored there. Responds with status code 400 if the namespace parameter, +ns+, is missing or invalid, or if the +data+ parameter is missing. Responds with status code 409 if the requested scope caused a conflict and data was not stored. This happens when storing data at the requested scope would cause data at an outer scope to be lost. e.g., if +/custom_data+ was +{"fashion_app": {"hair": "blonde"}}+, but you tried to +`PUT /custom_data/fashion_app/hair/style -F data=buzz`+, then for the request to succeed,the value of +/custom_data/fashion_app/hair+ would have to become a hash, and its old string value would be lost. In this situation, an error object is returned with the following format: !!!javascript { "message": "write conflict for custom_data hash", "conflict_scope": "fashion_app/hair", "type_at_conflict": "String", "value_at_conflict": "blonde" } """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # REQUIRED - ns """The namespace under which to store the data. This should be something other Canvas API apps aren't likely to use, such as a reverse DNS for your organization.""" data["ns"] = ns # REQUIRED - data """The data you want to store for the user, at the specified scope. If the data is composed of (possibly nested) JSON objects, scopes will be generated for the (nested) keys (see examples).""" data["data"] = data self.logger.debug("PUT /api/v1/users/{user_id}/custom_data with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/{user_id}/custom_data".format(**path), data=data, params=params, no_data=True)
[ "def", "store_custom_data", "(", "self", ",", "ns", ",", "data", ",", "user_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - user_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"user_id\"", "]", "=", "us...
Store custom data. Store arbitrary user data as JSON. Arbitrary JSON data can be stored for a User. A typical scenario would be an external site/service that registers users in Canvas and wants to capture additional info about them. The part of the URL that follows +/custom_data/+ defines the scope of the request, and it reflects the structure of the JSON data to be stored or retrieved. The value +self+ may be used for +user_id+ to store data associated with the calling user. In order to access another user's custom data, you must be an account administrator with permission to manage users. A namespace parameter, +ns+, is used to prevent custom_data collisions between different apps. This parameter is required for all custom_data requests. A request with Content-Type multipart/form-data or Content-Type application/x-www-form-urlencoded can only be used to store strings. Example PUT with multipart/form-data data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/telephone' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data=555-1234' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "555-1234" } Subscopes (or, generated scopes) can also be specified by passing values to +data+[+subscope+]. Example PUT specifying subscopes: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements' \ -X PUT \ -F 'ns=com.my-organization.canvas-app' \ -F 'data[waist]=32in' \ -F 'data[inseam]=34in' \ -F 'data[chest]=40in' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "chest": "40in", "waist": "32in", "inseam": "34in" } } Following such a request, subsets of the stored data to be retrieved directly from a subscope. Example {api:UsersController#get_custom_data GET} from a generated scope curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/body/measurements/chest' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "40in" } If you want to store more than just strings (i.e. numbers, arrays, hashes, true, false, and/or null), you must make a request with Content-Type application/json as in the following example. Example PUT with JSON data: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data' \ -H 'Content-Type: application/json' \ -X PUT \ -d '{ "ns": "com.my-organization.canvas-app", "data": { "a-number": 6.02e23, "a-bool": true, "a-string": "true", "a-hash": {"a": {"b": "ohai"}}, "an-array": [1, "two", null, false] } }' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": { "a-number": 6.02e+23, "a-bool": true, "a-string": "true", "a-hash": { "a": { "b": "ohai" } }, "an-array": [1, "two", null, false] } } If the data is an Object (as it is in the above example), then subsets of the data can be accessed by including the object's (possibly nested) keys in the scope of a GET request. Example {api:UsersController#get_custom_data GET} with a generated scope: curl 'https://<canvas>/api/v1/users/<user_id>/custom_data/a-hash/a/b' \ -X GET \ -F 'ns=com.my-organization.canvas-app' \ -H 'Authorization: Bearer <token>' Response: !!!javascript { "data": "ohai" } On success, this endpoint returns an object containing the data that was stored. Responds with status code 200 if the scope already contained data, and it was overwritten by the data specified in the request. Responds with status code 201 if the scope was previously empty, and the data specified in the request was successfully stored there. Responds with status code 400 if the namespace parameter, +ns+, is missing or invalid, or if the +data+ parameter is missing. Responds with status code 409 if the requested scope caused a conflict and data was not stored. This happens when storing data at the requested scope would cause data at an outer scope to be lost. e.g., if +/custom_data+ was +{"fashion_app": {"hair": "blonde"}}+, but you tried to +`PUT /custom_data/fashion_app/hair/style -F data=buzz`+, then for the request to succeed,the value of +/custom_data/fashion_app/hair+ would have to become a hash, and its old string value would be lost. In this situation, an error object is returned with the following format: !!!javascript { "message": "write conflict for custom_data hash", "conflict_scope": "fashion_app/hair", "type_at_conflict": "String", "value_at_conflict": "blonde" }
[ "Store", "custom", "data", ".", "Store", "arbitrary", "user", "data", "as", "JSON", ".", "Arbitrary", "JSON", "data", "can", "be", "stored", "for", "a", "User", ".", "A", "typical", "scenario", "would", "be", "an", "external", "site", "/", "service", "th...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L1040-L1210
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.list_course_nicknames
def list_course_nicknames(self): """ List course nicknames. Returns all course nicknames you have set. """ path = {} data = {} params = {} self.logger.debug("GET /api/v1/users/self/course_nicknames with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/self/course_nicknames".format(**path), data=data, params=params, all_pages=True)
python
def list_course_nicknames(self): """ List course nicknames. Returns all course nicknames you have set. """ path = {} data = {} params = {} self.logger.debug("GET /api/v1/users/self/course_nicknames with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/self/course_nicknames".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_course_nicknames", "(", "self", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "self", ".", "logger", ".", "debug", "(", "\"GET /api/v1/users/self/course_nicknames with query params: {params} and form data: {data}\"", "...
List course nicknames. Returns all course nicknames you have set.
[ "List", "course", "nicknames", ".", "Returns", "all", "course", "nicknames", "you", "have", "set", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L1368-L1379
PGower/PyCanvas
pycanvas/apis/users.py
UsersAPI.set_course_nickname
def set_course_nickname(self, nickname, course_id): """ Set course nickname. Set a nickname for the given course. This will replace the course's name in output of API calls you make subsequently, as well as in selected places in the Canvas web user interface. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - nickname """The nickname to set. It must be non-empty and shorter than 60 characters.""" data["nickname"] = nickname self.logger.debug("PUT /api/v1/users/self/course_nicknames/{course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/course_nicknames/{course_id}".format(**path), data=data, params=params, single_item=True)
python
def set_course_nickname(self, nickname, course_id): """ Set course nickname. Set a nickname for the given course. This will replace the course's name in output of API calls you make subsequently, as well as in selected places in the Canvas web user interface. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - nickname """The nickname to set. It must be non-empty and shorter than 60 characters.""" data["nickname"] = nickname self.logger.debug("PUT /api/v1/users/self/course_nicknames/{course_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/users/self/course_nicknames/{course_id}".format(**path), data=data, params=params, single_item=True)
[ "def", "set_course_nickname", "(", "self", ",", "nickname", ",", "course_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]", "=", "cours...
Set course nickname. Set a nickname for the given course. This will replace the course's name in output of API calls you make subsequently, as well as in selected places in the Canvas web user interface.
[ "Set", "course", "nickname", ".", "Set", "a", "nickname", "for", "the", "given", "course", ".", "This", "will", "replace", "the", "course", "s", "name", "in", "output", "of", "API", "calls", "you", "make", "subsequently", "as", "well", "as", "in", "selec...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/users.py#L1398-L1419
PGower/PyCanvas
pycanvas/apis/sis_imports.py
SisImportsAPI.get_sis_import_list
def get_sis_import_list(self, account_id, created_since=None): """ Get SIS import list. Returns the list of SIS imports for an account Example: curl 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports' \ -H "Authorization: Bearer <token>" """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - created_since """If set, only shows imports created after the specified date (use ISO8601 format)""" if created_since is not None: if issubclass(created_since.__class__, basestring): created_since = self._validate_iso8601_string(created_since) elif issubclass(created_since.__class__, date) or issubclass(created_since.__class__, datetime): created_since = created_since.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["created_since"] = created_since self.logger.debug("GET /api/v1/accounts/{account_id}/sis_imports with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/sis_imports".format(**path), data=data, params=params, data_key='sis_imports', all_pages=True)
python
def get_sis_import_list(self, account_id, created_since=None): """ Get SIS import list. Returns the list of SIS imports for an account Example: curl 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports' \ -H "Authorization: Bearer <token>" """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - created_since """If set, only shows imports created after the specified date (use ISO8601 format)""" if created_since is not None: if issubclass(created_since.__class__, basestring): created_since = self._validate_iso8601_string(created_since) elif issubclass(created_since.__class__, date) or issubclass(created_since.__class__, datetime): created_since = created_since.strftime('%Y-%m-%dT%H:%M:%S+00:00') params["created_since"] = created_since self.logger.debug("GET /api/v1/accounts/{account_id}/sis_imports with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/accounts/{account_id}/sis_imports".format(**path), data=data, params=params, data_key='sis_imports', all_pages=True)
[ "def", "get_sis_import_list", "(", "self", ",", "account_id", ",", "created_since", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"account_id\"...
Get SIS import list. Returns the list of SIS imports for an account Example: curl 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports' \ -H "Authorization: Bearer <token>"
[ "Get", "SIS", "import", "list", ".", "Returns", "the", "list", "of", "SIS", "imports", "for", "an", "account", "Example", ":", "curl", "https", ":", "//", "<canvas", ">", "/", "api", "/", "v1", "/", "accounts", "/", "<account_id", ">", "/", "sis_import...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sis_imports.py#L20-L48
PGower/PyCanvas
pycanvas/apis/sis_imports.py
SisImportsAPI.import_sis_data
def import_sis_data(self, account_id, add_sis_stickiness=None, attachment=None, batch_mode=None, batch_mode_term_id=None, clear_sis_stickiness=None, diffing_data_set_identifier=None, diffing_remaster_data_set=None, extension=None, import_type=None, override_sis_stickiness=None): """ Import SIS data. Import SIS data into Canvas. Must be on a root account with SIS imports enabled. For more information on the format that's expected here, please see the "SIS CSV" section in the API docs. """ path = {} data = {} params = {} files = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - import_type """Choose the data format for reading SIS data. With a standard Canvas install, this option can only be 'instructure_csv', and if unprovided, will be assumed to be so. Can be part of the query string.""" if import_type is not None: data["import_type"] = import_type # OPTIONAL - attachment """There are two ways to post SIS import data - either via a multipart/form-data form-field-style attachment, or via a non-multipart raw post request. 'attachment' is required for multipart/form-data style posts. Assumed to be SIS data from a file upload form field named 'attachment'. Examples: curl -F attachment=@<filename> -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' If you decide to do a raw post, you can skip the 'attachment' argument, but you will then be required to provide a suitable Content-Type header. You are encouraged to also provide the 'extension' argument. Examples: curl -H 'Content-Type: application/octet-stream' --data-binary @<filename>.zip \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv&extension=zip' curl -H 'Content-Type: application/zip' --data-binary @<filename>.zip \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' curl -H 'Content-Type: text/csv' --data-binary @<filename>.csv \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' curl -H 'Content-Type: text/csv' --data-binary @<filename>.csv \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv&batch_mode=1&batch_mode_term_id=15'""" if attachment is not None: if type(attachment) is file: files['attachment'] = (os.path.basename(attachment.name), attachment) elif os.path.exists(attachment): files['attachment'] = (os.path.basename(attachment), open(attachment, 'rb')) else: raise ValueError('The attachment must be an open file or a path to a readable file.') # OPTIONAL - extension """Recommended for raw post request style imports. This field will be used to distinguish between zip, xml, csv, and other file format extensions that would usually be provided with the filename in the multipart post request scenario. If not provided, this value will be inferred from the Content-Type, falling back to zip-file format if all else fails.""" if extension is not None: data["extension"] = extension # OPTIONAL - batch_mode """If set, this SIS import will be run in batch mode, deleting any data previously imported via SIS that is not present in this latest import. See the SIS CSV Format page for details.""" if batch_mode is not None: data["batch_mode"] = batch_mode # OPTIONAL - batch_mode_term_id """Limit deletions to only this term. Required if batch mode is enabled.""" if batch_mode_term_id is not None: data["batch_mode_term_id"] = batch_mode_term_id # OPTIONAL - override_sis_stickiness """Many fields on records in Canvas can be marked "sticky," which means that when something changes in the UI apart from the SIS, that field gets "stuck." In this way, by default, SIS imports do not override UI changes. If this field is present, however, it will tell the SIS import to ignore "stickiness" and override all fields.""" if override_sis_stickiness is not None: data["override_sis_stickiness"] = override_sis_stickiness # OPTIONAL - add_sis_stickiness """This option, if present, will process all changes as if they were UI changes. This means that "stickiness" will be added to changed fields. This option is only processed if 'override_sis_stickiness' is also provided.""" if add_sis_stickiness is not None: data["add_sis_stickiness"] = add_sis_stickiness # OPTIONAL - clear_sis_stickiness """This option, if present, will clear "stickiness" from all fields touched by this import. Requires that 'override_sis_stickiness' is also provided. If 'add_sis_stickiness' is also provided, 'clear_sis_stickiness' will overrule the behavior of 'add_sis_stickiness'""" if clear_sis_stickiness is not None: data["clear_sis_stickiness"] = clear_sis_stickiness # OPTIONAL - diffing_data_set_identifier """If set on a CSV import, Canvas will attempt to optimize the SIS import by comparing this set of CSVs to the previous set that has the same data set identifier, and only appliying the difference between the two. See the SIS CSV Format documentation for more details.""" if diffing_data_set_identifier is not None: data["diffing_data_set_identifier"] = diffing_data_set_identifier # OPTIONAL - diffing_remaster_data_set """If true, and diffing_data_set_identifier is sent, this SIS import will be part of the data set, but diffing will not be performed. See the SIS CSV Format documentation for details.""" if diffing_remaster_data_set is not None: data["diffing_remaster_data_set"] = diffing_remaster_data_set self.logger.debug("POST /api/v1/accounts/{account_id}/sis_imports with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/sis_imports".format(**path), data=data, params=params, files=files, single_item=True)
python
def import_sis_data(self, account_id, add_sis_stickiness=None, attachment=None, batch_mode=None, batch_mode_term_id=None, clear_sis_stickiness=None, diffing_data_set_identifier=None, diffing_remaster_data_set=None, extension=None, import_type=None, override_sis_stickiness=None): """ Import SIS data. Import SIS data into Canvas. Must be on a root account with SIS imports enabled. For more information on the format that's expected here, please see the "SIS CSV" section in the API docs. """ path = {} data = {} params = {} files = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - import_type """Choose the data format for reading SIS data. With a standard Canvas install, this option can only be 'instructure_csv', and if unprovided, will be assumed to be so. Can be part of the query string.""" if import_type is not None: data["import_type"] = import_type # OPTIONAL - attachment """There are two ways to post SIS import data - either via a multipart/form-data form-field-style attachment, or via a non-multipart raw post request. 'attachment' is required for multipart/form-data style posts. Assumed to be SIS data from a file upload form field named 'attachment'. Examples: curl -F attachment=@<filename> -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' If you decide to do a raw post, you can skip the 'attachment' argument, but you will then be required to provide a suitable Content-Type header. You are encouraged to also provide the 'extension' argument. Examples: curl -H 'Content-Type: application/octet-stream' --data-binary @<filename>.zip \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv&extension=zip' curl -H 'Content-Type: application/zip' --data-binary @<filename>.zip \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' curl -H 'Content-Type: text/csv' --data-binary @<filename>.csv \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv' curl -H 'Content-Type: text/csv' --data-binary @<filename>.csv \ -H "Authorization: Bearer <token>" \ 'https://<canvas>/api/v1/accounts/<account_id>/sis_imports.json?import_type=instructure_csv&batch_mode=1&batch_mode_term_id=15'""" if attachment is not None: if type(attachment) is file: files['attachment'] = (os.path.basename(attachment.name), attachment) elif os.path.exists(attachment): files['attachment'] = (os.path.basename(attachment), open(attachment, 'rb')) else: raise ValueError('The attachment must be an open file or a path to a readable file.') # OPTIONAL - extension """Recommended for raw post request style imports. This field will be used to distinguish between zip, xml, csv, and other file format extensions that would usually be provided with the filename in the multipart post request scenario. If not provided, this value will be inferred from the Content-Type, falling back to zip-file format if all else fails.""" if extension is not None: data["extension"] = extension # OPTIONAL - batch_mode """If set, this SIS import will be run in batch mode, deleting any data previously imported via SIS that is not present in this latest import. See the SIS CSV Format page for details.""" if batch_mode is not None: data["batch_mode"] = batch_mode # OPTIONAL - batch_mode_term_id """Limit deletions to only this term. Required if batch mode is enabled.""" if batch_mode_term_id is not None: data["batch_mode_term_id"] = batch_mode_term_id # OPTIONAL - override_sis_stickiness """Many fields on records in Canvas can be marked "sticky," which means that when something changes in the UI apart from the SIS, that field gets "stuck." In this way, by default, SIS imports do not override UI changes. If this field is present, however, it will tell the SIS import to ignore "stickiness" and override all fields.""" if override_sis_stickiness is not None: data["override_sis_stickiness"] = override_sis_stickiness # OPTIONAL - add_sis_stickiness """This option, if present, will process all changes as if they were UI changes. This means that "stickiness" will be added to changed fields. This option is only processed if 'override_sis_stickiness' is also provided.""" if add_sis_stickiness is not None: data["add_sis_stickiness"] = add_sis_stickiness # OPTIONAL - clear_sis_stickiness """This option, if present, will clear "stickiness" from all fields touched by this import. Requires that 'override_sis_stickiness' is also provided. If 'add_sis_stickiness' is also provided, 'clear_sis_stickiness' will overrule the behavior of 'add_sis_stickiness'""" if clear_sis_stickiness is not None: data["clear_sis_stickiness"] = clear_sis_stickiness # OPTIONAL - diffing_data_set_identifier """If set on a CSV import, Canvas will attempt to optimize the SIS import by comparing this set of CSVs to the previous set that has the same data set identifier, and only appliying the difference between the two. See the SIS CSV Format documentation for more details.""" if diffing_data_set_identifier is not None: data["diffing_data_set_identifier"] = diffing_data_set_identifier # OPTIONAL - diffing_remaster_data_set """If true, and diffing_data_set_identifier is sent, this SIS import will be part of the data set, but diffing will not be performed. See the SIS CSV Format documentation for details.""" if diffing_remaster_data_set is not None: data["diffing_remaster_data_set"] = diffing_remaster_data_set self.logger.debug("POST /api/v1/accounts/{account_id}/sis_imports with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/sis_imports".format(**path), data=data, params=params, files=files, single_item=True)
[ "def", "import_sis_data", "(", "self", ",", "account_id", ",", "add_sis_stickiness", "=", "None", ",", "attachment", "=", "None", ",", "batch_mode", "=", "None", ",", "batch_mode_term_id", "=", "None", ",", "clear_sis_stickiness", "=", "None", ",", "diffing_data...
Import SIS data. Import SIS data into Canvas. Must be on a root account with SIS imports enabled. For more information on the format that's expected here, please see the "SIS CSV" section in the API docs.
[ "Import", "SIS", "data", ".", "Import", "SIS", "data", "into", "Canvas", ".", "Must", "be", "on", "a", "root", "account", "with", "SIS", "imports", "enabled", ".", "For", "more", "information", "on", "the", "format", "that", "s", "expected", "here", "ple...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sis_imports.py#L50-L177
PGower/PyCanvas
pycanvas/apis/sis_imports.py
SisImportsAPI.abort_all_pending_sis_imports
def abort_all_pending_sis_imports(self, account_id): """ Abort all pending SIS imports. Abort already created but not processed or processing SIS imports. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id self.logger.debug("PUT /api/v1/accounts/{account_id}/sis_imports/abort_all_pending with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/accounts/{account_id}/sis_imports/abort_all_pending".format(**path), data=data, params=params)
python
def abort_all_pending_sis_imports(self, account_id): """ Abort all pending SIS imports. Abort already created but not processed or processing SIS imports. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id self.logger.debug("PUT /api/v1/accounts/{account_id}/sis_imports/abort_all_pending with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/accounts/{account_id}/sis_imports/abort_all_pending".format(**path), data=data, params=params)
[ "def", "abort_all_pending_sis_imports", "(", "self", ",", "account_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"account_id\"", "]", "=", "account_id", ...
Abort all pending SIS imports. Abort already created but not processed or processing SIS imports.
[ "Abort", "all", "pending", "SIS", "imports", ".", "Abort", "already", "created", "but", "not", "processed", "or", "processing", "SIS", "imports", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/sis_imports.py#L225-L240
jaraco/hgtools
hgtools/plugins.py
file_finder
def file_finder(dirname="."): """ Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ). """ import distutils.log dirname = dirname or '.' try: valid_mgrs = managers.RepoManager.get_valid_managers(dirname) valid_mgrs = managers.RepoManager.existing_only(valid_mgrs) for mgr in valid_mgrs: try: return mgr.find_all_files() except Exception: e = sys.exc_info()[1] distutils.log.warn( "hgtools.%s could not find files: %s", mgr, e) except Exception: e = sys.exc_info()[1] distutils.log.warn( "Unexpected error finding valid managers in " "hgtools.file_finder_plugin: %s", e) return []
python
def file_finder(dirname="."): """ Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ). """ import distutils.log dirname = dirname or '.' try: valid_mgrs = managers.RepoManager.get_valid_managers(dirname) valid_mgrs = managers.RepoManager.existing_only(valid_mgrs) for mgr in valid_mgrs: try: return mgr.find_all_files() except Exception: e = sys.exc_info()[1] distutils.log.warn( "hgtools.%s could not find files: %s", mgr, e) except Exception: e = sys.exc_info()[1] distutils.log.warn( "Unexpected error finding valid managers in " "hgtools.file_finder_plugin: %s", e) return []
[ "def", "file_finder", "(", "dirname", "=", "\".\"", ")", ":", "import", "distutils", ".", "log", "dirname", "=", "dirname", "or", "'.'", "try", ":", "valid_mgrs", "=", "managers", ".", "RepoManager", ".", "get_valid_managers", "(", "dirname", ")", "valid_mgr...
Find the files in ``dirname`` under Mercurial version control according to the setuptools spec (see http://peak.telecommunity.com/DevCenter/setuptools#adding-support-for-other-revision-control-systems ).
[ "Find", "the", "files", "in", "dirname", "under", "Mercurial", "version", "control", "according", "to", "the", "setuptools", "spec", "(", "see", "http", ":", "//", "peak", ".", "telecommunity", ".", "com", "/", "DevCenter", "/", "setuptools#adding", "-", "su...
train
https://github.com/jaraco/hgtools/blob/bf5fe2324e5ae15e012487f95f0c97c3775c5d2e/hgtools/plugins.py#L19-L44
jaraco/hgtools
hgtools/plugins.py
patch_egg_info
def patch_egg_info(force_hg_version=False): """ A hack to replace egg_info.tagged_version with a wrapped version that will use the mercurial version if indicated. `force_hg_version` is used for hgtools itself. """ from setuptools.command.egg_info import egg_info from pkg_resources import safe_version import functools orig_ver = egg_info.tagged_version @functools.wraps(orig_ver) def tagged_version(self): vcs_param = ( getattr(self.distribution, 'use_vcs_version', False) or getattr(self.distribution, 'use_hg_version', False) ) using_hg_version = force_hg_version or vcs_param if force_hg_version: # disable patched `tagged_version` to avoid affecting # subsequent installs in the same interpreter instance. egg_info.tagged_version = orig_ver if using_hg_version: result = safe_version(self.distribution.get_version()) else: result = orig_ver(self) self.tag_build = result return result egg_info.tagged_version = tagged_version
python
def patch_egg_info(force_hg_version=False): """ A hack to replace egg_info.tagged_version with a wrapped version that will use the mercurial version if indicated. `force_hg_version` is used for hgtools itself. """ from setuptools.command.egg_info import egg_info from pkg_resources import safe_version import functools orig_ver = egg_info.tagged_version @functools.wraps(orig_ver) def tagged_version(self): vcs_param = ( getattr(self.distribution, 'use_vcs_version', False) or getattr(self.distribution, 'use_hg_version', False) ) using_hg_version = force_hg_version or vcs_param if force_hg_version: # disable patched `tagged_version` to avoid affecting # subsequent installs in the same interpreter instance. egg_info.tagged_version = orig_ver if using_hg_version: result = safe_version(self.distribution.get_version()) else: result = orig_ver(self) self.tag_build = result return result egg_info.tagged_version = tagged_version
[ "def", "patch_egg_info", "(", "force_hg_version", "=", "False", ")", ":", "from", "setuptools", ".", "command", ".", "egg_info", "import", "egg_info", "from", "pkg_resources", "import", "safe_version", "import", "functools", "orig_ver", "=", "egg_info", ".", "tagg...
A hack to replace egg_info.tagged_version with a wrapped version that will use the mercurial version if indicated. `force_hg_version` is used for hgtools itself.
[ "A", "hack", "to", "replace", "egg_info", ".", "tagged_version", "with", "a", "wrapped", "version", "that", "will", "use", "the", "mercurial", "version", "if", "indicated", "." ]
train
https://github.com/jaraco/hgtools/blob/bf5fe2324e5ae15e012487f95f0c97c3775c5d2e/hgtools/plugins.py#L47-L76
jaraco/hgtools
hgtools/plugins.py
version_calc
def version_calc(dist, attr, value): """ Handler for parameter to setup(use_vcs_version=value) attr should be 'use_vcs_version' (also allows use_hg_version for compatibility). bool(value) should be true to invoke this plugin. value may optionally be a dict and supply options to the plugin. """ expected_attrs = 'use_hg_version', 'use_vcs_version' if not value or attr not in expected_attrs: return options = value if isinstance(value, dict) else {} dist.metadata.version = calculate_version(options) patch_egg_info()
python
def version_calc(dist, attr, value): """ Handler for parameter to setup(use_vcs_version=value) attr should be 'use_vcs_version' (also allows use_hg_version for compatibility). bool(value) should be true to invoke this plugin. value may optionally be a dict and supply options to the plugin. """ expected_attrs = 'use_hg_version', 'use_vcs_version' if not value or attr not in expected_attrs: return options = value if isinstance(value, dict) else {} dist.metadata.version = calculate_version(options) patch_egg_info()
[ "def", "version_calc", "(", "dist", ",", "attr", ",", "value", ")", ":", "expected_attrs", "=", "'use_hg_version'", ",", "'use_vcs_version'", "if", "not", "value", "or", "attr", "not", "in", "expected_attrs", ":", "return", "options", "=", "value", "if", "is...
Handler for parameter to setup(use_vcs_version=value) attr should be 'use_vcs_version' (also allows use_hg_version for compatibility). bool(value) should be true to invoke this plugin. value may optionally be a dict and supply options to the plugin.
[ "Handler", "for", "parameter", "to", "setup", "(", "use_vcs_version", "=", "value", ")", "attr", "should", "be", "use_vcs_version", "(", "also", "allows", "use_hg_version", "for", "compatibility", ")", ".", "bool", "(", "value", ")", "should", "be", "true", ...
train
https://github.com/jaraco/hgtools/blob/bf5fe2324e5ae15e012487f95f0c97c3775c5d2e/hgtools/plugins.py#L111-L124
20c/vodka
vodka/storage.py
get_or_create
def get_or_create(name, value): """ returns the storage space defined by name if space does not exist yet it will first be created with the specified value """ if name not in storage: storage[name] = value return storage[name]
python
def get_or_create(name, value): """ returns the storage space defined by name if space does not exist yet it will first be created with the specified value """ if name not in storage: storage[name] = value return storage[name]
[ "def", "get_or_create", "(", "name", ",", "value", ")", ":", "if", "name", "not", "in", "storage", ":", "storage", "[", "name", "]", "=", "value", "return", "storage", "[", "name", "]" ]
returns the storage space defined by name if space does not exist yet it will first be created with the specified value
[ "returns", "the", "storage", "space", "defined", "by", "name" ]
train
https://github.com/20c/vodka/blob/9615148ac6560298453704bb5246b35b66b3339c/vodka/storage.py#L6-L17
Fizzadar/pydocs
pydocs/parse.py
parse_module
def parse_module(module): '''Parse a module's attributes and generate a markdown document.''' attributes = [ (name, type_) for (name, type_) in getmembers(module) if (isclass(type_) or isfunction(type_)) and type_.__module__ == module.__name__ and not type_.__name__.startswith('_') ] attribute_docs = ['## {0}'.format(module.__name__), ''] if module.__doc__: docstring, _ = _parse_docstring(module.__doc__) attribute_docs.append(docstring) if hasattr(module, '__all__'): for name in module.__all__: link = '+ [{0}](./{0}.md)'.format(name) attribute_docs.append(link) for (name, type_) in attributes: if isfunction(type_): attribute_docs.append(_parse_function(module, name, type_)) else: attribute_docs.append(_parse_class(module, name, type_)) return u'{0}\n'.format( u'\n'.join(attribute_docs).strip() )
python
def parse_module(module): '''Parse a module's attributes and generate a markdown document.''' attributes = [ (name, type_) for (name, type_) in getmembers(module) if (isclass(type_) or isfunction(type_)) and type_.__module__ == module.__name__ and not type_.__name__.startswith('_') ] attribute_docs = ['## {0}'.format(module.__name__), ''] if module.__doc__: docstring, _ = _parse_docstring(module.__doc__) attribute_docs.append(docstring) if hasattr(module, '__all__'): for name in module.__all__: link = '+ [{0}](./{0}.md)'.format(name) attribute_docs.append(link) for (name, type_) in attributes: if isfunction(type_): attribute_docs.append(_parse_function(module, name, type_)) else: attribute_docs.append(_parse_class(module, name, type_)) return u'{0}\n'.format( u'\n'.join(attribute_docs).strip() )
[ "def", "parse_module", "(", "module", ")", ":", "attributes", "=", "[", "(", "name", ",", "type_", ")", "for", "(", "name", ",", "type_", ")", "in", "getmembers", "(", "module", ")", "if", "(", "isclass", "(", "type_", ")", "or", "isfunction", "(", ...
Parse a module's attributes and generate a markdown document.
[ "Parse", "a", "module", "s", "attributes", "and", "generate", "a", "markdown", "document", "." ]
train
https://github.com/Fizzadar/pydocs/blob/72713201dc4cf40335f9c3d380c9111b23c2c38b/pydocs/parse.py#L86-L115
Sanji-IO/sanji
sanji/publish.py
Retry
def Retry(target=None, args=[], kwargs={}, options={"retry": True, "interval": 1}): """ options retry True, infinity retries False, no retries Number, retries times interval time period for retry return None if no success Message if success """ retry = options["retry"] interval = options["interval"] while True: try: resp = target(*args, **kwargs) # status error if resp.code == 200: return resp _logger.debug("Request got response status: %s" % (resp.code,) + " retry: %s" % (retry,)) except TimeoutError: _logger.debug("Request message is timeout") _logger.debug(args) _logger.debug(kwargs) # register unsuccessful goes here # infinity retry if retry is True: sleep(interval) continue # no retry if retry is False: return None # retrying try: retry = retry - 1 if retry <= 0: return None except TypeError as e: raise e sleep(interval)
python
def Retry(target=None, args=[], kwargs={}, options={"retry": True, "interval": 1}): """ options retry True, infinity retries False, no retries Number, retries times interval time period for retry return None if no success Message if success """ retry = options["retry"] interval = options["interval"] while True: try: resp = target(*args, **kwargs) # status error if resp.code == 200: return resp _logger.debug("Request got response status: %s" % (resp.code,) + " retry: %s" % (retry,)) except TimeoutError: _logger.debug("Request message is timeout") _logger.debug(args) _logger.debug(kwargs) # register unsuccessful goes here # infinity retry if retry is True: sleep(interval) continue # no retry if retry is False: return None # retrying try: retry = retry - 1 if retry <= 0: return None except TypeError as e: raise e sleep(interval)
[ "def", "Retry", "(", "target", "=", "None", ",", "args", "=", "[", "]", ",", "kwargs", "=", "{", "}", ",", "options", "=", "{", "\"retry\"", ":", "True", ",", "\"interval\"", ":", "1", "}", ")", ":", "retry", "=", "options", "[", "\"retry\"", "]"...
options retry True, infinity retries False, no retries Number, retries times interval time period for retry return None if no success Message if success
[ "options", "retry", "True", "infinity", "retries", "False", "no", "retries", "Number", "retries", "times", "interval", "time", "period", "for", "retry", "return", "None", "if", "no", "success", "Message", "if", "success" ]
train
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/publish.py#L159-L207
Sanji-IO/sanji
sanji/publish.py
Publish.create_crud_func
def create_crud_func(self, method, request_type="CRUD"): """ create_crud_func """ def _crud(resource, data=None, block=True, timeout=60, topic="/controller", tunnel=None, qos=0): """ _crud block True: wait until response arrival False: wait until message is already published to local broker """ headers = { "resource": resource, "method": method } # DIRECT message needs put tunnel in headers for controller if request_type == "DIRECT": if tunnel is not None: headers["tunnel"] = tunnel elif self._conn.tunnels["view"][0] is not None: headers["tunnel"] = self._conn.tunnels["view"][0] elif self._conn.tunnels["model"][0] is not None: headers["tunnel"] = self._conn.tunnels["model"][0] else: headers["tunnel"] = self._conn.tunnels["internel"][0] message = self._create_message(headers, data) with self._session.session_lock: mid = self._conn.publish(topic=topic, qos=qos, payload=message.to_dict()) session = self._session.create(message, mid=mid, age=timeout) session["status"] = Status.SENDING # blocking, until we get response or published if block is False: return self._wait_published(session) return self._wait_resolved(session) return _crud
python
def create_crud_func(self, method, request_type="CRUD"): """ create_crud_func """ def _crud(resource, data=None, block=True, timeout=60, topic="/controller", tunnel=None, qos=0): """ _crud block True: wait until response arrival False: wait until message is already published to local broker """ headers = { "resource": resource, "method": method } # DIRECT message needs put tunnel in headers for controller if request_type == "DIRECT": if tunnel is not None: headers["tunnel"] = tunnel elif self._conn.tunnels["view"][0] is not None: headers["tunnel"] = self._conn.tunnels["view"][0] elif self._conn.tunnels["model"][0] is not None: headers["tunnel"] = self._conn.tunnels["model"][0] else: headers["tunnel"] = self._conn.tunnels["internel"][0] message = self._create_message(headers, data) with self._session.session_lock: mid = self._conn.publish(topic=topic, qos=qos, payload=message.to_dict()) session = self._session.create(message, mid=mid, age=timeout) session["status"] = Status.SENDING # blocking, until we get response or published if block is False: return self._wait_published(session) return self._wait_resolved(session) return _crud
[ "def", "create_crud_func", "(", "self", ",", "method", ",", "request_type", "=", "\"CRUD\"", ")", ":", "def", "_crud", "(", "resource", ",", "data", "=", "None", ",", "block", "=", "True", ",", "timeout", "=", "60", ",", "topic", "=", "\"/controller\"", ...
create_crud_func
[ "create_crud_func" ]
train
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/publish.py#L92-L138
Sanji-IO/sanji
sanji/publish.py
Publish.create_response
def create_response(self, message, sign): """ return function for response """ def _response(code=200, data=None): """ _response """ resp_msg = message.to_response(code=code, data=data, sign=sign) with self._session.session_lock: mid = self._conn.publish(topic="/controller", qos=0, payload=resp_msg.to_dict()) session = self._session.create(resp_msg, mid=mid, age=10) logging.debug("sending response as mid: %s" % mid) return self._wait_published(session, no_response=True) return _response
python
def create_response(self, message, sign): """ return function for response """ def _response(code=200, data=None): """ _response """ resp_msg = message.to_response(code=code, data=data, sign=sign) with self._session.session_lock: mid = self._conn.publish(topic="/controller", qos=0, payload=resp_msg.to_dict()) session = self._session.create(resp_msg, mid=mid, age=10) logging.debug("sending response as mid: %s" % mid) return self._wait_published(session, no_response=True) return _response
[ "def", "create_response", "(", "self", ",", "message", ",", "sign", ")", ":", "def", "_response", "(", "code", "=", "200", ",", "data", "=", "None", ")", ":", "\"\"\"\n _response\n \"\"\"", "resp_msg", "=", "message", ".", "to_response", ...
return function for response
[ "return", "function", "for", "response" ]
train
https://github.com/Sanji-IO/sanji/blob/5c54cc2772bdfeae3337f785de1957237b828b34/sanji/publish.py#L140-L156
PGower/PyCanvas
pycanvas/apis/assignment_groups.py
AssignmentGroupsAPI.list_assignment_groups
def list_assignment_groups(self, course_id, exclude_assignment_submission_types=None, grading_period_id=None, include=None, override_assignment_dates=None, scope_assignments_to_student=None): """ List assignment groups. Returns the list of assignment groups for the current context. The returned groups are sorted by their position field. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - include """Associations to include with the group. "discussion_topic", "all_dates" "assignment_visibility" & "submission" are only valid are only valid if "assignments" is also included. The "assignment_visibility" option additionally requires that the Differentiated Assignments course feature be turned on.""" if include is not None: self._validate_enum(include, ["assignments", "discussion_topic", "all_dates", "assignment_visibility", "overrides", "submission"]) params["include"] = include # OPTIONAL - exclude_assignment_submission_types """If "assignments" are included, those with the specified submission types will be excluded from the assignment groups.""" if exclude_assignment_submission_types is not None: self._validate_enum(exclude_assignment_submission_types, ["online_quiz", "discussion_topic", "wiki_page", "external_tool"]) params["exclude_assignment_submission_types"] = exclude_assignment_submission_types # OPTIONAL - override_assignment_dates """Apply assignment overrides for each assignment, defaults to true.""" if override_assignment_dates is not None: params["override_assignment_dates"] = override_assignment_dates # OPTIONAL - grading_period_id """The id of the grading period in which assignment groups are being requested (Requires the Multiple Grading Periods feature turned on.)""" if grading_period_id is not None: params["grading_period_id"] = grading_period_id # OPTIONAL - scope_assignments_to_student """If true, all assignments returned will apply to the current user in the specified grading period. If assignments apply to other students in the specified grading period, but not the current user, they will not be returned. (Requires the grading_period_id argument and the Multiple Grading Periods feature turned on. In addition, the current user must be a student.)""" if scope_assignments_to_student is not None: params["scope_assignments_to_student"] = scope_assignments_to_student self.logger.debug("GET /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/assignment_groups".format(**path), data=data, params=params, all_pages=True)
python
def list_assignment_groups(self, course_id, exclude_assignment_submission_types=None, grading_period_id=None, include=None, override_assignment_dates=None, scope_assignments_to_student=None): """ List assignment groups. Returns the list of assignment groups for the current context. The returned groups are sorted by their position field. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - include """Associations to include with the group. "discussion_topic", "all_dates" "assignment_visibility" & "submission" are only valid are only valid if "assignments" is also included. The "assignment_visibility" option additionally requires that the Differentiated Assignments course feature be turned on.""" if include is not None: self._validate_enum(include, ["assignments", "discussion_topic", "all_dates", "assignment_visibility", "overrides", "submission"]) params["include"] = include # OPTIONAL - exclude_assignment_submission_types """If "assignments" are included, those with the specified submission types will be excluded from the assignment groups.""" if exclude_assignment_submission_types is not None: self._validate_enum(exclude_assignment_submission_types, ["online_quiz", "discussion_topic", "wiki_page", "external_tool"]) params["exclude_assignment_submission_types"] = exclude_assignment_submission_types # OPTIONAL - override_assignment_dates """Apply assignment overrides for each assignment, defaults to true.""" if override_assignment_dates is not None: params["override_assignment_dates"] = override_assignment_dates # OPTIONAL - grading_period_id """The id of the grading period in which assignment groups are being requested (Requires the Multiple Grading Periods feature turned on.)""" if grading_period_id is not None: params["grading_period_id"] = grading_period_id # OPTIONAL - scope_assignments_to_student """If true, all assignments returned will apply to the current user in the specified grading period. If assignments apply to other students in the specified grading period, but not the current user, they will not be returned. (Requires the grading_period_id argument and the Multiple Grading Periods feature turned on. In addition, the current user must be a student.)""" if scope_assignments_to_student is not None: params["scope_assignments_to_student"] = scope_assignments_to_student self.logger.debug("GET /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/assignment_groups".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_assignment_groups", "(", "self", ",", "course_id", ",", "exclude_assignment_submission_types", "=", "None", ",", "grading_period_id", "=", "None", ",", "include", "=", "None", ",", "override_assignment_dates", "=", "None", ",", "scope_assignments_to_student...
List assignment groups. Returns the list of assignment groups for the current context. The returned groups are sorted by their position field.
[ "List", "assignment", "groups", ".", "Returns", "the", "list", "of", "assignment", "groups", "for", "the", "current", "context", ".", "The", "returned", "groups", "are", "sorted", "by", "their", "position", "field", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignment_groups.py#L19-L70
PGower/PyCanvas
pycanvas/apis/assignment_groups.py
AssignmentGroupsAPI.get_assignment_group
def get_assignment_group(self, course_id, assignment_group_id, grading_period_id=None, include=None, override_assignment_dates=None): """ Get an Assignment Group. Returns the assignment group with the given id. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - assignment_group_id """ID""" path["assignment_group_id"] = assignment_group_id # OPTIONAL - include """Associations to include with the group. "discussion_topic" and "assignment_visibility" and "submission" are only valid if "assignments" is also included. The "assignment_visibility" option additionally requires that the Differentiated Assignments course feature be turned on.""" if include is not None: self._validate_enum(include, ["assignments", "discussion_topic", "assignment_visibility", "submission"]) params["include"] = include # OPTIONAL - override_assignment_dates """Apply assignment overrides for each assignment, defaults to true.""" if override_assignment_dates is not None: params["override_assignment_dates"] = override_assignment_dates # OPTIONAL - grading_period_id """The id of the grading period in which assignment groups are being requested (Requires the Multiple Grading Periods account feature turned on)""" if grading_period_id is not None: params["grading_period_id"] = grading_period_id self.logger.debug("GET /api/v1/courses/{course_id}/assignment_groups/{assignment_group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/assignment_groups/{assignment_group_id}".format(**path), data=data, params=params, single_item=True)
python
def get_assignment_group(self, course_id, assignment_group_id, grading_period_id=None, include=None, override_assignment_dates=None): """ Get an Assignment Group. Returns the assignment group with the given id. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - assignment_group_id """ID""" path["assignment_group_id"] = assignment_group_id # OPTIONAL - include """Associations to include with the group. "discussion_topic" and "assignment_visibility" and "submission" are only valid if "assignments" is also included. The "assignment_visibility" option additionally requires that the Differentiated Assignments course feature be turned on.""" if include is not None: self._validate_enum(include, ["assignments", "discussion_topic", "assignment_visibility", "submission"]) params["include"] = include # OPTIONAL - override_assignment_dates """Apply assignment overrides for each assignment, defaults to true.""" if override_assignment_dates is not None: params["override_assignment_dates"] = override_assignment_dates # OPTIONAL - grading_period_id """The id of the grading period in which assignment groups are being requested (Requires the Multiple Grading Periods account feature turned on)""" if grading_period_id is not None: params["grading_period_id"] = grading_period_id self.logger.debug("GET /api/v1/courses/{course_id}/assignment_groups/{assignment_group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/assignment_groups/{assignment_group_id}".format(**path), data=data, params=params, single_item=True)
[ "def", "get_assignment_group", "(", "self", ",", "course_id", ",", "assignment_group_id", ",", "grading_period_id", "=", "None", ",", "include", "=", "None", ",", "override_assignment_dates", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}...
Get an Assignment Group. Returns the assignment group with the given id.
[ "Get", "an", "Assignment", "Group", ".", "Returns", "the", "assignment", "group", "with", "the", "given", "id", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignment_groups.py#L72-L110
PGower/PyCanvas
pycanvas/apis/assignment_groups.py
AssignmentGroupsAPI.create_assignment_group
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None): """ Create an Assignment Group. Create a new assignment group for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - name """The assignment group's name""" if name is not None: data["name"] = name # OPTIONAL - position """The position of this assignment group in relation to the other assignment groups""" if position is not None: data["position"] = position # OPTIONAL - group_weight """The percent of the total grade that this assignment group represents""" if group_weight is not None: data["group_weight"] = group_weight # OPTIONAL - sis_source_id """The sis source id of the Assignment Group""" if sis_source_id is not None: data["sis_source_id"] = sis_source_id # OPTIONAL - integration_data """The integration data of the Assignment Group""" if integration_data is not None: data["integration_data"] = integration_data # OPTIONAL - rules """The grading rules that are applied within this assignment group See the Assignment Group object definition for format""" if rules is not None: data["rules"] = rules self.logger.debug("POST /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/assignment_groups".format(**path), data=data, params=params, single_item=True)
python
def create_assignment_group(self, course_id, group_weight=None, integration_data=None, name=None, position=None, rules=None, sis_source_id=None): """ Create an Assignment Group. Create a new assignment group for this course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - name """The assignment group's name""" if name is not None: data["name"] = name # OPTIONAL - position """The position of this assignment group in relation to the other assignment groups""" if position is not None: data["position"] = position # OPTIONAL - group_weight """The percent of the total grade that this assignment group represents""" if group_weight is not None: data["group_weight"] = group_weight # OPTIONAL - sis_source_id """The sis source id of the Assignment Group""" if sis_source_id is not None: data["sis_source_id"] = sis_source_id # OPTIONAL - integration_data """The integration data of the Assignment Group""" if integration_data is not None: data["integration_data"] = integration_data # OPTIONAL - rules """The grading rules that are applied within this assignment group See the Assignment Group object definition for format""" if rules is not None: data["rules"] = rules self.logger.debug("POST /api/v1/courses/{course_id}/assignment_groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/assignment_groups".format(**path), data=data, params=params, single_item=True)
[ "def", "create_assignment_group", "(", "self", ",", "course_id", ",", "group_weight", "=", "None", ",", "integration_data", "=", "None", ",", "name", "=", "None", ",", "position", "=", "None", ",", "rules", "=", "None", ",", "sis_source_id", "=", "None", "...
Create an Assignment Group. Create a new assignment group for this course.
[ "Create", "an", "Assignment", "Group", ".", "Create", "a", "new", "assignment", "group", "for", "this", "course", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignment_groups.py#L112-L158
PGower/PyCanvas
pycanvas/apis/assignment_groups.py
AssignmentGroupsAPI.edit_assignment_group
def edit_assignment_group(self, course_id, assignment_group_id): """ Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - assignment_group_id """ID""" path["assignment_group_id"] = assignment_group_id self.logger.debug("PUT /api/v1/courses/{course_id}/assignment_groups/{assignment_group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/assignment_groups/{assignment_group_id}".format(**path), data=data, params=params, single_item=True)
python
def edit_assignment_group(self, course_id, assignment_group_id): """ Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - assignment_group_id """ID""" path["assignment_group_id"] = assignment_group_id self.logger.debug("PUT /api/v1/courses/{course_id}/assignment_groups/{assignment_group_id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/assignment_groups/{assignment_group_id}".format(**path), data=data, params=params, single_item=True)
[ "def", "edit_assignment_group", "(", "self", ",", "course_id", ",", "assignment_group_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]", ...
Edit an Assignment Group. Modify an existing Assignment Group. Accepts the same parameters as Assignment Group creation
[ "Edit", "an", "Assignment", "Group", ".", "Modify", "an", "existing", "Assignment", "Group", ".", "Accepts", "the", "same", "parameters", "as", "Assignment", "Group", "creation" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/assignment_groups.py#L160-L180
PGower/PyCanvas
pycanvas/apis/quiz_question_groups.py
QuizQuestionGroupsAPI.create_question_group
def create_question_group(self, quiz_id, course_id, quiz_groups_assessment_question_bank_id=None, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None): """ Create a question group. Create a new question group for this quiz <b>201 Created</b> response code is returned if the creation was successful. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - quiz_id """ID""" path["quiz_id"] = quiz_id # OPTIONAL - quiz_groups[name] """The name of the question group.""" if quiz_groups_name is not None: data["quiz_groups[name]"] = quiz_groups_name # OPTIONAL - quiz_groups[pick_count] """The number of questions to randomly select for this group.""" if quiz_groups_pick_count is not None: data["quiz_groups[pick_count]"] = quiz_groups_pick_count # OPTIONAL - quiz_groups[question_points] """The number of points to assign to each question in the group.""" if quiz_groups_question_points is not None: data["quiz_groups[question_points]"] = quiz_groups_question_points # OPTIONAL - quiz_groups[assessment_question_bank_id] """The id of the assessment question bank to pull questions from.""" if quiz_groups_assessment_question_bank_id is not None: data["quiz_groups[assessment_question_bank_id]"] = quiz_groups_assessment_question_bank_id self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups".format(**path), data=data, params=params, no_data=True)
python
def create_question_group(self, quiz_id, course_id, quiz_groups_assessment_question_bank_id=None, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None): """ Create a question group. Create a new question group for this quiz <b>201 Created</b> response code is returned if the creation was successful. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # REQUIRED - PATH - quiz_id """ID""" path["quiz_id"] = quiz_id # OPTIONAL - quiz_groups[name] """The name of the question group.""" if quiz_groups_name is not None: data["quiz_groups[name]"] = quiz_groups_name # OPTIONAL - quiz_groups[pick_count] """The number of questions to randomly select for this group.""" if quiz_groups_pick_count is not None: data["quiz_groups[pick_count]"] = quiz_groups_pick_count # OPTIONAL - quiz_groups[question_points] """The number of points to assign to each question in the group.""" if quiz_groups_question_points is not None: data["quiz_groups[question_points]"] = quiz_groups_question_points # OPTIONAL - quiz_groups[assessment_question_bank_id] """The id of the assessment question bank to pull questions from.""" if quiz_groups_assessment_question_bank_id is not None: data["quiz_groups[assessment_question_bank_id]"] = quiz_groups_assessment_question_bank_id self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups".format(**path), data=data, params=params, no_data=True)
[ "def", "create_question_group", "(", "self", ",", "quiz_id", ",", "course_id", ",", "quiz_groups_assessment_question_bank_id", "=", "None", ",", "quiz_groups_name", "=", "None", ",", "quiz_groups_pick_count", "=", "None", ",", "quiz_groups_question_points", "=", "None",...
Create a question group. Create a new question group for this quiz <b>201 Created</b> response code is returned if the creation was successful.
[ "Create", "a", "question", "group", ".", "Create", "a", "new", "question", "group", "for", "this", "quiz", "<b", ">", "201", "Created<", "/", "b", ">", "response", "code", "is", "returned", "if", "the", "creation", "was", "successful", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_question_groups.py#L44-L85
PGower/PyCanvas
pycanvas/apis/quiz_question_groups.py
QuizQuestionGroupsAPI.update_question_group
def update_question_group(self, id, quiz_id, course_id, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None): """ Update a question group. Update a question group """ path = {} data = {} params = {} # REQUIRED - 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 # OPTIONAL - quiz_groups[name] """The name of the question group.""" if quiz_groups_name is not None: data["quiz_groups[name]"] = quiz_groups_name # OPTIONAL - quiz_groups[pick_count] """The number of questions to randomly select for this group.""" if quiz_groups_pick_count is not None: data["quiz_groups[pick_count]"] = quiz_groups_pick_count # OPTIONAL - quiz_groups[question_points] """The number of points to assign to each question in the group.""" if quiz_groups_question_points is not None: data["quiz_groups[question_points]"] = quiz_groups_question_points self.logger.debug("PUT /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}".format(**path), data=data, params=params, no_data=True)
python
def update_question_group(self, id, quiz_id, course_id, quiz_groups_name=None, quiz_groups_pick_count=None, quiz_groups_question_points=None): """ Update a question group. Update a question group """ path = {} data = {} params = {} # REQUIRED - 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 # OPTIONAL - quiz_groups[name] """The name of the question group.""" if quiz_groups_name is not None: data["quiz_groups[name]"] = quiz_groups_name # OPTIONAL - quiz_groups[pick_count] """The number of questions to randomly select for this group.""" if quiz_groups_pick_count is not None: data["quiz_groups[pick_count]"] = quiz_groups_pick_count # OPTIONAL - quiz_groups[question_points] """The number of points to assign to each question in the group.""" if quiz_groups_question_points is not None: data["quiz_groups[question_points]"] = quiz_groups_question_points self.logger.debug("PUT /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}".format(**path), data=data, params=params, no_data=True)
[ "def", "update_question_group", "(", "self", ",", "id", ",", "quiz_id", ",", "course_id", ",", "quiz_groups_name", "=", "None", ",", "quiz_groups_pick_count", "=", "None", ",", "quiz_groups_question_points", "=", "None", ")", ":", "path", "=", "{", "}", "data"...
Update a question group. Update a question group
[ "Update", "a", "question", "group", ".", "Update", "a", "question", "group" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_question_groups.py#L87-L125
PGower/PyCanvas
pycanvas/apis/quiz_question_groups.py
QuizQuestionGroupsAPI.reorder_question_groups
def reorder_question_groups(self, id, quiz_id, order_id, course_id, order_type=None): """ Reorder question groups. Change the order of the quiz questions within the group <b>204 No Content<b> response code is returned if the reorder was successful. """ path = {} data = {} params = {} # REQUIRED - 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 - order[id] """The associated item's unique identifier""" data["order[id]"] = order_id # OPTIONAL - order[type] """The type of item is always 'question' for a group""" if order_type is not None: self._validate_enum(order_type, ["question"]) data["order[type]"] = order_type self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}/reorder with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}/reorder".format(**path), data=data, params=params, no_data=True)
python
def reorder_question_groups(self, id, quiz_id, order_id, course_id, order_type=None): """ Reorder question groups. Change the order of the quiz questions within the group <b>204 No Content<b> response code is returned if the reorder was successful. """ path = {} data = {} params = {} # REQUIRED - 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 - order[id] """The associated item's unique identifier""" data["order[id]"] = order_id # OPTIONAL - order[type] """The type of item is always 'question' for a group""" if order_type is not None: self._validate_enum(order_type, ["question"]) data["order[type]"] = order_type self.logger.debug("POST /api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}/reorder with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/groups/{id}/reorder".format(**path), data=data, params=params, no_data=True)
[ "def", "reorder_question_groups", "(", "self", ",", "id", ",", "quiz_id", ",", "order_id", ",", "course_id", ",", "order_type", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r",...
Reorder question groups. Change the order of the quiz questions within the group <b>204 No Content<b> response code is returned if the reorder was successful.
[ "Reorder", "question", "groups", ".", "Change", "the", "order", "of", "the", "quiz", "questions", "within", "the", "group", "<b", ">", "204", "No", "Content<b", ">", "response", "code", "is", "returned", "if", "the", "reorder", "was", "successful", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/quiz_question_groups.py#L154-L189
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.list_your_courses
def list_your_courses(self, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, state=None): """ List your courses. Returns the list of active courses for the current user. """ path = {} data = {} params = {} # OPTIONAL - enrollment_type """When set, only return courses where the user is enrolled as this type. For example, set to "teacher" to return only courses where the user is enrolled as a Teacher. This argument is ignored if enrollment_role is given.""" if enrollment_type is not None: self._validate_enum(enrollment_type, ["teacher", "student", "ta", "observer", "designer"]) params["enrollment_type"] = enrollment_type # OPTIONAL - enrollment_role """Deprecated When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a base role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role is not None: params["enrollment_role"] = enrollment_role # OPTIONAL - enrollment_role_id """When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a built_in role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role_id is not None: params["enrollment_role_id"] = enrollment_role_id # OPTIONAL - enrollment_state """When set, only return courses where the user has an enrollment with the given state. This will respect section/course/term date overrides.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited_or_pending", "completed"]) params["enrollment_state"] = enrollment_state # OPTIONAL - include """- "needs_grading_count": Optional information to include with each Course. When needs_grading_count is given, and the current user has grading rights, the total number of submissions needing grading for all assignments is returned. - "syllabus_body": Optional information to include with each Course. When syllabus_body is given the user-generated html for the course syllabus is returned. - "public_description": Optional information to include with each Course. When public_description is given the user-generated text for the course public description is returned. - "total_scores": Optional information to include with each Course. When total_scores is given, any student enrollments will also include the fields 'computed_current_score', 'computed_final_score', 'computed_current_grade', and 'computed_final_grade' (see Enrollment documentation for more information on these fields). This argument is ignored if the course is configured to hide final grades. - "current_grading_period_scores": Optional information to include with each Course. When current_grading_period_scores is given and total_scores is given, any student enrollments will also include the fields 'multiple_grading_periods_enabled', 'totals_for_all_grading_periods_option', 'current_grading_period_title', 'current_grading_period_id', current_period_computed_current_score', 'current_period_computed_final_score', 'current_period_computed_current_grade', and 'current_period_computed_final_grade' (see Enrollment documentation for more information on these fields). In addition, when this argument is passed, the course will have a 'multiple_grading_periods_enabled' attribute on it. This argument is ignored if the course is configured to hide final grades or if the total_scores argument is not included. - "term": Optional information to include with each Course. When term is given, the information for the enrollment term for each course is returned. - "course_progress": Optional information to include with each Course. When course_progress is given, each course will include a 'course_progress' object with the fields: 'requirement_count', an integer specifying the total number of requirements in the course, 'requirement_completed_count', an integer specifying the total number of requirements in this course that have been completed, and 'next_requirement_url', a string url to the next requirement item, and 'completed_at', the date the course was completed (null if incomplete). 'next_requirement_url' will be null if all requirements have been completed or the current module does not require sequential progress. "course_progress" will return an error message if the course is not module based or the user is not enrolled as a student in the course. - "sections": Section enrollment information to include with each Course. Returns an array of hashes containing the section ID (id), section name (name), start and end dates (start_at, end_at), as well as the enrollment type (enrollment_role, e.g. 'StudentEnrollment'). - "storage_quota_used_mb": The amount of storage space used by the files in this course - "total_students": Optional information to include with each Course. Returns an integer for the total amount of active and invited students. - "passback_status": Include the grade passback_status - "favorites": Optional information to include with each Course. Indicates if the user has marked the course as a favorite course. - "teachers": Teacher information to include with each Course. Returns an array of hashes containing the {api:Users:UserDisplay UserDisplay} information for each teacher in the course. - "observed_users": Optional information to include with each Course. Will include data for observed users if the current user has an observer enrollment. - "tabs": Optional information to include with each Course. Will include the list of tabs configured for each course. See the {api:TabsController#index List available tabs API} for more information.""" if include is not None: self._validate_enum(include, ["needs_grading_count", "syllabus_body", "public_description", "total_scores", "current_grading_period_scores", "term", "course_progress", "sections", "storage_quota_used_mb", "total_students", "passback_status", "favorites", "teachers", "observed_users"]) params["include"] = include # OPTIONAL - state """If set, only return courses that are in the given state(s). By default, "available" is returned for students and observers, and anything except "deleted", for all other enrollment types""" if state is not None: self._validate_enum(state, ["unpublished", "available", "completed", "deleted"]) params["state"] = state self.logger.debug("GET /api/v1/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses".format(**path), data=data, params=params, all_pages=True)
python
def list_your_courses(self, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, state=None): """ List your courses. Returns the list of active courses for the current user. """ path = {} data = {} params = {} # OPTIONAL - enrollment_type """When set, only return courses where the user is enrolled as this type. For example, set to "teacher" to return only courses where the user is enrolled as a Teacher. This argument is ignored if enrollment_role is given.""" if enrollment_type is not None: self._validate_enum(enrollment_type, ["teacher", "student", "ta", "observer", "designer"]) params["enrollment_type"] = enrollment_type # OPTIONAL - enrollment_role """Deprecated When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a base role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role is not None: params["enrollment_role"] = enrollment_role # OPTIONAL - enrollment_role_id """When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a built_in role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role_id is not None: params["enrollment_role_id"] = enrollment_role_id # OPTIONAL - enrollment_state """When set, only return courses where the user has an enrollment with the given state. This will respect section/course/term date overrides.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited_or_pending", "completed"]) params["enrollment_state"] = enrollment_state # OPTIONAL - include """- "needs_grading_count": Optional information to include with each Course. When needs_grading_count is given, and the current user has grading rights, the total number of submissions needing grading for all assignments is returned. - "syllabus_body": Optional information to include with each Course. When syllabus_body is given the user-generated html for the course syllabus is returned. - "public_description": Optional information to include with each Course. When public_description is given the user-generated text for the course public description is returned. - "total_scores": Optional information to include with each Course. When total_scores is given, any student enrollments will also include the fields 'computed_current_score', 'computed_final_score', 'computed_current_grade', and 'computed_final_grade' (see Enrollment documentation for more information on these fields). This argument is ignored if the course is configured to hide final grades. - "current_grading_period_scores": Optional information to include with each Course. When current_grading_period_scores is given and total_scores is given, any student enrollments will also include the fields 'multiple_grading_periods_enabled', 'totals_for_all_grading_periods_option', 'current_grading_period_title', 'current_grading_period_id', current_period_computed_current_score', 'current_period_computed_final_score', 'current_period_computed_current_grade', and 'current_period_computed_final_grade' (see Enrollment documentation for more information on these fields). In addition, when this argument is passed, the course will have a 'multiple_grading_periods_enabled' attribute on it. This argument is ignored if the course is configured to hide final grades or if the total_scores argument is not included. - "term": Optional information to include with each Course. When term is given, the information for the enrollment term for each course is returned. - "course_progress": Optional information to include with each Course. When course_progress is given, each course will include a 'course_progress' object with the fields: 'requirement_count', an integer specifying the total number of requirements in the course, 'requirement_completed_count', an integer specifying the total number of requirements in this course that have been completed, and 'next_requirement_url', a string url to the next requirement item, and 'completed_at', the date the course was completed (null if incomplete). 'next_requirement_url' will be null if all requirements have been completed or the current module does not require sequential progress. "course_progress" will return an error message if the course is not module based or the user is not enrolled as a student in the course. - "sections": Section enrollment information to include with each Course. Returns an array of hashes containing the section ID (id), section name (name), start and end dates (start_at, end_at), as well as the enrollment type (enrollment_role, e.g. 'StudentEnrollment'). - "storage_quota_used_mb": The amount of storage space used by the files in this course - "total_students": Optional information to include with each Course. Returns an integer for the total amount of active and invited students. - "passback_status": Include the grade passback_status - "favorites": Optional information to include with each Course. Indicates if the user has marked the course as a favorite course. - "teachers": Teacher information to include with each Course. Returns an array of hashes containing the {api:Users:UserDisplay UserDisplay} information for each teacher in the course. - "observed_users": Optional information to include with each Course. Will include data for observed users if the current user has an observer enrollment. - "tabs": Optional information to include with each Course. Will include the list of tabs configured for each course. See the {api:TabsController#index List available tabs API} for more information.""" if include is not None: self._validate_enum(include, ["needs_grading_count", "syllabus_body", "public_description", "total_scores", "current_grading_period_scores", "term", "course_progress", "sections", "storage_quota_used_mb", "total_students", "passback_status", "favorites", "teachers", "observed_users"]) params["include"] = include # OPTIONAL - state """If set, only return courses that are in the given state(s). By default, "available" is returned for students and observers, and anything except "deleted", for all other enrollment types""" if state is not None: self._validate_enum(state, ["unpublished", "available", "completed", "deleted"]) params["state"] = state self.logger.debug("GET /api/v1/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_your_courses", "(", "self", ",", "enrollment_role", "=", "None", ",", "enrollment_role_id", "=", "None", ",", "enrollment_state", "=", "None", ",", "enrollment_type", "=", "None", ",", "include", "=", "None", ",", "state", "=", "None", ")", ":",...
List your courses. Returns the list of active courses for the current user.
[ "List", "your", "courses", ".", "Returns", "the", "list", "of", "active", "courses", "for", "the", "current", "user", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L19-L140
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.list_courses_for_user
def list_courses_for_user(self, user_id, enrollment_state=None, include=None, state=None): """ List courses for a user. Returns a list of active courses for this user. To view the course list for a user other than yourself, you must be either an observer of that user or an administrator. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - include """- "needs_grading_count": Optional information to include with each Course. When needs_grading_count is given, and the current user has grading rights, the total number of submissions needing grading for all assignments is returned. - "syllabus_body": Optional information to include with each Course. When syllabus_body is given the user-generated html for the course syllabus is returned. - "public_description": Optional information to include with each Course. When public_description is given the user-generated text for the course public description is returned. - "total_scores": Optional information to include with each Course. When total_scores is given, any student enrollments will also include the fields 'computed_current_score', 'computed_final_score', 'computed_current_grade', and 'computed_final_grade' (see Enrollment documentation for more information on these fields). This argument is ignored if the course is configured to hide final grades. - "current_grading_period_scores": Optional information to include with each Course. When current_grading_period_scores is given and total_scores is given, any student enrollments will also include the fields 'multiple_grading_periods_enabled', 'totals_for_all_grading_periods_option', 'current_grading_period_title', 'current_grading_period_id', current_period_computed_current_score', 'current_period_computed_final_score', 'current_period_computed_current_grade', and 'current_period_computed_final_grade' (see Enrollment documentation for more information on these fields). In addition, when this argument is passed, the course will have a 'multiple_grading_periods_enabled' attribute on it. This argument is ignored if the course is configured to hide final grades or if the total_scores argument is not included. - "term": Optional information to include with each Course. When term is given, the information for the enrollment term for each course is returned. - "course_progress": Optional information to include with each Course. When course_progress is given, each course will include a 'course_progress' object with the fields: 'requirement_count', an integer specifying the total number of requirements in the course, 'requirement_completed_count', an integer specifying the total number of requirements in this course that have been completed, and 'next_requirement_url', a string url to the next requirement item, and 'completed_at', the date the course was completed (null if incomplete). 'next_requirement_url' will be null if all requirements have been completed or the current module does not require sequential progress. "course_progress" will return an error message if the course is not module based or the user is not enrolled as a student in the course. - "sections": Section enrollment information to include with each Course. Returns an array of hashes containing the section ID (id), section name (name), start and end dates (start_at, end_at), as well as the enrollment type (enrollment_role, e.g. 'StudentEnrollment'). - "storage_quota_used_mb": The amount of storage space used by the files in this course - "total_students": Optional information to include with each Course. Returns an integer for the total amount of active and invited students. - "passback_status": Include the grade passback_status - "favorites": Optional information to include with each Course. Indicates if the user has marked the course as a favorite course. - "teachers": Teacher information to include with each Course. Returns an array of hashes containing the {api:Users:UserDisplay UserDisplay} information for each teacher in the course. - "observed_users": Optional information to include with each Course. Will include data for observed users if the current user has an observer enrollment. - "tabs": Optional information to include with each Course. Will include the list of tabs configured for each course. See the {api:TabsController#index List available tabs API} for more information.""" if include is not None: self._validate_enum(include, ["needs_grading_count", "syllabus_body", "public_description", "total_scores", "current_grading_period_scores", "term", "course_progress", "sections", "storage_quota_used_mb", "total_students", "passback_status", "favorites", "teachers", "observed_users"]) params["include"] = include # OPTIONAL - state """If set, only return courses that are in the given state(s). By default, "available" is returned for students and observers, and anything except "deleted", for all other enrollment types""" if state is not None: self._validate_enum(state, ["unpublished", "available", "completed", "deleted"]) params["state"] = state # OPTIONAL - enrollment_state """When set, only return courses where the user has an enrollment with the given state. This will respect section/course/term date overrides.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited_or_pending", "completed"]) params["enrollment_state"] = enrollment_state self.logger.debug("GET /api/v1/users/{user_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/courses".format(**path), data=data, params=params, all_pages=True)
python
def list_courses_for_user(self, user_id, enrollment_state=None, include=None, state=None): """ List courses for a user. Returns a list of active courses for this user. To view the course list for a user other than yourself, you must be either an observer of that user or an administrator. """ path = {} data = {} params = {} # REQUIRED - PATH - user_id """ID""" path["user_id"] = user_id # OPTIONAL - include """- "needs_grading_count": Optional information to include with each Course. When needs_grading_count is given, and the current user has grading rights, the total number of submissions needing grading for all assignments is returned. - "syllabus_body": Optional information to include with each Course. When syllabus_body is given the user-generated html for the course syllabus is returned. - "public_description": Optional information to include with each Course. When public_description is given the user-generated text for the course public description is returned. - "total_scores": Optional information to include with each Course. When total_scores is given, any student enrollments will also include the fields 'computed_current_score', 'computed_final_score', 'computed_current_grade', and 'computed_final_grade' (see Enrollment documentation for more information on these fields). This argument is ignored if the course is configured to hide final grades. - "current_grading_period_scores": Optional information to include with each Course. When current_grading_period_scores is given and total_scores is given, any student enrollments will also include the fields 'multiple_grading_periods_enabled', 'totals_for_all_grading_periods_option', 'current_grading_period_title', 'current_grading_period_id', current_period_computed_current_score', 'current_period_computed_final_score', 'current_period_computed_current_grade', and 'current_period_computed_final_grade' (see Enrollment documentation for more information on these fields). In addition, when this argument is passed, the course will have a 'multiple_grading_periods_enabled' attribute on it. This argument is ignored if the course is configured to hide final grades or if the total_scores argument is not included. - "term": Optional information to include with each Course. When term is given, the information for the enrollment term for each course is returned. - "course_progress": Optional information to include with each Course. When course_progress is given, each course will include a 'course_progress' object with the fields: 'requirement_count', an integer specifying the total number of requirements in the course, 'requirement_completed_count', an integer specifying the total number of requirements in this course that have been completed, and 'next_requirement_url', a string url to the next requirement item, and 'completed_at', the date the course was completed (null if incomplete). 'next_requirement_url' will be null if all requirements have been completed or the current module does not require sequential progress. "course_progress" will return an error message if the course is not module based or the user is not enrolled as a student in the course. - "sections": Section enrollment information to include with each Course. Returns an array of hashes containing the section ID (id), section name (name), start and end dates (start_at, end_at), as well as the enrollment type (enrollment_role, e.g. 'StudentEnrollment'). - "storage_quota_used_mb": The amount of storage space used by the files in this course - "total_students": Optional information to include with each Course. Returns an integer for the total amount of active and invited students. - "passback_status": Include the grade passback_status - "favorites": Optional information to include with each Course. Indicates if the user has marked the course as a favorite course. - "teachers": Teacher information to include with each Course. Returns an array of hashes containing the {api:Users:UserDisplay UserDisplay} information for each teacher in the course. - "observed_users": Optional information to include with each Course. Will include data for observed users if the current user has an observer enrollment. - "tabs": Optional information to include with each Course. Will include the list of tabs configured for each course. See the {api:TabsController#index List available tabs API} for more information.""" if include is not None: self._validate_enum(include, ["needs_grading_count", "syllabus_body", "public_description", "total_scores", "current_grading_period_scores", "term", "course_progress", "sections", "storage_quota_used_mb", "total_students", "passback_status", "favorites", "teachers", "observed_users"]) params["include"] = include # OPTIONAL - state """If set, only return courses that are in the given state(s). By default, "available" is returned for students and observers, and anything except "deleted", for all other enrollment types""" if state is not None: self._validate_enum(state, ["unpublished", "available", "completed", "deleted"]) params["state"] = state # OPTIONAL - enrollment_state """When set, only return courses where the user has an enrollment with the given state. This will respect section/course/term date overrides.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited_or_pending", "completed"]) params["enrollment_state"] = enrollment_state self.logger.debug("GET /api/v1/users/{user_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/users/{user_id}/courses".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_courses_for_user", "(", "self", ",", "user_id", ",", "enrollment_state", "=", "None", ",", "include", "=", "None", ",", "state", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PA...
List courses for a user. Returns a list of active courses for this user. To view the course list for a user other than yourself, you must be either an observer of that user or an administrator.
[ "List", "courses", "for", "a", "user", ".", "Returns", "a", "list", "of", "active", "courses", "for", "this", "user", ".", "To", "view", "the", "course", "list", "for", "a", "user", "other", "than", "yourself", "you", "must", "be", "either", "an", "obs...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L142-L240
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.create_new_course
def create_new_course(self, account_id, course_allow_student_forum_attachments=None, course_allow_student_wiki_edits=None, course_allow_wiki_comments=None, course_apply_assignment_group_weights=None, course_course_code=None, course_course_format=None, course_end_at=None, course_grading_standard_id=None, course_hide_final_grades=None, course_integration_id=None, course_is_public=None, course_is_public_to_auth_users=None, course_license=None, course_name=None, course_open_enrollment=None, course_public_description=None, course_public_syllabus=None, course_public_syllabus_to_auth=None, course_restrict_enrollments_to_course_dates=None, course_self_enrollment=None, course_sis_course_id=None, course_start_at=None, course_syllabus_body=None, course_term_id=None, course_time_zone=None, enable_sis_reactivation=None, enroll_me=None, offer=None): """ Create a new course. Create a new course """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - course[name] """The name of the course. If omitted, the course will be named "Unnamed Course." """ if course_name is not None: data["course[name]"] = course_name # OPTIONAL - course[course_code] """The course code for the course.""" if course_course_code is not None: data["course[course_code]"] = course_course_code # OPTIONAL - course[start_at] """Course start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_start_at is not None: data["course[start_at]"] = course_start_at # OPTIONAL - course[end_at] """Course end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_end_at is not None: data["course[end_at]"] = course_end_at # OPTIONAL - course[license] """The name of the licensing. Should be one of the following abbreviations (a descriptive name is included in parenthesis for reference): - 'private' (Private Copyrighted) - 'cc_by_nc_nd' (CC Attribution Non-Commercial No Derivatives) - 'cc_by_nc_sa' (CC Attribution Non-Commercial Share Alike) - 'cc_by_nc' (CC Attribution Non-Commercial) - 'cc_by_nd' (CC Attribution No Derivatives) - 'cc_by_sa' (CC Attribution Share Alike) - 'cc_by' (CC Attribution) - 'public_domain' (Public Domain).""" if course_license is not None: data["course[license]"] = course_license # OPTIONAL - course[is_public] """Set to true if course is public to both authenticated and unauthenticated users.""" if course_is_public is not None: data["course[is_public]"] = course_is_public # OPTIONAL - course[is_public_to_auth_users] """Set to true if course is public only to authenticated users.""" if course_is_public_to_auth_users is not None: data["course[is_public_to_auth_users]"] = course_is_public_to_auth_users # OPTIONAL - course[public_syllabus] """Set to true to make the course syllabus public.""" if course_public_syllabus is not None: data["course[public_syllabus]"] = course_public_syllabus # OPTIONAL - course[public_syllabus_to_auth] """Set to true to make the course syllabus public for authenticated users.""" if course_public_syllabus_to_auth is not None: data["course[public_syllabus_to_auth]"] = course_public_syllabus_to_auth # OPTIONAL - course[public_description] """A publicly visible description of the course.""" if course_public_description is not None: data["course[public_description]"] = course_public_description # OPTIONAL - course[allow_student_wiki_edits] """If true, students will be able to modify the course wiki.""" if course_allow_student_wiki_edits is not None: data["course[allow_student_wiki_edits]"] = course_allow_student_wiki_edits # OPTIONAL - course[allow_wiki_comments] """If true, course members will be able to comment on wiki pages.""" if course_allow_wiki_comments is not None: data["course[allow_wiki_comments]"] = course_allow_wiki_comments # OPTIONAL - course[allow_student_forum_attachments] """If true, students can attach files to forum posts.""" if course_allow_student_forum_attachments is not None: data["course[allow_student_forum_attachments]"] = course_allow_student_forum_attachments # OPTIONAL - course[open_enrollment] """Set to true if the course is open enrollment.""" if course_open_enrollment is not None: data["course[open_enrollment]"] = course_open_enrollment # OPTIONAL - course[self_enrollment] """Set to true if the course is self enrollment.""" if course_self_enrollment is not None: data["course[self_enrollment]"] = course_self_enrollment # OPTIONAL - course[restrict_enrollments_to_course_dates] """Set to true to restrict user enrollments to the start and end dates of the course.""" if course_restrict_enrollments_to_course_dates is not None: data["course[restrict_enrollments_to_course_dates]"] = course_restrict_enrollments_to_course_dates # OPTIONAL - course[term_id] """The unique ID of the term to create to course in.""" if course_term_id is not None: data["course[term_id]"] = course_term_id # OPTIONAL - course[sis_course_id] """The unique SIS identifier.""" if course_sis_course_id is not None: data["course[sis_course_id]"] = course_sis_course_id # OPTIONAL - course[integration_id] """The unique Integration identifier.""" if course_integration_id is not None: data["course[integration_id]"] = course_integration_id # OPTIONAL - course[hide_final_grades] """If this option is set to true, the totals in student grades summary will be hidden.""" if course_hide_final_grades is not None: data["course[hide_final_grades]"] = course_hide_final_grades # OPTIONAL - course[apply_assignment_group_weights] """Set to true to weight final grade based on assignment groups percentages.""" if course_apply_assignment_group_weights is not None: data["course[apply_assignment_group_weights]"] = course_apply_assignment_group_weights # OPTIONAL - course[time_zone] """The time zone for the course. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if course_time_zone is not None: data["course[time_zone]"] = course_time_zone # OPTIONAL - offer """If this option is set to true, the course will be available to students immediately.""" if offer is not None: data["offer"] = offer # OPTIONAL - enroll_me """Set to true to enroll the current user as the teacher.""" if enroll_me is not None: data["enroll_me"] = enroll_me # OPTIONAL - course[syllabus_body] """The syllabus body for the course""" if course_syllabus_body is not None: data["course[syllabus_body]"] = course_syllabus_body # OPTIONAL - course[grading_standard_id] """The grading standard id to set for the course. If no value is provided for this argument the current grading_standard will be un-set from this course.""" if course_grading_standard_id is not None: data["course[grading_standard_id]"] = course_grading_standard_id # OPTIONAL - course[course_format] """Optional. Specifies the format of the course. (Should be 'on_campus', 'online', or 'blended')""" if course_course_format is not None: data["course[course_format]"] = course_course_format # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted course with matching sis_course_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, single_item=True)
python
def create_new_course(self, account_id, course_allow_student_forum_attachments=None, course_allow_student_wiki_edits=None, course_allow_wiki_comments=None, course_apply_assignment_group_weights=None, course_course_code=None, course_course_format=None, course_end_at=None, course_grading_standard_id=None, course_hide_final_grades=None, course_integration_id=None, course_is_public=None, course_is_public_to_auth_users=None, course_license=None, course_name=None, course_open_enrollment=None, course_public_description=None, course_public_syllabus=None, course_public_syllabus_to_auth=None, course_restrict_enrollments_to_course_dates=None, course_self_enrollment=None, course_sis_course_id=None, course_start_at=None, course_syllabus_body=None, course_term_id=None, course_time_zone=None, enable_sis_reactivation=None, enroll_me=None, offer=None): """ Create a new course. Create a new course """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # OPTIONAL - course[name] """The name of the course. If omitted, the course will be named "Unnamed Course." """ if course_name is not None: data["course[name]"] = course_name # OPTIONAL - course[course_code] """The course code for the course.""" if course_course_code is not None: data["course[course_code]"] = course_course_code # OPTIONAL - course[start_at] """Course start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_start_at is not None: data["course[start_at]"] = course_start_at # OPTIONAL - course[end_at] """Course end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_end_at is not None: data["course[end_at]"] = course_end_at # OPTIONAL - course[license] """The name of the licensing. Should be one of the following abbreviations (a descriptive name is included in parenthesis for reference): - 'private' (Private Copyrighted) - 'cc_by_nc_nd' (CC Attribution Non-Commercial No Derivatives) - 'cc_by_nc_sa' (CC Attribution Non-Commercial Share Alike) - 'cc_by_nc' (CC Attribution Non-Commercial) - 'cc_by_nd' (CC Attribution No Derivatives) - 'cc_by_sa' (CC Attribution Share Alike) - 'cc_by' (CC Attribution) - 'public_domain' (Public Domain).""" if course_license is not None: data["course[license]"] = course_license # OPTIONAL - course[is_public] """Set to true if course is public to both authenticated and unauthenticated users.""" if course_is_public is not None: data["course[is_public]"] = course_is_public # OPTIONAL - course[is_public_to_auth_users] """Set to true if course is public only to authenticated users.""" if course_is_public_to_auth_users is not None: data["course[is_public_to_auth_users]"] = course_is_public_to_auth_users # OPTIONAL - course[public_syllabus] """Set to true to make the course syllabus public.""" if course_public_syllabus is not None: data["course[public_syllabus]"] = course_public_syllabus # OPTIONAL - course[public_syllabus_to_auth] """Set to true to make the course syllabus public for authenticated users.""" if course_public_syllabus_to_auth is not None: data["course[public_syllabus_to_auth]"] = course_public_syllabus_to_auth # OPTIONAL - course[public_description] """A publicly visible description of the course.""" if course_public_description is not None: data["course[public_description]"] = course_public_description # OPTIONAL - course[allow_student_wiki_edits] """If true, students will be able to modify the course wiki.""" if course_allow_student_wiki_edits is not None: data["course[allow_student_wiki_edits]"] = course_allow_student_wiki_edits # OPTIONAL - course[allow_wiki_comments] """If true, course members will be able to comment on wiki pages.""" if course_allow_wiki_comments is not None: data["course[allow_wiki_comments]"] = course_allow_wiki_comments # OPTIONAL - course[allow_student_forum_attachments] """If true, students can attach files to forum posts.""" if course_allow_student_forum_attachments is not None: data["course[allow_student_forum_attachments]"] = course_allow_student_forum_attachments # OPTIONAL - course[open_enrollment] """Set to true if the course is open enrollment.""" if course_open_enrollment is not None: data["course[open_enrollment]"] = course_open_enrollment # OPTIONAL - course[self_enrollment] """Set to true if the course is self enrollment.""" if course_self_enrollment is not None: data["course[self_enrollment]"] = course_self_enrollment # OPTIONAL - course[restrict_enrollments_to_course_dates] """Set to true to restrict user enrollments to the start and end dates of the course.""" if course_restrict_enrollments_to_course_dates is not None: data["course[restrict_enrollments_to_course_dates]"] = course_restrict_enrollments_to_course_dates # OPTIONAL - course[term_id] """The unique ID of the term to create to course in.""" if course_term_id is not None: data["course[term_id]"] = course_term_id # OPTIONAL - course[sis_course_id] """The unique SIS identifier.""" if course_sis_course_id is not None: data["course[sis_course_id]"] = course_sis_course_id # OPTIONAL - course[integration_id] """The unique Integration identifier.""" if course_integration_id is not None: data["course[integration_id]"] = course_integration_id # OPTIONAL - course[hide_final_grades] """If this option is set to true, the totals in student grades summary will be hidden.""" if course_hide_final_grades is not None: data["course[hide_final_grades]"] = course_hide_final_grades # OPTIONAL - course[apply_assignment_group_weights] """Set to true to weight final grade based on assignment groups percentages.""" if course_apply_assignment_group_weights is not None: data["course[apply_assignment_group_weights]"] = course_apply_assignment_group_weights # OPTIONAL - course[time_zone] """The time zone for the course. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if course_time_zone is not None: data["course[time_zone]"] = course_time_zone # OPTIONAL - offer """If this option is set to true, the course will be available to students immediately.""" if offer is not None: data["offer"] = offer # OPTIONAL - enroll_me """Set to true to enroll the current user as the teacher.""" if enroll_me is not None: data["enroll_me"] = enroll_me # OPTIONAL - course[syllabus_body] """The syllabus body for the course""" if course_syllabus_body is not None: data["course[syllabus_body]"] = course_syllabus_body # OPTIONAL - course[grading_standard_id] """The grading standard id to set for the course. If no value is provided for this argument the current grading_standard will be un-set from this course.""" if course_grading_standard_id is not None: data["course[grading_standard_id]"] = course_grading_standard_id # OPTIONAL - course[course_format] """Optional. Specifies the format of the course. (Should be 'on_campus', 'online', or 'blended')""" if course_course_format is not None: data["course[course_format]"] = course_course_format # OPTIONAL - enable_sis_reactivation """When true, will first try to re-activate a deleted course with matching sis_course_id if possible.""" if enable_sis_reactivation is not None: data["enable_sis_reactivation"] = enable_sis_reactivation self.logger.debug("POST /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, single_item=True)
[ "def", "create_new_course", "(", "self", ",", "account_id", ",", "course_allow_student_forum_attachments", "=", "None", ",", "course_allow_student_wiki_edits", "=", "None", ",", "course_allow_wiki_comments", "=", "None", ",", "course_apply_assignment_group_weights", "=", "N...
Create a new course. Create a new course
[ "Create", "a", "new", "course", ".", "Create", "a", "new", "course" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L242-L412
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.list_users_in_course_users
def list_users_in_course_users(self, course_id, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, search_term=None, user_id=None, user_ids=None): """ List users in course. Returns the list of users in this course. And optionally the user's enrollments in the course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - search_term """The partial name or full ID of the users to match and return in the results list.""" if search_term is not None: params["search_term"] = search_term # OPTIONAL - enrollment_type """When set, only return users where the user is enrolled as this type. "student_view" implies include[]=test_student. This argument is ignored if enrollment_role is given.""" if enrollment_type is not None: self._validate_enum(enrollment_type, ["teacher", "student", "student_view", "ta", "observer", "designer"]) params["enrollment_type"] = enrollment_type # OPTIONAL - enrollment_role """Deprecated When set, only return users enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a base role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role is not None: params["enrollment_role"] = enrollment_role # OPTIONAL - enrollment_role_id """When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a built_in role id with type 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role_id is not None: params["enrollment_role_id"] = enrollment_role_id # OPTIONAL - include """- "email": Optional user email. - "enrollments": Optionally include with each Course the user's current and invited enrollments. If the user is enrolled as a student, and the account has permission to manage or view all grades, each enrollment will include a 'grades' key with 'current_score', 'final_score', 'current_grade' and 'final_grade' values. - "locked": Optionally include whether an enrollment is locked. - "avatar_url": Optionally include avatar_url. - "bio": Optionally include each user's bio. - "test_student": Optionally include the course's Test Student, if present. Default is to not include Test Student. - "custom_links": Optionally include plugin-supplied custom links for each student, such as analytics information""" if include is not None: self._validate_enum(include, ["email", "enrollments", "locked", "avatar_url", "test_student", "bio", "custom_links"]) params["include"] = include # OPTIONAL - user_id """If this parameter is given and it corresponds to a user in the course, the +page+ parameter will be ignored and the page containing the specified user will be returned instead.""" if user_id is not None: params["user_id"] = user_id # OPTIONAL - user_ids """If included, the course users set will only include users with IDs specified by the param. Note: this will not work in conjunction with the "user_id" argument but multiple user_ids can be included.""" if user_ids is not None: params["user_ids"] = user_ids # OPTIONAL - enrollment_state """When set, only return users where the enrollment workflow state is of one of the given types. "active" and "invited" enrollments are returned by default.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited", "rejected", "completed", "inactive"]) params["enrollment_state"] = enrollment_state self.logger.debug("GET /api/v1/courses/{course_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/users".format(**path), data=data, params=params, all_pages=True)
python
def list_users_in_course_users(self, course_id, enrollment_role=None, enrollment_role_id=None, enrollment_state=None, enrollment_type=None, include=None, search_term=None, user_id=None, user_ids=None): """ List users in course. Returns the list of users in this course. And optionally the user's enrollments in the course. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - search_term """The partial name or full ID of the users to match and return in the results list.""" if search_term is not None: params["search_term"] = search_term # OPTIONAL - enrollment_type """When set, only return users where the user is enrolled as this type. "student_view" implies include[]=test_student. This argument is ignored if enrollment_role is given.""" if enrollment_type is not None: self._validate_enum(enrollment_type, ["teacher", "student", "student_view", "ta", "observer", "designer"]) params["enrollment_type"] = enrollment_type # OPTIONAL - enrollment_role """Deprecated When set, only return users enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a base role type of 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role is not None: params["enrollment_role"] = enrollment_role # OPTIONAL - enrollment_role_id """When set, only return courses where the user is enrolled with the specified course-level role. This can be a role created with the {api:RoleOverridesController#add_role Add Role API} or a built_in role id with type 'StudentEnrollment', 'TeacherEnrollment', 'TaEnrollment', 'ObserverEnrollment', or 'DesignerEnrollment'.""" if enrollment_role_id is not None: params["enrollment_role_id"] = enrollment_role_id # OPTIONAL - include """- "email": Optional user email. - "enrollments": Optionally include with each Course the user's current and invited enrollments. If the user is enrolled as a student, and the account has permission to manage or view all grades, each enrollment will include a 'grades' key with 'current_score', 'final_score', 'current_grade' and 'final_grade' values. - "locked": Optionally include whether an enrollment is locked. - "avatar_url": Optionally include avatar_url. - "bio": Optionally include each user's bio. - "test_student": Optionally include the course's Test Student, if present. Default is to not include Test Student. - "custom_links": Optionally include plugin-supplied custom links for each student, such as analytics information""" if include is not None: self._validate_enum(include, ["email", "enrollments", "locked", "avatar_url", "test_student", "bio", "custom_links"]) params["include"] = include # OPTIONAL - user_id """If this parameter is given and it corresponds to a user in the course, the +page+ parameter will be ignored and the page containing the specified user will be returned instead.""" if user_id is not None: params["user_id"] = user_id # OPTIONAL - user_ids """If included, the course users set will only include users with IDs specified by the param. Note: this will not work in conjunction with the "user_id" argument but multiple user_ids can be included.""" if user_ids is not None: params["user_ids"] = user_ids # OPTIONAL - enrollment_state """When set, only return users where the enrollment workflow state is of one of the given types. "active" and "invited" enrollments are returned by default.""" if enrollment_state is not None: self._validate_enum(enrollment_state, ["active", "invited", "rejected", "completed", "inactive"]) params["enrollment_state"] = enrollment_state self.logger.debug("GET /api/v1/courses/{course_id}/users with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/users".format(**path), data=data, params=params, all_pages=True)
[ "def", "list_users_in_course_users", "(", "self", ",", "course_id", ",", "enrollment_role", "=", "None", ",", "enrollment_role_id", "=", "None", ",", "enrollment_state", "=", "None", ",", "enrollment_type", "=", "None", ",", "include", "=", "None", ",", "search_...
List users in course. Returns the list of users in this course. And optionally the user's enrollments in the course.
[ "List", "users", "in", "course", ".", "Returns", "the", "list", "of", "users", "in", "this", "course", ".", "And", "optionally", "the", "user", "s", "enrollments", "in", "the", "course", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L458-L544
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.conclude_course
def conclude_course(self, id, event): """ Conclude a course. Delete or conclude an existing course """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - event """The action to take on the course.""" self._validate_enum(event, ["delete", "conclude"]) params["event"] = event self.logger.debug("DELETE /api/v1/courses/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("DELETE", "/api/v1/courses/{id}".format(**path), data=data, params=params, no_data=True)
python
def conclude_course(self, id, event): """ Conclude a course. Delete or conclude an existing course """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # REQUIRED - event """The action to take on the course.""" self._validate_enum(event, ["delete", "conclude"]) params["event"] = event self.logger.debug("DELETE /api/v1/courses/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("DELETE", "/api/v1/courses/{id}".format(**path), data=data, params=params, no_data=True)
[ "def", "conclude_course", "(", "self", ",", "id", ",", "event", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - id\r", "\"\"\"ID\"\"\"", "path", "[", "\"id\"", "]", "=", "id", "# REQUIRED - event\r", ...
Conclude a course. Delete or conclude an existing course
[ "Conclude", "a", "course", ".", "Delete", "or", "conclude", "an", "existing", "course" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L759-L779
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.update_course_settings
def update_course_settings(self, course_id, allow_student_discussion_editing=None, allow_student_discussion_topics=None, allow_student_forum_attachments=None, allow_student_organized_groups=None, hide_distribution_graphs=None, hide_final_grades=None, home_page_announcement_limit=None, lock_all_announcements=None, restrict_student_future_view=None, restrict_student_past_view=None, show_announcements_on_home_page=None): """ Update course settings. Can update the following course settings: """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - allow_student_discussion_topics """Let students create discussion topics""" if allow_student_discussion_topics is not None: data["allow_student_discussion_topics"] = allow_student_discussion_topics # OPTIONAL - allow_student_forum_attachments """Let students attach files to discussions""" if allow_student_forum_attachments is not None: data["allow_student_forum_attachments"] = allow_student_forum_attachments # OPTIONAL - allow_student_discussion_editing """Let students edit or delete their own discussion posts""" if allow_student_discussion_editing is not None: data["allow_student_discussion_editing"] = allow_student_discussion_editing # OPTIONAL - allow_student_organized_groups """Let students organize their own groups""" if allow_student_organized_groups is not None: data["allow_student_organized_groups"] = allow_student_organized_groups # OPTIONAL - hide_final_grades """Hide totals in student grades summary""" if hide_final_grades is not None: data["hide_final_grades"] = hide_final_grades # OPTIONAL - hide_distribution_graphs """Hide grade distribution graphs from students""" if hide_distribution_graphs is not None: data["hide_distribution_graphs"] = hide_distribution_graphs # OPTIONAL - lock_all_announcements """Disable comments on announcements""" if lock_all_announcements is not None: data["lock_all_announcements"] = lock_all_announcements # OPTIONAL - restrict_student_past_view """Restrict students from viewing courses after end date""" if restrict_student_past_view is not None: data["restrict_student_past_view"] = restrict_student_past_view # OPTIONAL - restrict_student_future_view """Restrict students from viewing courses before start date""" if restrict_student_future_view is not None: data["restrict_student_future_view"] = restrict_student_future_view # OPTIONAL - show_announcements_on_home_page """Show the most recent announcements on the Course home page (if a Wiki, defaults to five announcements, configurable via home_page_announcement_limit)""" if show_announcements_on_home_page is not None: data["show_announcements_on_home_page"] = show_announcements_on_home_page # OPTIONAL - home_page_announcement_limit """Limit the number of announcements on the home page if enabled via show_announcements_on_home_page""" if home_page_announcement_limit is not None: data["home_page_announcement_limit"] = home_page_announcement_limit self.logger.debug("PUT /api/v1/courses/{course_id}/settings with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/settings".format(**path), data=data, params=params, no_data=True)
python
def update_course_settings(self, course_id, allow_student_discussion_editing=None, allow_student_discussion_topics=None, allow_student_forum_attachments=None, allow_student_organized_groups=None, hide_distribution_graphs=None, hide_final_grades=None, home_page_announcement_limit=None, lock_all_announcements=None, restrict_student_future_view=None, restrict_student_past_view=None, show_announcements_on_home_page=None): """ Update course settings. Can update the following course settings: """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - allow_student_discussion_topics """Let students create discussion topics""" if allow_student_discussion_topics is not None: data["allow_student_discussion_topics"] = allow_student_discussion_topics # OPTIONAL - allow_student_forum_attachments """Let students attach files to discussions""" if allow_student_forum_attachments is not None: data["allow_student_forum_attachments"] = allow_student_forum_attachments # OPTIONAL - allow_student_discussion_editing """Let students edit or delete their own discussion posts""" if allow_student_discussion_editing is not None: data["allow_student_discussion_editing"] = allow_student_discussion_editing # OPTIONAL - allow_student_organized_groups """Let students organize their own groups""" if allow_student_organized_groups is not None: data["allow_student_organized_groups"] = allow_student_organized_groups # OPTIONAL - hide_final_grades """Hide totals in student grades summary""" if hide_final_grades is not None: data["hide_final_grades"] = hide_final_grades # OPTIONAL - hide_distribution_graphs """Hide grade distribution graphs from students""" if hide_distribution_graphs is not None: data["hide_distribution_graphs"] = hide_distribution_graphs # OPTIONAL - lock_all_announcements """Disable comments on announcements""" if lock_all_announcements is not None: data["lock_all_announcements"] = lock_all_announcements # OPTIONAL - restrict_student_past_view """Restrict students from viewing courses after end date""" if restrict_student_past_view is not None: data["restrict_student_past_view"] = restrict_student_past_view # OPTIONAL - restrict_student_future_view """Restrict students from viewing courses before start date""" if restrict_student_future_view is not None: data["restrict_student_future_view"] = restrict_student_future_view # OPTIONAL - show_announcements_on_home_page """Show the most recent announcements on the Course home page (if a Wiki, defaults to five announcements, configurable via home_page_announcement_limit)""" if show_announcements_on_home_page is not None: data["show_announcements_on_home_page"] = show_announcements_on_home_page # OPTIONAL - home_page_announcement_limit """Limit the number of announcements on the home page if enabled via show_announcements_on_home_page""" if home_page_announcement_limit is not None: data["home_page_announcement_limit"] = home_page_announcement_limit self.logger.debug("PUT /api/v1/courses/{course_id}/settings with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{course_id}/settings".format(**path), data=data, params=params, no_data=True)
[ "def", "update_course_settings", "(", "self", ",", "course_id", ",", "allow_student_discussion_editing", "=", "None", ",", "allow_student_discussion_topics", "=", "None", ",", "allow_student_forum_attachments", "=", "None", ",", "allow_student_organized_groups", "=", "None"...
Update course settings. Can update the following course settings:
[ "Update", "course", "settings", ".", "Can", "update", "the", "following", "course", "settings", ":" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L798-L868
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.update_course
def update_course(self, id, course_account_id=None, course_allow_student_forum_attachments=None, course_allow_student_wiki_edits=None, course_allow_wiki_comments=None, course_apply_assignment_group_weights=None, course_course_code=None, course_course_format=None, course_end_at=None, course_event=None, course_grading_standard_id=None, course_hide_final_grades=None, course_image_id=None, course_image_url=None, course_integration_id=None, course_is_public=None, course_is_public_to_auth_users=None, course_license=None, course_name=None, course_open_enrollment=None, course_public_description=None, course_public_syllabus=None, course_public_syllabus_to_auth=None, course_remove_image=None, course_restrict_enrollments_to_course_dates=None, course_self_enrollment=None, course_sis_course_id=None, course_start_at=None, course_storage_quota_mb=None, course_syllabus_body=None, course_term_id=None, course_time_zone=None, offer=None): """ Update a course. Update an existing course. Arguments are the same as Courses#create, with a few exceptions (enroll_me). If a user has content management rights, but not full course editing rights, the only attribute editable through this endpoint will be "syllabus_body" """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - course[account_id] """The unique ID of the account to move the course to.""" if course_account_id is not None: data["course[account_id]"] = course_account_id # OPTIONAL - course[name] """The name of the course. If omitted, the course will be named "Unnamed Course." """ if course_name is not None: data["course[name]"] = course_name # OPTIONAL - course[course_code] """The course code for the course.""" if course_course_code is not None: data["course[course_code]"] = course_course_code # OPTIONAL - course[start_at] """Course start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_start_at is not None: data["course[start_at]"] = course_start_at # OPTIONAL - course[end_at] """Course end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_end_at is not None: data["course[end_at]"] = course_end_at # OPTIONAL - course[license] """The name of the licensing. Should be one of the following abbreviations (a descriptive name is included in parenthesis for reference): - 'private' (Private Copyrighted) - 'cc_by_nc_nd' (CC Attribution Non-Commercial No Derivatives) - 'cc_by_nc_sa' (CC Attribution Non-Commercial Share Alike) - 'cc_by_nc' (CC Attribution Non-Commercial) - 'cc_by_nd' (CC Attribution No Derivatives) - 'cc_by_sa' (CC Attribution Share Alike) - 'cc_by' (CC Attribution) - 'public_domain' (Public Domain).""" if course_license is not None: data["course[license]"] = course_license # OPTIONAL - course[is_public] """Set to true if course is public to both authenticated and unauthenticated users.""" if course_is_public is not None: data["course[is_public]"] = course_is_public # OPTIONAL - course[is_public_to_auth_users] """Set to true if course is public only to authenticated users.""" if course_is_public_to_auth_users is not None: data["course[is_public_to_auth_users]"] = course_is_public_to_auth_users # OPTIONAL - course[public_syllabus] """Set to true to make the course syllabus public.""" if course_public_syllabus is not None: data["course[public_syllabus]"] = course_public_syllabus # OPTIONAL - course[public_syllabus_to_auth] """Set to true to make the course syllabus to public for authenticated users.""" if course_public_syllabus_to_auth is not None: data["course[public_syllabus_to_auth]"] = course_public_syllabus_to_auth # OPTIONAL - course[public_description] """A publicly visible description of the course.""" if course_public_description is not None: data["course[public_description]"] = course_public_description # OPTIONAL - course[allow_student_wiki_edits] """If true, students will be able to modify the course wiki.""" if course_allow_student_wiki_edits is not None: data["course[allow_student_wiki_edits]"] = course_allow_student_wiki_edits # OPTIONAL - course[allow_wiki_comments] """If true, course members will be able to comment on wiki pages.""" if course_allow_wiki_comments is not None: data["course[allow_wiki_comments]"] = course_allow_wiki_comments # OPTIONAL - course[allow_student_forum_attachments] """If true, students can attach files to forum posts.""" if course_allow_student_forum_attachments is not None: data["course[allow_student_forum_attachments]"] = course_allow_student_forum_attachments # OPTIONAL - course[open_enrollment] """Set to true if the course is open enrollment.""" if course_open_enrollment is not None: data["course[open_enrollment]"] = course_open_enrollment # OPTIONAL - course[self_enrollment] """Set to true if the course is self enrollment.""" if course_self_enrollment is not None: data["course[self_enrollment]"] = course_self_enrollment # OPTIONAL - course[restrict_enrollments_to_course_dates] """Set to true to restrict user enrollments to the start and end dates of the course.""" if course_restrict_enrollments_to_course_dates is not None: data["course[restrict_enrollments_to_course_dates]"] = course_restrict_enrollments_to_course_dates # OPTIONAL - course[term_id] """The unique ID of the term to create to course in.""" if course_term_id is not None: data["course[term_id]"] = course_term_id # OPTIONAL - course[sis_course_id] """The unique SIS identifier.""" if course_sis_course_id is not None: data["course[sis_course_id]"] = course_sis_course_id # OPTIONAL - course[integration_id] """The unique Integration identifier.""" if course_integration_id is not None: data["course[integration_id]"] = course_integration_id # OPTIONAL - course[hide_final_grades] """If this option is set to true, the totals in student grades summary will be hidden.""" if course_hide_final_grades is not None: data["course[hide_final_grades]"] = course_hide_final_grades # OPTIONAL - course[time_zone] """The time zone for the course. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if course_time_zone is not None: data["course[time_zone]"] = course_time_zone # OPTIONAL - course[apply_assignment_group_weights] """Set to true to weight final grade based on assignment groups percentages.""" if course_apply_assignment_group_weights is not None: data["course[apply_assignment_group_weights]"] = course_apply_assignment_group_weights # OPTIONAL - course[storage_quota_mb] """Set the storage quota for the course, in megabytes. The caller must have the "Manage storage quotas" account permission.""" if course_storage_quota_mb is not None: data["course[storage_quota_mb]"] = course_storage_quota_mb # OPTIONAL - offer """If this option is set to true, the course will be available to students immediately.""" if offer is not None: data["offer"] = offer # OPTIONAL - course[event] """The action to take on each course. * 'claim' makes a course no longer visible to students. This action is also called "unpublish" on the web site. A course cannot be unpublished if students have received graded submissions. * 'offer' makes a course visible to students. This action is also called "publish" on the web site. * 'conclude' prevents future enrollments and makes a course read-only for all participants. The course still appears in prior-enrollment lists. * 'delete' completely removes the course from the web site (including course menus and prior-enrollment lists). All enrollments are deleted. Course content may be physically deleted at a future date. * 'undelete' attempts to recover a course that has been deleted. (Recovery is not guaranteed; please conclude rather than delete a course if there is any possibility the course will be used again.) The recovered course will be unpublished. Deleted enrollments will not be recovered.""" if course_event is not None: self._validate_enum(course_event, ["claim", "offer", "conclude", "delete", "undelete"]) data["course[event]"] = course_event # OPTIONAL - course[syllabus_body] """The syllabus body for the course""" if course_syllabus_body is not None: data["course[syllabus_body]"] = course_syllabus_body # OPTIONAL - course[grading_standard_id] """The grading standard id to set for the course. If no value is provided for this argument the current grading_standard will be un-set from this course.""" if course_grading_standard_id is not None: data["course[grading_standard_id]"] = course_grading_standard_id # OPTIONAL - course[course_format] """Optional. Specifies the format of the course. (Should be either 'on_campus' or 'online')""" if course_course_format is not None: data["course[course_format]"] = course_course_format # OPTIONAL - course[image_id] """This is a file ID corresponding to an image file in the course that will be used as the course image. This will clear the course's image_url setting if set. If you attempt to provide image_url and image_id in a request it will fail.""" if course_image_id is not None: data["course[image_id]"] = course_image_id # OPTIONAL - course[image_url] """This is a URL to an image to be used as the course image. This will clear the course's image_id setting if set. If you attempt to provide image_url and image_id in a request it will fail.""" if course_image_url is not None: data["course[image_url]"] = course_image_url # OPTIONAL - course[remove_image] """If this option is set to true, the course image url and course image ID are both set to nil""" if course_remove_image is not None: data["course[remove_image]"] = course_remove_image self.logger.debug("PUT /api/v1/courses/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{id}".format(**path), data=data, params=params, no_data=True)
python
def update_course(self, id, course_account_id=None, course_allow_student_forum_attachments=None, course_allow_student_wiki_edits=None, course_allow_wiki_comments=None, course_apply_assignment_group_weights=None, course_course_code=None, course_course_format=None, course_end_at=None, course_event=None, course_grading_standard_id=None, course_hide_final_grades=None, course_image_id=None, course_image_url=None, course_integration_id=None, course_is_public=None, course_is_public_to_auth_users=None, course_license=None, course_name=None, course_open_enrollment=None, course_public_description=None, course_public_syllabus=None, course_public_syllabus_to_auth=None, course_remove_image=None, course_restrict_enrollments_to_course_dates=None, course_self_enrollment=None, course_sis_course_id=None, course_start_at=None, course_storage_quota_mb=None, course_syllabus_body=None, course_term_id=None, course_time_zone=None, offer=None): """ Update a course. Update an existing course. Arguments are the same as Courses#create, with a few exceptions (enroll_me). If a user has content management rights, but not full course editing rights, the only attribute editable through this endpoint will be "syllabus_body" """ path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - course[account_id] """The unique ID of the account to move the course to.""" if course_account_id is not None: data["course[account_id]"] = course_account_id # OPTIONAL - course[name] """The name of the course. If omitted, the course will be named "Unnamed Course." """ if course_name is not None: data["course[name]"] = course_name # OPTIONAL - course[course_code] """The course code for the course.""" if course_course_code is not None: data["course[course_code]"] = course_course_code # OPTIONAL - course[start_at] """Course start date in ISO8601 format, e.g. 2011-01-01T01:00Z""" if course_start_at is not None: data["course[start_at]"] = course_start_at # OPTIONAL - course[end_at] """Course end date in ISO8601 format. e.g. 2011-01-01T01:00Z""" if course_end_at is not None: data["course[end_at]"] = course_end_at # OPTIONAL - course[license] """The name of the licensing. Should be one of the following abbreviations (a descriptive name is included in parenthesis for reference): - 'private' (Private Copyrighted) - 'cc_by_nc_nd' (CC Attribution Non-Commercial No Derivatives) - 'cc_by_nc_sa' (CC Attribution Non-Commercial Share Alike) - 'cc_by_nc' (CC Attribution Non-Commercial) - 'cc_by_nd' (CC Attribution No Derivatives) - 'cc_by_sa' (CC Attribution Share Alike) - 'cc_by' (CC Attribution) - 'public_domain' (Public Domain).""" if course_license is not None: data["course[license]"] = course_license # OPTIONAL - course[is_public] """Set to true if course is public to both authenticated and unauthenticated users.""" if course_is_public is not None: data["course[is_public]"] = course_is_public # OPTIONAL - course[is_public_to_auth_users] """Set to true if course is public only to authenticated users.""" if course_is_public_to_auth_users is not None: data["course[is_public_to_auth_users]"] = course_is_public_to_auth_users # OPTIONAL - course[public_syllabus] """Set to true to make the course syllabus public.""" if course_public_syllabus is not None: data["course[public_syllabus]"] = course_public_syllabus # OPTIONAL - course[public_syllabus_to_auth] """Set to true to make the course syllabus to public for authenticated users.""" if course_public_syllabus_to_auth is not None: data["course[public_syllabus_to_auth]"] = course_public_syllabus_to_auth # OPTIONAL - course[public_description] """A publicly visible description of the course.""" if course_public_description is not None: data["course[public_description]"] = course_public_description # OPTIONAL - course[allow_student_wiki_edits] """If true, students will be able to modify the course wiki.""" if course_allow_student_wiki_edits is not None: data["course[allow_student_wiki_edits]"] = course_allow_student_wiki_edits # OPTIONAL - course[allow_wiki_comments] """If true, course members will be able to comment on wiki pages.""" if course_allow_wiki_comments is not None: data["course[allow_wiki_comments]"] = course_allow_wiki_comments # OPTIONAL - course[allow_student_forum_attachments] """If true, students can attach files to forum posts.""" if course_allow_student_forum_attachments is not None: data["course[allow_student_forum_attachments]"] = course_allow_student_forum_attachments # OPTIONAL - course[open_enrollment] """Set to true if the course is open enrollment.""" if course_open_enrollment is not None: data["course[open_enrollment]"] = course_open_enrollment # OPTIONAL - course[self_enrollment] """Set to true if the course is self enrollment.""" if course_self_enrollment is not None: data["course[self_enrollment]"] = course_self_enrollment # OPTIONAL - course[restrict_enrollments_to_course_dates] """Set to true to restrict user enrollments to the start and end dates of the course.""" if course_restrict_enrollments_to_course_dates is not None: data["course[restrict_enrollments_to_course_dates]"] = course_restrict_enrollments_to_course_dates # OPTIONAL - course[term_id] """The unique ID of the term to create to course in.""" if course_term_id is not None: data["course[term_id]"] = course_term_id # OPTIONAL - course[sis_course_id] """The unique SIS identifier.""" if course_sis_course_id is not None: data["course[sis_course_id]"] = course_sis_course_id # OPTIONAL - course[integration_id] """The unique Integration identifier.""" if course_integration_id is not None: data["course[integration_id]"] = course_integration_id # OPTIONAL - course[hide_final_grades] """If this option is set to true, the totals in student grades summary will be hidden.""" if course_hide_final_grades is not None: data["course[hide_final_grades]"] = course_hide_final_grades # OPTIONAL - course[time_zone] """The time zone for the course. Allowed time zones are {http://www.iana.org/time-zones IANA time zones} or friendlier {http://api.rubyonrails.org/classes/ActiveSupport/TimeZone.html Ruby on Rails time zones}.""" if course_time_zone is not None: data["course[time_zone]"] = course_time_zone # OPTIONAL - course[apply_assignment_group_weights] """Set to true to weight final grade based on assignment groups percentages.""" if course_apply_assignment_group_weights is not None: data["course[apply_assignment_group_weights]"] = course_apply_assignment_group_weights # OPTIONAL - course[storage_quota_mb] """Set the storage quota for the course, in megabytes. The caller must have the "Manage storage quotas" account permission.""" if course_storage_quota_mb is not None: data["course[storage_quota_mb]"] = course_storage_quota_mb # OPTIONAL - offer """If this option is set to true, the course will be available to students immediately.""" if offer is not None: data["offer"] = offer # OPTIONAL - course[event] """The action to take on each course. * 'claim' makes a course no longer visible to students. This action is also called "unpublish" on the web site. A course cannot be unpublished if students have received graded submissions. * 'offer' makes a course visible to students. This action is also called "publish" on the web site. * 'conclude' prevents future enrollments and makes a course read-only for all participants. The course still appears in prior-enrollment lists. * 'delete' completely removes the course from the web site (including course menus and prior-enrollment lists). All enrollments are deleted. Course content may be physically deleted at a future date. * 'undelete' attempts to recover a course that has been deleted. (Recovery is not guaranteed; please conclude rather than delete a course if there is any possibility the course will be used again.) The recovered course will be unpublished. Deleted enrollments will not be recovered.""" if course_event is not None: self._validate_enum(course_event, ["claim", "offer", "conclude", "delete", "undelete"]) data["course[event]"] = course_event # OPTIONAL - course[syllabus_body] """The syllabus body for the course""" if course_syllabus_body is not None: data["course[syllabus_body]"] = course_syllabus_body # OPTIONAL - course[grading_standard_id] """The grading standard id to set for the course. If no value is provided for this argument the current grading_standard will be un-set from this course.""" if course_grading_standard_id is not None: data["course[grading_standard_id]"] = course_grading_standard_id # OPTIONAL - course[course_format] """Optional. Specifies the format of the course. (Should be either 'on_campus' or 'online')""" if course_course_format is not None: data["course[course_format]"] = course_course_format # OPTIONAL - course[image_id] """This is a file ID corresponding to an image file in the course that will be used as the course image. This will clear the course's image_url setting if set. If you attempt to provide image_url and image_id in a request it will fail.""" if course_image_id is not None: data["course[image_id]"] = course_image_id # OPTIONAL - course[image_url] """This is a URL to an image to be used as the course image. This will clear the course's image_id setting if set. If you attempt to provide image_url and image_id in a request it will fail.""" if course_image_url is not None: data["course[image_url]"] = course_image_url # OPTIONAL - course[remove_image] """If this option is set to true, the course image url and course image ID are both set to nil""" if course_remove_image is not None: data["course[remove_image]"] = course_remove_image self.logger.debug("PUT /api/v1/courses/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/courses/{id}".format(**path), data=data, params=params, no_data=True)
[ "def", "update_course", "(", "self", ",", "id", ",", "course_account_id", "=", "None", ",", "course_allow_student_forum_attachments", "=", "None", ",", "course_allow_student_wiki_edits", "=", "None", ",", "course_allow_wiki_comments", "=", "None", ",", "course_apply_ass...
Update a course. Update an existing course. Arguments are the same as Courses#create, with a few exceptions (enroll_me). If a user has content management rights, but not full course editing rights, the only attribute editable through this endpoint will be "syllabus_body"
[ "Update", "a", "course", ".", "Update", "an", "existing", "course", ".", "Arguments", "are", "the", "same", "as", "Courses#create", "with", "a", "few", "exceptions", "(", "enroll_me", ")", ".", "If", "a", "user", "has", "content", "management", "rights", "...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L930-L1143
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.update_courses
def update_courses(self, event, account_id, course_ids): """ Update courses. Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. The action to take on each course. Must be one of 'offer', 'conclude', 'delete', or 'undelete'. * 'offer' makes a course visible to students. This action is also called "publish" on the web site. * 'conclude' prevents future enrollments and makes a course read-only for all participants. The course still appears in prior-enrollment lists. * 'delete' completely removes the course from the web site (including course menus and prior-enrollment lists). All enrollments are deleted. Course content may be physically deleted at a future date. * 'undelete' attempts to recover a course that has been deleted. (Recovery is not guaranteed; please conclude rather than delete a course if there is any possibility the course will be used again.) The recovered course will be unpublished. Deleted enrollments will not be recovered. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - course_ids """List of ids of courses to update. At most 500 courses may be updated in one call.""" data["course_ids"] = course_ids # REQUIRED - event """no description""" self._validate_enum(event, ["offer", "conclude", "delete", "undelete"]) data["event"] = event self.logger.debug("PUT /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, single_item=True)
python
def update_courses(self, event, account_id, course_ids): """ Update courses. Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. The action to take on each course. Must be one of 'offer', 'conclude', 'delete', or 'undelete'. * 'offer' makes a course visible to students. This action is also called "publish" on the web site. * 'conclude' prevents future enrollments and makes a course read-only for all participants. The course still appears in prior-enrollment lists. * 'delete' completely removes the course from the web site (including course menus and prior-enrollment lists). All enrollments are deleted. Course content may be physically deleted at a future date. * 'undelete' attempts to recover a course that has been deleted. (Recovery is not guaranteed; please conclude rather than delete a course if there is any possibility the course will be used again.) The recovered course will be unpublished. Deleted enrollments will not be recovered. """ path = {} data = {} params = {} # REQUIRED - PATH - account_id """ID""" path["account_id"] = account_id # REQUIRED - course_ids """List of ids of courses to update. At most 500 courses may be updated in one call.""" data["course_ids"] = course_ids # REQUIRED - event """no description""" self._validate_enum(event, ["offer", "conclude", "delete", "undelete"]) data["event"] = event self.logger.debug("PUT /api/v1/accounts/{account_id}/courses with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/accounts/{account_id}/courses".format(**path), data=data, params=params, single_item=True)
[ "def", "update_courses", "(", "self", ",", "event", ",", "account_id", ",", "course_ids", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - account_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"account_id\"", "]...
Update courses. Update multiple courses in an account. Operates asynchronously; use the {api:ProgressController#show progress endpoint} to query the status of an operation. The action to take on each course. Must be one of 'offer', 'conclude', 'delete', or 'undelete'. * 'offer' makes a course visible to students. This action is also called "publish" on the web site. * 'conclude' prevents future enrollments and makes a course read-only for all participants. The course still appears in prior-enrollment lists. * 'delete' completely removes the course from the web site (including course menus and prior-enrollment lists). All enrollments are deleted. Course content may be physically deleted at a future date. * 'undelete' attempts to recover a course that has been deleted. (Recovery is not guaranteed; please conclude rather than delete a course if there is any possibility the course will be used again.) The recovered course will be unpublished. Deleted enrollments will not be recovered.
[ "Update", "courses", ".", "Update", "multiple", "courses", "in", "an", "account", ".", "Operates", "asynchronously", ";", "use", "the", "{", "api", ":", "ProgressController#show", "progress", "endpoint", "}", "to", "query", "the", "status", "of", "an", "operat...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1145-L1180
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.reset_course
def reset_course(self, course_id): """ Reset a course. Deletes the current course, and creates a new equivalent course with no content, but all sections and users moved over. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id self.logger.debug("POST /api/v1/courses/{course_id}/reset_content with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/reset_content".format(**path), data=data, params=params, single_item=True)
python
def reset_course(self, course_id): """ Reset a course. Deletes the current course, and creates a new equivalent course with no content, but all sections and users moved over. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id self.logger.debug("POST /api/v1/courses/{course_id}/reset_content with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/reset_content".format(**path), data=data, params=params, single_item=True)
[ "def", "reset_course", "(", "self", ",", "course_id", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]", "=", "course_id", "self", ".", "l...
Reset a course. Deletes the current course, and creates a new equivalent course with no content, but all sections and users moved over.
[ "Reset", "a", "course", ".", "Deletes", "the", "current", "course", "and", "creates", "a", "new", "equivalent", "course", "with", "no", "content", "but", "all", "sections", "and", "users", "moved", "over", "." ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1182-L1198
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.get_effective_due_dates
def get_effective_due_dates(self, course_id, assignment_ids=None): """ Get effective due dates. For each assignment in the course, returns each assigned student's ID and their corresponding due date along with some Multiple Grading Periods data. Returns a collection with keys representing assignment IDs and values as a collection containing keys representing student IDs and values representing the student's effective due_at, the grading_period_id of which the due_at falls in, and whether or not the grading period is closed (in_closed_grading_period) The list of assignment IDs for which effective student due dates are requested. If not provided, all assignments in the course will be used. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - assignment_ids """no description""" if assignment_ids is not None: params["assignment_ids"] = assignment_ids self.logger.debug("GET /api/v1/courses/{course_id}/effective_due_dates with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/effective_due_dates".format(**path), data=data, params=params, single_item=True)
python
def get_effective_due_dates(self, course_id, assignment_ids=None): """ Get effective due dates. For each assignment in the course, returns each assigned student's ID and their corresponding due date along with some Multiple Grading Periods data. Returns a collection with keys representing assignment IDs and values as a collection containing keys representing student IDs and values representing the student's effective due_at, the grading_period_id of which the due_at falls in, and whether or not the grading period is closed (in_closed_grading_period) The list of assignment IDs for which effective student due dates are requested. If not provided, all assignments in the course will be used. """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - assignment_ids """no description""" if assignment_ids is not None: params["assignment_ids"] = assignment_ids self.logger.debug("GET /api/v1/courses/{course_id}/effective_due_dates with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/effective_due_dates".format(**path), data=data, params=params, single_item=True)
[ "def", "get_effective_due_dates", "(", "self", ",", "course_id", ",", "assignment_ids", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id...
Get effective due dates. For each assignment in the course, returns each assigned student's ID and their corresponding due date along with some Multiple Grading Periods data. Returns a collection with keys representing assignment IDs and values as a collection containing keys representing student IDs and values representing the student's effective due_at, the grading_period_id of which the due_at falls in, and whether or not the grading period is closed (in_closed_grading_period) The list of assignment IDs for which effective student due dates are requested. If not provided, all assignments in the course will be used.
[ "Get", "effective", "due", "dates", ".", "For", "each", "assignment", "in", "the", "course", "returns", "each", "assigned", "student", "s", "ID", "and", "their", "corresponding", "due", "date", "along", "with", "some", "Multiple", "Grading", "Periods", "data",...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1200-L1228
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.permissions
def permissions(self, course_id, permissions=None): """ Permissions. Returns permission information for provided course & current_user """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - permissions """List of permissions to check against authenticated user""" if permissions is not None: params["permissions"] = permissions self.logger.debug("GET /api/v1/courses/{course_id}/permissions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/permissions".format(**path), data=data, params=params, no_data=True)
python
def permissions(self, course_id, permissions=None): """ Permissions. Returns permission information for provided course & current_user """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - permissions """List of permissions to check against authenticated user""" if permissions is not None: params["permissions"] = permissions self.logger.debug("GET /api/v1/courses/{course_id}/permissions with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("GET", "/api/v1/courses/{course_id}/permissions".format(**path), data=data, params=params, no_data=True)
[ "def", "permissions", "(", "self", ",", "course_id", ",", "permissions", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH - course_id\r", "\"\"\"ID\"\"\"", "path", "[", "\"course_id\"", "]", "...
Permissions. Returns permission information for provided course & current_user
[ "Permissions", ".", "Returns", "permission", "information", "for", "provided", "course", "&", "current_user" ]
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1230-L1250
PGower/PyCanvas
pycanvas/apis/courses.py
CoursesAPI.copy_course_content
def copy_course_content(self, course_id, exclude=None, only=None, source_course=None): """ Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy all course content. You can control specific types to copy by using either the 'except' option or the 'only' option. The response is the same as the course copy status endpoint """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - source_course """ID or SIS-ID of the course to copy the content from""" if source_course is not None: data["source_course"] = source_course # OPTIONAL - except """A list of the course content types to exclude, all areas not listed will be copied.""" if exclude is not None: self._validate_enum(exclude, ["course_settings", "assignments", "external_tools", "files", "topics", "calendar_events", "quizzes", "wiki_pages", "modules", "outcomes"]) data["except"] = exclude # OPTIONAL - only """A list of the course content types to copy, all areas not listed will not be copied.""" if only is not None: self._validate_enum(only, ["course_settings", "assignments", "external_tools", "files", "topics", "calendar_events", "quizzes", "wiki_pages", "modules", "outcomes"]) data["only"] = only self.logger.debug("POST /api/v1/courses/{course_id}/course_copy with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/course_copy".format(**path), data=data, params=params, no_data=True)
python
def copy_course_content(self, course_id, exclude=None, only=None, source_course=None): """ Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy all course content. You can control specific types to copy by using either the 'except' option or the 'only' option. The response is the same as the course copy status endpoint """ path = {} data = {} params = {} # REQUIRED - PATH - course_id """ID""" path["course_id"] = course_id # OPTIONAL - source_course """ID or SIS-ID of the course to copy the content from""" if source_course is not None: data["source_course"] = source_course # OPTIONAL - except """A list of the course content types to exclude, all areas not listed will be copied.""" if exclude is not None: self._validate_enum(exclude, ["course_settings", "assignments", "external_tools", "files", "topics", "calendar_events", "quizzes", "wiki_pages", "modules", "outcomes"]) data["except"] = exclude # OPTIONAL - only """A list of the course content types to copy, all areas not listed will not be copied.""" if only is not None: self._validate_enum(only, ["course_settings", "assignments", "external_tools", "files", "topics", "calendar_events", "quizzes", "wiki_pages", "modules", "outcomes"]) data["only"] = only self.logger.debug("POST /api/v1/courses/{course_id}/course_copy with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("POST", "/api/v1/courses/{course_id}/course_copy".format(**path), data=data, params=params, no_data=True)
[ "def", "copy_course_content", "(", "self", ",", "course_id", ",", "exclude", "=", "None", ",", "only", "=", "None", ",", "source_course", "=", "None", ")", ":", "path", "=", "{", "}", "data", "=", "{", "}", "params", "=", "{", "}", "# REQUIRED - PATH -...
Copy course content. DEPRECATED: Please use the {api:ContentMigrationsController#create Content Migrations API} Copies content from one course into another. The default is to copy all course content. You can control specific types to copy by using either the 'except' option or the 'only' option. The response is the same as the course copy status endpoint
[ "Copy", "course", "content", ".", "DEPRECATED", ":", "Please", "use", "the", "{", "api", ":", "ContentMigrationsController#create", "Content", "Migrations", "API", "}", "Copies", "content", "from", "one", "course", "into", "another", ".", "The", "default", "is",...
train
https://github.com/PGower/PyCanvas/blob/68520005382b440a1e462f9df369f54d364e21e8/pycanvas/apis/courses.py#L1275-L1315
LIVVkit/LIVVkit
livvkit/util/elements.py
page
def page(title, description, element_list=None, tab_list=None): """ Returns a dictionary representing a new page to display elements. This can be thought of as a simple container for displaying multiple types of information. The ``section`` method can be used to create separate tabs. Args: title: The title to display description: A description of the section element_list: The list of elements to display. If a single element is given it will be wrapped in a list. tab_list: A list of tabs to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tabs. """ _page = { 'Type': 'Page', 'Title': title, 'Description': description, 'Data': {}, } if element_list is not None: if isinstance(element_list, list): _page['Data']['Elements'] = element_list else: _page['Data']['Elements'] = [element_list] if tab_list is not None: if isinstance(tab_list, list): _page['Data']['Tabs'] = tab_list else: _page['Data']['Tabs'] = [tab_list] return _page
python
def page(title, description, element_list=None, tab_list=None): """ Returns a dictionary representing a new page to display elements. This can be thought of as a simple container for displaying multiple types of information. The ``section`` method can be used to create separate tabs. Args: title: The title to display description: A description of the section element_list: The list of elements to display. If a single element is given it will be wrapped in a list. tab_list: A list of tabs to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tabs. """ _page = { 'Type': 'Page', 'Title': title, 'Description': description, 'Data': {}, } if element_list is not None: if isinstance(element_list, list): _page['Data']['Elements'] = element_list else: _page['Data']['Elements'] = [element_list] if tab_list is not None: if isinstance(tab_list, list): _page['Data']['Tabs'] = tab_list else: _page['Data']['Tabs'] = [tab_list] return _page
[ "def", "page", "(", "title", ",", "description", ",", "element_list", "=", "None", ",", "tab_list", "=", "None", ")", ":", "_page", "=", "{", "'Type'", ":", "'Page'", ",", "'Title'", ":", "title", ",", "'Description'", ":", "description", ",", "'Data'", ...
Returns a dictionary representing a new page to display elements. This can be thought of as a simple container for displaying multiple types of information. The ``section`` method can be used to create separate tabs. Args: title: The title to display description: A description of the section element_list: The list of elements to display. If a single element is given it will be wrapped in a list. tab_list: A list of tabs to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tabs.
[ "Returns", "a", "dictionary", "representing", "a", "new", "page", "to", "display", "elements", ".", "This", "can", "be", "thought", "of", "as", "a", "simple", "container", "for", "displaying", "multiple", "types", "of", "information", ".", "The", "section", ...
train
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/elements.py#L54-L89
LIVVkit/LIVVkit
livvkit/util/elements.py
tab
def tab(tab_name, element_list=None, section_list=None): """ Returns a dictionary representing a new tab to display elements. This can be thought of as a simple container for displaying multiple types of information. Args: tab_name: The title to display element_list: The list of elements to display. If a single element is given it will be wrapped in a list. section_list: A list of sections to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tab. """ _tab = { 'Type': 'Tab', 'Title': tab_name, } if element_list is not None: if isinstance(element_list, list): _tab['Elements'] = element_list else: _tab['Elements'] = [element_list] if section_list is not None: if isinstance(section_list, list): _tab['Sections'] = section_list else: if 'Elements' not in section_list: _tab['Elements'] = element_list else: _tab['Elements'].append(element_list) return _tab
python
def tab(tab_name, element_list=None, section_list=None): """ Returns a dictionary representing a new tab to display elements. This can be thought of as a simple container for displaying multiple types of information. Args: tab_name: The title to display element_list: The list of elements to display. If a single element is given it will be wrapped in a list. section_list: A list of sections to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tab. """ _tab = { 'Type': 'Tab', 'Title': tab_name, } if element_list is not None: if isinstance(element_list, list): _tab['Elements'] = element_list else: _tab['Elements'] = [element_list] if section_list is not None: if isinstance(section_list, list): _tab['Sections'] = section_list else: if 'Elements' not in section_list: _tab['Elements'] = element_list else: _tab['Elements'].append(element_list) return _tab
[ "def", "tab", "(", "tab_name", ",", "element_list", "=", "None", ",", "section_list", "=", "None", ")", ":", "_tab", "=", "{", "'Type'", ":", "'Tab'", ",", "'Title'", ":", "tab_name", ",", "}", "if", "element_list", "is", "not", "None", ":", "if", "i...
Returns a dictionary representing a new tab to display elements. This can be thought of as a simple container for displaying multiple types of information. Args: tab_name: The title to display element_list: The list of elements to display. If a single element is given it will be wrapped in a list. section_list: A list of sections to display. Returns: A dictionary with metadata specifying that it is to be rendered as a page containing multiple elements and/or tab.
[ "Returns", "a", "dictionary", "representing", "a", "new", "tab", "to", "display", "elements", ".", "This", "can", "be", "thought", "of", "as", "a", "simple", "container", "for", "displaying", "multiple", "types", "of", "information", "." ]
train
https://github.com/LIVVkit/LIVVkit/blob/680120cd437e408673e62e535fc0a246c7fc17db/livvkit/util/elements.py#L92-L126