_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q55600
Issuer._sync_revoc
train
async def _sync_revoc(self, rr_id: str, rr_size: int = None) -> None: """ Create revoc registry if need be for input revocation registry identifier; open and cache tails file reader. :param rr_id: revocation registry identifier :param rr_size: if new revocation registry necessar...
python
{ "resource": "" }
q55601
quote_xml
train
def quote_xml(text): """Format a value for display as an XML text node. Returns: Unicode string (str on Python 3, unicode on Python 2) """ text = _coerce_unicode(text) # If it's a CDATA block, return the text as is. if text.startswith(CDATA_START): return text # If it's no...
python
{ "resource": "" }
q55602
_NamespaceInfo.__construct_from_components
train
def __construct_from_components(self, ns_uri, prefix=None, schema_location=None): """Initialize this instance from a namespace URI, and optional prefix and schema location URI.""" assert ns_uri # other fields are optional self.uri = ns_uri self.schema_location = schema_locatio...
python
{ "resource": "" }
q55603
NamespaceSet.namespace_for_prefix
train
def namespace_for_prefix(self, prefix): """Get the namespace the given prefix maps to. Args: prefix (str): The prefix Returns: str: The namespace, or None if the prefix isn't mapped to anything in this set. """ try: ni = self....
python
{ "resource": "" }
q55604
NamespaceSet.set_preferred_prefix_for_namespace
train
def set_preferred_prefix_for_namespace(self, ns_uri, prefix, add_if_not_exist=False): """Sets the preferred prefix for ns_uri. If add_if_not_exist is True, the prefix is added if it's not already registered. Otherwise, setting an unknown prefix as preferred is an error. The default is...
python
{ "resource": "" }
q55605
NamespaceSet.__merge_schema_locations
train
def __merge_schema_locations(self, ni, incoming_schemaloc): """Merge incoming_schemaloc into the given `_NamespaceInfo`, ni. If we don't have one yet and the incoming value is non-None, update ours with theirs. This modifies ni. """ if ni.schema_location == incoming_schemaloc: ...
python
{ "resource": "" }
q55606
NamespaceSet.add_namespace_uri
train
def add_namespace_uri(self, ns_uri, prefix=None, schema_location=None): """Adds a new namespace to this set, optionally with a prefix and schema location URI. If the namespace already exists, the given prefix and schema location are merged with the existing entry: * If non-N...
python
{ "resource": "" }
q55607
NamespaceSet.remove_namespace
train
def remove_namespace(self, ns_uri): """Removes the indicated namespace from this set.""" if not self.contains_namespace(ns_uri): return ni = self.__ns_uri_map.pop(ns_uri) for prefix in ni.prefixes: del self.__prefix_map[prefix]
python
{ "resource": "" }
q55608
NamespaceSet.add_prefix
train
def add_prefix(self, ns_uri, prefix, set_as_preferred=False): """Adds prefix for the given namespace URI. The namespace must already exist in this set. If set_as_preferred is True, also set this namespace as the preferred one. ``prefix`` must be non-None; a default preference can't be...
python
{ "resource": "" }
q55609
NamespaceSet.prefix_iter
train
def prefix_iter(self, ns_uri): """Gets an iterator over the prefixes for the given namespace.""" ni = self.__lookup_uri(ns_uri) return iter(ni.prefixes)
python
{ "resource": "" }
q55610
NamespaceSet.remove_prefix
train
def remove_prefix(self, prefix): """Removes prefix from this set. This is a no-op if the prefix doesn't exist in it. """ if prefix not in self.__prefix_map: return ni = self.__lookup_prefix(prefix) ni.prefixes.discard(prefix) del self.__prefix_map[pr...
python
{ "resource": "" }
q55611
NamespaceSet.set_schema_location
train
def set_schema_location(self, ns_uri, schema_location, replace=False): """Sets the schema location of the given namespace. If ``replace`` is ``True``, then any existing schema location is replaced. Otherwise, if the schema location is already set to a different value, an exception is r...
python
{ "resource": "" }
q55612
NamespaceSet.get_schemaloc_string
train
def get_schemaloc_string(self, ns_uris=None, sort=False, delim="\n"): """Constructs and returns a schemalocation attribute. If no namespaces in this set have any schema locations defined, returns an empty string. Args: ns_uris (iterable): The namespaces to include in the co...
python
{ "resource": "" }
q55613
NamespaceSet.get_uri_prefix_map
train
def get_uri_prefix_map(self): """Constructs and returns a map from namespace URI to prefix, representing all namespaces in this set. The prefix chosen for each namespace is its preferred prefix if it's not None. If the preferred prefix is None, one is chosen from the set of registered ...
python
{ "resource": "" }
q55614
NamespaceSet.get_uri_schemaloc_map
train
def get_uri_schemaloc_map(self): """Constructs and returns a map from namespace URI to schema location URI. Namespaces without schema locations are excluded.""" mapping = {} for ni in six.itervalues(self.__ns_uri_map): if ni.schema_location: mapping[ni.uri] ...
python
{ "resource": "" }
q55615
NamespaceSet.subset
train
def subset(self, ns_uris): """Return a subset of this NamespaceSet containing only data for the given namespaces. Args: ns_uris (iterable): An iterable of namespace URIs which select the namespaces for the subset. Returns: The subset Rai...
python
{ "resource": "" }
q55616
NamespaceSet.import_from
train
def import_from(self, other_ns, replace=False): """Imports namespaces into this set, from other_ns. Args: other_ns (NamespaceSet): The set to import from replace (bool): If a namespace exists in both sets, do we replace our data with other_ns's data? We could ge...
python
{ "resource": "" }
q55617
EntityParser._get_version
train
def _get_version(self, root): """Return the version of the root element passed in. Args: root (etree.Element) Returns: distutils.StrictVersion Raises: UnknownVersionError """ # Note: STIX and MAEC use a "version" attribute. To suppor...
python
{ "resource": "" }
q55618
EntityParser._check_version
train
def _check_version(self, root): """Ensure the root element is a supported version. Args: root (etree.Element) Raises: UnsupportedVersionError """ version = self._get_version(root) supported = [StrictVersion(x) for x in self.s...
python
{ "resource": "" }
q55619
EntityParser._check_root_tag
train
def _check_root_tag(self, root): """Check that the XML element tree has a supported root element. Args: root (etree.Element) Raises: UnsupportedRootElementError """ supported = self.supported_tags() if root.tag in supported: return ...
python
{ "resource": "" }
q55620
EntityParser.parse_xml_to_obj
train
def parse_xml_to_obj(self, xml_file, check_version=True, check_root=True, encoding=None): """Creates a STIX binding object from the supplied xml file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document ...
python
{ "resource": "" }
q55621
EntityParser.parse_xml
train
def parse_xml(self, xml_file, check_version=True, check_root=True, encoding=None): """Creates a python-stix STIXPackage object from the supplied xml_file. Args: xml_file: A filename/path or a file-like object representing a STIX instance document ...
python
{ "resource": "" }
q55622
CommunitySchemaV1.get_logo_url
train
def get_logo_url(self, obj): """Get the community logo URL.""" if current_app and obj.logo_url: return u'{site_url}{path}'.format( site_url=current_app.config.get('THEME_SITEURL'), path=obj.logo_url, )
python
{ "resource": "" }
q55623
CommunitySchemaV1.item_links_addition
train
def item_links_addition(self, data): """Add the links for each community.""" links_item_factory = self.context.get('links_item_factory', default_links_item_factory) data['links'] = links_item_factory(data) return data
python
{ "resource": "" }
q55624
CommunitySchemaV1.envelope
train
def envelope(self, data, many): """Wrap result in envelope.""" if not many: return data result = dict( hits=dict( hits=data, total=self.context.get('total', len(data)) ) ) page = self.context.get('page') ...
python
{ "resource": "" }
q55625
parse_datetime
train
def parse_datetime(value): """Attempts to parse `value` into an instance of ``datetime.datetime``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string or datetime.datetime value. """ if not value: return None elif isinstanc...
python
{ "resource": "" }
q55626
parse_date
train
def parse_date(value): """Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value. """ if not value: return Non...
python
{ "resource": "" }
q55627
correct_word
train
def correct_word(word_string): ''' Finds all valid one and two letter corrections for word_string, returning the word with the highest relative probability as type str. ''' if word_string is None: return "" elif isinstance(word_string, str): return max(find_candidates(word_string...
python
{ "resource": "" }
q55628
find_candidates
train
def find_candidates(word_string): ''' Finds all potential words word_string could have intended to mean. If a word is not incorrectly spelled, it will return this word first, else if will look for one letter edits that are correct. If there are no valid one letter edits, it will perform a two letter edi...
python
{ "resource": "" }
q55629
find_word_prob
train
def find_word_prob(word_string, word_total=sum(WORD_DISTRIBUTION.values())): ''' Finds the relative probability of the word appearing given context of a base corpus. Returns this probability value as a float instance. ''' if word_string is None: return 0 elif isinstance(word_string, str)...
python
{ "resource": "" }
q55630
validate_words
train
def validate_words(word_list): ''' Checks for each edited word in word_list if that word is a valid english word.abs Returns all validated words as a set instance. ''' if word_list is None: return {} elif isinstance(word_list, list): if not word_list: return {} ...
python
{ "resource": "" }
q55631
search_star
train
def search_star(star): ''' It is also possible to query the stars by label, here is an example of querying for the star labeled as Sun. http://star-api.herokuapp.com/api/v1/stars/Sun ''' base_url = "http://star-api.herokuapp.com/api/v1/stars/" if not isinstance(star, str): raise Value...
python
{ "resource": "" }
q55632
search_exoplanet
train
def search_exoplanet(exoplanet): ''' It is also possible to query the exoplanets by label, here is an example of querying for the exoplanet labeled as 11 Com http://star-api.herokuapp.com/api/v1/exo_planets/11 Com ''' base_url = "http://star-api.herokuapp.com/api/v1/exo_planets/" if not isins...
python
{ "resource": "" }
q55633
search_local_galaxies
train
def search_local_galaxies(galaxy): ''' It is also possible to query the local galaxies by label, here is an example of querying for the local galaxy labeled IC 10 http://star-api.herokuapp.com/api/v1/local_groups/IC 10 ''' base_url = "http://star-api.herokuapp.com/api/v1/local_groups/" if no...
python
{ "resource": "" }
q55634
search_star_cluster
train
def search_star_cluster(cluster): ''' It is also possible to query the star clusters by label, here is an example of querying for the star cluster labeled Berkeley 59 http://star-api.herokuapp.com/api/v1/open_cluster/Berkeley 59 ''' base_url = "http://star-api.herokuapp.com/api/v1/open_cluster/" ...
python
{ "resource": "" }
q55635
JSGLexerRuleBlock.as_python
train
def as_python(self, name: str) -> str: """ Return the python representation """ if self._ruleTokens: pattern = "jsg.JSGPattern(r'{}'.format({}))".\ format(self._rulePattern, ', '.join(['{v}={v}.pattern'.format(v=v) for v in sorted(self._ruleTokens)])) else: ...
python
{ "resource": "" }
q55636
increment_slug
train
def increment_slug(s): """Generate next slug for a series. Some docstore types will use slugs (see above) as document ids. To support unique ids, we'll serialize them as follows: TestUserA/my-test TestUserA/my-test-2 TestUserA/my-test-3 ... """ slug_parts =...
python
{ "resource": "" }
q55637
underscored2camel_case
train
def underscored2camel_case(v): """converts ott_id to ottId.""" vlist = v.split('_') c = [] for n, el in enumerate(vlist): if el: if n == 0: c.append(el) else: c.extend([el[0].upper(), el[1:]]) return ''.join(c)
python
{ "resource": "" }
q55638
JSGContext.unvalidated_parm
train
def unvalidated_parm(self, parm: str) -> bool: """Return true if the pair name should be ignored :param parm: string part of pair string:value :return: True if it should be accepted """ return parm.startswith("_") or parm == self.TYPE or parm in self.IGNORE or \ (sel...
python
{ "resource": "" }
q55639
Registry.dispatch
train
def dispatch(self, request): """Takes a request and dispatches its data to a jsonrpc method. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: json output of the corresponding method :rtype: str .. versionadded:: 0.1.0 ...
python
{ "resource": "" }
q55640
Registry.register
train
def register(self, name, method, method_signature=None): """Registers a method with a given name and signature. :param name: The name used to register the method :type name: str :param method: The method to register :type method: function :param method_signature: The met...
python
{ "resource": "" }
q55641
Registry.method
train
def method(self, returns, **parameter_types): """Syntactic sugar for registering a method Example: >>> registry = Registry() >>> @registry.method(returns=int, x=int, y=int) ... def add(x, y): ... return x + y :param returns: The method's ret...
python
{ "resource": "" }
q55642
Registry._collect_parameters
train
def _collect_parameters(parameter_names, args, kwargs, defaults): """Creates a dictionary mapping parameters names to their values in the method call. :param parameter_names: The method's parameter names :type parameter_names: list[string] :param args: *args passed into the method ...
python
{ "resource": "" }
q55643
Registry._get_request_messages
train
def _get_request_messages(self, request): """Parses the request as a json message. :param request: a werkzeug request with json data :type request: werkzeug.wrappers.Request :return: The parsed json object :rtype: dict[str, object] """ data = request.get_data(as_...
python
{ "resource": "" }
q55644
Registry._check_request
train
def _check_request(self, msg): """Checks that the request json is well-formed. :param msg: The request's json data :type msg: dict[str, object] """ if "jsonrpc" not in msg: raise InvalidRequestError("'\"jsonrpc\": \"2.0\"' must be included.") if msg["jsonrpc"...
python
{ "resource": "" }
q55645
render_template_to_string
train
def render_template_to_string(input, _from_string=False, **context): """Render a template from the template folder with the given context. Code based on `<https://github.com/mitsuhiko/flask/blob/master/flask/templating.py>`_ :param input: the string template, or name of the template to be ...
python
{ "resource": "" }
q55646
save_and_validate_logo
train
def save_and_validate_logo(logo_stream, logo_filename, community_id): """Validate if communities logo is in limit size and save it.""" cfg = current_app.config logos_bucket_id = cfg['COMMUNITIES_BUCKET_UUID'] logo_max_size = cfg['COMMUNITIES_LOGO_MAX_SIZE'] logos_bucket = Bucket.query.get(logos_buc...
python
{ "resource": "" }
q55647
initialize_communities_bucket
train
def initialize_communities_bucket(): """Initialize the communities file bucket. :raises: `invenio_files_rest.errors.FilesException` """ bucket_id = UUID(current_app.config['COMMUNITIES_BUCKET_UUID']) if Bucket.query.get(bucket_id): raise FilesException("Bucket with UUID {} already exists."...
python
{ "resource": "" }
q55648
format_request_email_templ
train
def format_request_email_templ(increq, template, **ctx): """Format the email message element for inclusion request notification. Formats the message according to the provided template file, using some default fields from 'increq' object as default context. Arbitrary context can be provided as keywords ...
python
{ "resource": "" }
q55649
format_request_email_title
train
def format_request_email_title(increq, **ctx): """Format the email message title for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to...
python
{ "resource": "" }
q55650
format_request_email_body
train
def format_request_email_body(increq, **ctx): """Format the email message body for inclusion request notification. :param increq: Inclusion request object for which the request is made. :type increq: `invenio_communities.models.InclusionRequest` :param ctx: Optional extra context parameters passed to f...
python
{ "resource": "" }
q55651
send_community_request_email
train
def send_community_request_email(increq): """Signal for sending emails after community inclusion request.""" from flask_mail import Message from invenio_mail.tasks import send_email msg_body = format_request_email_body(increq) msg_title = format_request_email_title(increq) sender = current_app...
python
{ "resource": "" }
q55652
modifydocs
train
def modifydocs(a, b, desc=''): """ Convenience function for writing documentation. For a class method `a` that is essentially a wrapper for an outside function `b`, rope in the docstring from `b` and append to that of `a`. Also modify the docstring of `a` to get the indentation right. W...
python
{ "resource": "" }
q55653
tab_join
train
def tab_join(ToMerge, keycols=None, nullvals=None, renamer=None, returnrenaming=False, Names=None): ''' Database-join for tabular arrays. Wrapper for :func:`tabular.spreadsheet.join` that deals with the coloring and returns the result as a tabarray. Method calls:: data ...
python
{ "resource": "" }
q55654
tabarray.extract
train
def extract(self): """ Creates a copy of this tabarray in the form of a numpy ndarray. Useful if you want to do math on array elements, e.g. if you have a subset of the columns that are all numerical, you can construct a numerical matrix and do matrix operations. """ ...
python
{ "resource": "" }
q55655
tabarray.addrecords
train
def addrecords(self, new): """ Append one or more records to the end of the array. Method wraps:: tabular.spreadsheet.addrecords(self, new) """ data = spreadsheet.addrecords(self,new) data = data.view(tabarray) data.coloring = self.coloring ...
python
{ "resource": "" }
q55656
tabarray.addcols
train
def addcols(self, cols, names=None): """ Add one or more new columns. Method wraps:: tabular.spreadsheet.addcols(self, cols, names) """ data = spreadsheet.addcols(self, cols, names) data = data.view(tabarray) data.coloring = self.coloring ...
python
{ "resource": "" }
q55657
tabarray.renamecol
train
def renamecol(self, old, new): """ Rename column or color in-place. Method wraps:: tabular.spreadsheet.renamecol(self, old, new) """ spreadsheet.renamecol(self,old,new) for x in self.coloring.keys(): if old in self.coloring[x]: ...
python
{ "resource": "" }
q55658
tabarray.colstack
train
def colstack(self, new, mode='abort'): """ Horizontal stacking for tabarrays. Stack tabarray(s) in `new` to the right of `self`. **See also** :func:`tabular.tabarray.tab_colstack`, :func:`tabular.spreadsheet.colstack` """ if isinstance...
python
{ "resource": "" }
q55659
tabarray.rowstack
train
def rowstack(self, new, mode='nulls'): """ Vertical stacking for tabarrays. Stack tabarray(s) in `new` below `self`. **See also** :func:`tabular.tabarray.tab_rowstack`, :func:`tabular.spreadsheet.rowstack` """ if isinstance(new,list): ...
python
{ "resource": "" }
q55660
tabarray.aggregate
train
def aggregate(self, On=None, AggFuncDict=None, AggFunc=None, AggList = None, returnsort=False,KeepOthers=True, keyfuncdict=None): """ Aggregate a tabarray on columns for given functions. Method wraps:: tabular.spreadsheet.aggregate(self, On, AggFuncDict, AggFu...
python
{ "resource": "" }
q55661
tabarray.aggregate_in
train
def aggregate_in(self, On=None, AggFuncDict=None, AggFunc=None, AggList=None, interspersed=True): """ Aggregate a tabarray and include original data in the result. See the :func:`aggregate` method. Method wraps:: tabular.summarize.aggregate_in(self, On...
python
{ "resource": "" }
q55662
tabarray.pivot
train
def pivot(self, a, b, Keep=None, NullVals=None, order = None, prefix='_'): """ Pivot with `a` as the row axis and `b` values as the column axis. Method wraps:: tabular.spreadsheet.pivot(X, a, b, Keep) """ [data,coloring] = spreadsheet.pivot(X=self, a=a, b=b, Ke...
python
{ "resource": "" }
q55663
tabarray.join
train
def join(self, ToMerge, keycols=None, nullvals=None, renamer=None, returnrenaming=False, selfname=None, Names=None): """ Wrapper for spreadsheet.join, but handles coloring attributes. The `selfname` argument allows naming of `self` to be used if `ToMerge` is a dictionary....
python
{ "resource": "" }
q55664
tabarray.argsort
train
def argsort(self, axis=-1, kind='quicksort', order=None): """ Returns the indices that would sort an array. .. note:: This method wraps `numpy.argsort`. This documentation is modified from that of `numpy.argsort`. Perform an indirect sort along the gi...
python
{ "resource": "" }
q55665
JSGPattern.matches
train
def matches(self, txt: str) -> bool: """Determine whether txt matches pattern :param txt: text to check :return: True if match """ # rval = ref.getText()[1:-1].encode('utf-8').decode('unicode-escape') if r'\\u' in self.pattern_re.pattern: txt = txt.encode('ut...
python
{ "resource": "" }
q55666
Point2HexColor
train
def Point2HexColor(a, lfrac, tfrac): """ Return web-safe hex triplets. """ [H,S,V] = [math.floor(360 * a), lfrac, tfrac] RGB = hsvToRGB(H, S, V) H = [hex(int(math.floor(255 * x))) for x in RGB] HEX = [a[a.find('x') + 1:] for a in H] HEX = ['0' + h if len(h) == 1 else h for h in HEX]...
python
{ "resource": "" }
q55667
warn_from_util_logger
train
def warn_from_util_logger(msg): """Only to be used in this file and peyotl.utility.get_config""" global _LOG # This check is necessary to avoid infinite recursion when called from get_config, because # the _read_logging_conf can require reading a conf file. if _LOG is None and _LOGGING_CONF is Non...
python
{ "resource": "" }
q55668
PIFX.state_delta
train
def state_delta(self, selector='all', power=None, duration=1.0, infrared=None, hue=None, saturation=None, brightness=None, kelvin=None): """Given a state delta, apply the modifications to lights' state over a given period of time. selector: required String The select...
python
{ "resource": "" }
q55669
PIFX.breathe_lights
train
def breathe_lights(self, color, selector='all', from_color=None, period=1.0, cycles=1.0, persist=False, power_on=True, peak=0.5): """Perform breathe effect on lights. selector: String The selector to limit which lights will run the effect. default: all c...
python
{ "resource": "" }
q55670
PIFX.cycle_lights
train
def cycle_lights(self, states, defaults, direction='forward', selector='all'): """Cycle through list of effects. Provide array states as a list of dictionaries with set_state arguments. See http://api.developer.lifx.com/docs/cycle selector: String The selector to li...
python
{ "resource": "" }
q55671
PIFX.activate_scene
train
def activate_scene(self, scene_uuid, duration=1.0): """Activate a scene. See http://api.developer.lifx.com/docs/activate-scene scene_uuid: required String The UUID for the scene you wish to activate duration: Double The time in seconds to spend performing the s...
python
{ "resource": "" }
q55672
count_num_trees
train
def count_num_trees(nexson, nexson_version=None): """Returns the number of trees summed across all tree groups. """ if nexson_version is None: nexson_version = detect_nexson_version(nexson) nex = get_nexml_el(nexson) num_trees_by_group = [] if _is_by_id_hbf(nexson_version): f...
python
{ "resource": "" }
q55673
TreeCollectionStore
train
def TreeCollectionStore(repos_dict=None, repos_par=None, with_caching=True, assumed_doc_version=None, git_ssh=None, pkey=None, git_action_class=TreeCollectionsGitAction, ...
python
{ "resource": "" }
q55674
_TreeCollectionStore._slugify_internal_collection_name
train
def _slugify_internal_collection_name(self, json_repr): """Parse the JSON, find its name, return a slug of its name""" collection = self._coerce_json_to_collection(json_repr) if collection is None: return None internal_name = collection['name'] return slugify(internal...
python
{ "resource": "" }
q55675
discover_roku
train
def discover_roku(): """ Search LAN for available Roku devices. Returns a Roku object. """ print("Searching for Roku devices within LAN ...") rokus = Roku.discover() if not rokus: print("Unable to discover Roku devices. " + "Try again, or manually specify the IP address with " + ...
python
{ "resource": "" }
q55676
ot_tnrs_match_names
train
def ot_tnrs_match_names(name_list, context_name=None, do_approximate_matching=True, include_dubious=False, include_deprecated=True, tnrs_wrapper=None): """Uses a peyotl wrapper around an Open Tree...
python
{ "resource": "" }
q55677
_objectify
train
def _objectify(field, value, ns_info): """Make `value` suitable for a binding object. If `value` is an Entity, call to_obj() on it. Otherwise, pass it off to the TypedField for an appropriate value. """ if (getattr(field.type_, "_treat_none_as_empty_list", False) and value is None): ...
python
{ "resource": "" }
q55678
_dictify
train
def _dictify(field, value): """Make `value` suitable for a dictionary. * If `value` is an Entity, call to_dict() on it. * If value is a timestamp, turn it into a string value. * If none of the above are satisfied, return the input value """ if value is None: return None elif field.t...
python
{ "resource": "" }
q55679
EntityFactory.from_dict
train
def from_dict(cls, cls_dict, fallback_xsi_type=None): """Parse the dictionary and return an Entity instance. This will attempt to extract type information from the input dictionary and pass it to entity_class to resolve the correct class for the type. Args: cls_dict...
python
{ "resource": "" }
q55680
EntityFactory.from_obj
train
def from_obj(cls, cls_obj): """Parse the generateDS object and return an Entity instance. This will attempt to extract type information from the input object and pass it to entity_class to resolve the correct class for the type. Args: cls_obj: A generateDS object. ...
python
{ "resource": "" }
q55681
Entity.typed_fields
train
def typed_fields(cls): """Return a tuple of this entity's TypedFields.""" # Checking cls._typed_fields could return a superclass _typed_fields # value. So we check our class __dict__ which does not include # inherited attributes. klassdict = cls.__dict__ try: ...
python
{ "resource": "" }
q55682
Entity.to_obj
train
def to_obj(self, ns_info=None): """Convert to a GenerateDS binding object. Subclasses can override this function. Returns: An instance of this Entity's ``_binding_class`` with properties set from this Entity. """ if ns_info: ns_info.collect(s...
python
{ "resource": "" }
q55683
Entity.to_dict
train
def to_dict(self): """Convert to a ``dict`` Subclasses can override this function. Returns: Python dict with keys set from this Entity. """ entity_dict = {} for field, val in six.iteritems(self._fields): if field.multiple: if val...
python
{ "resource": "" }
q55684
Entity.from_json
train
def from_json(cls, json_doc): """Parse a JSON string and build an entity.""" try: d = json.load(json_doc) except AttributeError: # catch the read() error d = json.loads(json_doc) return cls.from_dict(d)
python
{ "resource": "" }
q55685
EntityList._multiple_field
train
def _multiple_field(cls): """Return the "multiple" TypedField associated with this EntityList. This also lazily sets the ``_entitylist_multiplefield`` value if it hasn't been set yet. This is set to a tuple containing one item because if we set the class attribute to the TypedField, we ...
python
{ "resource": "" }
q55686
NamespaceCollector._finalize_namespaces
train
def _finalize_namespaces(self, ns_dict=None): """Returns a dictionary of namespaces to be exported with an XML document. This loops over all the namespaces that were discovered and built during the execution of ``collect()`` and ``_parse_collected_classes()`` and attempts to mer...
python
{ "resource": "" }
q55687
CommunitiesResource.get
train
def get(self, query, sort, page, size): """Get a list of all the communities. .. http:get:: /communities/(string:id) Returns a JSON list with all the communities. **Request**: .. sourcecode:: http GET /communities HTTP/1.1 Accept: appl...
python
{ "resource": "" }
q55688
CommunityDetailsResource.get
train
def get(self, community_id): """Get the details of the specified community. .. http:get:: /communities/(string:id) Returns a JSON dictionary with the details of the specified community. **Request**: .. sourcecode:: http GET /communities/co...
python
{ "resource": "" }
q55689
Phylesystem
train
def Phylesystem(repos_dict=None, repos_par=None, with_caching=True, repo_nexml2json=None, git_ssh=None, pkey=None, git_action_class=PhylesystemGitAction, mirror_info=None, new_study_prefix=Non...
python
{ "resource": "" }
q55690
convert_html_entities
train
def convert_html_entities(text_string): ''' Converts HTML5 character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-str...
python
{ "resource": "" }
q55691
convert_ligatures
train
def convert_ligatures(text_string): ''' Coverts Latin character references within text_string to their corresponding unicode characters and returns converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a string or No...
python
{ "resource": "" }
q55692
correct_spelling
train
def correct_spelling(text_string): ''' Splits string and converts words not found within a pre-built dictionary to their most likely actual word based on a relative probability dictionary. Returns edited string as type str. Keyword argument: - text_string: string instance Exceptions raise...
python
{ "resource": "" }
q55693
create_sentence_list
train
def create_sentence_list(text_string): ''' Splits text_string into a list of sentences based on NLTK's english.pickle tokenizer, and returns said list as type list of str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argumen...
python
{ "resource": "" }
q55694
keyword_tokenize
train
def keyword_tokenize(text_string): ''' Extracts keywords from text_string using NLTK's list of English stopwords, ignoring words of a length smaller than 3, and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs sh...
python
{ "resource": "" }
q55695
lemmatize
train
def lemmatize(text_string): ''' Returns base from of text_string using NLTK's WordNetLemmatizer as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None ...
python
{ "resource": "" }
q55696
lowercase
train
def lowercase(text_string): ''' Converts text_string into lowercase and returns the converted string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or text_string ...
python
{ "resource": "" }
q55697
preprocess_text
train
def preprocess_text(text_string, function_list): ''' Given each function within function_list, applies the order of functions put forward onto text_string, returning the processed string as type str. Keyword argument: - function_list: list of functions available in preprocessing.text - text_st...
python
{ "resource": "" }
q55698
remove_esc_chars
train
def remove_esc_chars(text_string): ''' Removes any escape character within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is None or...
python
{ "resource": "" }
q55699
remove_numbers
train
def remove_numbers(text_string): ''' Removes any digit value discovered within text_string and returns the new string as type str. Keyword argument: - text_string: string instance Exceptions raised: - InputError: occurs should a non-string argument be passed ''' if text_string is Non...
python
{ "resource": "" }