_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q33400 | _create_equivalence_transform | train | def _create_equivalence_transform(equiv):
"""Compute an equivalence transformation that transforms this compound
to another compound's coordinate system.
Parameters
----------
equiv : np.ndarray, shape=(n, 3), dtype=float
Array of equivalent points.
Returns
-------
T : Coordina... | python | {
"resource": ""
} |
q33401 | _choose_correct_port | train | def _choose_correct_port(from_port, to_port):
"""Chooses the direction when using an equivalence transform on two Ports.
Each Port object actually contains 2 sets of 4 atoms, either of which can be
used to make a connection with an equivalence transform. This function
chooses the set of 4 atoms that ma... | python | {
"resource": ""
} |
q33402 | translate | train | def translate(compound, pos):
"""Translate a compound by a vector.
Parameters
----------
compound : mb.Compound
The compound being translated.
pos : np.ndarray, shape=(3,), dtype=float
The vector to translate the compound by.
"""
atom_positions = compound.xyz_with_ports
... | python | {
"resource": ""
} |
q33403 | translate_to | train | def translate_to(compound, pos):
"""Translate a compound to a coordinate.
Parameters
----------
compound : mb.Compound
The compound being translated.
pos : np.ndarray, shape=(3,), dtype=float
The coordinate to translate the compound to.
"""
atom_positions = compound.xyz_wit... | python | {
"resource": ""
} |
q33404 | _translate_to | train | def _translate_to(coordinates, to):
"""Translate a set of coordinates to a location.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being translated.
to : np.ndarray, shape=(3,), dtype=float
The new average position of the coordinates.
... | python | {
"resource": ""
} |
q33405 | _rotate | train | def _rotate(coordinates, theta, around):
"""Rotate a set of coordinates around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being rotated.
theta : float
The angle by which to rotate the coordinates, in radians.
aro... | python | {
"resource": ""
} |
q33406 | rotate | train | def rotate(compound, theta, around):
"""Rotate a compound around an arbitrary vector.
Parameters
----------
compound : mb.Compound
The compound being rotated.
theta : float
The angle by which to rotate the compound, in radians.
around : np.ndarray, shape=(3,), dtype=float
... | python | {
"resource": ""
} |
q33407 | spin | train | def spin(compound, theta, around):
"""Rotate a compound in place around an arbitrary vector.
Parameters
----------
compound : mb.Compound
The compound being rotated.
theta : float
The angle by which to rotate the compound, in radians.
around : np.ndarray, shape=(3,), dtype=float... | python | {
"resource": ""
} |
q33408 | _spin | train | def _spin(coordinates, theta, around):
"""Rotate a set of coordinates in place around an arbitrary vector.
Parameters
----------
coordinates : np.ndarray, shape=(n,3), dtype=float
The coordinates being spun.
theta : float
The angle by which to spin the coordinates, in radians.
a... | python | {
"resource": ""
} |
q33409 | x_axis_transform | train | def x_axis_transform(compound, new_origin=None,
point_on_x_axis=None,
point_on_xy_plane=None):
"""Move a compound such that the x-axis lies on specified points.
Parameters
----------
compound : mb.Compound
The compound to move.
new_origin : mb.Compo... | python | {
"resource": ""
} |
q33410 | y_axis_transform | train | def y_axis_transform(compound, new_origin=None,
point_on_y_axis=None,
point_on_xy_plane=None):
"""Move a compound such that the y-axis lies on specified points.
Parameters
----------
compound : mb.Compound
The compound to move.
new_origin : mb.Compo... | python | {
"resource": ""
} |
q33411 | z_axis_transform | train | def z_axis_transform(compound, new_origin=None,
point_on_z_axis=None,
point_on_zx_plane=None):
"""Move a compound such that the z-axis lies on specified points.
Parameters
----------
compound : mb.Compound
The compound to move.
new_origin : mb.Compo... | python | {
"resource": ""
} |
q33412 | CoordinateTransform.apply_to | train | def apply_to(self, A):
"""Apply the coordinate transformation to points in A. """
if A.ndim == 1:
A = np.expand_dims(A, axis=0)
rows, cols = A.shape
A_new = np.hstack([A, np.ones((rows, 1))])
A_new = np.transpose(self.T.dot(np.transpose(A_new)))
return A_new[... | python | {
"resource": ""
} |
q33413 | TiledCompound._add_tile | train | def _add_tile(self, new_tile, ijk):
"""Add a tile with a label indicating its tiling position. """
tile_label = "{0}_{1}".format(self.name, '-'.join(str(d) for d in ijk))
self.add(new_tile, label=tile_label, inherit_periodicity=False) | python | {
"resource": ""
} |
q33414 | TiledCompound._find_particle_image | train | def _find_particle_image(self, query, match, all_particles):
"""Find particle with the same index as match in a neighboring tile. """
_, idxs = self.particle_kdtree.query(query.pos, k=10)
neighbors = all_particles[idxs]
for particle in neighbors:
if particle.index == match.... | python | {
"resource": ""
} |
q33415 | RB_to_OPLS | train | def RB_to_OPLS(c0, c1, c2, c3, c4, c5):
"""Converts Ryckaert-Bellemans type dihedrals to OPLS type.
Parameters
----------
c0, c1, c2, c3, c4, c5 : Ryckaert-Belleman coefficients (in kcal/mol)
Returns
-------
opls_coeffs : np.array, shape=(4,)
Array containing the OPLS dihedrals coe... | python | {
"resource": ""
} |
q33416 | write_hoomdxml | train | def write_hoomdxml(structure, filename, ref_distance=1.0, ref_mass=1.0,
ref_energy=1.0, rigid_bodies=None, shift_coords=True,
auto_scale=False):
"""Output a HOOMD XML file.
Parameters
----------
structure : parmed.Structure
ParmEd structure object
filen... | python | {
"resource": ""
} |
q33417 | _write_dihedral_information | train | def _write_dihedral_information(xml_file, structure, ref_energy):
"""Write dihedrals in the system.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
structure : parmed.Structure
Parmed structure object
ref_energy : float, default=1.... | python | {
"resource": ""
} |
q33418 | _write_rigid_information | train | def _write_rigid_information(xml_file, rigid_bodies):
"""Write rigid body information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
rigid_bodies : list, len=n_particles
The rigid body that each particle belongs to (-1 for none)
... | python | {
"resource": ""
} |
q33419 | _write_box_information | train | def _write_box_information(xml_file, structure, ref_distance):
"""Write box information.
Parameters
----------
xml_file : file object
The file object of the hoomdxml file being written
structure : parmed.Structure
Parmed structure object
ref_energy : float, default=1.0
R... | python | {
"resource": ""
} |
q33420 | Port.access_labels | train | def access_labels(self):
"""List of labels used to access the Port
Returns
-------
list of str
Strings that can be used to access this Port relative to self.root
"""
access_labels = []
for referrer in self.referrers:
referrer_labels = [key... | python | {
"resource": ""
} |
q33421 | signed_area | train | def signed_area(coords):
"""Return the signed area enclosed by a ring using the linear time
algorithm. A value >= 0 indicates a counter-clockwise oriented ring.
"""
xs, ys = map(list, zip(*coords))
xs.append(xs[1])
ys.append(ys[1])
return sum(xs[i]*(ys[i+1]-ys[i-1]) for i in range(1, ... | python | {
"resource": ""
} |
q33422 | Reader.load | train | def load(self, shapefile=None):
"""Opens a shapefile from a filename or file-like
object. Normally this method would be called by the
constructor with the file name as an argument."""
if shapefile:
(shapeName, ext) = os.path.splitext(shapefile)
self.shapeNam... | python | {
"resource": ""
} |
q33423 | Reader.load_shp | train | def load_shp(self, shapefile_name):
"""
Attempts to load file with .shp extension as both lower and upper case
"""
shp_ext = 'shp'
try:
self.shp = open("%s.%s" % (shapefile_name, shp_ext), "rb")
except IOError:
try:
self.sh... | python | {
"resource": ""
} |
q33424 | Reader.load_shx | train | def load_shx(self, shapefile_name):
"""
Attempts to load file with .shx extension as both lower and upper case
"""
shx_ext = 'shx'
try:
self.shx = open("%s.%s" % (shapefile_name, shx_ext), "rb")
except IOError:
try:
self.sh... | python | {
"resource": ""
} |
q33425 | Reader.load_dbf | train | def load_dbf(self, shapefile_name):
"""
Attempts to load file with .dbf extension as both lower and upper case
"""
dbf_ext = 'dbf'
try:
self.dbf = open("%s.%s" % (shapefile_name, dbf_ext), "rb")
except IOError:
try:
self.db... | python | {
"resource": ""
} |
q33426 | Reader.__getFileObj | train | def __getFileObj(self, f):
"""Checks to see if the requested shapefile file object is
available. If not a ShapefileException is raised."""
if not f:
raise ShapefileException("Shapefile Reader requires a shapefile or file-like object.")
if self.shp and self.shpLength is N... | python | {
"resource": ""
} |
q33427 | Reader.__restrictIndex | train | def __restrictIndex(self, i):
"""Provides list-like handling of a record index with a clearer
error message if the index is out of bounds."""
if self.numRecords:
rmax = self.numRecords - 1
if abs(i) > rmax:
raise IndexError("Shape or Record index out... | python | {
"resource": ""
} |
q33428 | Reader.iterShapes | train | def iterShapes(self):
"""Serves up shapes in a shapefile as an iterator. Useful
for handling large shapefiles."""
shp = self.__getFileObj(self.shp)
shp.seek(0,2)
self.shpLength = shp.tell()
shp.seek(100)
while shp.tell() < self.shpLength:
yield... | python | {
"resource": ""
} |
q33429 | Reader.iterRecords | train | def iterRecords(self):
"""Serves up records in a dbf file as an iterator.
Useful for large shapefiles or dbf files."""
if self.numRecords is None:
self.__dbfHeader()
f = self.__getFileObj(self.dbf)
f.seek(self.__dbfHdrLength)
for i in xrange(self.numRec... | python | {
"resource": ""
} |
q33430 | Writer.close | train | def close(self):
"""
Write final shp, shx, and dbf headers, close opened files.
"""
# Check if any of the files have already been closed
shp_open = self.shp and not (hasattr(self.shp, 'closed') and self.shp.closed)
shx_open = self.shx and not (hasattr(self.shx, 'clo... | python | {
"resource": ""
} |
q33431 | Writer.__getFileObj | train | def __getFileObj(self, f):
"""Safety handler to verify file-like objects"""
if not f:
raise ShapefileException("No file-like object available.")
elif hasattr(f, "write"):
return f
else:
pth = os.path.split(f)[0]
if pth and not os.pa... | python | {
"resource": ""
} |
q33432 | Writer.balance | train | def balance(self):
"""Adds corresponding empty attributes or null geometry records depending
on which type of record was created to make sure all three files
are in synch."""
while self.recNum > self.shpNum:
self.null()
while self.recNum < self.shpNum:
... | python | {
"resource": ""
} |
q33433 | Writer.point | train | def point(self, x, y):
"""Creates a POINT shape."""
shapeType = POINT
pointShape = Shape(shapeType)
pointShape.points.append([x, y])
self.shape(pointShape) | python | {
"resource": ""
} |
q33434 | Writer.multipoint | train | def multipoint(self, points):
"""Creates a MULTIPOINT shape.
Points is a list of xy values."""
shapeType = MULTIPOINT
points = [points] # nest the points inside a list to be compatible with the generic shapeparts method
self._shapeparts(parts=points, shapeType=shapeType) | python | {
"resource": ""
} |
q33435 | Writer.line | train | def line(self, lines):
"""Creates a POLYLINE shape.
Lines is a collection of lines, each made up of a list of xy values."""
shapeType = POLYLINE
self._shapeparts(parts=lines, shapeType=shapeType) | python | {
"resource": ""
} |
q33436 | Writer.poly | train | def poly(self, polys):
"""Creates a POLYGON shape.
Polys is a collection of polygons, each made up of a list of xy values.
Note that for ordinary polygons the coordinates must run in a clockwise direction.
If some of the polygons are holes, these must run in a counterclockwise direct... | python | {
"resource": ""
} |
q33437 | forecast | train | def forecast(stl, fc_func, steps=10, seasonal=False, **fc_func_kwargs):
"""Forecast the given decomposition ``stl`` forward by ``steps`` steps using the forecasting
function ``fc_func``, optionally including the calculated seasonality.
This is an additive model, Y[t] = T[t] + S[t] + e[t]
Args:
... | python | {
"resource": ""
} |
q33438 | mean | train | def mean(data, n=3, **kwargs):
"""The mean forecast for the next point is the mean value of the previous ``n`` points in
the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate the mean
Returns:
float: a single... | python | {
"resource": ""
} |
q33439 | drift | train | def drift(data, n=3, **kwargs):
"""The drift forecast for the next point is a linear extrapolation from the previous ``n``
points in the series.
Args:
data (np.array): Observed data, presumed to be ordered in time.
n (int): period over which to calculate linear model for extrapolation
... | python | {
"resource": ""
} |
q33440 | Client.exchange_token | train | def exchange_token(self, code):
"""Given the value of the code parameter, request an access token."""
url = '%s%s/oauth2/token' % (self.scheme, self.host)
options = {
'grant_type': 'authorization_code',
'redirect_uri': self._redirect_uri(),
'client_id': self.o... | python | {
"resource": ""
} |
q33441 | Client._authorization_code_flow | train | def _authorization_code_flow(self):
"""Build the the auth URL so the user can authorize the app."""
options = {
'scope': getattr(self, 'scope', 'non-expiring'),
'client_id': self.options.get('client_id'),
'response_type': 'code',
'redirect_uri': self._redi... | python | {
"resource": ""
} |
q33442 | Client._refresh_token_flow | train | def _refresh_token_flow(self):
"""Given a refresh token, obtain a new access token."""
url = '%s%s/oauth2/token' % (self.scheme, self.host)
options = {
'grant_type': 'refresh_token',
'client_id': self.options.get('client_id'),
'client_secret': self.options.get... | python | {
"resource": ""
} |
q33443 | Client._request | train | def _request(self, method, resource, **kwargs):
"""Given an HTTP method, a resource name and kwargs, construct a
request and return the response.
"""
url = self._resolve_resource_name(resource)
if hasattr(self, 'access_token'):
kwargs.update(dict(oauth_token=self.acc... | python | {
"resource": ""
} |
q33444 | extract_files_from_dict | train | def extract_files_from_dict(d):
"""Return any file objects from the provided dict.
>>> extract_files_from_dict({
... 'oauth_token': 'foo',
... 'track': {
... 'title': 'bar',
... 'asset_data': open('setup.py', 'rb')
... }}) # doctest:+ELLIPSIS
{'track': {'asset_data': <...}}
""... | python | {
"resource": ""
} |
q33445 | remove_files_from_dict | train | def remove_files_from_dict(d):
"""Return the provided dict with any file objects removed.
>>> remove_files_from_dict({
... 'oauth_token': 'foo',
... 'track': {
... 'title': 'bar',
... 'asset_data': open('setup.py', 'rb')
... }
... }) == {'track': {'title': 'bar'}, 'oau... | python | {
"resource": ""
} |
q33446 | namespaced_query_string | train | def namespaced_query_string(d, prefix=""):
"""Transform a nested dict into a string with namespaced query params.
>>> namespaced_query_string({
... 'oauth_token': 'foo',
... 'track': {'title': 'bar', 'sharing': 'private'}}) == {
... 'track[sharing]': 'private',
... 'oauth_token': 'f... | python | {
"resource": ""
} |
q33447 | make_request | train | def make_request(method, url, params):
"""Make an HTTP request, formatting params as required."""
empty = []
# TODO
# del params[key]
# without list
for key, value in six.iteritems(params):
if value is None:
empty.append(key)
for key in empty:
del params[key]
... | python | {
"resource": ""
} |
q33448 | wrapped_resource | train | def wrapped_resource(response):
"""Return a response wrapped in the appropriate wrapper type.
Lists will be returned as a ```ResourceList``` instance,
dicts will be returned as a ```Resource``` instance.
"""
# decode response text, assuming utf-8 if unset
response_content = response.content.dec... | python | {
"resource": ""
} |
q33449 | normalize_param | train | def normalize_param(key, value):
"""Convert a set of key, value parameters into a dictionary suitable for
passing into requests. This will convert lists into the syntax required
by SoundCloud. Heavily lifted from HTTParty.
>>> normalize_param('playlist', {
... 'title': 'foo',
... 'sharing': '... | python | {
"resource": ""
} |
q33450 | SmartObject.open | train | def open(self, external_dir=None):
"""
Open the smart object as binary IO.
:param external_dir: Path to the directory of the external file.
Example::
with layer.smart_object.open() as f:
data = f.read()
"""
if self.kind == 'data':
... | python | {
"resource": ""
} |
q33451 | SmartObject.data | train | def data(self):
"""Embedded file content, or empty if kind is `external` or `alias`"""
if self.kind == 'data':
return self._data.data
else:
with self.open() as f:
return f.read() | python | {
"resource": ""
} |
q33452 | SmartObject.filesize | train | def filesize(self):
"""File size of the object."""
if self.kind == 'data':
return len(self._data.data)
return self._data.filesize | python | {
"resource": ""
} |
q33453 | SmartObject.save | train | def save(self, filename=None):
"""
Save the smart object to a file.
:param filename: File name to export. If None, use the embedded name.
"""
if filename is None:
filename = self.filename
with open(filename, 'wb') as f:
f.write(self.data) | python | {
"resource": ""
} |
q33454 | BaseElement._traverse | train | def _traverse(element, condition=None):
"""
Traversal API intended for debugging.
"""
if condition is None or condition(element):
yield element
if isinstance(element, DictElement):
for child in element.values():
for _ in BaseElement._traver... | python | {
"resource": ""
} |
q33455 | read_length_and_key | train | def read_length_and_key(fp):
"""
Helper to read descriptor key.
"""
length = read_fmt('I', fp)[0]
key = fp.read(length or 4)
if length == 0 and key not in _TERMS:
logger.debug('Unknown term: %r' % (key))
_TERMS.add(key)
return key | python | {
"resource": ""
} |
q33456 | write_length_and_key | train | def write_length_and_key(fp, value):
"""
Helper to write descriptor key.
"""
written = write_fmt(fp, 'I', 0 if value in _TERMS else len(value))
written += write_bytes(fp, value)
return written | python | {
"resource": ""
} |
q33457 | main | train | def main(argv=None):
"""
psd-tools command line utility.
Usage:
psd-tools export <input_file> <output_file> [options]
psd-tools show <input_file> [options]
psd-tools debug <input_file> [options]
psd-tools -h | --help
psd-tools --version
Options:
-v --ver... | python | {
"resource": ""
} |
q33458 | PSDImage.new | train | def new(cls, mode, size, color=0, depth=8, **kwargs):
"""
Create a new PSD document.
:param mode: The color mode to use for the new image.
:param size: A tuple containing (width, height) in pixels.
:param color: What color to use for the image. Default is black.
:return:... | python | {
"resource": ""
} |
q33459 | PSDImage.frompil | train | def frompil(cls, image, compression=Compression.PACK_BITS):
"""
Create a new PSD document from PIL Image.
:param image: PIL Image object.
:param compression: ImageData compression option. See
:py:class:`~psd_tools.constants.Compression`.
:return: A :py:class:`~psd_to... | python | {
"resource": ""
} |
q33460 | PSDImage.open | train | def open(cls, fp):
"""
Open a PSD document.
:param fp: filename or file-like object.
:return: A :py:class:`~psd_tools.api.psd_image.PSDImage` object.
"""
if hasattr(fp, 'read'):
self = cls(PSD.read(fp))
else:
with open(fp, 'rb') as f:
... | python | {
"resource": ""
} |
q33461 | PSDImage.save | train | def save(self, fp, mode='wb'):
"""
Save the PSD file.
:param fp: filename or file-like object.
:param mode: file open mode, default 'wb'.
"""
if hasattr(fp, 'write'):
self._record.write(fp)
else:
with open(fp, mode) as f:
s... | python | {
"resource": ""
} |
q33462 | PSDImage.topil | train | def topil(self, **kwargs):
"""
Get PIL Image.
:return: :py:class:`PIL.Image`, or `None` if the composed image is not
available.
"""
if self.has_preview():
return pil_io.convert_image_data_to_pil(self._record, **kwargs)
return None | python | {
"resource": ""
} |
q33463 | PSDImage.compose | train | def compose(self, force=False, bbox=None, **kwargs):
"""
Compose the PSD image.
See :py:func:`~psd_tools.compose` for available extra arguments.
:param bbox: Viewport tuple (left, top, right, bottom).
:return: :py:class:`PIL.Image`, or `None` if there is no pixel.
"""
... | python | {
"resource": ""
} |
q33464 | PSDImage.bbox | train | def bbox(self):
"""
Minimal bounding box that contains all the visible layers.
Use :py:attr:`~psd_tools.api.psd_image.PSDImage.viewbox` to get
viewport bounding box. When the psd is empty, bbox is equal to the
canvas bounding box.
:return: (left, top, right, bottom) `tu... | python | {
"resource": ""
} |
q33465 | PSDImage.viewbox | train | def viewbox(self):
"""
Return bounding box of the viewport.
:return: (left, top, right, bottom) `tuple`.
"""
return self.left, self.top, self.right, self.bottom | python | {
"resource": ""
} |
q33466 | PSDImage.thumbnail | train | def thumbnail(self):
"""
Returns a thumbnail image in PIL.Image. When the file does not
contain an embedded thumbnail image, returns None.
"""
if 'THUMBNAIL_RESOURCE' in self.image_resources:
return pil_io.convert_thumbnail_to_pil(
self.image_resources... | python | {
"resource": ""
} |
q33467 | PSDImage._get_pattern | train | def _get_pattern(self, pattern_id):
"""Get pattern item by id."""
for key in ('PATTERNS1', 'PATTERNS2', 'PATTERNS3'):
if key in self.tagged_blocks:
data = self.tagged_blocks.get_data(key)
for pattern in data:
if pattern.pattern_id == patter... | python | {
"resource": ""
} |
q33468 | PSDImage._init | train | def _init(self):
"""Initialize layer structure."""
group_stack = [self]
clip_stack = []
last_layer = None
for record, channels in self._record._iter_layers():
current_group = group_stack[-1]
blocks = record.tagged_blocks
end_of_group = False
... | python | {
"resource": ""
} |
q33469 | _AngleMixin.angle | train | def angle(self):
"""Angle value."""
if self.use_global_light:
return self._image_resources.get_data('global_angle', 30.0)
return self.value.get(Key.LocalLightingAngle).value | python | {
"resource": ""
} |
q33470 | get_color_mode | train | def get_color_mode(mode):
"""Convert PIL mode to ColorMode."""
name = mode.upper()
name = name.rstrip('A') # Trim alpha.
name = {'1': 'BITMAP', 'L': 'GRAYSCALE'}.get(name, name)
return getattr(ColorMode, name) | python | {
"resource": ""
} |
q33471 | get_pil_mode | train | def get_pil_mode(value, alpha=False):
"""Get PIL mode from ColorMode."""
name = {
'GRAYSCALE': 'L',
'BITMAP': '1',
'DUOTONE': 'L',
'INDEXED': 'P',
}.get(value, value)
if alpha and name in ('L', 'RGB'):
name += 'A'
return name | python | {
"resource": ""
} |
q33472 | convert_image_data_to_pil | train | def convert_image_data_to_pil(psd, apply_icc=True, **kwargs):
"""Convert ImageData to PIL Image.
.. note:: Image resources contain extra alpha channels in these keys:
`ALPHA_NAMES_UNICODE`, `ALPHA_NAMES_PASCAL`, `ALPHA_IDENTIFIERS`.
"""
from PIL import Image, ImageOps
header = psd.header
... | python | {
"resource": ""
} |
q33473 | convert_layer_to_pil | train | def convert_layer_to_pil(layer, apply_icc=True, **kwargs):
"""Convert Layer to PIL Image."""
from PIL import Image
header = layer._psd._record.header
if header.color_mode == ColorMode.BITMAP:
raise NotImplementedError
width, height = layer.width, layer.height
channels, alpha = [], None
... | python | {
"resource": ""
} |
q33474 | convert_mask_to_pil | train | def convert_mask_to_pil(mask, real=True):
"""Convert Mask to PIL Image."""
from PIL import Image
header = mask._layer._psd._record.header
channel_ids = [ci.id for ci in mask._layer._record.channel_info]
if real and mask._has_real():
width = mask._data.real_right - mask._data.real_left
... | python | {
"resource": ""
} |
q33475 | convert_pattern_to_pil | train | def convert_pattern_to_pil(pattern, version=1):
"""Convert Pattern to PIL Image."""
from PIL import Image
mode = get_pil_mode(pattern.image_mode.name, False)
# The order is different here.
size = pattern.data.rectangle[3], pattern.data.rectangle[2]
channels = [
_create_channel(size, c.ge... | python | {
"resource": ""
} |
q33476 | convert_thumbnail_to_pil | train | def convert_thumbnail_to_pil(thumbnail, mode='RGB'):
"""Convert thumbnail resource."""
from PIL import Image
if thumbnail.fmt == 0:
size = (thumbnail.width, thumbnail.height)
stride = thumbnail.widthbytes
return Image.frombytes('RGBX', size, thumbnail.data, 'raw', mode,
... | python | {
"resource": ""
} |
q33477 | _apply_icc | train | def _apply_icc(image, icc_profile):
"""Apply ICC Color profile."""
from io import BytesIO
try:
from PIL import ImageCms
except ImportError:
logger.debug(
'ICC profile found but not supported. Install little-cms.'
)
return image
if image.mode not in ('RGB'... | python | {
"resource": ""
} |
q33478 | _remove_white_background | train | def _remove_white_background(image):
"""Remove white background in the preview image."""
from PIL import ImageMath, Image
if image.mode == "RGBA":
bands = image.split()
a = bands[3]
rgb = [
ImageMath.eval(
'convert('
'float(x + a - 255) * 2... | python | {
"resource": ""
} |
q33479 | Mask.background_color | train | def background_color(self):
"""Background color."""
if self._has_real():
return self._data.real_background_color
return self._data.background_color | python | {
"resource": ""
} |
q33480 | Mask.left | train | def left(self):
"""Left coordinate."""
if self._has_real():
return self._data.real_left
return self._data.left | python | {
"resource": ""
} |
q33481 | Mask.right | train | def right(self):
"""Right coordinate."""
if self._has_real():
return self._data.real_right
return self._data.right | python | {
"resource": ""
} |
q33482 | Mask.top | train | def top(self):
"""Top coordinate."""
if self._has_real():
return self._data.real_top
return self._data.top | python | {
"resource": ""
} |
q33483 | Mask.bottom | train | def bottom(self):
"""Bottom coordinate."""
if self._has_real():
return self._data.real_bottom
return self._data.bottom | python | {
"resource": ""
} |
q33484 | compress | train | def compress(data, compression, width, height, depth, version=1):
"""Compress raw data.
:param data: raw data bytes to write.
:param compression: compression type, see :py:class:`.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth of the pixel.
:param version:... | python | {
"resource": ""
} |
q33485 | decompress | train | def decompress(data, compression, width, height, depth, version=1):
"""Decompress raw data.
:param data: compressed data bytes.
:param compression: compression type,
see :py:class:`~psd_tools.constants.Compression`.
:param width: width.
:param height: height.
:param depth: bit depth... | python | {
"resource": ""
} |
q33486 | _shuffled_order | train | def _shuffled_order(w, h):
"""
Generator for the order of 4-byte values.
32bit channels are also encoded using delta encoding,
but it make no sense to apply delta compression to bytes.
It is possible to apply delta compression to 2-byte or 4-byte
words, but it seems it is not the best way eithe... | python | {
"resource": ""
} |
q33487 | compose_layer | train | def compose_layer(layer, force=False, **kwargs):
"""Compose a single layer with pixels."""
from PIL import Image, ImageChops
assert layer.bbox != (0, 0, 0, 0), 'Layer bbox is (0, 0, 0, 0)'
image = layer.topil(**kwargs)
if image is None or force:
texture = create_fill(layer)
if textu... | python | {
"resource": ""
} |
q33488 | apply_effect | train | def apply_effect(layer, image):
"""Apply effect to the image.
..note: Correct effect order is the following. All the effects are first
applied to the original image then blended together.
* dropshadow
* outerglow
* (original)
* patternoverlay
* gradientoverlay
... | python | {
"resource": ""
} |
q33489 | _generate_symbol | train | def _generate_symbol(path, width, height, command='C'):
"""Sequence generator for SVG path."""
if len(path) == 0:
return
# Initial point.
yield 'M'
yield path[0].anchor[1] * width
yield path[0].anchor[0] * height
yield command
# Closed path or open path
points = (zip(path, ... | python | {
"resource": ""
} |
q33490 | draw_pattern_fill | train | def draw_pattern_fill(image, psd, setting, blend=True):
"""
Draw pattern fill on the image.
:param image: Image to be filled.
:param psd: :py:class:`PSDImage`.
:param setting: Descriptor containing pattern fill.
:param blend: Blend the fill or ignore. Effects blend.
"""
from PIL import ... | python | {
"resource": ""
} |
q33491 | _make_linear_gradient | train | def _make_linear_gradient(width, height, angle=90.):
"""Generates index map for linear gradients."""
import numpy as np
X, Y = np.meshgrid(np.linspace(0, 1, width), np.linspace(0, 1, height))
theta = np.radians(angle % 360)
c, s = np.cos(theta), np.sin(theta)
if 0 <= theta and theta < 0.5 * np.p... | python | {
"resource": ""
} |
q33492 | Stroke.line_cap_type | train | def line_cap_type(self):
"""Cap type, one of `butt`, `round`, `square`."""
key = self._data.get(b'strokeStyleLineCapType').enum
return self.STROKE_STYLE_LINE_CAP_TYPES.get(key, str(key)) | python | {
"resource": ""
} |
q33493 | Stroke.line_join_type | train | def line_join_type(self):
"""Join type, one of `miter`, `round`, `bevel`."""
key = self._data.get(b'strokeStyleLineJoinType').enum
return self.STROKE_STYLE_LINE_JOIN_TYPES.get(key, str(key)) | python | {
"resource": ""
} |
q33494 | Stroke.line_alignment | train | def line_alignment(self):
"""Alignment, one of `inner`, `outer`, `center`."""
key = self._data.get(b'strokeStyleLineAlignment').enum
return self.STROKE_STYLE_LINE_ALIGNMENTS.get(key, str(key)) | python | {
"resource": ""
} |
q33495 | Origination.bbox | train | def bbox(self):
"""
Bounding box of the live shape.
:return: :py:class:`~psd_tools.psd.descriptor.Descriptor`
"""
bbox = self._data.get(b'keyOriginShapeBBox')
if bbox:
return (
bbox.get(b'Left').value,
bbox.get(b'Top ').value,
... | python | {
"resource": ""
} |
q33496 | Layer.mask | train | def mask(self):
"""
Returns mask associated with this layer.
:return: :py:class:`~psd_tools.api.mask.Mask` or `None`
"""
if not hasattr(self, "_mask"):
self._mask = Mask(self) if self.has_mask() else None
return self._mask | python | {
"resource": ""
} |
q33497 | Layer.vector_mask | train | def vector_mask(self):
"""
Returns vector mask associated with this layer.
:return: :py:class:`~psd_tools.api.shape.VectorMask` or `None`
"""
if not hasattr(self, '_vector_mask'):
self._vector_mask = None
blocks = self.tagged_blocks
for key in... | python | {
"resource": ""
} |
q33498 | Layer.origination | train | def origination(self):
"""
Property for a list of live shapes or a line.
Some of the vector masks have associated live shape properties, that
are Photoshop feature to handle primitive shapes such as a rectangle,
an ellipse, or a line. Vector masks without live shape properties a... | python | {
"resource": ""
} |
q33499 | Layer.effects | train | def effects(self):
"""
Layer effects.
:return: :py:class:`~psd_tools.api.effects.Effects`
"""
if not hasattr(self, '_effects'):
self._effects = Effects(self)
return self._effects | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.