_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q13600
_to_ufo_kerning
train
def _to_ufo_kerning(self, ufo, kerning_data): """Add .glyphs kerning to an UFO.""" warning_msg = "Non-existent glyph class %s found in kerning rules." for left, pairs in kerning_data.items(): match = re.match(r"@MMK_L_(.+)", left) left_is_class = bool(match) if left_is_class: ...
python
{ "resource": "" }
q13601
to_glyphs_kerning
train
def to_glyphs_kerning(self): """Add UFO kerning to GSFont.""" for master_id, source in self._sources.items(): for (left, right), value in source.font.kerning.items(): left_match = UFO_KERN_GROUP_PATTERN.match(left) right_match = UFO_KERN_GROUP_PATTERN.match(right) if ...
python
{ "resource": "" }
q13602
_set_default_params
train
def _set_default_params(ufo): """ Set Glyphs.app's default parameters when different from ufo2ft ones. """ for _, ufo_name, default_value in DEFAULT_PARAMETERS: if getattr(ufo.info, ufo_name) is None: if isinstance(default_value, list): # Prevent problem if the same defau...
python
{ "resource": "" }
q13603
GlyphsObjectProxy.get_custom_value
train
def get_custom_value(self, key): """Return the first and only custom parameter matching the given name.""" self._handled.add(key) values = self._lookup[key] if len(values) > 1: raise RuntimeError( "More than one value for this customParameter: {}".format(key) ...
python
{ "resource": "" }
q13604
GlyphsObjectProxy.get_custom_values
train
def get_custom_values(self, key): """Return a set of values for the given customParameter name.""" self._handled.add(key) return self._lookup[key]
python
{ "resource": "" }
q13605
GlyphsObjectProxy.set_custom_value
train
def set_custom_value(self, key, value): """Set one custom parameter with the given value. We assume that the list of custom parameters does not already contain the given parameter so we only append. """ self._owner.customParameters.append( self._glyphs_module.GSCustom...
python
{ "resource": "" }
q13606
GlyphsObjectProxy.set_custom_values
train
def set_custom_values(self, key, values): """Set several values for the customParameter with the given key. We append one GSCustomParameter per value. """ for value in values: self.set_custom_value(key, value)
python
{ "resource": "" }
q13607
GSCustomParameter.setValue
train
def setValue(self, value): """Cast some known data in custom parameters.""" if self.name in self._CUSTOM_INT_PARAMS: value = int(value) elif self.name in self._CUSTOM_FLOAT_PARAMS: value = float(value) elif self.name in self._CUSTOM_BOOL_PARAMS: value ...
python
{ "resource": "" }
q13608
GSFontMaster.name
train
def name(self, name): """This function will take the given name and split it into components weight, width, customName, and possibly the full name. This is what Glyphs 1113 seems to be doing, approximately. """ weight, width, custom_name = self._splitName(name) self.set_a...
python
{ "resource": "" }
q13609
GSFontMaster.set_all_name_components
train
def set_all_name_components(self, name, weight, width, custom_name): """This function ensures that after being called, the master.name, master.weight, master.width, and master.customName match the given values. """ self.weight = weight or "Regular" self.width = width or "...
python
{ "resource": "" }
q13610
GSNode._encode_dict_as_string
train
def _encode_dict_as_string(value): """Takes the PLIST string of a dict, and returns the same string encoded such that it can be included in the string representation of a GSNode.""" # Strip the first and last newlines if value.startswith("{\n"): value = "{" + value[2:...
python
{ "resource": "" }
q13611
GSNode._indices
train
def _indices(self): """Find the path_index and node_index that identify the given node.""" path = self.parent layer = path.parent for path_index in range(len(layer.paths)): if path == layer.paths[path_index]: for node_index in range(len(path.nodes)): ...
python
{ "resource": "" }
q13612
GSLayer._find_node_by_indices
train
def _find_node_by_indices(self, point): """"Find the GSNode that is refered to by the given indices. See GSNode::_indices() """ path_index, node_index = point path = self.paths[int(path_index)] node = path.nodes[int(node_index)] return node
python
{ "resource": "" }
q13613
GSLayer.background
train
def background(self): """Only a getter on purpose. See the tests.""" if self._background is None: self._background = GSBackgroundLayer() self._background._foreground = self return self._background
python
{ "resource": "" }
q13614
to_ufo_propagate_font_anchors
train
def to_ufo_propagate_font_anchors(self, ufo): """Copy anchors from parent glyphs' components to the parent.""" processed = set() for glyph in ufo: _propagate_glyph_anchors(self, ufo, glyph, processed)
python
{ "resource": "" }
q13615
_propagate_glyph_anchors
train
def _propagate_glyph_anchors(self, ufo, parent, processed): """Propagate anchors for a single parent glyph.""" if parent.name in processed: return processed.add(parent.name) base_components = [] mark_components = [] anchor_names = set() to_add = {} for component in parent.compo...
python
{ "resource": "" }
q13616
_adjust_anchors
train
def _adjust_anchors(anchor_data, ufo, component): """Adjust anchors to which a mark component may have been attached.""" glyph = ufo[component.baseGlyph] t = Transform(*component.transformation) for anchor in glyph.anchors: # only adjust if this anchor has data and the component also contains ...
python
{ "resource": "" }
q13617
to_ufo_glyph_anchors
train
def to_ufo_glyph_anchors(self, glyph, anchors): """Add .glyphs anchors to a glyph.""" for anchor in anchors: x, y = anchor.position anchor_dict = {"name": anchor.name, "x": x, "y": y} glyph.appendAnchor(anchor_dict)
python
{ "resource": "" }
q13618
to_glyphs_glyph_anchors
train
def to_glyphs_glyph_anchors(self, ufo_glyph, layer): """Add UFO glif anchors to a GSLayer.""" for ufo_anchor in ufo_glyph.anchors: anchor = self.glyphs_module.GSAnchor() anchor.name = ufo_anchor.name anchor.position = Point(ufo_anchor.x, ufo_anchor.y) layer.anchors.append(anchor)
python
{ "resource": "" }
q13619
cached_property
train
def cached_property(func): """Special property decorator that caches the computed property value in the object's instance dict the first time it is accessed. """ name = func.__name__ doc = func.__doc__ def getter(self, name=name): try: return self.__dict__[name] ...
python
{ "resource": "" }
q13620
cos_sin_deg
train
def cos_sin_deg(deg): """Return the cosine and sin for the given angle in degrees, with special-case handling of multiples of 90 for perfect right angles """ deg = deg % 360.0 if deg == 90.0: return 0.0, 1.0 elif deg == 180.0: return -1.0, 0 elif deg == 270.0: ret...
python
{ "resource": "" }
q13621
Affine.scale
train
def scale(cls, *scaling): """Create a scaling transform from a scalar or vector. :param scaling: The scaling factor. A scalar value will scale in both dimensions equally. A vector scaling value scales the dimensions independently. :type scaling: float or sequence ...
python
{ "resource": "" }
q13622
Affine.shear
train
def shear(cls, x_angle=0, y_angle=0): """Create a shear transform along one or both axes. :param x_angle: Angle in degrees to shear along the x-axis. :type x_angle: float :param y_angle: Angle in degrees to shear along the y-axis. :type y_angle: float :rtype: Affine ...
python
{ "resource": "" }
q13623
Affine.rotation
train
def rotation(cls, angle, pivot=None): """Create a rotation transform at the specified angle, optionally about the specified pivot point. :param angle: Rotation angle in degrees :type angle: float :param pivot: Point to rotate about, if omitted the rotation is about t...
python
{ "resource": "" }
q13624
Affine.determinant
train
def determinant(self): """The determinant of the transform matrix. This value is equal to the area scaling factor when the transform is applied to a shape. """ a, b, c, d, e, f, g, h, i = self return a * e - b * d
python
{ "resource": "" }
q13625
Affine.is_rectilinear
train
def is_rectilinear(self): """True if the transform is rectilinear, i.e., whether a shape would remain axis-aligned, within rounding limits, after applying the transform. """ a, b, c, d, e, f, g, h, i = self return (abs(a) < EPSILON and abs(e) < EPSILON) or ( a...
python
{ "resource": "" }
q13626
Affine.is_conformal
train
def is_conformal(self): """True if the transform is conformal, i.e., if angles between points are preserved after applying the transform, within rounding limits. This implies that the transform has no effective shear. """ a, b, c, d, e, f, g, h, i = self return abs(a * b ...
python
{ "resource": "" }
q13627
Affine.is_orthonormal
train
def is_orthonormal(self): """True if the transform is orthonormal, which means that the transform represents a rigid motion, which has no effective scaling or shear. Mathematically, this means that the axis vectors of the transform matrix are perpendicular and unit-length. Applying an ...
python
{ "resource": "" }
q13628
Affine.column_vectors
train
def column_vectors(self): """The values of the transform as three 2D column vectors""" a, b, c, d, e, f, _, _, _ = self return (a, d), (b, e), (c, f)
python
{ "resource": "" }
q13629
Affine.almost_equals
train
def almost_equals(self, other): """Compare transforms for approximate equality. :param other: Transform being compared. :type other: Affine :return: True if absolute difference between each element of each respective tranform matrix < ``EPSILON``. """ for i i...
python
{ "resource": "" }
q13630
Affine.itransform
train
def itransform(self, seq): """Transform a sequence of points or vectors in place. :param seq: Mutable sequence of :class:`~planar.Vec2` to be transformed. :returns: None, the input sequence is mutated in place. """ if self is not identity and self != identity: ...
python
{ "resource": "" }
q13631
_lookup_attributes
train
def _lookup_attributes(glyph_name, data): """Look up glyph attributes in data by glyph name, alternative name or production name in order or return empty dictionary. Look up by alternative and production names for legacy projects and because of issue #232. """ attributes = ( data.names....
python
{ "resource": "" }
q13632
_agl_compliant_name
train
def _agl_compliant_name(glyph_name): """Return an AGL-compliant name string or None if we can't make one.""" MAX_GLYPH_NAME_LENGTH = 63 clean_name = re.sub("[^0-9a-zA-Z_.]", "", glyph_name) if len(clean_name) > MAX_GLYPH_NAME_LENGTH: return None return clean_name
python
{ "resource": "" }
q13633
_translate_category
train
def _translate_category(glyph_name, unicode_category): """Return a translation from Unicode category letters to Glyphs categories.""" DEFAULT_CATEGORIES = { None: ("Letter", None), "Cc": ("Separator", None), "Cf": ("Separator", "Format"), "Cn": ("Symbol", None), "Co":...
python
{ "resource": "" }
q13634
_construct_production_name
train
def _construct_production_name(glyph_name, data=None): """Return the production name for a glyph name from the GlyphData.xml database according to the AGL specification. This should be run only if there is no official entry with a production name in it. Handles single glyphs (e.g. "brevecomb") and...
python
{ "resource": "" }
q13635
GlyphData.from_files
train
def from_files(cls, *glyphdata_files): """Return GlyphData holding data from a list of XML file paths.""" name_mapping = {} alt_name_mapping = {} production_name_mapping = {} for glyphdata_file in glyphdata_files: glyph_data = xml.etree.ElementTree.parse(glyphdata_fi...
python
{ "resource": "" }
q13636
load_to_ufos
train
def load_to_ufos( file_or_path, include_instances=False, family_name=None, propagate_anchors=True ): """Load an unpacked .glyphs object to UFO objects.""" if hasattr(file_or_path, "read"): font = load(file_or_path) else: with open(file_or_path, "r", encoding="utf-8") as ifile: ...
python
{ "resource": "" }
q13637
build_masters
train
def build_masters( filename, master_dir, designspace_instance_dir=None, designspace_path=None, family_name=None, propagate_anchors=True, minimize_glyphs_diffs=False, normalize_ufos=False, create_background_layers=False, generate_GDEF=True, store_editor_state=True, ): """W...
python
{ "resource": "" }
q13638
glyphs2ufo
train
def glyphs2ufo(options): """Converts a Glyphs.app source file into UFO masters and a designspace file.""" if options.output_dir is None: options.output_dir = os.path.dirname(options.glyphs_file) or "." if options.designspace_path is None: options.designspace_path = os.path.join( ...
python
{ "resource": "" }
q13639
ufo2glyphs
train
def ufo2glyphs(options): """Convert one designspace file or one or more UFOs to a Glyphs.app source file.""" import fontTools.designspaceLib import defcon sources = options.designspace_file_or_UFOs designspace_file = None if ( len(sources) == 1 and sources[0].endswith(".designsp...
python
{ "resource": "" }
q13640
_has_manual_kern_feature
train
def _has_manual_kern_feature(font): """Return true if the GSFont contains a manually written 'kern' feature.""" return any(f for f in font.features if f.name == "kern" and not f.automatic)
python
{ "resource": "" }
q13641
to_ufo_family_user_data
train
def to_ufo_family_user_data(self, ufo): """Set family-wide user data as Glyphs does.""" if not self.use_designspace: ufo.lib[FONT_USER_DATA_KEY] = dict(self.font.userData)
python
{ "resource": "" }
q13642
to_ufo_master_user_data
train
def to_ufo_master_user_data(self, ufo, master): """Set master-specific user data as Glyphs does.""" for key in master.userData.keys(): if _user_data_has_no_special_meaning(key): ufo.lib[key] = master.userData[key] # Restore UFO data files. This code assumes that all paths are POSIX path...
python
{ "resource": "" }
q13643
to_glyphs_family_user_data_from_designspace
train
def to_glyphs_family_user_data_from_designspace(self): """Set the GSFont userData from the designspace family-wide lib data.""" target_user_data = self.font.userData for key, value in self.designspace.lib.items(): if key == UFO2FT_FEATURE_WRITERS_KEY and value == DEFAULT_FEATURE_WRITERS: ...
python
{ "resource": "" }
q13644
to_glyphs_family_user_data_from_ufo
train
def to_glyphs_family_user_data_from_ufo(self, ufo): """Set the GSFont userData from the UFO family-wide lib data.""" target_user_data = self.font.userData try: for key, value in ufo.lib[FONT_USER_DATA_KEY].items(): # Existing values taken from the designspace lib take precedence ...
python
{ "resource": "" }
q13645
to_glyphs_master_user_data
train
def to_glyphs_master_user_data(self, ufo, master): """Set the GSFontMaster userData from the UFO master-specific lib data.""" target_user_data = master.userData for key, value in ufo.lib.items(): if _user_data_has_no_special_meaning(key): target_user_data[key] = value # Save UFO dat...
python
{ "resource": "" }
q13646
to_ufos
train
def to_ufos( font, include_instances=False, family_name=None, propagate_anchors=True, ufo_module=defcon, minimize_glyphs_diffs=False, generate_GDEF=True, store_editor_state=True, ): """Take a GSFont object and convert it into one UFO per master. Takes in data as Glyphs.app-compa...
python
{ "resource": "" }
q13647
to_glyphs
train
def to_glyphs(ufos_or_designspace, glyphs_module=classes, minimize_ufo_diffs=False): """ Take a list of UFOs or a single DesignspaceDocument with attached UFOs and converts it into a GSFont object. The GSFont object is in-memory, it's up to the user to write it to the disk if needed. This shou...
python
{ "resource": "" }
q13648
FlaskRestyPlugin.path_helper
train
def path_helper(self, path, view, **kwargs): """Path helper for Flask-RESTy views. :param view: An `ApiView` object. """ super(FlaskRestyPlugin, self).path_helper( path=path, view=view, **kwargs ) resource = self.get_state().views[vie...
python
{ "resource": "" }
q13649
user_loc_string_to_value
train
def user_loc_string_to_value(axis_tag, user_loc): """Go from Glyphs UI strings to user space location. Returns None if the string is invalid. >>> user_loc_string_to_value('wght', 'ExtraLight') 200 >>> user_loc_string_to_value('wdth', 'SemiCondensed') 87.5 >>> user_loc_string_to_value('wdth'...
python
{ "resource": "" }
q13650
get_regular_master
train
def get_regular_master(font): """Find the "regular" master among the GSFontMasters. Tries to find the master with the passed 'regularName'. If there is no such master or if regularName is None, tries to find a base style shared between all masters (defaulting to "Regular"), and then tries to find a...
python
{ "resource": "" }
q13651
find_base_style
train
def find_base_style(masters): """Find a base style shared between all masters. Return empty string if none is found. """ if not masters: return "" base_style = (masters[0].name or "").split() for master in masters: style = master.name.split() base_style = [s for s in styl...
python
{ "resource": "" }
q13652
interp
train
def interp(mapping, x): """Compute the piecewise linear interpolation given by mapping for input x. >>> interp(((1, 1), (2, 4)), 1.5) 2.5 """ mapping = sorted(mapping) if len(mapping) == 1: xa, ya = mapping[0] if xa == x: return ya return x for (xa, ya), ...
python
{ "resource": "" }
q13653
AxisDefinition.get_user_loc
train
def get_user_loc(self, master_or_instance): """Get the user location of a Glyphs master or instance. Masters in Glyphs can have a user location in the "Axis Location" custom parameter. The user location is what the user sees on the slider in his variable-font-enabled UI. For wei...
python
{ "resource": "" }
q13654
AxisDefinition.set_user_loc
train
def set_user_loc(self, master_or_instance, value): """Set the user location of a Glyphs master or instance.""" if hasattr(master_or_instance, "instanceInterpolations"): # The following code is only valid for instances. # Masters also the keys `weight` and `width` but they should ...
python
{ "resource": "" }
q13655
SanitizedHTML._deserialize
train
def _deserialize(self, value, attr, data): """Deserialize string by sanitizing HTML.""" value = super(SanitizedHTML, self)._deserialize(value, attr, data) return bleach.clean( value, tags=self.tags, attributes=self.attrs, strip=True, ).stri...
python
{ "resource": "" }
q13656
build_default_endpoint_prefixes
train
def build_default_endpoint_prefixes(records_rest_endpoints): """Build the default_endpoint_prefixes map.""" pid_types = set() guessed = set() endpoint_prefixes = {} for key, endpoint in records_rest_endpoints.items(): pid_type = endpoint['pid_type'] pid_types.add(pid_type) i...
python
{ "resource": "" }
q13657
load_or_import_from_config
train
def load_or_import_from_config(key, app=None, default=None): """Load or import value from config. :returns: The loaded value. """ app = app or current_app imp = app.config.get(key) return obj_or_import_string(imp, default=default)
python
{ "resource": "" }
q13658
check_elasticsearch
train
def check_elasticsearch(record, *args, **kwargs): """Return permission that check if the record exists in ES index. :params record: A record object. :returns: A object instance with a ``can()`` method. """ def can(self): """Try to search for given record.""" search = request._method...
python
{ "resource": "" }
q13659
LazyPIDValue.data
train
def data(self): """Resolve PID from a value and return a tuple with PID and the record. :returns: A tuple with the PID and the record resolved. """ try: return self.resolver.resolve(self.value) except PIDDoesNotExistError as pid_error: raise PIDDoesNotExi...
python
{ "resource": "" }
q13660
create_error_handlers
train
def create_error_handlers(blueprint, error_handlers_registry=None): """Create error handlers on blueprint. :params blueprint: Records API blueprint. :params error_handlers_registry: Configuration of error handlers per exception or HTTP status code and view name. The dictionary has the foll...
python
{ "resource": "" }
q13661
create_blueprint
train
def create_blueprint(endpoints): """Create Invenio-Records-REST blueprint. :params endpoints: Dictionary representing the endpoints configuration. :returns: Configured blueprint. """ endpoints = endpoints or {} blueprint = Blueprint( 'invenio_records_rest', __name__, ur...
python
{ "resource": "" }
q13662
pass_record
train
def pass_record(f): """Decorator to retrieve persistent identifier and record. This decorator will resolve the ``pid_value`` parameter from the route pattern and resolve it to a PID and a record, which are then available in the decorated function as ``pid`` and ``record`` kwargs respectively. """ ...
python
{ "resource": "" }
q13663
verify_record_permission
train
def verify_record_permission(permission_factory, record): """Check that the current user has the required permissions on record. In case the permission check fails, an Flask abort is launched. If the user was previously logged-in, a HTTP error 403 is returned. Otherwise, is returned a HTTP error 401. ...
python
{ "resource": "" }
q13664
need_record_permission
train
def need_record_permission(factory_name): """Decorator checking that the user has the required permissions on record. :param factory_name: name of the permission factory. """ def need_record_permission_builder(f): @wraps(f) def need_record_permission_decorator(self, record=None, *args, ...
python
{ "resource": "" }
q13665
RecordsListOptionsResource.get
train
def get(self): """Get options.""" opts = current_app.config['RECORDS_REST_SORT_OPTIONS'].get( self.search_index) sort_fields = [] if opts: for key, item in sorted(opts.items(), key=lambda x: x[1]['order']): sort_fields.append( ...
python
{ "resource": "" }
q13666
RecordsListResource.get
train
def get(self, **kwargs): """Search records. Permissions: the `list_permission_factory` permissions are checked. :returns: Search result containing hits and aggregations as returned by invenio-search. """ default_results_size = current_app.config.ge...
python
{ "resource": "" }
q13667
RecordsListResource.post
train
def post(self, **kwargs): """Create a record. Permissions: ``create_permission_factory`` Procedure description: #. First of all, the `create_permission_factory` permissions are checked. #. Then, the record is deserialized by the proper loader. #. A second...
python
{ "resource": "" }
q13668
RecordResource.get
train
def get(self, pid, record, **kwargs): """Get a record. Permissions: ``read_permission_factory`` Procedure description: #. The record is resolved reading the pid value from the url. #. The ETag and If-Modifed-Since is checked. #. The HTTP response is built with the he...
python
{ "resource": "" }
q13669
RecordResource.patch
train
def patch(self, pid, record, **kwargs): """Modify a record. Permissions: ``update_permission_factory`` The data should be a JSON-patch, which will be applied to the record. Requires header ``Content-Type: application/json-patch+json``. Procedure description: #. The re...
python
{ "resource": "" }
q13670
RecordResource.put
train
def put(self, pid, record, **kwargs): """Replace a record. Permissions: ``update_permission_factory`` The body should be a JSON object, which will fully replace the current record metadata. Procedure description: #. The ETag is checked. #. The record is updat...
python
{ "resource": "" }
q13671
SuggestResource.get
train
def get(self, **kwargs): """Get suggestions.""" completions = [] size = request.values.get('size', type=int) for k in self.suggesters.keys(): val = request.values.get(k) if val: # Get completion suggestions opts = copy.deepcopy(sel...
python
{ "resource": "" }
q13672
DateString._serialize
train
def _serialize(self, value, attr, obj): """Serialize an ISO8601-formatted date.""" try: return super(DateString, self)._serialize( arrow.get(value).date(), attr, obj) except ParserError: return missing
python
{ "resource": "" }
q13673
DateString._deserialize
train
def _deserialize(self, value, attr, data): """Deserialize an ISO8601-formatted date.""" return super(DateString, self)._deserialize(value, attr, data).isoformat()
python
{ "resource": "" }
q13674
PreprocessorMixin.preprocess_record
train
def preprocess_record(self, pid, record, links_factory=None, **kwargs): """Prepare a record and persistent identifier for serialization.""" links_factory = links_factory or (lambda x, record=None, **k: dict()) metadata = copy.deepcopy(record.replace_refs()) if self.replace_refs \ els...
python
{ "resource": "" }
q13675
PreprocessorMixin.preprocess_search_hit
train
def preprocess_search_hit(pid, record_hit, links_factory=None, **kwargs): """Prepare a record hit from Elasticsearch for serialization.""" links_factory = links_factory or (lambda x, **k: dict()) record = dict( pid=pid, metadata=record_hit['_source'], links=li...
python
{ "resource": "" }
q13676
_flatten_marshmallow_errors
train
def _flatten_marshmallow_errors(errors): """Flatten marshmallow errors.""" res = [] for field, error in errors.items(): if isinstance(error, list): res.append( dict(field=field, message=' '.join([str(x) for x in error]))) elif isinstance(error, dict): ...
python
{ "resource": "" }
q13677
marshmallow_loader
train
def marshmallow_loader(schema_class): """Marshmallow loader for JSON requests.""" def json_loader(): request_json = request.get_json() context = {} pid_data = request.view_args.get('pid_value') if pid_data: pid, _ = pid_data.data context['pid'] = pid ...
python
{ "resource": "" }
q13678
_RecordRESTState.reset_permission_factories
train
def reset_permission_factories(self): """Remove cached permission factories.""" for key in ('read', 'create', 'update', 'delete'): full_key = '{0}_permission_factory'.format(key) if full_key in self.__dict__: del self.__dict__[full_key]
python
{ "resource": "" }
q13679
range_filter
train
def range_filter(field, start_date_math=None, end_date_math=None, **kwargs): """Create a range filter. :param field: Field name. :param start_date_math: Starting date. :param end_date_math: Ending date. :param kwargs: Addition arguments passed to the Range query. :returns: Function that returns...
python
{ "resource": "" }
q13680
_create_filter_dsl
train
def _create_filter_dsl(urlkwargs, definitions): """Create a filter DSL expression.""" filters = [] for name, filter_factory in definitions.items(): values = request.values.getlist(name, type=text_type) if values: filters.append(filter_factory(values)) for v in values:...
python
{ "resource": "" }
q13681
_post_filter
train
def _post_filter(search, urlkwargs, definitions): """Ingest post filter in query.""" filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions) for filter_ in filters: search = search.post_filter(filter_) return (search, urlkwargs)
python
{ "resource": "" }
q13682
_query_filter
train
def _query_filter(search, urlkwargs, definitions): """Ingest query filter in query.""" filters, urlkwargs = _create_filter_dsl(urlkwargs, definitions) for filter_ in filters: search = search.filter(filter_) return (search, urlkwargs)
python
{ "resource": "" }
q13683
_aggregations
train
def _aggregations(search, definitions): """Add aggregations to query.""" if definitions: for name, agg in definitions.items(): search.aggs[name] = agg if not callable(agg) else agg() return search
python
{ "resource": "" }
q13684
default_facets_factory
train
def default_facets_factory(search, index): """Add a default facets to query. :param search: Basic search object. :param index: Index name. :returns: A tuple containing the new search object and a dictionary with all fields and values used. """ urlkwargs = MultiDict() facets = curre...
python
{ "resource": "" }
q13685
pid_from_context
train
def pid_from_context(_, context): """Get PID from marshmallow context.""" pid = (context or {}).get('pid') return pid.pid_value if pid else missing
python
{ "resource": "" }
q13686
record_responsify
train
def record_responsify(serializer, mimetype): """Create a Records-REST response serializer. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response. """ def view(pid, record, code=200, headers=None, links_factory=No...
python
{ "resource": "" }
q13687
search_responsify
train
def search_responsify(serializer, mimetype): """Create a Records-REST search result response serializer. :param serializer: Serializer instance. :param mimetype: MIME type of response. :returns: Function that generates a record HTTP response. """ def view(pid_fetcher, search_result, code=200, h...
python
{ "resource": "" }
q13688
add_link_header
train
def add_link_header(response, links): """Add a Link HTTP header to a REST response. :param response: REST response instance :param links: Dictionary of links """ if links is not None: response.headers.extend({ 'Link': ', '.join([ '<{0}>; rel="{1}"'.format(l, r) f...
python
{ "resource": "" }
q13689
CiteprocSerializer._get_args
train
def _get_args(cls, **kwargs): """Parse style and locale. Argument location precedence: kwargs > view_args > query """ csl_args = { 'style': cls._default_style, 'locale': cls._default_locale } if has_request_context(): parser = FlaskPa...
python
{ "resource": "" }
q13690
CiteprocSerializer._get_source
train
def _get_source(self, data): """Get source data object for citeproc-py.""" if self.record_format == 'csl': return CiteProcJSON([json.loads(data)]) elif self.record_format == 'bibtex': return BibTeX(data)
python
{ "resource": "" }
q13691
CiteprocSerializer._clean_result
train
def _clean_result(self, text): """Remove double spaces, punctuation and escapes apostrophes.""" text = re.sub('\s\s+', ' ', text) text = re.sub('\.\.+', '.', text) text = text.replace("'", "\\'") return text
python
{ "resource": "" }
q13692
CiteprocSerializer.serialize
train
def serialize(self, pid, record, links_factory=None, **kwargs): """Serialize a single record. :param pid: Persistent identifier instance. :param record: Record instance. :param links_factory: Factory function for record links. """ data = self.serializer.serialize(pid, re...
python
{ "resource": "" }
q13693
SanitizedUnicode.is_valid_xml_char
train
def is_valid_xml_char(self, char): """Check if a character is valid based on the XML specification.""" codepoint = ord(char) return (0x20 <= codepoint <= 0xD7FF or codepoint in (0x9, 0xA, 0xD) or 0xE000 <= codepoint <= 0xFFFD or 0x10000 <= codepoin...
python
{ "resource": "" }
q13694
SanitizedUnicode._deserialize
train
def _deserialize(self, value, attr, data): """Deserialize sanitized string value.""" value = super(SanitizedUnicode, self)._deserialize(value, attr, data) value = fix_text(value) # NOTE: This `join` might be ineffiecient... There's a solution with a # large compiled regex lying ...
python
{ "resource": "" }
q13695
TrimmedString._deserialize
train
def _deserialize(self, value, attr, data): """Deserialize string value.""" value = super(TrimmedString, self)._deserialize(value, attr, data) return value.strip()
python
{ "resource": "" }
q13696
default_search_factory
train
def default_search_factory(self, search, query_parser=None): """Parse query using elasticsearch DSL query. :param self: REST view. :param search: Elastic search DSL search instance. :returns: Tuple with search instance and URL arguments. """ def _default_parser(qstr=None): """Default pa...
python
{ "resource": "" }
q13697
_get_func_args
train
def _get_func_args(func): """Get a list of the arguments a function or method has.""" if isinstance(func, functools.partial): return _get_func_args(func.func) if inspect.isfunction(func) or inspect.ismethod(func): return list(inspect.getargspec(func).args) if callable(func): retu...
python
{ "resource": "" }
q13698
JSONLDTransformerMixin.expanded
train
def expanded(self): """Get JSON-LD expanded state.""" # Ensure we can run outside a application/request context. if request: if 'expanded' in request.args: return True elif 'compacted' in request.args: return False return self._expa...
python
{ "resource": "" }
q13699
JSONLDTransformerMixin.transform_jsonld
train
def transform_jsonld(self, obj): """Compact JSON according to context.""" rec = copy.deepcopy(obj) rec.update(self.context) compacted = jsonld.compact(rec, self.context) if not self.expanded: return compacted else: return jsonld.expand(compacted)[0...
python
{ "resource": "" }