_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q235000
NSFGrant.getInvestigators
train
def getInvestigators(self, tags = None, seperator = ";", _getTag = False): """Returns a list of the names of investigators. The optional arguments are ignored. # Returns `list [str]` > A list of all the found investigator's names """ if tags is None: tags =...
python
{ "resource": "" }
q235001
nameStringGender
train
def nameStringGender(s, noExcept = False): """Expects `first, last`""" global mappingDict try: first = s.split(', ')[1].split(' ')[0].title() except IndexError: if noExcept: return 'Unknown' else: return GenderException("The given String: '{}' does not hav...
python
{ "resource": "" }
q235002
j9urlGenerator
train
def j9urlGenerator(nameDict = False): """How to get all the urls for the WOS Journal Title Abbreviations. Each is varies by only a few characters. These are the currently in use urls they may change. They are of the form: > "https://images.webofknowledge.com/images/help/WOS/{VAL}_abrvjt.html" > Where ...
python
{ "resource": "" }
q235003
_j9SaveCurrent
train
def _j9SaveCurrent(sDir = '.'): """Downloads and saves all the webpages For Backend """ dname = os.path.normpath(sDir + '/' + datetime.datetime.now().strftime("%Y-%m-%d_J9_AbbreviationDocs")) if not os.path.isdir(dname): os.mkdir(dname) os.chdir(dname) else: os.chdir(dn...
python
{ "resource": "" }
q235004
_getDict
train
def _getDict(j9Page): """Parses a Journal Title Abbreviations page Note the pages are not well formatted html as the <DT> tags are not closes so html parses (Beautiful Soup) do not work. This is a simple parser that only works on the webpages and may fail if they are changed For Backend """ slines...
python
{ "resource": "" }
q235005
_getCurrentj9Dict
train
def _getCurrentj9Dict(): """Downloads and parses all the webpages For Backend """ urls = j9urlGenerator() j9Dict = {} for url in urls: d = _getDict(urllib.request.urlopen(url)) if len(d) == 0: raise RuntimeError("Parsing failed, this is could require an update of the...
python
{ "resource": "" }
q235006
updatej9DB
train
def updatej9DB(dbname = abrevDBname, saveRawHTML = False): """Updates the database of Journal Title Abbreviations. Requires an internet connection. The data base is saved relative to the source file not the working directory. # Parameters _dbname_ : `optional [str]` > The name of the database file, d...
python
{ "resource": "" }
q235007
getj9dict
train
def getj9dict(dbname = abrevDBname, manualDB = manualDBname, returnDict ='both'): """Returns the dictionary of journal abbreviations mapping to a list of the associated journal names. By default the local database is used. The database is in the file _dbname_ in the same directory as this source file # Paramet...
python
{ "resource": "" }
q235008
normalizeToTag
train
def normalizeToTag(val): """Converts tags or full names to 2 character tags, case insensitive # Parameters _val_: `str` > A two character string giving the tag or its full name # Returns `str` > The short name of _val_ """ try: val = val.upper() except AttributeErro...
python
{ "resource": "" }
q235009
normalizeToName
train
def normalizeToName(val): """Converts tags or full names to full names, case sensitive # Parameters _val_: `str` > A two character string giving the tag or its full name # Returns `str` > The full name of _val_ """ if val not in tagsAndNameSet: raise KeyError("{} is not...
python
{ "resource": "" }
q235010
Grant.update
train
def update(self, other): """Adds all the tag-entry pairs from _other_ to the `Grant`. If there is a conflict _other_ takes precedence. # Parameters _other_ : `Grant` > Another `Grant` of the same type as _self_ """ if type(self) != type(other): return NotIm...
python
{ "resource": "" }
q235011
EventDispatcher.relay_events_from
train
def relay_events_from(self, originator, event_type, *more_event_types): """ Configure this handler to re-dispatch events from another handler. This method configures this handler dispatch an event of type *event_type* whenever *originator* dispatches events of the same type or...
python
{ "resource": "" }
q235012
EventDispatcher.start_event
train
def start_event(self, event_type, *args, dt=1/60): """ Begin dispatching the given event at the given frequency. Calling this method will cause an event of type *event_type* with arguments *args* to be dispatched every *dt* seconds. This will continue until `stop_event()` is ...
python
{ "resource": "" }
q235013
EventDispatcher.stop_event
train
def stop_event(self, event_type): """ Stop dispatching the given event. It is not an error to attempt to stop an event that was never started, the request will just be silently ignored. """ if event_type in self.__timers: pyglet.clock.unschedule(self.__timer...
python
{ "resource": "" }
q235014
EventDispatcher.__yield_handlers
train
def __yield_handlers(self, event_type): """ Yield all the handlers registered for the given event type. """ if event_type not in self.event_types: raise ValueError("%r not found in %r.event_types == %r" % (event_type, self, self.event_types)) # Search handler stack f...
python
{ "resource": "" }
q235015
HoldUpdatesMixin._filter_pending_updates
train
def _filter_pending_updates(self): """ Return all the updates that need to be applied, from a list of all the updates that were called while the hold was active. This method is meant to be overridden by subclasses that want to customize how held updates are applied. ...
python
{ "resource": "" }
q235016
ReposToHTML.get_html
train
def get_html(self): """Method to convert the repository list to a search results page.""" here = path.abspath(path.dirname(__file__)) env = Environment(loader=FileSystemLoader(path.join(here, "res/"))) suggest = env.get_template("suggest.htm.j2") return suggest.render( ...
python
{ "resource": "" }
q235017
ReposToHTML.to_html
train
def to_html(self, write_to): """Method to convert the repository list to a search results page and write it to a HTML file. :param write_to: File/Path to write the html file to. """ page_html = self.get_html() with open(write_to, "wb") as writefile: writefil...
python
{ "resource": "" }
q235018
GitSuggest.get_unique_repositories
train
def get_unique_repositories(repo_list): """Method to create unique list of repositories from the list of repositories given. :param repo_list: List of repositories which might contain duplicates. :return: List of repositories with no duplicate in them. """ unique_list = ...
python
{ "resource": "" }
q235019
GitSuggest.minus
train
def minus(repo_list_a, repo_list_b): """Method to create a list of repositories such that the repository belongs to repo list a but not repo list b. In an ideal scenario we should be able to do this by set(a) - set(b) but as GithubRepositories have shown that set() on them is not reliab...
python
{ "resource": "" }
q235020
GitSuggest.__populate_repositories_of_interest
train
def __populate_repositories_of_interest(self, username): """Method to populate repositories which will be used to suggest repositories for the user. For this purpose we use two kinds of repositories. 1. Repositories starred by user him/herself. 2. Repositories starred by the use...
python
{ "resource": "" }
q235021
GitSuggest.__get_interests
train
def __get_interests(self): """Method to procure description of repositories the authenticated user is interested in. We currently attribute interest to: 1. The repositories the authenticated user has starred. 2. The repositories the users the authenticated user follows have ...
python
{ "resource": "" }
q235022
GitSuggest.__get_words_to_ignore
train
def __get_words_to_ignore(self): """Compiles list of all words to ignore. :return: List of words to ignore. """ # Stop words in English. english_stopwords = stopwords.words("english") here = path.abspath(path.dirname(__file__)) # Languages in git repositories. ...
python
{ "resource": "" }
q235023
GitSuggest.__clean_and_tokenize
train
def __clean_and_tokenize(self, doc_list): """Method to clean and tokenize the document list. :param doc_list: Document list to clean and tokenize. :return: Cleaned and tokenized document list. """ # Some repositories fill entire documentation in description. We ignore # ...
python
{ "resource": "" }
q235024
GitSuggest.__construct_lda_model
train
def __construct_lda_model(self): """Method to create LDA model to procure list of topics from. We do that by first fetching the descriptions of repositories user has shown interest in. We tokenize the hence fetched descriptions to procure list of cleaned tokens by dropping all the stop ...
python
{ "resource": "" }
q235025
GitSuggest.__get_query_for_repos
train
def __get_query_for_repos(self, term_count=5): """Method to procure query based on topics authenticated user is interested in. :param term_count: Count of terms in query. :return: Query string. """ repo_query_terms = list() for term in self.lda_model.get_topic_te...
python
{ "resource": "" }
q235026
GitSuggest.get_suggested_repositories
train
def get_suggested_repositories(self): """Method to procure suggested repositories for the user. :return: Iterator to procure suggested repositories for the user. """ if self.suggested_repositories is None: # Procure repositories to suggest to user. repository_set...
python
{ "resource": "" }
q235027
guess_type
train
def guess_type(s): """ attempt to convert string value into numeric type """ sc = s.replace(',', '') # remove comma from potential numbers try: return int(sc) except ValueError: pass try: return float(sc) except ValueError: pass return s
python
{ "resource": "" }
q235028
FieldReader.parse
train
def parse(self, node): """ Return generator yielding Field objects for a given node """ self._attrs = {} vals = [] yielded = False for x in self._read_parts(node): if isinstance(x, Field): yielded = True x.attrs = self....
python
{ "resource": "" }
q235029
RowReader.parse
train
def parse(self, *nodes): """ Parse one or more `tr` nodes, yielding wikitables.Row objects """ for n in nodes: if not n.contents: continue row = self._parse(n) if not row.is_null: yield row
python
{ "resource": "" }
q235030
WikiTable._find_header_row
train
def _find_header_row(self): """ Evaluate all rows and determine header position, based on greatest number of 'th' tagged elements """ th_max = 0 header_idx = 0 for idx, tr in enumerate(self._tr_nodes): th_count = len(tr.contents.filter_tags(matches=fta...
python
{ "resource": "" }
q235031
WikiTable._make_default_header
train
def _make_default_header(self): """ Return a generic placeholder header based on the tables column count """ td_max = 0 for idx, tr in enumerate(self._tr_nodes): td_count = len(tr.contents.filter_tags(matches=ftag('td'))) if td_count > td_max: ...
python
{ "resource": "" }
q235032
Client.fetch_page
train
def fetch_page(self, title, method='GET'): """ Query for page by title """ params = { 'prop': 'revisions', 'format': 'json', 'action': 'query', 'explaintext': '', 'titles': title, 'rvprop': 'content' } ...
python
{ "resource": "" }
q235033
print_stack
train
def print_stack(pid, include_greenlet=False, debugger=None, verbose=False): """Executes a file in a running Python process.""" # TextIOWrapper of Python 3 is so strange. sys_stdout = getattr(sys.stdout, 'buffer', sys.stdout) sys_stderr = getattr(sys.stderr, 'buffer', sys.stderr) make_args = make_gd...
python
{ "resource": "" }
q235034
cli_main
train
def cli_main(pid, include_greenlet, debugger, verbose): '''Print stack of python process. $ pystack <pid> ''' try: print_stack(pid, include_greenlet, debugger, verbose) except DebuggerNotFound as e: click.echo('DebuggerNotFound: %s' % e.args[0], err=True) click.get_current_c...
python
{ "resource": "" }
q235035
hmm.forward_algo
train
def forward_algo(self,observations): """ Finds the probability of an observation sequence for given model parameters **Arguments**: :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. :type observations: A...
python
{ "resource": "" }
q235036
hmm.viterbi
train
def viterbi(self,observations): """ The probability of occurence of the observation sequence **Arguments**: :param observations: The observation sequence, where each element belongs to 'observations' variable declared with __init__ object. :type observations: A list or tuple ...
python
{ "resource": "" }
q235037
hmm.train_hmm
train
def train_hmm(self,observation_list, iterations, quantities): """ Runs the Baum Welch Algorithm and finds the new model parameters **Arguments**: :param observation_list: A nested list, or a list of lists :type observation_list: Contains a list multiple observation sequences. ...
python
{ "resource": "" }
q235038
hmm.log_prob
train
def log_prob(self,observations_list, quantities): """ Finds Weighted log probability of a list of observation sequences **Arguments**: :param observation_list: A nested list, or a list of lists :type observation_list: Contains a list multiple observation sequences. :param ...
python
{ "resource": "" }
q235039
Fred.__fetch_data
train
def __fetch_data(self, url): """ helper function for fetching data given a request URL """ url += '&api_key=' + self.api_key try: response = urlopen(url) root = ET.fromstring(response.read()) except HTTPError as exc: root = ET.fromstrin...
python
{ "resource": "" }
q235040
Fred._parse
train
def _parse(self, date_str, format='%Y-%m-%d'): """ helper function for parsing FRED date string into datetime """ rv = pd.to_datetime(date_str, format=format) if hasattr(rv, 'to_pydatetime'): rv = rv.to_pydatetime() return rv
python
{ "resource": "" }
q235041
Fred.get_series_first_release
train
def get_series_first_release(self, series_id): """ Get first-release data for a Fred series id. This ignores any revision to the data series. For instance, The US GDP for Q1 2014 was first released to be 17149.6, and then later revised to 17101.3, and 17016.0. This will ignore revisions ...
python
{ "resource": "" }
q235042
Fred.get_series_as_of_date
train
def get_series_as_of_date(self, series_id, as_of_date): """ Get latest data for a Fred series id as known on a particular date. This includes any revision to the data series before or on as_of_date, but ignores any revision on dates after as_of_date. Parameters ---------- ...
python
{ "resource": "" }
q235043
Fred.get_series_vintage_dates
train
def get_series_vintage_dates(self, series_id): """ Get a list of vintage dates for a series. Vintage dates are the dates in history when a series' data values were revised or new data values were released. Parameters ---------- series_id : str Fred series id ...
python
{ "resource": "" }
q235044
Fred.__do_series_search
train
def __do_series_search(self, url): """ helper function for making one HTTP request for data, and parsing the returned results into a DataFrame """ root = self.__fetch_data(url) series_ids = [] data = {} num_results_returned = 0 # number of results returned in t...
python
{ "resource": "" }
q235045
Fred.__get_search_results
train
def __get_search_results(self, url, limit, order_by, sort_order, filter): """ helper function for getting search results up to specified limit on the number of results. The Fred HTTP API truncates to 1000 results per request, so this may issue multiple HTTP requests to obtain more available data...
python
{ "resource": "" }
q235046
Fred.search
train
def search(self, text, limit=1000, order_by=None, sort_order=None, filter=None): """ Do a fulltext search for series in the Fred dataset. Returns information about matching series in a DataFrame. Parameters ---------- text : str text to do fulltext search on, e.g., '...
python
{ "resource": "" }
q235047
Fred.search_by_release
train
def search_by_release(self, release_id, limit=0, order_by=None, sort_order=None, filter=None): """ Search for series that belongs to a release id. Returns information about matching series in a DataFrame. Parameters ---------- release_id : int release id, e.g., 151 ...
python
{ "resource": "" }
q235048
Fred.search_by_category
train
def search_by_category(self, category_id, limit=0, order_by=None, sort_order=None, filter=None): """ Search for series that belongs to a category id. Returns information about matching series in a DataFrame. Parameters ---------- category_id : int category id, e.g., ...
python
{ "resource": "" }
q235049
CertificateManager.init
train
def init(self, ca, csr, **kwargs): """Create a signed certificate from a CSR and store it to the database. All parameters are passed on to :py:func:`Certificate.objects.sign_cert() <django_ca.managers.CertificateManager.sign_cert>`. """ c = self.model(ca=ca) c.x509, csr...
python
{ "resource": "" }
q235050
CertificateMixin.download_bundle_view
train
def download_bundle_view(self, request, pk): """A view that allows the user to download a certificate bundle in PEM format.""" return self._download_response(request, pk, bundle=True)
python
{ "resource": "" }
q235051
CertificateMixin.get_actions
train
def get_actions(self, request): """Disable the "delete selected" admin action. Otherwise the action is present even though has_delete_permission is False, it just doesn't work. """ actions = super(CertificateMixin, self).get_actions(request) actions.pop('delete_selected'...
python
{ "resource": "" }
q235052
get_cert_profile_kwargs
train
def get_cert_profile_kwargs(name=None): """Get kwargs suitable for get_cert X509 keyword arguments from the given profile.""" if name is None: name = ca_settings.CA_DEFAULT_PROFILE profile = deepcopy(ca_settings.CA_PROFILES[name]) kwargs = { 'cn_in_san': profile['cn_in_san'], '...
python
{ "resource": "" }
q235053
format_name
train
def format_name(subject): """Convert a subject into the canonical form for distinguished names. This function does not take care of sorting the subject in any meaningful order. Examples:: >>> format_name([('CN', 'example.com'), ]) '/CN=example.com' >>> format_name([('CN', 'example...
python
{ "resource": "" }
q235054
format_general_name
train
def format_general_name(name): """Format a single general name. >>> import ipaddress >>> format_general_name(x509.DNSName('example.com')) 'DNS:example.com' >>> format_general_name(x509.IPAddress(ipaddress.IPv4Address('127.0.0.1'))) 'IP:127.0.0.1' """ if isinstance(name, x509.DirectoryN...
python
{ "resource": "" }
q235055
add_colons
train
def add_colons(s): """Add colons after every second digit. This function is used in functions to prettify serials. >>> add_colons('teststring') 'te:st:st:ri:ng' """ return ':'.join([s[i:i + 2] for i in range(0, len(s), 2)])
python
{ "resource": "" }
q235056
int_to_hex
train
def int_to_hex(i): """Create a hex-representation of the given serial. >>> int_to_hex(12345678) 'BC:61:4E' """ s = hex(i)[2:].upper() if six.PY2 is True and isinstance(i, long): # pragma: only py2 # NOQA # Strip the "L" suffix, since hex(1L) -> 0x1L. # NOTE: Do not convert to ...
python
{ "resource": "" }
q235057
parse_name
train
def parse_name(name): """Parses a subject string as used in OpenSSLs command line utilities. The ``name`` is expected to be close to the subject format commonly used by OpenSSL, for example ``/C=AT/L=Vienna/CN=example.com/emailAddress=user@example.com``. The function does its best to be lenient on devi...
python
{ "resource": "" }
q235058
parse_general_name
train
def parse_general_name(name): """Parse a general name from user input. This function will do its best to detect the intended type of any value passed to it: >>> parse_general_name('example.com') <DNSName(value='example.com')> >>> parse_general_name('*.example.com') <DNSName(value='*.example.co...
python
{ "resource": "" }
q235059
parse_hash_algorithm
train
def parse_hash_algorithm(value=None): """Parse a hash algorithm value. The most common use case is to pass a str naming a class in :py:mod:`~cg:cryptography.hazmat.primitives.hashes`. For convenience, passing ``None`` will return the value of :ref:`CA_DIGEST_ALGORITHM <settings-ca-digest-algorithm...
python
{ "resource": "" }
q235060
parse_encoding
train
def parse_encoding(value=None): """Parse a value to a valid encoding. This function accepts either a member of :py:class:`~cg:cryptography.hazmat.primitives.serialization.Encoding` or a string describing a member. If no value is passed, it will assume ``PEM`` as a default value. Note that ``"ASN1"`` is...
python
{ "resource": "" }
q235061
parse_key_curve
train
def parse_key_curve(value=None): """Parse an elliptic curve value. This function uses a value identifying an elliptic curve to return an :py:class:`~cg:cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve` instance. The name must match a class name of one of the classes named under "Elliptic Curv...
python
{ "resource": "" }
q235062
get_cert_builder
train
def get_cert_builder(expires): """Get a basic X509 cert builder object. Parameters ---------- expires : datetime When this certificate will expire. """ now = datetime.utcnow().replace(second=0, microsecond=0) if expires is None: expires = get_expires(expires, now=now) ...
python
{ "resource": "" }
q235063
wrap_file_exceptions
train
def wrap_file_exceptions(): """Contextmanager to wrap file exceptions into identicaly exceptions in py2 and py3. This should be removed once py2 support is dropped. """ try: yield except (PermissionError, FileNotFoundError): # pragma: only py3 # In py3, we want to raise Exception u...
python
{ "resource": "" }
q235064
read_file
train
def read_file(path): """Read the file from the given path. If ``path`` is an absolute path, reads a file from the local filesystem. For relative paths, read the file using the storage backend configured using :ref:`CA_FILE_STORAGE <settings-ca-file-storage>`. """ if os.path.isabs(path): wit...
python
{ "resource": "" }
q235065
get_extension_name
train
def get_extension_name(ext): """Function to get the name of an extension.""" # In cryptography 2.2, SCTs return "Unknown OID" if ext.oid == ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: return 'SignedCertificateTimestampList' # Until at least cryptography 2.6.1, PrecertPoison has no name...
python
{ "resource": "" }
q235066
shlex_split
train
def shlex_split(s, sep): """Split a character on the given set of characters. Example:: >>> shlex_split('foo,bar', ', ') ['foo', 'bar'] >>> shlex_split('foo\\\\,bar1', ',') # escape a separator ['foo,bar1'] >>> shlex_split('"foo,bar", bla', ', ') ['foo,bar', 'b...
python
{ "resource": "" }
q235067
X509CertMixin.get_revocation_reason
train
def get_revocation_reason(self): """Get the revocation reason of this certificate.""" if self.revoked is False: return if self.revoked_reason == '' or self.revoked_reason is None: return x509.ReasonFlags.unspecified else: return getattr(x509.ReasonFla...
python
{ "resource": "" }
q235068
X509CertMixin.get_revocation_time
train
def get_revocation_time(self): """Get the revocation time as naive datetime. Note that this method is only used by cryptography>=2.4. """ if self.revoked is False: return if timezone.is_aware(self.revoked_date): # convert datetime object to UTC and make ...
python
{ "resource": "" }
q235069
CertificateAuthority.get_authority_key_identifier
train
def get_authority_key_identifier(self): """Return the AuthorityKeyIdentifier extension used in certificates signed by this CA.""" try: ski = self.x509.extensions.get_extension_for_class(x509.SubjectKeyIdentifier) except x509.ExtensionNotFound: return x509.AuthorityKeyIde...
python
{ "resource": "" }
q235070
CertificateAuthority.max_pathlen
train
def max_pathlen(self): """The maximum pathlen for any intermediate CAs signed by this CA. This value is either ``None``, if this and all parent CAs don't have a ``pathlen`` attribute, or an ``int`` if any parent CA has the attribute. """ pathlen = self.pathlen if self.p...
python
{ "resource": "" }
q235071
CertificateAuthority.bundle
train
def bundle(self): """A list of any parent CAs, including this CA. The list is ordered so the Root CA will be the first. """ ca = self bundle = [ca] while ca.parent is not None: bundle.append(ca.parent) ca = ca.parent return bundle
python
{ "resource": "" }
q235072
CertificateQuerySet.valid
train
def valid(self): """Return valid certificates.""" now = timezone.now() return self.filter(revoked=False, expires__gt=now, valid_from__lt=now)
python
{ "resource": "" }
q235073
_release_version
train
def _release_version(): ''' Returns release version ''' with io.open(os.path.join(SETUP_DIRNAME, 'saltpylint', 'version.py'), encoding='utf-8') as fh_: exec_locals = {} exec_globals = {} contents = fh_.read() if not isinstance(contents, str): contents = conten...
python
{ "resource": "" }
q235074
get_versions
train
def get_versions(source): """Return information about the Python versions required for specific features. The return value is a dictionary with keys as a version number as a tuple (for example Python 2.6 is (2,6)) and the value are a list of features that require the indicated Python version. """ ...
python
{ "resource": "" }
q235075
StringLiteralChecker.process_non_raw_string_token
train
def process_non_raw_string_token(self, prefix, string_body, start_row): ''' check for bad escapes in a non-raw string. prefix: lowercase string of eg 'ur' string prefix markers. string_body: the un-parsed body of the string, not including the quote marks. start_row: inte...
python
{ "resource": "" }
q235076
register
train
def register(linter): ''' Required method to auto register this checker ''' linter.register_checker(ResourceLeakageChecker(linter)) linter.register_checker(BlacklistedImportsChecker(linter)) linter.register_checker(MovedTestCaseClassChecker(linter)) linter.register_checker(BlacklistedLoaderM...
python
{ "resource": "" }
q235077
register
train
def register(linter): ''' Register the transformation functions. ''' try: MANAGER.register_transform(nodes.Class, rootlogger_transform) except AttributeError: MANAGER.register_transform(nodes.ClassDef, rootlogger_transform)
python
{ "resource": "" }
q235078
XBlockWithSettingsMixin.get_xblock_settings
train
def get_xblock_settings(self, default=None): """ Gets XBlock-specific settigns for current XBlock Returns default if settings service is not available. Parameters: default - default value to be used in two cases: * No settings service is available ...
python
{ "resource": "" }
q235079
ThemableXBlockMixin.include_theme_files
train
def include_theme_files(self, fragment): """ Gets theme configuration and renders theme css into fragment """ theme = self.get_theme() if not theme or 'package' not in theme: return theme_package, theme_files = theme.get('package', None), theme.get('locations...
python
{ "resource": "" }
q235080
ResourceLoader.load_unicode
train
def load_unicode(self, resource_path): """ Gets the content of a resource """ resource_content = pkg_resources.resource_string(self.module_name, resource_path) return resource_content.decode('utf-8')
python
{ "resource": "" }
q235081
ResourceLoader.render_django_template
train
def render_django_template(self, template_path, context=None, i18n_service=None): """ Evaluate a django template by resource path, applying the provided context. """ context = context or {} context['_i18n_service'] = i18n_service libraries = { 'i18n': 'xblocku...
python
{ "resource": "" }
q235082
ResourceLoader.render_mako_template
train
def render_mako_template(self, template_path, context=None): """ Evaluate a mako template by resource path, applying the provided context """ context = context or {} template_str = self.load_unicode(template_path) lookup = MakoTemplateLookup(directories=[pkg_resources.res...
python
{ "resource": "" }
q235083
ResourceLoader.render_template
train
def render_template(self, template_path, context=None): """ This function has been deprecated. It calls render_django_template to support backwards compatibility. """ warnings.warn( "ResourceLoader.render_template has been deprecated in favor of ResourceLoader.render_django_t...
python
{ "resource": "" }
q235084
ResourceLoader.render_js_template
train
def render_js_template(self, template_path, element_id, context=None): """ Render a js template. """ context = context or {} return u"<script type='text/template' id='{}'>\n{}\n</script>".format( element_id, self.render_template(template_path, context) ...
python
{ "resource": "" }
q235085
ProxyTransNode.merge_translation
train
def merge_translation(self, context): """ Context wrapper which modifies the given language's translation catalog using the i18n service, if found. """ language = get_language() i18n_service = context.get('_i18n_service', None) if i18n_service: # Cache the ori...
python
{ "resource": "" }
q235086
ProxyTransNode.render
train
def render(self, context): """ Renders the translated text using the XBlock i18n service, if available. """ with self.merge_translation(context): django_translated = self.do_translate.render(context) return django_translated
python
{ "resource": "" }
q235087
StudioEditableXBlockMixin.studio_view
train
def studio_view(self, context): """ Render a form for editing this XBlock """ fragment = Fragment() context = {'fields': []} # Build a list of all the fields that can be edited: for field_name in self.editable_fields: field = self.fields[field_name] ...
python
{ "resource": "" }
q235088
StudioEditableXBlockMixin.validate
train
def validate(self): """ Validates the state of this XBlock. Subclasses should override validate_field_data() to validate fields and override this only for validation not related to this block's field values. """ validation = super(StudioEditableXBlockMixin, self).validat...
python
{ "resource": "" }
q235089
StudioContainerXBlockMixin.render_children
train
def render_children(self, context, fragment, can_reorder=True, can_add=False): """ Renders the children of the module with HTML appropriate for Studio. If can_reorder is True, then the children will be rendered to support drag and drop. """ contents = [] child_context = ...
python
{ "resource": "" }
q235090
StudioContainerXBlockMixin.author_view
train
def author_view(self, context): """ Display a the studio editor when the user has clicked "View" to see the container view, otherwise just show the normal 'author_preview_view' or 'student_view' preview. """ root_xblock = context.get('root_xblock') if root_xblock and roo...
python
{ "resource": "" }
q235091
StudioContainerXBlockMixin.author_edit_view
train
def author_edit_view(self, context): """ Child blocks can override this to control the view shown to authors in Studio when editing this block's children. """ fragment = Fragment() self.render_children(context, fragment, can_reorder=True, can_add=False) return fra...
python
{ "resource": "" }
q235092
XBlockWithPreviewMixin.preview_view
train
def preview_view(self, context): """ Preview view - used by StudioContainerWithNestedXBlocksMixin to render nested xblocks in preview context. Default implementation uses author_view if available, otherwise falls back to student_view Child classes can override this method to control thei...
python
{ "resource": "" }
q235093
StudioContainerWithNestedXBlocksMixin.get_nested_blocks_spec
train
def get_nested_blocks_spec(self): """ Converts allowed_nested_blocks items to NestedXBlockSpec to provide common interface """ return [ block_spec if isinstance(block_spec, NestedXBlockSpec) else NestedXBlockSpec(block_spec) for block_spec in self.allowed_nested_b...
python
{ "resource": "" }
q235094
StudioContainerWithNestedXBlocksMixin.author_preview_view
train
def author_preview_view(self, context): """ View for previewing contents in studio. """ children_contents = [] fragment = Fragment() for child_id in self.children: child = self.runtime.get_block(child_id) child_fragment = self._render_child_fragme...
python
{ "resource": "" }
q235095
StudioContainerWithNestedXBlocksMixin._render_child_fragment
train
def _render_child_fragment(self, child, context, view='student_view'): """ Helper method to overcome html block rendering quirks """ try: child_fragment = child.render(view, context) except NoSuchViewError: if child.scope_ids.block_type == 'html' and getat...
python
{ "resource": "" }
q235096
package_data
train
def package_data(pkg, root_list): """Generic function to find package_data for `pkg` under `root`.""" data = [] for root in root_list: for dirname, _, files in os.walk(os.path.join(pkg, root)): for fname in files: data.append(os.path.relpath(os.path.join(dirname, fname), ...
python
{ "resource": "" }
q235097
load_requirements
train
def load_requirements(*requirements_paths): """ Load all requirements from the specified requirements files. Returns a list of requirement strings. """ requirements = set() for path in requirements_paths: requirements.update( line.split('#')[0].strip() for line in open(path)....
python
{ "resource": "" }
q235098
is_requirement
train
def is_requirement(line): """ Return True if the requirement line is a package requirement; that is, it is not blank, a comment, a URL, or an included file. """ return not ( line == '' or line.startswith('-r') or line.startswith('#') or line.startswith('-e') or ...
python
{ "resource": "" }
q235099
PublishEventMixin.publish_event
train
def publish_event(self, data, suffix=''): """ AJAX handler to allow client-side code to publish a server-side event """ try: event_type = data.pop('event_type') except KeyError: return {'result': 'error', 'message': 'Missing event_type in JSON data'} ...
python
{ "resource": "" }