_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q17000
NNAUTILUS.next_iteration
train
def next_iteration(self, ref_point, bounds=None): """ Calculate the next iteration point to be shown to the DM Parameters ---------- ref_point : list of float Reference point given by the DM """ if bounds: self.problem.points = reachable_point...
python
{ "resource": "" }
q17001
html_to_dom
train
def html_to_dom(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """Converts HTML to DOM.""" if isinstance(html, unicode): decoded_html = html # encode HTML for case it's XML with encoding declaration forced_encoding = encoding if encoding else default_...
python
{ "resource": "" }
q17002
decode_html
train
def decode_html(html, default_encoding=DEFAULT_ENCODING, encoding=None, errors=DEFAULT_ENC_ERRORS): """ Converts a `html` containing an HTML page into Unicode. Tries to guess character encoding from meta tag. """ if isinstance(html, unicode): return html if encoding: return html...
python
{ "resource": "" }
q17003
preprocessor
train
def preprocessor(dom): "Removes unwanted parts of DOM." options = { "processing_instructions": False, "remove_unknown_tags": False, "safe_attrs_only": False, "page_structure": False, "annoying_tags": False, "frames": False, "meta": False, "links": ...
python
{ "resource": "" }
q17004
classify_paragraphs
train
def classify_paragraphs(paragraphs, stoplist, length_low=LENGTH_LOW_DEFAULT, length_high=LENGTH_HIGH_DEFAULT, stopwords_low=STOPWORDS_LOW_DEFAULT, stopwords_high=STOPWORDS_HIGH_DEFAULT, max_link_density=MAX_LINK_DENSITY_DEFAULT, no_headings=NO_HEADINGS_DEFAULT): "Context-free paragraph class...
python
{ "resource": "" }
q17005
revise_paragraph_classification
train
def revise_paragraph_classification(paragraphs, max_heading_distance=MAX_HEADING_DISTANCE_DEFAULT): """ Context-sensitive paragraph classification. Assumes that classify_pragraphs has already been called. """ # copy classes for paragraph in paragraphs: paragraph.class_type = paragraph.cf...
python
{ "resource": "" }
q17006
get_stoplists
train
def get_stoplists(): """Returns a collection of built-in stop-lists.""" path_to_stoplists = os.path.dirname(sys.modules["justext"].__file__) path_to_stoplists = os.path.join(path_to_stoplists, "stoplists") stoplist_names = [] for filename in os.listdir(path_to_stoplists): name, extension = ...
python
{ "resource": "" }
q17007
get_stoplist
train
def get_stoplist(language): """Returns an built-in stop-list for the language as a set of words.""" file_path = os.path.join("stoplists", "%s.txt" % language) try: stopwords = pkgutil.get_data("justext", file_path) except IOError: raise ValueError( "Stoplist for language '%s'...
python
{ "resource": "" }
q17008
get_boto_client
train
def get_boto_client( client, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto3 client connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( client, region, aw...
python
{ "resource": "" }
q17009
get_boto_resource
train
def get_boto_resource( resource, region=None, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None, endpoint_url=None ): """Get a boto resource connection.""" cache_key = '{0}:{1}:{2}:{3}'.format( resource, region, ...
python
{ "resource": "" }
q17010
get_boto_session
train
def get_boto_session( region, aws_access_key_id=None, aws_secret_access_key=None, aws_session_token=None ): """Get a boto3 session.""" return boto3.session.Session( region_name=region, aws_secret_access_key=aws_secret_access_key, aws_access_key_id=...
python
{ "resource": "" }
q17011
ensure_text
train
def ensure_text(str_or_bytes, encoding='utf-8'): """Ensures an input is a string, decoding if it is bytes. """ if not isinstance(str_or_bytes, six.text_type): return str_or_bytes.decode(encoding) return str_or_bytes
python
{ "resource": "" }
q17012
ensure_bytes
train
def ensure_bytes(str_or_bytes, encoding='utf-8', errors='strict'): """Ensures an input is bytes, encoding if it is a string. """ if isinstance(str_or_bytes, six.text_type): return str_or_bytes.encode(encoding, errors) return str_or_bytes
python
{ "resource": "" }
q17013
KMSTokenValidator._get_key_alias_from_cache
train
def _get_key_alias_from_cache(self, key_arn): ''' Find a key's alias by looking up its key_arn in the KEY_METADATA cache. This function will only work after a key has been lookedup by its alias and is meant as a convenience function for turning an ARN that's already been looked u...
python
{ "resource": "" }
q17014
KMSTokenValidator.decrypt_token
train
def decrypt_token(self, username, token): ''' Decrypt a token. ''' version, user_type, _from = self._parse_username(username) if (version > self.maximum_token_version or version < self.minimum_token_version): raise TokenValidationError('Unacceptable to...
python
{ "resource": "" }
q17015
KMSTokenGenerator.get_username
train
def get_username(self): """Get a username formatted for a specific token version.""" _from = self.auth_context['from'] if self.token_version == 1: return '{0}'.format(_from) elif self.token_version == 2: _user_type = self.auth_context['user_type'] retu...
python
{ "resource": "" }
q17016
Annotator.properties
train
def properties(self): """ Defines a Java property to define this anntoator to CoreNLP. """ return { "customAnnotatorClass.{}".format(self.name): "edu.stanford.nlp.pipeline.GenericWebServiceAnnotator", "generic.endpoint": "http://{}:{}".format(self.host, self.port)...
python
{ "resource": "" }
q17017
translate
train
def translate(patterns, *, flags=0): """Translate `fnmatch` pattern.""" flags = _flag_transform(flags) return _wcparse.translate(_wcparse.split(patterns, flags), flags)
python
{ "resource": "" }
q17018
WcMatch._valid_file
train
def _valid_file(self, base, name): """Return whether a file can be searched.""" valid = False fullpath = os.path.join(base, name) if self.file_check is not None and self.compare_file(fullpath[self._base_len:] if self.file_pathname else name): valid = True if valid an...
python
{ "resource": "" }
q17019
WcMatch._valid_folder
train
def _valid_folder(self, base, name): """Return whether a folder can be searched.""" valid = True fullpath = os.path.join(base, name) if ( not self.recursive or ( self.folder_exclude_check is not None and not self.compare_directory(...
python
{ "resource": "" }
q17020
WcMatch.compare_directory
train
def compare_directory(self, directory): """Compare folder.""" return not self.folder_exclude_check.match(directory + self.sep if self.dir_pathname else directory)
python
{ "resource": "" }
q17021
WcMatch._walk
train
def _walk(self): """Start search for valid files.""" self._base_len = len(self.base) for base, dirs, files in os.walk(self.base, followlinks=self.follow_links): # Remove child folders based on exclude rules for name in dirs[:]: try: i...
python
{ "resource": "" }
q17022
is_negative
train
def is_negative(pattern, flags): """Check if negative pattern.""" if flags & MINUSNEGATE: return flags & NEGATE and pattern[0:1] in MINUS_NEGATIVE_SYM else: return flags & NEGATE and pattern[0:1] in NEGATIVE_SYM
python
{ "resource": "" }
q17023
expand_braces
train
def expand_braces(patterns, flags): """Expand braces.""" if flags & BRACE: for p in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): try: yield from bracex.iexpand(p, keep_escapes=True) except Exception: # pragma: no cover # We w...
python
{ "resource": "" }
q17024
get_case
train
def get_case(flags): """Parse flags for case sensitivity settings.""" if not bool(flags & CASE_FLAGS): case_sensitive = util.is_case_sensitive() elif flags & FORCECASE: case_sensitive = True else: case_sensitive = False return case_sensitive
python
{ "resource": "" }
q17025
is_unix_style
train
def is_unix_style(flags): """Check if we should use Unix style.""" return (util.platform() != "windows" or (not bool(flags & REALPATH) and get_case(flags))) and not flags & _FORCEWIN
python
{ "resource": "" }
q17026
translate
train
def translate(patterns, flags): """Translate patterns.""" positive = [] negative = [] if isinstance(patterns, (str, bytes)): patterns = [patterns] flags |= _TRANSLATE for pattern in patterns: for expanded in expand_braces(pattern, flags): (negative if is_negative(e...
python
{ "resource": "" }
q17027
split
train
def split(patterns, flags): """Split patterns.""" if flags & SPLIT: splitted = [] for pattern in ([patterns] if isinstance(patterns, (str, bytes)) else patterns): splitted.extend(WcSplit(pattern, flags).split()) return splitted else: return patterns
python
{ "resource": "" }
q17028
_compile
train
def _compile(pattern, flags): """Compile the pattern to regex.""" return re.compile(WcParse(pattern, flags & FLAG_MASK).parse())
python
{ "resource": "" }
q17029
_fs_match
train
def _fs_match(pattern, filename, sep, follow, symlinks): """ Match path against the pattern. Since `globstar` doesn't match symlinks (unless `FOLLOW` is enabled), we must look for symlinks. If we identify a symlink in a `globstar` match, we know this result should not actually match. """ match...
python
{ "resource": "" }
q17030
_match_real
train
def _match_real(filename, include, exclude, follow, symlinks): """Match real filename includes and excludes.""" sep = '\\' if util.platform() == "windows" else '/' if isinstance(filename, bytes): sep = os.fsencode(sep) if not filename.endswith(sep) and os.path.isdir(filename): filename ...
python
{ "resource": "" }
q17031
_match_pattern
train
def _match_pattern(filename, include, exclude, real, path, follow): """Match includes and excludes.""" if real: symlinks = {} if isinstance(filename, bytes): curdir = os.fsencode(os.curdir) mount = RE_BWIN_MOUNT if util.platform() == "windows" else RE_BMOUNT else...
python
{ "resource": "" }
q17032
WcPathSplit.store
train
def store(self, value, l, dir_only): """Group patterns by literals and potential magic patterns.""" if l and value in (b'', ''): return globstar = value in (b'**', '**') and self.globstar magic = self.is_magic(value) if magic: value = compile(value, self...
python
{ "resource": "" }
q17033
WcParse.update_dir_state
train
def update_dir_state(self): """ Update the directory state. If we are at the directory start, update to after start state (the character right after). If at after start, reset state. """ if self.dir_start and not self.after_start: self.set_after_star...
python
{ "resource": "" }
q17034
WcParse._restrict_sequence
train
def _restrict_sequence(self): """Restrict sequence.""" if self.pathname: value = self.seq_path_dot if self.after_start and not self.dot else self.seq_path if self.after_start: value = self.no_dir + value else: value = _NO_DOT if self.after_sta...
python
{ "resource": "" }
q17035
WcParse._sequence_range_check
train
def _sequence_range_check(self, result, last): """ If range backwards, remove it. A bad range will cause the regular expression to fail, so we need to remove it, but return that we removed it so the caller can know the sequence wasn't empty. Caller will have to craft a s...
python
{ "resource": "" }
q17036
WcParse._handle_posix
train
def _handle_posix(self, i, result, end_range): """Handle posix classes.""" last_posix = False m = i.match(RE_POSIX) if m: last_posix = True # Cannot do range with posix class # so escape last `-` if we think this # is the end of a range. ...
python
{ "resource": "" }
q17037
WcParse._handle_star
train
def _handle_star(self, i, current): """Handle star.""" if self.pathname: if self.after_start and not self.dot: star = self.path_star_dot2 globstar = self.path_gstar_dot2 elif self.after_start: star = self.path_star_dot1 ...
python
{ "resource": "" }
q17038
WcParse.clean_up_inverse
train
def clean_up_inverse(self, current): """ Clean up current. Python doesn't have variable lookbehinds, so we have to do negative lookaheads. !(...) when converted to regular expression is atomic, so once it matches, that's it. So we use the pattern `(?:(?!(?:stuff|to|exclude)<x>))...
python
{ "resource": "" }
q17039
WcParse.consume_path_sep
train
def consume_path_sep(self, i): """Consume any consecutive path separators are they count as one.""" try: if self.bslash_abort: count = -1 c = '\\' while c == '\\': count += 1 c = next(i) ...
python
{ "resource": "" }
q17040
WcParse.parse
train
def parse(self): """Parse pattern list.""" result = [''] negative = False p = util.norm_pattern(self.pattern, not self.unix, self.raw_chars) p = p.decode('latin-1') if self.is_bytes else p if is_negative(p, self.flags): negative = True p = p[1:]...
python
{ "resource": "" }
q17041
WcRegexp.match
train
def match(self, filename): """Match filename.""" return _match_pattern(filename, self._include, self._exclude, self._real, self._path, self._follow)
python
{ "resource": "" }
q17042
_flag_transform
train
def _flag_transform(flags): """Transform flags to glob defaults.""" # Here we force `PATHNAME`. flags = (flags & FLAG_MASK) | _wcparse.PATHNAME if flags & _wcparse.REALPATH and util.platform() == "windows": flags |= _wcparse._FORCEWIN if flags & _wcparse.FORCECASE: flags ^= ...
python
{ "resource": "" }
q17043
globmatch
train
def globmatch(filename, patterns, *, flags=0): """ Check if filename matches pattern. By default case sensitivity is determined by the file system, but if `case_sensitive` is set, respect that instead. """ flags = _flag_transform(flags) if not _wcparse.is_unix_style(flags): filenam...
python
{ "resource": "" }
q17044
globfilter
train
def globfilter(filenames, patterns, *, flags=0): """Filter names using pattern.""" matches = [] flags = _flag_transform(flags) unix = _wcparse.is_unix_style(flags) obj = _wcparse.compile(_wcparse.split(patterns, flags), flags) for filename in filenames: if not unix: filena...
python
{ "resource": "" }
q17045
raw_escape
train
def raw_escape(pattern, unix=False): """Apply raw character transform before applying escape.""" pattern = util.norm_pattern(pattern, False, True) return escape(pattern, unix)
python
{ "resource": "" }
q17046
Glob._parse_patterns
train
def _parse_patterns(self, pattern): """Parse patterns.""" self.pattern = [] self.npatterns = None npattern = [] for p in pattern: if _wcparse.is_negative(p, self.flags): # Treat the inverse pattern as a normal pattern if it matches, we will exclude. ...
python
{ "resource": "" }
q17047
Glob._match_excluded
train
def _match_excluded(self, filename, patterns): """Call match real directly to skip unnecessary `exists` check.""" return _wcparse._match_real( filename, patterns._include, patterns._exclude, patterns._follow, self.symlinks )
python
{ "resource": "" }
q17048
Glob._is_excluded
train
def _is_excluded(self, path, dir_only): """Check if file is excluded.""" return self.npatterns and self._match_excluded(path, self.npatterns)
python
{ "resource": "" }
q17049
Glob._match_literal
train
def _match_literal(self, a, b=None): """Match two names.""" return a.lower() == b if not self.case_sensitive else a == b
python
{ "resource": "" }
q17050
Glob._get_matcher
train
def _get_matcher(self, target): """Get deep match.""" if target is None: matcher = None elif isinstance(target, (str, bytes)): # Plain text match if not self.case_sensitive: match = target.lower() else: match = targ...
python
{ "resource": "" }
q17051
Glob._glob_dir
train
def _glob_dir(self, curdir, matcher, dir_only=False, deep=False): """Non recursive directory glob.""" scandir = self.current if not curdir else curdir # Python will never return . or .., so fake it. if os.path.isdir(scandir) and matcher is not None: for special in self.spec...
python
{ "resource": "" }
q17052
Glob._glob
train
def _glob(self, curdir, this, rest): """ Handle glob flow. There are really only a couple of cases: - File name. - File name pattern (magic). - Directory. - Directory name pattern (magic). - Extra slashes `////`. - `globstar` `**`. """ ...
python
{ "resource": "" }
q17053
Glob._get_starting_paths
train
def _get_starting_paths(self, curdir): """ Get the starting location. For case sensitive paths, we have to "glob" for it first as Python doesn't like for its users to think about case. By scanning for it, we can get the actual casing and then compare. """ ...
python
{ "resource": "" }
q17054
Glob.glob
train
def glob(self): """Starts off the glob iterator.""" # Cached symlinks self.symlinks = {} if self.is_bytes: curdir = os.fsencode(os.curdir) else: curdir = os.curdir for pattern in self.pattern: # If the pattern ends with `/` we return...
python
{ "resource": "" }
q17055
norm_slash
train
def norm_slash(name): """Normalize path slashes.""" if isinstance(name, str): return name.replace('/', "\\") if not is_case_sensitive() else name else: return name.replace(b'/', b"\\") if not is_case_sensitive() else name
python
{ "resource": "" }
q17056
norm_pattern
train
def norm_pattern(pattern, normalize, is_raw_chars): r""" Normalize pattern. - For windows systems we want to normalize slashes to \. - If raw string chars is enabled, we want to also convert encoded string chars to literal characters. - If `normalize` is enabled, take care to convert \/ to \\...
python
{ "resource": "" }
q17057
is_hidden
train
def is_hidden(path): """Check if file is hidden.""" hidden = False f = os.path.basename(path) if f[:1] in ('.', b'.'): # Count dot file as hidden on all systems hidden = True elif _PLATFORM == 'windows': # On Windows, look for `FILE_ATTRIBUTE_HIDDEN` FILE_ATTRIBUTE_H...
python
{ "resource": "" }
q17058
StringIter.match
train
def match(self, pattern): """Perform regex match at index.""" m = pattern.match(self._string, self._index) if m: self._index = m.end() return m
python
{ "resource": "" }
q17059
StringIter.iternext
train
def iternext(self): """Iterate through characters of the string.""" try: char = self._string[self._index] self._index += 1 except IndexError: # pragma: no cover raise StopIteration return char
python
{ "resource": "" }
q17060
update_media_file
train
def update_media_file(upload_file): ''' Update the Current Media Folder. Returns list of files copied across or raises an exception. ''' temp_directory = tempfile.mkdtemp() temp_file = tempfile.TemporaryFile() # assumes the zip file contains a directory called media temp_media_file ...
python
{ "resource": "" }
q17061
get_image_hash
train
def get_image_hash(image): ''' Returns an MD5 hash of the image file Handles images stored locally and on AWS I know this code is ugly. Please don't ask. The rabbit hole is deep. ''' md5 = hashlib.md5() try: for chunk in image.file.chunks(): md5.update(chunk) ...
python
{ "resource": "" }
q17062
attach_image
train
def attach_image(field, nested_fields, page, record_keeper=None): ''' Returns a function that attaches an image to page if it exists Currenlty assumes that images have already been imported and info has been stored in record_keeper ''' if (field in nested_fields) and nested_fields[field]: ...
python
{ "resource": "" }
q17063
rotate_content
train
def rotate_content(day=None): """ this method gets the parameters that are needed for rotate_latest and rotate_featured_in_homepage methods, and calls them both""" # getting the content rotation settings from site settings for main in Main.objects.all(): site = main.sites_rooted_here.all().firs...
python
{ "resource": "" }
q17064
run_wagtail_migration_before_core_34
train
def run_wagtail_migration_before_core_34(apps, schema_editor): """ Migration 34 needs migration 0040 from wagtail core and this Migration will run wagtail migration before molo core migration 34 """ db_alias = schema_editor.connection.alias emit_pre_migrate_signal(verbosity=2, interactive=Fa...
python
{ "resource": "" }
q17065
load_child_articles_for_section
train
def load_child_articles_for_section( context, section, featured_in_section=None, count=5): """ Returns all child articles If the `locale_code` in the context is not the main language, it will return the translations of the live articles. """ request = context.get('request') locale = ...
python
{ "resource": "" }
q17066
load_child_sections_for_section
train
def load_child_sections_for_section(context, section, count=None): ''' Returns all child sections If the `locale_code` in the context is not the main language, it will return the translations of the live articles. ''' page = section.get_main_language_page() locale = context.get('locale_code'...
python
{ "resource": "" }
q17067
load_sibling_sections
train
def load_sibling_sections(context, section, count=None): ''' Returns all sibling sections If the `locale_code` in the context is not the main language, it will return the translations of the live articles. ''' page = section.get_main_language_page() locale = context.get('locale_code') q...
python
{ "resource": "" }
q17068
ImportableMixin.create_page
train
def create_page(self, content, class_, record_keeper=None, logger=None): ''' Robust as possible Attempts to create the page If any of the functions used to attach content to the page fail, keep going, keep a record of those errors in a context dict return the page and th...
python
{ "resource": "" }
q17069
upload_file
train
def upload_file(request): '''Upload a Zip File Containing a single file containing media.''' if request.method == 'POST': form = MediaForm(request.POST, request.FILES) if form.is_valid(): context_dict = {} try: context_dict['copied_files'] = update_media_f...
python
{ "resource": "" }
q17070
download_file
train
def download_file(request): '''Create and download a zip file containing the media file.''' if request.method == "GET": if path.exists(settings.MEDIA_ROOT): zipfile_name = 'media_%s.zip' % settings.SITE_NAME in_memory_file = BytesIO() media_zipfile = zipfile.ZipFile(...
python
{ "resource": "" }
q17071
update_permissions_for_group
train
def update_permissions_for_group(apps, schema_editor): ''' Update permissions for some users. Give bulk-delete permissions to moderators. Give edit permission to moderators and editors in order to display 'Main' page in the explorer. ''' db_alias = schema_editor.connection.alias try: ...
python
{ "resource": "" }
q17072
MainLanguageFilter.filter_queryset
train
def filter_queryset(self, request, queryset, view): """ Returns only pages in the main language for a site """ if 'is_main_language' in request.GET: # TODO investigate possible error cases where page # does not have language return queryset.filter(lang...
python
{ "resource": "" }
q17073
create_recomended_articles
train
def create_recomended_articles(main_article, article_list): ''' Creates recommended article objects from article_list and _prepends_ to existing recommended articles. ''' # store existing recommended articles existing_recommended_articles = [ ra.recommended_article.specific for ...
python
{ "resource": "" }
q17074
seperate_end_page_links
train
def seperate_end_page_links(stream_data): ''' Seperate out page blocks at the end of a StreamField. Accepts: List of streamfield blocks Returns: Tuple of 2 lists of blocks - (remaining body, final article) ''' stream_data_copy = list(stream_data) end_page_links = [] for block in stream...
python
{ "resource": "" }
q17075
cookiecutter
train
def cookiecutter(template, checkout=None, no_input=False, extra_context=None): """ Replacement for cookiecutter's own cookiecutter. The difference with cookiecutter's cookiecutter function is that this one doesn't automatically str() all the values passed along to the template. :param template...
python
{ "resource": "" }
q17076
MoloPagesEndpoint.get_queryset
train
def get_queryset(self): ''' This is overwritten in order to not exclude drafts and pages submitted for moderation ''' request = self.request # Allow pages to be filtered to a specific type if 'type' not in request.GET: model = Page else: ...
python
{ "resource": "" }
q17077
LanguagesAPIEndpoint.get_queryset
train
def get_queryset(self): ''' Only serve site-specific languages ''' request = self.request return (Languages.for_site(request.site) .languages.filter().order_by('pk'))
python
{ "resource": "" }
q17078
list_of_objects_from_api
train
def list_of_objects_from_api(url): ''' API only serves 20 pages by default This fetches info on all of items and return them as a list Assumption: limit of API is not less than 20 ''' response = requests.get(url) content = json.loads(response.content) count = content["meta"]["total_cou...
python
{ "resource": "" }
q17079
PageImporter.get_content_from_url
train
def get_content_from_url(self, base_url): """ Sections can have SectionPage and ArticlePage child objects. These have different fields, and thus have to be treated differently. """ # assemble url base_url = base_url.rstrip("/") url = base_url + API_PAGES_E...
python
{ "resource": "" }
q17080
SectionPageImporter.save
train
def save(self, indexes, parent_id): """ Save the selected section. This will save the selected section as well as its direct child pages obtained through the ?child_of query parameter. The ?descendant_of query parameter is probably better suited because it all pages under that p...
python
{ "resource": "" }
q17081
ImageImporter.get_image_details
train
def get_image_details(self): ''' Create a reference of site images by hash If there are duplicate images, only store the first and create warnings for other images ''' if Image.objects.count() == 0: return None total = Image.objects.count() c...
python
{ "resource": "" }
q17082
ImageImporter.fetch_and_create_image
train
def fetch_and_create_image(self, url, image_title): ''' fetches, creates image object returns tuple with Image object and context dictionary containing request URL ''' context = { "file_url": url, "foreign_title": image_title, } t...
python
{ "resource": "" }
q17083
ImageImporter.import_image
train
def import_image(self, image_id): ''' Imports and returns tuple with image and context dict Input: foreign image ID Output: (Image: imported image, Dict: info about import) Side effects: If Importer object has a record_keeper, it will update the record of foreign to lo...
python
{ "resource": "" }
q17084
ImageImporter.import_images
train
def import_images(self): ''' Fetches all images from site Handles Errors in creation process Updates record_keeper Logs the result of each attempt to create an image ''' self.log(ACTION, "Importing Images") try: images = list_of_objects_from_a...
python
{ "resource": "" }
q17085
LanguageImporter.get_language_ids
train
def get_language_ids(self): ''' Return list of foreign language IDs from API language endpoint TODO: add in validation before creating languages ''' languages = list_of_objects_from_api(self.language_url) language_ids = [] for language in languages: ...
python
{ "resource": "" }
q17086
ContentImporter.recreate_relationships
train
def recreate_relationships(self, class_, attribute_name, key): ''' Recreates one-to-many relationship ''' iterable = self.record_keeper.foreign_to_many_foreign_map[key] for foreign_page_id, foreign_page_id_list in iteritems(iterable): # Assumption: local page has bee...
python
{ "resource": "" }
q17087
ContentImporter.recreate_relationship
train
def recreate_relationship(self, attribute_name, key): ''' Recreates one-to-one relationship ''' iterable = self.record_keeper.foreign_to_foreign_map["banner_link_page"] # noqa for foreign_page_id, linked_page_foreign_id in iteritems(iterable): # get local banner page...
python
{ "resource": "" }
q17088
ContentImporter.recreate_article_body
train
def recreate_article_body(self): ''' Handles case where article body contained page or image. Assumes all articles and images have been created. ''' for foreign_id, body in iteritems(self.record_keeper.article_bodies): try: local_page_id = self.record...
python
{ "resource": "" }
q17089
ContentImporter.get_foreign_page_id_from_type
train
def get_foreign_page_id_from_type(self, page_type): ''' Get the foreign page id based on type Only works for index pages ''' # TODO: log this response = requests.get("{}pages/?type={}".format( self.api_url, page_type)) content = json.loads(response.co...
python
{ "resource": "" }
q17090
ContentImporter.attach_translated_content
train
def attach_translated_content(self, local_main_lang_page, content, locale): ''' Wrapper for attach_page Creates the content Then attaches a language relation from the main language page to the newly created Page Note: we get the parent ...
python
{ "resource": "" }
q17091
ContentImporter.copy_page_and_children
train
def copy_page_and_children(self, foreign_id, parent_id, depth=0): ''' Recusively copies over pages, their translations, and child pages ''' url = "{}/api/v2/pages/{}/".format(self.base_url, foreign_id) self.log(ACTION, "Requesting Data", {"url": url}, depth) try: ...
python
{ "resource": "" }
q17092
ContentImporter.copy_children
train
def copy_children(self, foreign_id, existing_node): ''' Initiates copying of tree, with existing_node acting as root ''' url = "{}/api/v2/pages/{}/".format(self.base_url, foreign_id) self.log( ACTION, "Copying Children", {"existing node type": ...
python
{ "resource": "" }
q17093
Logger.get_email_logs
train
def get_email_logs(self): ''' Returns a string representation of logs. Only displays errors and warnings in the email logs to avoid being verbose ''' message = "" for log in self.record: if log["log_type"] in [ERROR, WARNING]: message ...
python
{ "resource": "" }
q17094
GitRun.run
train
def run(self, cmd): """Execute git command in bash""" cmd = ['git', '--git-dir=%s' % self.path] + cmd print("cmd list", cmd) print("cmd", ' '.join(cmd)) res = None try: res = subprocess.check_output(cmd) except BaseException: pass i...
python
{ "resource": "" }
q17095
GitRun.update
train
def update(self): """Get a repository git or update it""" if not os.path.isdir(os.path.join(self.path)): os.makedirs(self.path) if not os.path.isdir(os.path.join(self.path, 'refs')): subprocess.check_output([ 'git', 'clone', '--bare', self.repo_git, self.p...
python
{ "resource": "" }
q17096
oauth_session
train
def oauth_session(request, state=None, token=None): """ Constructs the OAuth2 session object. """ if settings.DISCORD_REDIRECT_URI is not None: redirect_uri = settings.DISCORD_REDIRECT_URI else: redirect_uri = request.build_absolute_uri( reverse('discord_bind_callback')) scop...
python
{ "resource": "" }
q17097
create_audio_mp3_profile
train
def create_audio_mp3_profile(apps, schema_editor): """ Create audio_mp3 profile """ Profile = apps.get_model('edxval', 'Profile') Profile.objects.get_or_create(profile_name=AUDIO_MP3_PROFILE)
python
{ "resource": "" }
q17098
delete_audio_mp3_profile
train
def delete_audio_mp3_profile(apps, schema_editor): """ Delete audio_mp3 profile """ Profile = apps.get_model('edxval', 'Profile') Profile.objects.filter(profile_name=AUDIO_MP3_PROFILE).delete()
python
{ "resource": "" }
q17099
Transcript.convert
train
def convert(cls, content, input_format, output_format): """ Convert transcript `content` from `input_format` to `output_format`. Arguments: content: Transcript content byte-stream. input_format: Input transcript format. output_format: Output transcript format...
python
{ "resource": "" }