repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
marcomusy/vtkplotter | vtkplotter/analysis.py | alignLandmarks | def alignLandmarks(source, target, rigid=False):
"""
Find best matching of source points towards target
in the mean least square sense, in one single step.
"""
lmt = vtk.vtkLandmarkTransform()
ss = source.polydata().GetPoints()
st = target.polydata().GetPoints()
if source.N() != target.N():
vc.printc('~times Error in alignLandmarks(): Source and Target with != nr of points!',
source.N(), target.N(), c=1)
exit()
lmt.SetSourceLandmarks(ss)
lmt.SetTargetLandmarks(st)
if rigid:
lmt.SetModeToRigidBody()
lmt.Update()
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(source.polydata())
tf.SetTransform(lmt)
tf.Update()
actor = Actor(tf.GetOutput())
actor.info["transform"] = lmt
pr = vtk.vtkProperty()
pr.DeepCopy(source.GetProperty())
actor.SetProperty(pr)
return actor | python | def alignLandmarks(source, target, rigid=False):
"""
Find best matching of source points towards target
in the mean least square sense, in one single step.
"""
lmt = vtk.vtkLandmarkTransform()
ss = source.polydata().GetPoints()
st = target.polydata().GetPoints()
if source.N() != target.N():
vc.printc('~times Error in alignLandmarks(): Source and Target with != nr of points!',
source.N(), target.N(), c=1)
exit()
lmt.SetSourceLandmarks(ss)
lmt.SetTargetLandmarks(st)
if rigid:
lmt.SetModeToRigidBody()
lmt.Update()
tf = vtk.vtkTransformPolyDataFilter()
tf.SetInputData(source.polydata())
tf.SetTransform(lmt)
tf.Update()
actor = Actor(tf.GetOutput())
actor.info["transform"] = lmt
pr = vtk.vtkProperty()
pr.DeepCopy(source.GetProperty())
actor.SetProperty(pr)
return actor | [
"def",
"alignLandmarks",
"(",
"source",
",",
"target",
",",
"rigid",
"=",
"False",
")",
":",
"lmt",
"=",
"vtk",
".",
"vtkLandmarkTransform",
"(",
")",
"ss",
"=",
"source",
".",
"polydata",
"(",
")",
".",
"GetPoints",
"(",
")",
"st",
"=",
"target",
".... | Find best matching of source points towards target
in the mean least square sense, in one single step. | [
"Find",
"best",
"matching",
"of",
"source",
"points",
"towards",
"target",
"in",
"the",
"mean",
"least",
"square",
"sense",
"in",
"one",
"single",
"step",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L507-L533 | train | 210,500 |
marcomusy/vtkplotter | vtkplotter/analysis.py | alignICP | def alignICP(source, target, iters=100, rigid=False):
"""
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the transformation
that modify one surface to best match the other (in the least-square sense).
.. hint:: |align1| |align1.py|_
|align2| |align2.py|_
"""
if isinstance(source, Actor):
source = source.polydata()
if isinstance(target, Actor):
target = target.polydata()
icp = vtk.vtkIterativeClosestPointTransform()
icp.SetSource(source)
icp.SetTarget(target)
icp.SetMaximumNumberOfIterations(iters)
if rigid:
icp.GetLandmarkTransform().SetModeToRigidBody()
icp.StartByMatchingCentroidsOn()
icp.Update()
icpTransformFilter = vtk.vtkTransformPolyDataFilter()
icpTransformFilter.SetInputData(source)
icpTransformFilter.SetTransform(icp)
icpTransformFilter.Update()
poly = icpTransformFilter.GetOutput()
actor = Actor(poly)
# actor.info['transform'] = icp.GetLandmarkTransform() # not working!
# do it manually...
sourcePoints = vtk.vtkPoints()
targetPoints = vtk.vtkPoints()
for i in range(10):
p1 = [0, 0, 0]
source.GetPoints().GetPoint(i, p1)
sourcePoints.InsertNextPoint(p1)
p2 = [0, 0, 0]
poly.GetPoints().GetPoint(i, p2)
targetPoints.InsertNextPoint(p2)
# Setup the transform
landmarkTransform = vtk.vtkLandmarkTransform()
landmarkTransform.SetSourceLandmarks(sourcePoints)
landmarkTransform.SetTargetLandmarks(targetPoints)
if rigid:
landmarkTransform.SetModeToRigidBody()
actor.info["transform"] = landmarkTransform
return actor | python | def alignICP(source, target, iters=100, rigid=False):
"""
Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the transformation
that modify one surface to best match the other (in the least-square sense).
.. hint:: |align1| |align1.py|_
|align2| |align2.py|_
"""
if isinstance(source, Actor):
source = source.polydata()
if isinstance(target, Actor):
target = target.polydata()
icp = vtk.vtkIterativeClosestPointTransform()
icp.SetSource(source)
icp.SetTarget(target)
icp.SetMaximumNumberOfIterations(iters)
if rigid:
icp.GetLandmarkTransform().SetModeToRigidBody()
icp.StartByMatchingCentroidsOn()
icp.Update()
icpTransformFilter = vtk.vtkTransformPolyDataFilter()
icpTransformFilter.SetInputData(source)
icpTransformFilter.SetTransform(icp)
icpTransformFilter.Update()
poly = icpTransformFilter.GetOutput()
actor = Actor(poly)
# actor.info['transform'] = icp.GetLandmarkTransform() # not working!
# do it manually...
sourcePoints = vtk.vtkPoints()
targetPoints = vtk.vtkPoints()
for i in range(10):
p1 = [0, 0, 0]
source.GetPoints().GetPoint(i, p1)
sourcePoints.InsertNextPoint(p1)
p2 = [0, 0, 0]
poly.GetPoints().GetPoint(i, p2)
targetPoints.InsertNextPoint(p2)
# Setup the transform
landmarkTransform = vtk.vtkLandmarkTransform()
landmarkTransform.SetSourceLandmarks(sourcePoints)
landmarkTransform.SetTargetLandmarks(targetPoints)
if rigid:
landmarkTransform.SetModeToRigidBody()
actor.info["transform"] = landmarkTransform
return actor | [
"def",
"alignICP",
"(",
"source",
",",
"target",
",",
"iters",
"=",
"100",
",",
"rigid",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"Actor",
")",
":",
"source",
"=",
"source",
".",
"polydata",
"(",
")",
"if",
"isinstance",
"(",
... | Return a copy of source actor which is aligned to
target actor through the `Iterative Closest Point` algorithm.
The core of the algorithm is to match each vertex in one surface with
the closest surface point on the other, then apply the transformation
that modify one surface to best match the other (in the least-square sense).
.. hint:: |align1| |align1.py|_
|align2| |align2.py|_ | [
"Return",
"a",
"copy",
"of",
"source",
"actor",
"which",
"is",
"aligned",
"to",
"target",
"actor",
"through",
"the",
"Iterative",
"Closest",
"Point",
"algorithm",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L536-L589 | train | 210,501 |
marcomusy/vtkplotter | vtkplotter/analysis.py | alignProcrustes | def alignProcrustes(sources, rigid=False):
"""
Return an ``Assembly`` of aligned source actors with
the `Procrustes` algorithm. The output ``Assembly`` is normalized in size.
`Procrustes` algorithm takes N set of points and aligns them in a least-squares sense
to their mutual mean. The algorithm is iterated until convergence,
as the mean must be recomputed after each alignment.
:param bool rigid: if `True` scaling is disabled.
.. hint:: |align3| |align3.py|_
"""
group = vtk.vtkMultiBlockDataGroupFilter()
for source in sources:
if sources[0].N() != source.N():
vc.printc("~times Procrustes error in align():", c=1)
vc.printc(" sources have different nr of points", c=1)
exit(0)
group.AddInputData(source.polydata())
procrustes = vtk.vtkProcrustesAlignmentFilter()
procrustes.StartFromCentroidOn()
procrustes.SetInputConnection(group.GetOutputPort())
if rigid:
procrustes.GetLandmarkTransform().SetModeToRigidBody()
procrustes.Update()
acts = []
for i, s in enumerate(sources):
poly = procrustes.GetOutput().GetBlock(i)
actor = Actor(poly)
actor.SetProperty(s.GetProperty())
acts.append(actor)
assem = Assembly(acts)
assem.info["transform"] = procrustes.GetLandmarkTransform()
return assem | python | def alignProcrustes(sources, rigid=False):
"""
Return an ``Assembly`` of aligned source actors with
the `Procrustes` algorithm. The output ``Assembly`` is normalized in size.
`Procrustes` algorithm takes N set of points and aligns them in a least-squares sense
to their mutual mean. The algorithm is iterated until convergence,
as the mean must be recomputed after each alignment.
:param bool rigid: if `True` scaling is disabled.
.. hint:: |align3| |align3.py|_
"""
group = vtk.vtkMultiBlockDataGroupFilter()
for source in sources:
if sources[0].N() != source.N():
vc.printc("~times Procrustes error in align():", c=1)
vc.printc(" sources have different nr of points", c=1)
exit(0)
group.AddInputData(source.polydata())
procrustes = vtk.vtkProcrustesAlignmentFilter()
procrustes.StartFromCentroidOn()
procrustes.SetInputConnection(group.GetOutputPort())
if rigid:
procrustes.GetLandmarkTransform().SetModeToRigidBody()
procrustes.Update()
acts = []
for i, s in enumerate(sources):
poly = procrustes.GetOutput().GetBlock(i)
actor = Actor(poly)
actor.SetProperty(s.GetProperty())
acts.append(actor)
assem = Assembly(acts)
assem.info["transform"] = procrustes.GetLandmarkTransform()
return assem | [
"def",
"alignProcrustes",
"(",
"sources",
",",
"rigid",
"=",
"False",
")",
":",
"group",
"=",
"vtk",
".",
"vtkMultiBlockDataGroupFilter",
"(",
")",
"for",
"source",
"in",
"sources",
":",
"if",
"sources",
"[",
"0",
"]",
".",
"N",
"(",
")",
"!=",
"source... | Return an ``Assembly`` of aligned source actors with
the `Procrustes` algorithm. The output ``Assembly`` is normalized in size.
`Procrustes` algorithm takes N set of points and aligns them in a least-squares sense
to their mutual mean. The algorithm is iterated until convergence,
as the mean must be recomputed after each alignment.
:param bool rigid: if `True` scaling is disabled.
.. hint:: |align3| |align3.py|_ | [
"Return",
"an",
"Assembly",
"of",
"aligned",
"source",
"actors",
"with",
"the",
"Procrustes",
"algorithm",
".",
"The",
"output",
"Assembly",
"is",
"normalized",
"in",
"size",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L592-L627 | train | 210,502 |
marcomusy/vtkplotter | vtkplotter/analysis.py | fitLine | def fitLine(points, c="orange", lw=1):
"""
Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_
"""
data = np.array(points)
datamean = data.mean(axis=0)
uu, dd, vv = np.linalg.svd(data - datamean)
vv = vv[0] / np.linalg.norm(vv[0])
# vv contains the first principal component, i.e. the direction
# vector of the best fit line in the least squares sense.
xyz_min = points.min(axis=0)
xyz_max = points.max(axis=0)
a = np.linalg.norm(xyz_min - datamean)
b = np.linalg.norm(xyz_max - datamean)
p1 = datamean - a * vv
p2 = datamean + b * vv
l = vs.Line(p1, p2, c=c, lw=lw, alpha=1)
l.info["slope"] = vv
l.info["center"] = datamean
l.info["variances"] = dd
return l | python | def fitLine(points, c="orange", lw=1):
"""
Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_
"""
data = np.array(points)
datamean = data.mean(axis=0)
uu, dd, vv = np.linalg.svd(data - datamean)
vv = vv[0] / np.linalg.norm(vv[0])
# vv contains the first principal component, i.e. the direction
# vector of the best fit line in the least squares sense.
xyz_min = points.min(axis=0)
xyz_max = points.max(axis=0)
a = np.linalg.norm(xyz_min - datamean)
b = np.linalg.norm(xyz_max - datamean)
p1 = datamean - a * vv
p2 = datamean + b * vv
l = vs.Line(p1, p2, c=c, lw=lw, alpha=1)
l.info["slope"] = vv
l.info["center"] = datamean
l.info["variances"] = dd
return l | [
"def",
"fitLine",
"(",
"points",
",",
"c",
"=",
"\"orange\"",
",",
"lw",
"=",
"1",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"points",
")",
"datamean",
"=",
"data",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"uu",
",",
"dd",
",",
"vv",
"=... | Fits a line through points.
Extra info is stored in ``actor.info['slope']``, ``actor.info['center']``, ``actor.info['variances']``.
.. hint:: |fitline| |fitline.py|_ | [
"Fits",
"a",
"line",
"through",
"points",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L633-L657 | train | 210,503 |
marcomusy/vtkplotter | vtkplotter/analysis.py | fitPlane | def fitPlane(points, c="g", bc="darkgreen"):
"""
Fits a plane to a set of points.
Extra info is stored in ``actor.info['normal']``, ``actor.info['center']``, ``actor.info['variance']``.
.. hint:: Example: |fitplanes.py|_
"""
data = np.array(points)
datamean = data.mean(axis=0)
res = np.linalg.svd(data - datamean)
dd, vv = res[1], res[2]
xyz_min = points.min(axis=0)
xyz_max = points.max(axis=0)
s = np.linalg.norm(xyz_max - xyz_min)
n = np.cross(vv[0], vv[1])
pla = vs.Plane(datamean, n, s, s, c, bc)
pla.info["normal"] = n
pla.info["center"] = datamean
pla.info["variance"] = dd[2]
return pla | python | def fitPlane(points, c="g", bc="darkgreen"):
"""
Fits a plane to a set of points.
Extra info is stored in ``actor.info['normal']``, ``actor.info['center']``, ``actor.info['variance']``.
.. hint:: Example: |fitplanes.py|_
"""
data = np.array(points)
datamean = data.mean(axis=0)
res = np.linalg.svd(data - datamean)
dd, vv = res[1], res[2]
xyz_min = points.min(axis=0)
xyz_max = points.max(axis=0)
s = np.linalg.norm(xyz_max - xyz_min)
n = np.cross(vv[0], vv[1])
pla = vs.Plane(datamean, n, s, s, c, bc)
pla.info["normal"] = n
pla.info["center"] = datamean
pla.info["variance"] = dd[2]
return pla | [
"def",
"fitPlane",
"(",
"points",
",",
"c",
"=",
"\"g\"",
",",
"bc",
"=",
"\"darkgreen\"",
")",
":",
"data",
"=",
"np",
".",
"array",
"(",
"points",
")",
"datamean",
"=",
"data",
".",
"mean",
"(",
"axis",
"=",
"0",
")",
"res",
"=",
"np",
".",
"... | Fits a plane to a set of points.
Extra info is stored in ``actor.info['normal']``, ``actor.info['center']``, ``actor.info['variance']``.
.. hint:: Example: |fitplanes.py|_ | [
"Fits",
"a",
"plane",
"to",
"a",
"set",
"of",
"points",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L660-L680 | train | 210,504 |
marcomusy/vtkplotter | vtkplotter/analysis.py | fitSphere | def fitSphere(coords):
"""
Fits a sphere to a set of points.
Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``.
.. hint:: Example: |fitspheres1.py|_
|fitspheres2| |fitspheres2.py|_
"""
coords = np.array(coords)
n = len(coords)
A = np.zeros((n, 4))
A[:, :-1] = coords * 2
A[:, 3] = 1
f = np.zeros((n, 1))
x = coords[:, 0]
y = coords[:, 1]
z = coords[:, 2]
f[:, 0] = x * x + y * y + z * z
C, residue, rank, sv = np.linalg.lstsq(A, f) # solve AC=f
if rank < 4:
return None
t = (C[0] * C[0]) + (C[1] * C[1]) + (C[2] * C[2]) + C[3]
radius = np.sqrt(t)[0]
center = np.array([C[0][0], C[1][0], C[2][0]])
if len(residue):
residue = np.sqrt(residue[0]) / n
else:
residue = 0
s = vs.Sphere(center, radius, c="r", alpha=1).wire(1)
s.info["radius"] = radius
s.info["center"] = center
s.info["residue"] = residue
return s | python | def fitSphere(coords):
"""
Fits a sphere to a set of points.
Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``.
.. hint:: Example: |fitspheres1.py|_
|fitspheres2| |fitspheres2.py|_
"""
coords = np.array(coords)
n = len(coords)
A = np.zeros((n, 4))
A[:, :-1] = coords * 2
A[:, 3] = 1
f = np.zeros((n, 1))
x = coords[:, 0]
y = coords[:, 1]
z = coords[:, 2]
f[:, 0] = x * x + y * y + z * z
C, residue, rank, sv = np.linalg.lstsq(A, f) # solve AC=f
if rank < 4:
return None
t = (C[0] * C[0]) + (C[1] * C[1]) + (C[2] * C[2]) + C[3]
radius = np.sqrt(t)[0]
center = np.array([C[0][0], C[1][0], C[2][0]])
if len(residue):
residue = np.sqrt(residue[0]) / n
else:
residue = 0
s = vs.Sphere(center, radius, c="r", alpha=1).wire(1)
s.info["radius"] = radius
s.info["center"] = center
s.info["residue"] = residue
return s | [
"def",
"fitSphere",
"(",
"coords",
")",
":",
"coords",
"=",
"np",
".",
"array",
"(",
"coords",
")",
"n",
"=",
"len",
"(",
"coords",
")",
"A",
"=",
"np",
".",
"zeros",
"(",
"(",
"n",
",",
"4",
")",
")",
"A",
"[",
":",
",",
":",
"-",
"1",
"... | Fits a sphere to a set of points.
Extra info is stored in ``actor.info['radius']``, ``actor.info['center']``, ``actor.info['residue']``.
.. hint:: Example: |fitspheres1.py|_
|fitspheres2| |fitspheres2.py|_ | [
"Fits",
"a",
"sphere",
"to",
"a",
"set",
"of",
"points",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L683-L717 | train | 210,505 |
marcomusy/vtkplotter | vtkplotter/analysis.py | booleanOperation | def booleanOperation(actor1, operation, actor2, c=None, alpha=1,
wire=False, bc=None, texture=None):
"""Volumetric union, intersection and subtraction of surfaces.
:param str operation: allowed operations: ``'plus'``, ``'intersect'``, ``'minus'``.
.. hint:: |boolean| |boolean.py|_
"""
bf = vtk.vtkBooleanOperationPolyDataFilter()
poly1 = actor1.computeNormals().polydata()
poly2 = actor2.computeNormals().polydata()
if operation.lower() == "plus" or operation.lower() == "+":
bf.SetOperationToUnion()
elif operation.lower() == "intersect":
bf.SetOperationToIntersection()
elif operation.lower() == "minus" or operation.lower() == "-":
bf.SetOperationToDifference()
bf.ReorientDifferenceCellsOn()
bf.SetInputData(0, poly1)
bf.SetInputData(1, poly2)
bf.Update()
actor = Actor(bf.GetOutput(), c, alpha, wire, bc, texture)
return actor | python | def booleanOperation(actor1, operation, actor2, c=None, alpha=1,
wire=False, bc=None, texture=None):
"""Volumetric union, intersection and subtraction of surfaces.
:param str operation: allowed operations: ``'plus'``, ``'intersect'``, ``'minus'``.
.. hint:: |boolean| |boolean.py|_
"""
bf = vtk.vtkBooleanOperationPolyDataFilter()
poly1 = actor1.computeNormals().polydata()
poly2 = actor2.computeNormals().polydata()
if operation.lower() == "plus" or operation.lower() == "+":
bf.SetOperationToUnion()
elif operation.lower() == "intersect":
bf.SetOperationToIntersection()
elif operation.lower() == "minus" or operation.lower() == "-":
bf.SetOperationToDifference()
bf.ReorientDifferenceCellsOn()
bf.SetInputData(0, poly1)
bf.SetInputData(1, poly2)
bf.Update()
actor = Actor(bf.GetOutput(), c, alpha, wire, bc, texture)
return actor | [
"def",
"booleanOperation",
"(",
"actor1",
",",
"operation",
",",
"actor2",
",",
"c",
"=",
"None",
",",
"alpha",
"=",
"1",
",",
"wire",
"=",
"False",
",",
"bc",
"=",
"None",
",",
"texture",
"=",
"None",
")",
":",
"bf",
"=",
"vtk",
".",
"vtkBooleanOp... | Volumetric union, intersection and subtraction of surfaces.
:param str operation: allowed operations: ``'plus'``, ``'intersect'``, ``'minus'``.
.. hint:: |boolean| |boolean.py|_ | [
"Volumetric",
"union",
"intersection",
"and",
"subtraction",
"of",
"surfaces",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1004-L1026 | train | 210,506 |
marcomusy/vtkplotter | vtkplotter/analysis.py | surfaceIntersection | def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3):
"""Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_
"""
bf = vtk.vtkIntersectionPolyDataFilter()
poly1 = actor1.GetMapper().GetInput()
poly2 = actor2.GetMapper().GetInput()
bf.SetInputData(0, poly1)
bf.SetInputData(1, poly2)
bf.Update()
actor = Actor(bf.GetOutput(), "k", 1)
actor.GetProperty().SetLineWidth(lw)
return actor | python | def surfaceIntersection(actor1, actor2, tol=1e-06, lw=3):
"""Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_
"""
bf = vtk.vtkIntersectionPolyDataFilter()
poly1 = actor1.GetMapper().GetInput()
poly2 = actor2.GetMapper().GetInput()
bf.SetInputData(0, poly1)
bf.SetInputData(1, poly2)
bf.Update()
actor = Actor(bf.GetOutput(), "k", 1)
actor.GetProperty().SetLineWidth(lw)
return actor | [
"def",
"surfaceIntersection",
"(",
"actor1",
",",
"actor2",
",",
"tol",
"=",
"1e-06",
",",
"lw",
"=",
"3",
")",
":",
"bf",
"=",
"vtk",
".",
"vtkIntersectionPolyDataFilter",
"(",
")",
"poly1",
"=",
"actor1",
".",
"GetMapper",
"(",
")",
".",
"GetInput",
... | Intersect 2 surfaces and return a line actor.
.. hint:: |surfIntersect.py|_ | [
"Intersect",
"2",
"surfaces",
"and",
"return",
"a",
"line",
"actor",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1029-L1042 | train | 210,507 |
marcomusy/vtkplotter | vtkplotter/analysis.py | probePoints | def probePoints(img, pts):
"""
Takes a ``vtkImageData`` and probes its scalars at the specified points in space.
"""
src = vtk.vtkProgrammableSource()
def readPoints():
output = src.GetPolyDataOutput()
points = vtk.vtkPoints()
for p in pts:
x, y, z = p
points.InsertNextPoint(x, y, z)
output.SetPoints(points)
cells = vtk.vtkCellArray()
cells.InsertNextCell(len(pts))
for i in range(len(pts)):
cells.InsertCellPoint(i)
output.SetVerts(cells)
src.SetExecuteMethod(readPoints)
src.Update()
probeFilter = vtk.vtkProbeFilter()
probeFilter.SetSourceData(img)
probeFilter.SetInputConnection(src.GetOutputPort())
probeFilter.Update()
pact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn
pact.mapper.SetScalarRange(img.GetScalarRange())
return pact | python | def probePoints(img, pts):
"""
Takes a ``vtkImageData`` and probes its scalars at the specified points in space.
"""
src = vtk.vtkProgrammableSource()
def readPoints():
output = src.GetPolyDataOutput()
points = vtk.vtkPoints()
for p in pts:
x, y, z = p
points.InsertNextPoint(x, y, z)
output.SetPoints(points)
cells = vtk.vtkCellArray()
cells.InsertNextCell(len(pts))
for i in range(len(pts)):
cells.InsertCellPoint(i)
output.SetVerts(cells)
src.SetExecuteMethod(readPoints)
src.Update()
probeFilter = vtk.vtkProbeFilter()
probeFilter.SetSourceData(img)
probeFilter.SetInputConnection(src.GetOutputPort())
probeFilter.Update()
pact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn
pact.mapper.SetScalarRange(img.GetScalarRange())
return pact | [
"def",
"probePoints",
"(",
"img",
",",
"pts",
")",
":",
"src",
"=",
"vtk",
".",
"vtkProgrammableSource",
"(",
")",
"def",
"readPoints",
"(",
")",
":",
"output",
"=",
"src",
".",
"GetPolyDataOutput",
"(",
")",
"points",
"=",
"vtk",
".",
"vtkPoints",
"("... | Takes a ``vtkImageData`` and probes its scalars at the specified points in space. | [
"Takes",
"a",
"vtkImageData",
"and",
"probes",
"its",
"scalars",
"at",
"the",
"specified",
"points",
"in",
"space",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1045-L1073 | train | 210,508 |
marcomusy/vtkplotter | vtkplotter/analysis.py | probeLine | def probeLine(img, p1, p2, res=100):
"""
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
"""
line = vtk.vtkLineSource()
line.SetResolution(res)
line.SetPoint1(p1)
line.SetPoint2(p2)
probeFilter = vtk.vtkProbeFilter()
probeFilter.SetSourceData(img)
probeFilter.SetInputConnection(line.GetOutputPort())
probeFilter.Update()
lact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn
lact.mapper.SetScalarRange(img.GetScalarRange())
return lact | python | def probeLine(img, p1, p2, res=100):
"""
Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_
"""
line = vtk.vtkLineSource()
line.SetResolution(res)
line.SetPoint1(p1)
line.SetPoint2(p2)
probeFilter = vtk.vtkProbeFilter()
probeFilter.SetSourceData(img)
probeFilter.SetInputConnection(line.GetOutputPort())
probeFilter.Update()
lact = Actor(probeFilter.GetOutput(), c=None) # ScalarVisibilityOn
lact.mapper.SetScalarRange(img.GetScalarRange())
return lact | [
"def",
"probeLine",
"(",
"img",
",",
"p1",
",",
"p2",
",",
"res",
"=",
"100",
")",
":",
"line",
"=",
"vtk",
".",
"vtkLineSource",
"(",
")",
"line",
".",
"SetResolution",
"(",
"res",
")",
"line",
".",
"SetPoint1",
"(",
"p1",
")",
"line",
".",
"Set... | Takes a ``vtkImageData`` and probes its scalars along a line defined by 2 points `p1` and `p2`.
.. hint:: |probeLine| |probeLine.py|_ | [
"Takes",
"a",
"vtkImageData",
"and",
"probes",
"its",
"scalars",
"along",
"a",
"line",
"defined",
"by",
"2",
"points",
"p1",
"and",
"p2",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1076-L1093 | train | 210,509 |
marcomusy/vtkplotter | vtkplotter/analysis.py | probePlane | def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)):
"""
Takes a ``vtkImageData`` and probes its scalars on a plane.
.. hint:: |probePlane| |probePlane.py|_
"""
plane = vtk.vtkPlane()
plane.SetOrigin(origin)
plane.SetNormal(normal)
planeCut = vtk.vtkCutter()
planeCut.SetInputData(img)
planeCut.SetCutFunction(plane)
planeCut.Update()
cutActor = Actor(planeCut.GetOutput(), c=None) # ScalarVisibilityOn
cutActor.mapper.SetScalarRange(img.GetPointData().GetScalars().GetRange())
return cutActor | python | def probePlane(img, origin=(0, 0, 0), normal=(1, 0, 0)):
"""
Takes a ``vtkImageData`` and probes its scalars on a plane.
.. hint:: |probePlane| |probePlane.py|_
"""
plane = vtk.vtkPlane()
plane.SetOrigin(origin)
plane.SetNormal(normal)
planeCut = vtk.vtkCutter()
planeCut.SetInputData(img)
planeCut.SetCutFunction(plane)
planeCut.Update()
cutActor = Actor(planeCut.GetOutput(), c=None) # ScalarVisibilityOn
cutActor.mapper.SetScalarRange(img.GetPointData().GetScalars().GetRange())
return cutActor | [
"def",
"probePlane",
"(",
"img",
",",
"origin",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
",",
"normal",
"=",
"(",
"1",
",",
"0",
",",
"0",
")",
")",
":",
"plane",
"=",
"vtk",
".",
"vtkPlane",
"(",
")",
"plane",
".",
"SetOrigin",
"(",
"origin",... | Takes a ``vtkImageData`` and probes its scalars on a plane.
.. hint:: |probePlane| |probePlane.py|_ | [
"Takes",
"a",
"vtkImageData",
"and",
"probes",
"its",
"scalars",
"on",
"a",
"plane",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1096-L1112 | train | 210,510 |
marcomusy/vtkplotter | vtkplotter/analysis.py | recoSurface | def recoSurface(points, bins=256):
"""
Surface reconstruction from a scattered cloud of points.
:param int bins: number of voxels in x, y and z.
.. hint:: |recosurface| |recosurface.py|_
"""
if isinstance(points, vtk.vtkActor):
points = points.coordinates()
N = len(points)
if N < 50:
print("recoSurface: Use at least 50 points.")
return None
points = np.array(points)
ptsSource = vtk.vtkPointSource()
ptsSource.SetNumberOfPoints(N)
ptsSource.Update()
vpts = ptsSource.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
polyData = ptsSource.GetOutput()
distance = vtk.vtkSignedDistance()
f = 0.1
x0, x1, y0, y1, z0, z1 = polyData.GetBounds()
distance.SetBounds(x0-(x1-x0)*f, x1+(x1-x0)*f,
y0-(y1-y0)*f, y1+(y1-y0)*f,
z0-(z1-z0)*f, z1+(z1-z0)*f)
if polyData.GetPointData().GetNormals():
distance.SetInputData(polyData)
else:
normals = vtk.vtkPCANormalEstimation()
normals.SetInputData(polyData)
normals.SetSampleSize(int(N / 50))
normals.SetNormalOrientationToGraphTraversal()
distance.SetInputConnection(normals.GetOutputPort())
print("Recalculating normals for", N, "Points, sample size=", int(N / 50))
b = polyData.GetBounds()
diagsize = np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
radius = diagsize / bins * 5
distance.SetRadius(radius)
distance.SetDimensions(bins, bins, bins)
distance.Update()
print("Calculating mesh from points with R =", radius)
surface = vtk.vtkExtractSurface()
surface.SetRadius(radius * 0.99)
surface.HoleFillingOn()
surface.ComputeNormalsOff()
surface.ComputeGradientsOff()
surface.SetInputConnection(distance.GetOutputPort())
surface.Update()
return Actor(surface.GetOutput(), "gold", 1, 0, "tomato") | python | def recoSurface(points, bins=256):
"""
Surface reconstruction from a scattered cloud of points.
:param int bins: number of voxels in x, y and z.
.. hint:: |recosurface| |recosurface.py|_
"""
if isinstance(points, vtk.vtkActor):
points = points.coordinates()
N = len(points)
if N < 50:
print("recoSurface: Use at least 50 points.")
return None
points = np.array(points)
ptsSource = vtk.vtkPointSource()
ptsSource.SetNumberOfPoints(N)
ptsSource.Update()
vpts = ptsSource.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
polyData = ptsSource.GetOutput()
distance = vtk.vtkSignedDistance()
f = 0.1
x0, x1, y0, y1, z0, z1 = polyData.GetBounds()
distance.SetBounds(x0-(x1-x0)*f, x1+(x1-x0)*f,
y0-(y1-y0)*f, y1+(y1-y0)*f,
z0-(z1-z0)*f, z1+(z1-z0)*f)
if polyData.GetPointData().GetNormals():
distance.SetInputData(polyData)
else:
normals = vtk.vtkPCANormalEstimation()
normals.SetInputData(polyData)
normals.SetSampleSize(int(N / 50))
normals.SetNormalOrientationToGraphTraversal()
distance.SetInputConnection(normals.GetOutputPort())
print("Recalculating normals for", N, "Points, sample size=", int(N / 50))
b = polyData.GetBounds()
diagsize = np.sqrt((b[1] - b[0]) ** 2 + (b[3] - b[2]) ** 2 + (b[5] - b[4]) ** 2)
radius = diagsize / bins * 5
distance.SetRadius(radius)
distance.SetDimensions(bins, bins, bins)
distance.Update()
print("Calculating mesh from points with R =", radius)
surface = vtk.vtkExtractSurface()
surface.SetRadius(radius * 0.99)
surface.HoleFillingOn()
surface.ComputeNormalsOff()
surface.ComputeGradientsOff()
surface.SetInputConnection(distance.GetOutputPort())
surface.Update()
return Actor(surface.GetOutput(), "gold", 1, 0, "tomato") | [
"def",
"recoSurface",
"(",
"points",
",",
"bins",
"=",
"256",
")",
":",
"if",
"isinstance",
"(",
"points",
",",
"vtk",
".",
"vtkActor",
")",
":",
"points",
"=",
"points",
".",
"coordinates",
"(",
")",
"N",
"=",
"len",
"(",
"points",
")",
"if",
"N",... | Surface reconstruction from a scattered cloud of points.
:param int bins: number of voxels in x, y and z.
.. hint:: |recosurface| |recosurface.py|_ | [
"Surface",
"reconstruction",
"from",
"a",
"scattered",
"cloud",
"of",
"points",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1231-L1287 | train | 210,511 |
marcomusy/vtkplotter | vtkplotter/analysis.py | cluster | def cluster(points, radius):
"""
Clustering of points in space.
`radius` is the radius of local search.
Individual subsets can be accessed through ``actor.clusters``.
.. hint:: |clustering| |clustering.py|_
"""
if isinstance(points, vtk.vtkActor):
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
poly = src.GetOutput()
cluster = vtk.vtkEuclideanClusterExtraction()
cluster.SetInputData(poly)
cluster.SetExtractionModeToAllClusters()
cluster.SetRadius(radius)
cluster.ColorClustersOn()
cluster.Update()
idsarr = cluster.GetOutput().GetPointData().GetArray("ClusterId")
Nc = cluster.GetNumberOfExtractedClusters()
sets = [[] for i in range(Nc)]
for i, p in enumerate(points):
sets[idsarr.GetValue(i)].append(p)
acts = []
for i, aset in enumerate(sets):
acts.append(vs.Points(aset, c=i))
actor = Assembly(acts)
actor.info["clusters"] = sets
print("Nr. of extracted clusters", Nc)
if Nc > 10:
print("First ten:")
for i in range(Nc):
if i > 9:
print("...")
break
print("Cluster #" + str(i) + ", N =", len(sets[i]))
print("Access individual clusters through attribute: actor.cluster")
return actor | python | def cluster(points, radius):
"""
Clustering of points in space.
`radius` is the radius of local search.
Individual subsets can be accessed through ``actor.clusters``.
.. hint:: |clustering| |clustering.py|_
"""
if isinstance(points, vtk.vtkActor):
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
poly = src.GetOutput()
cluster = vtk.vtkEuclideanClusterExtraction()
cluster.SetInputData(poly)
cluster.SetExtractionModeToAllClusters()
cluster.SetRadius(radius)
cluster.ColorClustersOn()
cluster.Update()
idsarr = cluster.GetOutput().GetPointData().GetArray("ClusterId")
Nc = cluster.GetNumberOfExtractedClusters()
sets = [[] for i in range(Nc)]
for i, p in enumerate(points):
sets[idsarr.GetValue(i)].append(p)
acts = []
for i, aset in enumerate(sets):
acts.append(vs.Points(aset, c=i))
actor = Assembly(acts)
actor.info["clusters"] = sets
print("Nr. of extracted clusters", Nc)
if Nc > 10:
print("First ten:")
for i in range(Nc):
if i > 9:
print("...")
break
print("Cluster #" + str(i) + ", N =", len(sets[i]))
print("Access individual clusters through attribute: actor.cluster")
return actor | [
"def",
"cluster",
"(",
"points",
",",
"radius",
")",
":",
"if",
"isinstance",
"(",
"points",
",",
"vtk",
".",
"vtkActor",
")",
":",
"poly",
"=",
"points",
".",
"GetMapper",
"(",
")",
".",
"GetInput",
"(",
")",
"else",
":",
"src",
"=",
"vtk",
".",
... | Clustering of points in space.
`radius` is the radius of local search.
Individual subsets can be accessed through ``actor.clusters``.
.. hint:: |clustering| |clustering.py|_ | [
"Clustering",
"of",
"points",
"in",
"space",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1290-L1340 | train | 210,512 |
marcomusy/vtkplotter | vtkplotter/analysis.py | removeOutliers | def removeOutliers(points, radius):
"""
Remove outliers from a cloud of points within the specified `radius` search.
.. hint:: |clustering| |clustering.py|_
"""
isactor = False
if isinstance(points, vtk.vtkActor):
isactor = True
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
poly = src.GetOutput()
removal = vtk.vtkRadiusOutlierRemoval()
removal.SetInputData(poly)
removal.SetRadius(radius)
removal.SetNumberOfNeighbors(5)
removal.GenerateOutliersOff()
removal.Update()
rpoly = removal.GetOutput()
print("# of removed outlier points: ",
removal.GetNumberOfPointsRemoved(), '/', poly.GetNumberOfPoints())
outpts = []
for i in range(rpoly.GetNumberOfPoints()):
outpts.append(list(rpoly.GetPoint(i)))
outpts = np.array(outpts)
if not isactor:
return outpts
actor = vs.Points(outpts)
return actor | python | def removeOutliers(points, radius):
"""
Remove outliers from a cloud of points within the specified `radius` search.
.. hint:: |clustering| |clustering.py|_
"""
isactor = False
if isinstance(points, vtk.vtkActor):
isactor = True
poly = points.GetMapper().GetInput()
else:
src = vtk.vtkPointSource()
src.SetNumberOfPoints(len(points))
src.Update()
vpts = src.GetOutput().GetPoints()
for i, p in enumerate(points):
vpts.SetPoint(i, p)
poly = src.GetOutput()
removal = vtk.vtkRadiusOutlierRemoval()
removal.SetInputData(poly)
removal.SetRadius(radius)
removal.SetNumberOfNeighbors(5)
removal.GenerateOutliersOff()
removal.Update()
rpoly = removal.GetOutput()
print("# of removed outlier points: ",
removal.GetNumberOfPointsRemoved(), '/', poly.GetNumberOfPoints())
outpts = []
for i in range(rpoly.GetNumberOfPoints()):
outpts.append(list(rpoly.GetPoint(i)))
outpts = np.array(outpts)
if not isactor:
return outpts
actor = vs.Points(outpts)
return actor | [
"def",
"removeOutliers",
"(",
"points",
",",
"radius",
")",
":",
"isactor",
"=",
"False",
"if",
"isinstance",
"(",
"points",
",",
"vtk",
".",
"vtkActor",
")",
":",
"isactor",
"=",
"True",
"poly",
"=",
"points",
".",
"GetMapper",
"(",
")",
".",
"GetInpu... | Remove outliers from a cloud of points within the specified `radius` search.
.. hint:: |clustering| |clustering.py|_ | [
"Remove",
"outliers",
"from",
"a",
"cloud",
"of",
"points",
"within",
"the",
"specified",
"radius",
"search",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1343-L1379 | train | 210,513 |
marcomusy/vtkplotter | vtkplotter/analysis.py | thinPlateSpline | def thinPlateSpline(actor, sourcePts, targetPts, userFunctions=(None, None)):
"""
`Thin Plate Spline` transformations describe a nonlinear warp transform defined by a set
of source and target landmarks. Any point on the mesh close to a source landmark will
be moved to a place close to the corresponding target landmark.
The points in between are interpolated smoothly using Bookstein's Thin Plate Spline algorithm.
Transformation object is saved in ``actor.info['transform']``.
:param userFunctions: You must supply both the function
and its derivative with respect to r.
.. hint:: |thinplate| |thinplate.py|_
|thinplate_grid| |thinplate_grid.py|_
|thinplate_morphing| |thinplate_morphing.py|_
|interpolateField| |interpolateField.py|_
"""
ns = len(sourcePts)
ptsou = vtk.vtkPoints()
ptsou.SetNumberOfPoints(ns)
for i in range(ns):
ptsou.SetPoint(i, sourcePts[i])
nt = len(sourcePts)
if ns != nt:
vc.printc("~times thinPlateSpline Error: #source != #target points", ns, nt, c=1)
exit()
pttar = vtk.vtkPoints()
pttar.SetNumberOfPoints(nt)
for i in range(ns):
pttar.SetPoint(i, targetPts[i])
transform = vtk.vtkThinPlateSplineTransform()
transform.SetBasisToR()
if userFunctions[0]:
transform.SetBasisFunction(userFunctions[0])
transform.SetBasisDerivative(userFunctions[1])
transform.SetSigma(1)
transform.SetSourceLandmarks(ptsou)
transform.SetTargetLandmarks(pttar)
tfa = transformFilter(actor.polydata(), transform)
tfa.info["transform"] = transform
return tfa | python | def thinPlateSpline(actor, sourcePts, targetPts, userFunctions=(None, None)):
"""
`Thin Plate Spline` transformations describe a nonlinear warp transform defined by a set
of source and target landmarks. Any point on the mesh close to a source landmark will
be moved to a place close to the corresponding target landmark.
The points in between are interpolated smoothly using Bookstein's Thin Plate Spline algorithm.
Transformation object is saved in ``actor.info['transform']``.
:param userFunctions: You must supply both the function
and its derivative with respect to r.
.. hint:: |thinplate| |thinplate.py|_
|thinplate_grid| |thinplate_grid.py|_
|thinplate_morphing| |thinplate_morphing.py|_
|interpolateField| |interpolateField.py|_
"""
ns = len(sourcePts)
ptsou = vtk.vtkPoints()
ptsou.SetNumberOfPoints(ns)
for i in range(ns):
ptsou.SetPoint(i, sourcePts[i])
nt = len(sourcePts)
if ns != nt:
vc.printc("~times thinPlateSpline Error: #source != #target points", ns, nt, c=1)
exit()
pttar = vtk.vtkPoints()
pttar.SetNumberOfPoints(nt)
for i in range(ns):
pttar.SetPoint(i, targetPts[i])
transform = vtk.vtkThinPlateSplineTransform()
transform.SetBasisToR()
if userFunctions[0]:
transform.SetBasisFunction(userFunctions[0])
transform.SetBasisDerivative(userFunctions[1])
transform.SetSigma(1)
transform.SetSourceLandmarks(ptsou)
transform.SetTargetLandmarks(pttar)
tfa = transformFilter(actor.polydata(), transform)
tfa.info["transform"] = transform
return tfa | [
"def",
"thinPlateSpline",
"(",
"actor",
",",
"sourcePts",
",",
"targetPts",
",",
"userFunctions",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"ns",
"=",
"len",
"(",
"sourcePts",
")",
"ptsou",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"ptsou",
".",
"S... | `Thin Plate Spline` transformations describe a nonlinear warp transform defined by a set
of source and target landmarks. Any point on the mesh close to a source landmark will
be moved to a place close to the corresponding target landmark.
The points in between are interpolated smoothly using Bookstein's Thin Plate Spline algorithm.
Transformation object is saved in ``actor.info['transform']``.
:param userFunctions: You must supply both the function
and its derivative with respect to r.
.. hint:: |thinplate| |thinplate.py|_
|thinplate_grid| |thinplate_grid.py|_
|thinplate_morphing| |thinplate_morphing.py|_
|interpolateField| |interpolateField.py|_ | [
"Thin",
"Plate",
"Spline",
"transformations",
"describe",
"a",
"nonlinear",
"warp",
"transform",
"defined",
"by",
"a",
"set",
"of",
"source",
"and",
"target",
"landmarks",
".",
"Any",
"point",
"on",
"the",
"mesh",
"close",
"to",
"a",
"source",
"landmark",
"w... | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1382-L1429 | train | 210,514 |
marcomusy/vtkplotter | vtkplotter/analysis.py | transformFilter | def transformFilter(actor, transformation):
"""
Transform a ``vtkActor`` and return a new object.
"""
tf = vtk.vtkTransformPolyDataFilter()
tf.SetTransform(transformation)
prop = None
if isinstance(actor, vtk.vtkPolyData):
tf.SetInputData(actor)
else:
tf.SetInputData(actor.polydata())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
tf.Update()
tfa = Actor(tf.GetOutput())
if prop:
tfa.SetProperty(prop)
return tfa | python | def transformFilter(actor, transformation):
"""
Transform a ``vtkActor`` and return a new object.
"""
tf = vtk.vtkTransformPolyDataFilter()
tf.SetTransform(transformation)
prop = None
if isinstance(actor, vtk.vtkPolyData):
tf.SetInputData(actor)
else:
tf.SetInputData(actor.polydata())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
tf.Update()
tfa = Actor(tf.GetOutput())
if prop:
tfa.SetProperty(prop)
return tfa | [
"def",
"transformFilter",
"(",
"actor",
",",
"transformation",
")",
":",
"tf",
"=",
"vtk",
".",
"vtkTransformPolyDataFilter",
"(",
")",
"tf",
".",
"SetTransform",
"(",
"transformation",
")",
"prop",
"=",
"None",
"if",
"isinstance",
"(",
"actor",
",",
"vtk",
... | Transform a ``vtkActor`` and return a new object. | [
"Transform",
"a",
"vtkActor",
"and",
"return",
"a",
"new",
"object",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1432-L1450 | train | 210,515 |
marcomusy/vtkplotter | vtkplotter/analysis.py | splitByConnectivity | def splitByConnectivity(actor, maxdepth=100):
"""
Split a mesh by connectivity and order the pieces by increasing area.
:param int maxdepth: only consider this number of mesh parts.
.. hint:: |splitmesh| |splitmesh.py|_
"""
actor.addIDs()
pd = actor.polydata()
cf = vtk.vtkConnectivityFilter()
cf.SetInputData(pd)
cf.SetExtractionModeToAllRegions()
cf.ColorRegionsOn()
cf.Update()
cpd = cf.GetOutput()
a = Actor(cpd)
alist = []
for t in range(max(a.scalars("RegionId")) - 1):
if t == maxdepth:
break
suba = a.clone().threshold("RegionId", t - 0.1, t + 0.1)
area = suba.area()
alist.append([suba, area])
alist.sort(key=lambda x: x[1])
alist.reverse()
blist = []
for i, l in enumerate(alist):
l[0].color(i + 1)
l[0].mapper.ScalarVisibilityOff()
blist.append(l[0])
return blist | python | def splitByConnectivity(actor, maxdepth=100):
"""
Split a mesh by connectivity and order the pieces by increasing area.
:param int maxdepth: only consider this number of mesh parts.
.. hint:: |splitmesh| |splitmesh.py|_
"""
actor.addIDs()
pd = actor.polydata()
cf = vtk.vtkConnectivityFilter()
cf.SetInputData(pd)
cf.SetExtractionModeToAllRegions()
cf.ColorRegionsOn()
cf.Update()
cpd = cf.GetOutput()
a = Actor(cpd)
alist = []
for t in range(max(a.scalars("RegionId")) - 1):
if t == maxdepth:
break
suba = a.clone().threshold("RegionId", t - 0.1, t + 0.1)
area = suba.area()
alist.append([suba, area])
alist.sort(key=lambda x: x[1])
alist.reverse()
blist = []
for i, l in enumerate(alist):
l[0].color(i + 1)
l[0].mapper.ScalarVisibilityOff()
blist.append(l[0])
return blist | [
"def",
"splitByConnectivity",
"(",
"actor",
",",
"maxdepth",
"=",
"100",
")",
":",
"actor",
".",
"addIDs",
"(",
")",
"pd",
"=",
"actor",
".",
"polydata",
"(",
")",
"cf",
"=",
"vtk",
".",
"vtkConnectivityFilter",
"(",
")",
"cf",
".",
"SetInputData",
"("... | Split a mesh by connectivity and order the pieces by increasing area.
:param int maxdepth: only consider this number of mesh parts.
.. hint:: |splitmesh| |splitmesh.py|_ | [
"Split",
"a",
"mesh",
"by",
"connectivity",
"and",
"order",
"the",
"pieces",
"by",
"increasing",
"area",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1590-L1623 | train | 210,516 |
marcomusy/vtkplotter | vtkplotter/analysis.py | pointSampler | def pointSampler(actor, distance=None):
"""
Algorithm to generate points the specified distance apart.
"""
poly = actor.polydata(True)
pointSampler = vtk.vtkPolyDataPointSampler()
if not distance:
distance = actor.diagonalSize() / 100.0
pointSampler.SetDistance(distance)
# pointSampler.GenerateVertexPointsOff()
# pointSampler.GenerateEdgePointsOff()
# pointSampler.GenerateVerticesOn()
# pointSampler.GenerateInteriorPointsOn()
pointSampler.SetInputData(poly)
pointSampler.Update()
uactor = Actor(pointSampler.GetOutput())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
uactor.SetProperty(prop)
return uactor | python | def pointSampler(actor, distance=None):
"""
Algorithm to generate points the specified distance apart.
"""
poly = actor.polydata(True)
pointSampler = vtk.vtkPolyDataPointSampler()
if not distance:
distance = actor.diagonalSize() / 100.0
pointSampler.SetDistance(distance)
# pointSampler.GenerateVertexPointsOff()
# pointSampler.GenerateEdgePointsOff()
# pointSampler.GenerateVerticesOn()
# pointSampler.GenerateInteriorPointsOn()
pointSampler.SetInputData(poly)
pointSampler.Update()
uactor = Actor(pointSampler.GetOutput())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
uactor.SetProperty(prop)
return uactor | [
"def",
"pointSampler",
"(",
"actor",
",",
"distance",
"=",
"None",
")",
":",
"poly",
"=",
"actor",
".",
"polydata",
"(",
"True",
")",
"pointSampler",
"=",
"vtk",
".",
"vtkPolyDataPointSampler",
"(",
")",
"if",
"not",
"distance",
":",
"distance",
"=",
"ac... | Algorithm to generate points the specified distance apart. | [
"Algorithm",
"to",
"generate",
"points",
"the",
"specified",
"distance",
"apart",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1626-L1647 | train | 210,517 |
marcomusy/vtkplotter | vtkplotter/analysis.py | geodesic | def geodesic(actor, start, end):
"""
Dijkstra algorithm to compute the graph geodesic.
Takes as input a polygonal mesh and performs a single source shortest path calculation.
:param start: start vertex index or close point `[x,y,z]`
:type start: int, list
:param end: end vertex index or close point `[x,y,z]`
:type start: int, list
.. hint:: |geodesic| |geodesic.py|_
"""
dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
if vu.isSequence(start):
cc = actor.coordinates()
pa = vs.Points(cc)
start = pa.closestPoint(start, returnIds=True)
end = pa.closestPoint(end, returnIds=True)
dijkstra.SetInputData(pa.polydata())
else:
dijkstra.SetInputData(actor.polydata())
dijkstra.SetStartVertex(start)
dijkstra.SetEndVertex(end)
dijkstra.Update()
weights = vtk.vtkDoubleArray()
dijkstra.GetCumulativeWeights(weights)
length = weights.GetMaxId() + 1
arr = np.zeros(length)
for i in range(length):
arr[i] = weights.GetTuple(i)[0]
dactor = Actor(dijkstra.GetOutput())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
prop.SetLineWidth(3)
prop.SetOpacity(1)
dactor.SetProperty(prop)
dactor.info["CumulativeWeights"] = arr
return dactor | python | def geodesic(actor, start, end):
"""
Dijkstra algorithm to compute the graph geodesic.
Takes as input a polygonal mesh and performs a single source shortest path calculation.
:param start: start vertex index or close point `[x,y,z]`
:type start: int, list
:param end: end vertex index or close point `[x,y,z]`
:type start: int, list
.. hint:: |geodesic| |geodesic.py|_
"""
dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
if vu.isSequence(start):
cc = actor.coordinates()
pa = vs.Points(cc)
start = pa.closestPoint(start, returnIds=True)
end = pa.closestPoint(end, returnIds=True)
dijkstra.SetInputData(pa.polydata())
else:
dijkstra.SetInputData(actor.polydata())
dijkstra.SetStartVertex(start)
dijkstra.SetEndVertex(end)
dijkstra.Update()
weights = vtk.vtkDoubleArray()
dijkstra.GetCumulativeWeights(weights)
length = weights.GetMaxId() + 1
arr = np.zeros(length)
for i in range(length):
arr[i] = weights.GetTuple(i)[0]
dactor = Actor(dijkstra.GetOutput())
prop = vtk.vtkProperty()
prop.DeepCopy(actor.GetProperty())
prop.SetLineWidth(3)
prop.SetOpacity(1)
dactor.SetProperty(prop)
dactor.info["CumulativeWeights"] = arr
return dactor | [
"def",
"geodesic",
"(",
"actor",
",",
"start",
",",
"end",
")",
":",
"dijkstra",
"=",
"vtk",
".",
"vtkDijkstraGraphGeodesicPath",
"(",
")",
"if",
"vu",
".",
"isSequence",
"(",
"start",
")",
":",
"cc",
"=",
"actor",
".",
"coordinates",
"(",
")",
"pa",
... | Dijkstra algorithm to compute the graph geodesic.
Takes as input a polygonal mesh and performs a single source shortest path calculation.
:param start: start vertex index or close point `[x,y,z]`
:type start: int, list
:param end: end vertex index or close point `[x,y,z]`
:type start: int, list
.. hint:: |geodesic| |geodesic.py|_ | [
"Dijkstra",
"algorithm",
"to",
"compute",
"the",
"graph",
"geodesic",
".",
"Takes",
"as",
"input",
"a",
"polygonal",
"mesh",
"and",
"performs",
"a",
"single",
"source",
"shortest",
"path",
"calculation",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1650-L1693 | train | 210,518 |
marcomusy/vtkplotter | vtkplotter/analysis.py | convexHull | def convexHull(actor_or_list, alphaConstant=0):
"""
Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circumsphere (of radius alpha) will be output.
Otherwise, only tetrahedra will be output.
.. hint:: |convexHull| |convexHull.py|_
"""
if vu.isSequence(actor_or_list):
actor = vs.Points(actor_or_list)
else:
actor = actor_or_list
apoly = actor.clean().polydata()
triangleFilter = vtk.vtkTriangleFilter()
triangleFilter.SetInputData(apoly)
triangleFilter.Update()
poly = triangleFilter.GetOutput()
delaunay = vtk.vtkDelaunay3D() # Create the convex hull of the pointcloud
if alphaConstant:
delaunay.SetAlpha(alphaConstant)
delaunay.SetInputData(poly)
delaunay.Update()
surfaceFilter = vtk.vtkDataSetSurfaceFilter()
surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
surfaceFilter.Update()
chuact = Actor(surfaceFilter.GetOutput())
return chuact | python | def convexHull(actor_or_list, alphaConstant=0):
"""
Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circumsphere (of radius alpha) will be output.
Otherwise, only tetrahedra will be output.
.. hint:: |convexHull| |convexHull.py|_
"""
if vu.isSequence(actor_or_list):
actor = vs.Points(actor_or_list)
else:
actor = actor_or_list
apoly = actor.clean().polydata()
triangleFilter = vtk.vtkTriangleFilter()
triangleFilter.SetInputData(apoly)
triangleFilter.Update()
poly = triangleFilter.GetOutput()
delaunay = vtk.vtkDelaunay3D() # Create the convex hull of the pointcloud
if alphaConstant:
delaunay.SetAlpha(alphaConstant)
delaunay.SetInputData(poly)
delaunay.Update()
surfaceFilter = vtk.vtkDataSetSurfaceFilter()
surfaceFilter.SetInputConnection(delaunay.GetOutputPort())
surfaceFilter.Update()
chuact = Actor(surfaceFilter.GetOutput())
return chuact | [
"def",
"convexHull",
"(",
"actor_or_list",
",",
"alphaConstant",
"=",
"0",
")",
":",
"if",
"vu",
".",
"isSequence",
"(",
"actor_or_list",
")",
":",
"actor",
"=",
"vs",
".",
"Points",
"(",
"actor_or_list",
")",
"else",
":",
"actor",
"=",
"actor_or_list",
... | Create a 3D Delaunay triangulation of input points.
:param actor_or_list: can be either an ``Actor`` or a list of 3D points.
:param float alphaConstant: For a non-zero alpha value, only verts, edges, faces,
or tetra contained within the circumsphere (of radius alpha) will be output.
Otherwise, only tetrahedra will be output.
.. hint:: |convexHull| |convexHull.py|_ | [
"Create",
"a",
"3D",
"Delaunay",
"triangulation",
"of",
"input",
"points",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1696-L1729 | train | 210,519 |
marcomusy/vtkplotter | vtkplotter/analysis.py | extractSurface | def extractSurface(image, radius=0.5):
"""
``vtkExtractSurface`` filter. Input is a ``vtkImageData``.
Generate zero-crossing isosurface from truncated signed distance volume.
"""
fe = vtk.vtkExtractSurface()
fe.SetInputData(image)
fe.SetRadius(radius)
fe.Update()
return Actor(fe.GetOutput()) | python | def extractSurface(image, radius=0.5):
"""
``vtkExtractSurface`` filter. Input is a ``vtkImageData``.
Generate zero-crossing isosurface from truncated signed distance volume.
"""
fe = vtk.vtkExtractSurface()
fe.SetInputData(image)
fe.SetRadius(radius)
fe.Update()
return Actor(fe.GetOutput()) | [
"def",
"extractSurface",
"(",
"image",
",",
"radius",
"=",
"0.5",
")",
":",
"fe",
"=",
"vtk",
".",
"vtkExtractSurface",
"(",
")",
"fe",
".",
"SetInputData",
"(",
"image",
")",
"fe",
".",
"SetRadius",
"(",
"radius",
")",
"fe",
".",
"Update",
"(",
")",... | ``vtkExtractSurface`` filter. Input is a ``vtkImageData``.
Generate zero-crossing isosurface from truncated signed distance volume. | [
"vtkExtractSurface",
"filter",
".",
"Input",
"is",
"a",
"vtkImageData",
".",
"Generate",
"zero",
"-",
"crossing",
"isosurface",
"from",
"truncated",
"signed",
"distance",
"volume",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1803-L1812 | train | 210,520 |
marcomusy/vtkplotter | vtkplotter/analysis.py | projectSphereFilter | def projectSphereFilter(actor):
"""
Project a spherical-like object onto a plane.
.. hint:: |projectsphere| |projectsphere.py|_
"""
poly = actor.polydata()
psf = vtk.vtkProjectSphereFilter()
psf.SetInputData(poly)
psf.Update()
a = Actor(psf.GetOutput())
return a | python | def projectSphereFilter(actor):
"""
Project a spherical-like object onto a plane.
.. hint:: |projectsphere| |projectsphere.py|_
"""
poly = actor.polydata()
psf = vtk.vtkProjectSphereFilter()
psf.SetInputData(poly)
psf.Update()
a = Actor(psf.GetOutput())
return a | [
"def",
"projectSphereFilter",
"(",
"actor",
")",
":",
"poly",
"=",
"actor",
".",
"polydata",
"(",
")",
"psf",
"=",
"vtk",
".",
"vtkProjectSphereFilter",
"(",
")",
"psf",
".",
"SetInputData",
"(",
"poly",
")",
"psf",
".",
"Update",
"(",
")",
"a",
"=",
... | Project a spherical-like object onto a plane.
.. hint:: |projectsphere| |projectsphere.py|_ | [
"Project",
"a",
"spherical",
"-",
"like",
"object",
"onto",
"a",
"plane",
"."
] | 692c3396782722ec525bc1346a26999868c650c6 | https://github.com/marcomusy/vtkplotter/blob/692c3396782722ec525bc1346a26999868c650c6/vtkplotter/analysis.py#L1815-L1826 | train | 210,521 |
iancmcc/ouimeaux | ouimeaux/environment.py | Environment.wait | def wait(self, timeout=None):
"""
Wait for events.
"""
try:
if timeout:
gevent.sleep(timeout)
else:
while True:
gevent.sleep(1000)
except (KeyboardInterrupt, SystemExit, Exception):
pass | python | def wait(self, timeout=None):
"""
Wait for events.
"""
try:
if timeout:
gevent.sleep(timeout)
else:
while True:
gevent.sleep(1000)
except (KeyboardInterrupt, SystemExit, Exception):
pass | [
"def",
"wait",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"try",
":",
"if",
"timeout",
":",
"gevent",
".",
"sleep",
"(",
"timeout",
")",
"else",
":",
"while",
"True",
":",
"gevent",
".",
"sleep",
"(",
"1000",
")",
"except",
"(",
"KeyboardI... | Wait for events. | [
"Wait",
"for",
"events",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/environment.py#L88-L99 | train | 210,522 |
iancmcc/ouimeaux | ouimeaux/environment.py | Environment.discover | def discover(self, seconds=2):
"""
Discover devices in the environment.
@param seconds: Number of seconds to broadcast requests.
@type seconds: int
"""
log.info("Discovering devices")
with gevent.Timeout(seconds, StopBroadcasting) as timeout:
try:
try:
while True:
self.upnp.broadcast()
gevent.sleep(1)
except Exception as e:
raise StopBroadcasting(e)
except StopBroadcasting:
return | python | def discover(self, seconds=2):
"""
Discover devices in the environment.
@param seconds: Number of seconds to broadcast requests.
@type seconds: int
"""
log.info("Discovering devices")
with gevent.Timeout(seconds, StopBroadcasting) as timeout:
try:
try:
while True:
self.upnp.broadcast()
gevent.sleep(1)
except Exception as e:
raise StopBroadcasting(e)
except StopBroadcasting:
return | [
"def",
"discover",
"(",
"self",
",",
"seconds",
"=",
"2",
")",
":",
"log",
".",
"info",
"(",
"\"Discovering devices\"",
")",
"with",
"gevent",
".",
"Timeout",
"(",
"seconds",
",",
"StopBroadcasting",
")",
"as",
"timeout",
":",
"try",
":",
"try",
":",
"... | Discover devices in the environment.
@param seconds: Number of seconds to broadcast requests.
@type seconds: int | [
"Discover",
"devices",
"in",
"the",
"environment",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/environment.py#L101-L118 | train | 210,523 |
iancmcc/ouimeaux | ouimeaux/pysignals/dispatcher.py | Signal.send | def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Returns a list of tuple pairs [(receiver, response), ... ].
"""
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
for receiver in self._live_receivers(sender):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses | python | def send(self, sender, **named):
"""
Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Returns a list of tuple pairs [(receiver, response), ... ].
"""
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
for receiver in self._live_receivers(sender):
response = receiver(signal=self, sender=sender, **named)
responses.append((receiver, response))
return responses | [
"def",
"send",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"responses",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":",
"r... | Send signal from sender to all connected receivers.
If any receiver raises an error, the error propagates back through send,
terminating the dispatch loop. So it's possible that all receivers
won't be called if an error is raised.
Arguments:
sender
The sender of the signal. Either a specific object or None.
named
Named arguments which will be passed to receivers.
Returns a list of tuple pairs [(receiver, response), ... ]. | [
"Send",
"signal",
"from",
"sender",
"to",
"all",
"connected",
"receivers",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L178-L203 | train | 210,524 |
iancmcc/ouimeaux | ouimeaux/pysignals/dispatcher.py | Signal.send_robust | def send_robust(self, sender, **named):
"""
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the argument names defined in
providing_args.
Return a list of tuple pairs [(receiver, response), ... ]. May raise
DispatcherKeyError.
If any receiver raises an error (specifically any subclass of
Exception), the error instance is returned as the result for that
receiver. The traceback is always attached to the error at
``__traceback__``.
"""
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
for receiver in self._live_receivers(sender):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
if not hasattr(err, '__traceback__'):
err.__traceback__ = sys.exc_info()[2]
responses.append((receiver, err))
else:
responses.append((receiver, response))
return responses | python | def send_robust(self, sender, **named):
"""
Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the argument names defined in
providing_args.
Return a list of tuple pairs [(receiver, response), ... ]. May raise
DispatcherKeyError.
If any receiver raises an error (specifically any subclass of
Exception), the error instance is returned as the result for that
receiver. The traceback is always attached to the error at
``__traceback__``.
"""
responses = []
if not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS:
return responses
# Call each receiver with whatever arguments it can accept.
# Return a list of tuple pairs [(receiver, response), ... ].
for receiver in self._live_receivers(sender):
try:
response = receiver(signal=self, sender=sender, **named)
except Exception as err:
if not hasattr(err, '__traceback__'):
err.__traceback__ = sys.exc_info()[2]
responses.append((receiver, err))
else:
responses.append((receiver, response))
return responses | [
"def",
"send_robust",
"(",
"self",
",",
"sender",
",",
"*",
"*",
"named",
")",
":",
"responses",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"receivers",
"or",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",
")",
"is",
"NO_RECEIVERS",
":... | Send signal from sender to all connected receivers catching errors.
Arguments:
sender
The sender of the signal. Can be any python object (normally one
registered with a connect if you actually want something to
occur).
named
Named arguments which will be passed to receivers. These
arguments must be a subset of the argument names defined in
providing_args.
Return a list of tuple pairs [(receiver, response), ... ]. May raise
DispatcherKeyError.
If any receiver raises an error (specifically any subclass of
Exception), the error instance is returned as the result for that
receiver. The traceback is always attached to the error at
``__traceback__``. | [
"Send",
"signal",
"from",
"sender",
"to",
"all",
"connected",
"receivers",
"catching",
"errors",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L205-L244 | train | 210,525 |
iancmcc/ouimeaux | ouimeaux/pysignals/dispatcher.py | Signal._live_receivers | def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
receivers = None
if self.use_caching and not self._dead_receivers:
receivers = self.sender_receivers_cache.get(sender)
# We could end up here with NO_RECEIVERS even if we do check this case in
# .send() prior to calling _live_receivers() due to concurrent .send() call.
if receivers is NO_RECEIVERS:
return []
if receivers is None:
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
if self.use_caching:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers | python | def _live_receivers(self, sender):
"""
Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers.
"""
receivers = None
if self.use_caching and not self._dead_receivers:
receivers = self.sender_receivers_cache.get(sender)
# We could end up here with NO_RECEIVERS even if we do check this case in
# .send() prior to calling _live_receivers() due to concurrent .send() call.
if receivers is NO_RECEIVERS:
return []
if receivers is None:
with self.lock:
self._clear_dead_receivers()
senderkey = _make_id(sender)
receivers = []
for (receiverkey, r_senderkey), receiver in self.receivers:
if r_senderkey == NONE_ID or r_senderkey == senderkey:
receivers.append(receiver)
if self.use_caching:
if not receivers:
self.sender_receivers_cache[sender] = NO_RECEIVERS
else:
# Note, we must cache the weakref versions.
self.sender_receivers_cache[sender] = receivers
non_weak_receivers = []
for receiver in receivers:
if isinstance(receiver, weakref.ReferenceType):
# Dereference the weak reference.
receiver = receiver()
if receiver is not None:
non_weak_receivers.append(receiver)
else:
non_weak_receivers.append(receiver)
return non_weak_receivers | [
"def",
"_live_receivers",
"(",
"self",
",",
"sender",
")",
":",
"receivers",
"=",
"None",
"if",
"self",
".",
"use_caching",
"and",
"not",
"self",
".",
"_dead_receivers",
":",
"receivers",
"=",
"self",
".",
"sender_receivers_cache",
".",
"get",
"(",
"sender",... | Filter sequence of receivers to get resolved, live receivers.
This checks for weak references and resolves them, then returning only
live receivers. | [
"Filter",
"sequence",
"of",
"receivers",
"to",
"get",
"resolved",
"live",
"receivers",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/pysignals/dispatcher.py#L257-L294 | train | 210,526 |
iancmcc/ouimeaux | ouimeaux/device/switch.py | Switch.set_state | def set_state(self, state):
"""
Set the state of this device to on or off.
"""
self.basicevent.SetBinaryState(BinaryState=int(state))
self._state = int(state) | python | def set_state(self, state):
"""
Set the state of this device to on or off.
"""
self.basicevent.SetBinaryState(BinaryState=int(state))
self._state = int(state) | [
"def",
"set_state",
"(",
"self",
",",
"state",
")",
":",
"self",
".",
"basicevent",
".",
"SetBinaryState",
"(",
"BinaryState",
"=",
"int",
"(",
"state",
")",
")",
"self",
".",
"_state",
"=",
"int",
"(",
"state",
")"
] | Set the state of this device to on or off. | [
"Set",
"the",
"state",
"of",
"this",
"device",
"to",
"on",
"or",
"off",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/device/switch.py#L8-L13 | train | 210,527 |
iancmcc/ouimeaux | ouimeaux/discovery.py | UPnP.broadcast | def broadcast(self):
"""
Send a multicast M-SEARCH request asking for devices to report in.
"""
log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port)
request = '\r\n'.join(("M-SEARCH * HTTP/1.1",
"HOST:{mcast_ip}:{mcast_port}",
"ST:upnp:rootdevice",
"MX:2",
'MAN:"ssdp:discover"',
"", "")).format(**self.__dict__)
self.server.sendto(request.encode(), (self.mcast_ip, self.mcast_port)) | python | def broadcast(self):
"""
Send a multicast M-SEARCH request asking for devices to report in.
"""
log.debug("Broadcasting M-SEARCH to %s:%s", self.mcast_ip, self.mcast_port)
request = '\r\n'.join(("M-SEARCH * HTTP/1.1",
"HOST:{mcast_ip}:{mcast_port}",
"ST:upnp:rootdevice",
"MX:2",
'MAN:"ssdp:discover"',
"", "")).format(**self.__dict__)
self.server.sendto(request.encode(), (self.mcast_ip, self.mcast_port)) | [
"def",
"broadcast",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"\"Broadcasting M-SEARCH to %s:%s\"",
",",
"self",
".",
"mcast_ip",
",",
"self",
".",
"mcast_port",
")",
"request",
"=",
"'\\r\\n'",
".",
"join",
"(",
"(",
"\"M-SEARCH * HTTP/1.1\"",
",",
"... | Send a multicast M-SEARCH request asking for devices to report in. | [
"Send",
"a",
"multicast",
"M",
"-",
"SEARCH",
"request",
"asking",
"for",
"devices",
"to",
"report",
"in",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/discovery.py#L70-L81 | train | 210,528 |
iancmcc/ouimeaux | ouimeaux/utils.py | retry_with_delay | def retry_with_delay(f, delay=60):
"""
Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries.
"""
@wraps(f)
def inner(*args, **kwargs):
kwargs['timeout'] = 5
remaining = get_retries() + 1
while remaining:
remaining -= 1
try:
return f(*args, **kwargs)
except (requests.ConnectionError, requests.Timeout):
if not remaining:
raise
gevent.sleep(delay)
return inner | python | def retry_with_delay(f, delay=60):
"""
Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries.
"""
@wraps(f)
def inner(*args, **kwargs):
kwargs['timeout'] = 5
remaining = get_retries() + 1
while remaining:
remaining -= 1
try:
return f(*args, **kwargs)
except (requests.ConnectionError, requests.Timeout):
if not remaining:
raise
gevent.sleep(delay)
return inner | [
"def",
"retry_with_delay",
"(",
"f",
",",
"delay",
"=",
"60",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'timeout'",
"]",
"=",
"5",
"remaining",
"=",
"get_retries",
... | Retry the wrapped requests.request function in case of ConnectionError.
Optionally limit the number of retries or set the delay between retries. | [
"Retry",
"the",
"wrapped",
"requests",
".",
"request",
"function",
"in",
"case",
"of",
"ConnectionError",
".",
"Optionally",
"limit",
"the",
"number",
"of",
"retries",
"or",
"set",
"the",
"delay",
"between",
"retries",
"."
] | 89f3d05e7ae0a356690f898a4e1801ea3c104200 | https://github.com/iancmcc/ouimeaux/blob/89f3d05e7ae0a356690f898a4e1801ea3c104200/ouimeaux/utils.py#L68-L85 | train | 210,529 |
pkkid/python-plexapi | plexapi/utils.py | searchType | def searchType(libtype):
""" Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown libtype
"""
libtype = compat.ustr(libtype)
if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]:
return libtype
if SEARCHTYPES.get(libtype) is not None:
return SEARCHTYPES[libtype]
raise NotFound('Unknown libtype: %s' % libtype) | python | def searchType(libtype):
""" Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown libtype
"""
libtype = compat.ustr(libtype)
if libtype in [compat.ustr(v) for v in SEARCHTYPES.values()]:
return libtype
if SEARCHTYPES.get(libtype) is not None:
return SEARCHTYPES[libtype]
raise NotFound('Unknown libtype: %s' % libtype) | [
"def",
"searchType",
"(",
"libtype",
")",
":",
"libtype",
"=",
"compat",
".",
"ustr",
"(",
"libtype",
")",
"if",
"libtype",
"in",
"[",
"compat",
".",
"ustr",
"(",
"v",
")",
"for",
"v",
"in",
"SEARCHTYPES",
".",
"values",
"(",
")",
"]",
":",
"return... | Returns the integer value of the library string type.
Parameters:
libtype (str): LibType to lookup (movie, show, season, episode, artist, album, track,
collection)
Raises:
:class:`plexapi.exceptions.NotFound`: Unknown libtype | [
"Returns",
"the",
"integer",
"value",
"of",
"the",
"library",
"string",
"type",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L129-L143 | train | 210,530 |
pkkid/python-plexapi | plexapi/utils.py | toDatetime | def toDatetime(value, format=None):
""" Returns a datetime object from the specified value.
Parameters:
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str).
"""
if value and value is not None:
if format:
value = datetime.strptime(value, format)
else:
# https://bugs.python.org/issue30684
# And platform support for before epoch seems to be flaky.
# TODO check for others errors too.
if int(value) == 0:
value = 86400
value = datetime.fromtimestamp(int(value))
return value | python | def toDatetime(value, format=None):
""" Returns a datetime object from the specified value.
Parameters:
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str).
"""
if value and value is not None:
if format:
value = datetime.strptime(value, format)
else:
# https://bugs.python.org/issue30684
# And platform support for before epoch seems to be flaky.
# TODO check for others errors too.
if int(value) == 0:
value = 86400
value = datetime.fromtimestamp(int(value))
return value | [
"def",
"toDatetime",
"(",
"value",
",",
"format",
"=",
"None",
")",
":",
"if",
"value",
"and",
"value",
"is",
"not",
"None",
":",
"if",
"format",
":",
"value",
"=",
"datetime",
".",
"strptime",
"(",
"value",
",",
"format",
")",
"else",
":",
"# https:... | Returns a datetime object from the specified value.
Parameters:
value (str): value to return as a datetime
format (str): Format to pass strftime (optional; if value is a str). | [
"Returns",
"a",
"datetime",
"object",
"from",
"the",
"specified",
"value",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L170-L187 | train | 210,531 |
pkkid/python-plexapi | plexapi/utils.py | toList | def toList(value, itemcast=None, delim=','):
""" Returns a list of strings from the specified value.
Parameters:
value (str): comma delimited string to convert to list.
itemcast (func): Function to cast each list item to (default str).
delim (str): string delimiter (optional; default ',').
"""
value = value or ''
itemcast = itemcast or str
return [itemcast(item) for item in value.split(delim) if item != ''] | python | def toList(value, itemcast=None, delim=','):
""" Returns a list of strings from the specified value.
Parameters:
value (str): comma delimited string to convert to list.
itemcast (func): Function to cast each list item to (default str).
delim (str): string delimiter (optional; default ',').
"""
value = value or ''
itemcast = itemcast or str
return [itemcast(item) for item in value.split(delim) if item != ''] | [
"def",
"toList",
"(",
"value",
",",
"itemcast",
"=",
"None",
",",
"delim",
"=",
"','",
")",
":",
"value",
"=",
"value",
"or",
"''",
"itemcast",
"=",
"itemcast",
"or",
"str",
"return",
"[",
"itemcast",
"(",
"item",
")",
"for",
"item",
"in",
"value",
... | Returns a list of strings from the specified value.
Parameters:
value (str): comma delimited string to convert to list.
itemcast (func): Function to cast each list item to (default str).
delim (str): string delimiter (optional; default ','). | [
"Returns",
"a",
"list",
"of",
"strings",
"from",
"the",
"specified",
"value",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L190-L200 | train | 210,532 |
pkkid/python-plexapi | plexapi/utils.py | downloadSessionImages | def downloadSessionImages(server, filename=None, height=150, width=150,
opacity=100, saturation=100): # pragma: no cover
""" Helper to download a bif image or thumb.url from plex.server.sessions.
Parameters:
filename (str): default to None,
height (int): Height of the image.
width (int): width of the image.
opacity (int): Opacity of the resulting image (possibly deprecated).
saturation (int): Saturating of the resulting image.
Returns:
{'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'},
{'<username>': {filepath, url}}, ...
"""
info = {}
for media in server.sessions():
url = None
for part in media.iterParts():
if media.thumb:
url = media.thumb
if part.indexes: # always use bif images if available.
url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset)
if url:
if filename is None:
prettyname = media._prettyfilename()
filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time()))
url = server.transcodeImage(url, height, width, opacity, saturation)
filepath = download(url, filename=filename)
info['username'] = {'filepath': filepath, 'url': url}
return info | python | def downloadSessionImages(server, filename=None, height=150, width=150,
opacity=100, saturation=100): # pragma: no cover
""" Helper to download a bif image or thumb.url from plex.server.sessions.
Parameters:
filename (str): default to None,
height (int): Height of the image.
width (int): width of the image.
opacity (int): Opacity of the resulting image (possibly deprecated).
saturation (int): Saturating of the resulting image.
Returns:
{'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'},
{'<username>': {filepath, url}}, ...
"""
info = {}
for media in server.sessions():
url = None
for part in media.iterParts():
if media.thumb:
url = media.thumb
if part.indexes: # always use bif images if available.
url = '/library/parts/%s/indexes/%s/%s' % (part.id, part.indexes.lower(), media.viewOffset)
if url:
if filename is None:
prettyname = media._prettyfilename()
filename = 'session_transcode_%s_%s_%s' % (media.usernames[0], prettyname, int(time.time()))
url = server.transcodeImage(url, height, width, opacity, saturation)
filepath = download(url, filename=filename)
info['username'] = {'filepath': filepath, 'url': url}
return info | [
"def",
"downloadSessionImages",
"(",
"server",
",",
"filename",
"=",
"None",
",",
"height",
"=",
"150",
",",
"width",
"=",
"150",
",",
"opacity",
"=",
"100",
",",
"saturation",
"=",
"100",
")",
":",
"# pragma: no cover",
"info",
"=",
"{",
"}",
"for",
"... | Helper to download a bif image or thumb.url from plex.server.sessions.
Parameters:
filename (str): default to None,
height (int): Height of the image.
width (int): width of the image.
opacity (int): Opacity of the resulting image (possibly deprecated).
saturation (int): Saturating of the resulting image.
Returns:
{'hellowlol': {'filepath': '<filepath>', 'url': 'http://<url>'},
{'<username>': {filepath, url}}, ... | [
"Helper",
"to",
"download",
"a",
"bif",
"image",
"or",
"thumb",
".",
"url",
"from",
"plex",
".",
"server",
".",
"sessions",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L203-L233 | train | 210,533 |
pkkid/python-plexapi | plexapi/utils.py | download | def download(url, token, filename=None, savepath=None, session=None, chunksize=4024,
unpack=False, mocked=False, showstatus=False):
""" Helper to download a thumb, videofile or other media item. Returns the local
path to the downloaded file.
Parameters:
url (str): URL where the content be reached.
token (str): Plex auth token to include in headers.
filename (str): Filename of the downloaded file, default None.
savepath (str): Defaults to current working dir.
chunksize (int): What chunksize read/write at the time.
mocked (bool): Helper to do evertything except write the file.
unpack (bool): Unpack the zip file.
showstatus(bool): Display a progressbar.
Example:
>>> download(a_episode.getStreamURL(), a_episode.location)
/path/to/file
"""
from plexapi import log
# fetch the data to be saved
session = session or requests.Session()
headers = {'X-Plex-Token': token}
response = session.get(url, headers=headers, stream=True)
# make sure the savepath directory exists
savepath = savepath or os.getcwd()
compat.makedirs(savepath, exist_ok=True)
# try getting filename from header if not specified in arguments (used for logs, db)
if not filename and response.headers.get('Content-Disposition'):
filename = re.findall(r'filename=\"(.+)\"', response.headers.get('Content-Disposition'))
filename = filename[0] if filename[0] else None
filename = os.path.basename(filename)
fullpath = os.path.join(savepath, filename)
# append file.ext from content-type if not already there
extension = os.path.splitext(fullpath)[-1]
if not extension:
contenttype = response.headers.get('content-type')
if contenttype and 'image' in contenttype:
fullpath += contenttype.split('/')[1]
# check this is a mocked download (testing)
if mocked:
log.debug('Mocked download %s', fullpath)
return fullpath
# save the file to disk
log.info('Downloading: %s', fullpath)
if showstatus: # pragma: no cover
total = int(response.headers.get('content-length', 0))
bar = tqdm(unit='B', unit_scale=True, total=total, desc=filename)
with open(fullpath, 'wb') as handle:
for chunk in response.iter_content(chunk_size=chunksize):
handle.write(chunk)
if showstatus:
bar.update(len(chunk))
if showstatus: # pragma: no cover
bar.close()
# check we want to unzip the contents
if fullpath.endswith('zip') and unpack:
with zipfile.ZipFile(fullpath, 'r') as handle:
handle.extractall(savepath)
return fullpath | python | def download(url, token, filename=None, savepath=None, session=None, chunksize=4024,
unpack=False, mocked=False, showstatus=False):
""" Helper to download a thumb, videofile or other media item. Returns the local
path to the downloaded file.
Parameters:
url (str): URL where the content be reached.
token (str): Plex auth token to include in headers.
filename (str): Filename of the downloaded file, default None.
savepath (str): Defaults to current working dir.
chunksize (int): What chunksize read/write at the time.
mocked (bool): Helper to do evertything except write the file.
unpack (bool): Unpack the zip file.
showstatus(bool): Display a progressbar.
Example:
>>> download(a_episode.getStreamURL(), a_episode.location)
/path/to/file
"""
from plexapi import log
# fetch the data to be saved
session = session or requests.Session()
headers = {'X-Plex-Token': token}
response = session.get(url, headers=headers, stream=True)
# make sure the savepath directory exists
savepath = savepath or os.getcwd()
compat.makedirs(savepath, exist_ok=True)
# try getting filename from header if not specified in arguments (used for logs, db)
if not filename and response.headers.get('Content-Disposition'):
filename = re.findall(r'filename=\"(.+)\"', response.headers.get('Content-Disposition'))
filename = filename[0] if filename[0] else None
filename = os.path.basename(filename)
fullpath = os.path.join(savepath, filename)
# append file.ext from content-type if not already there
extension = os.path.splitext(fullpath)[-1]
if not extension:
contenttype = response.headers.get('content-type')
if contenttype and 'image' in contenttype:
fullpath += contenttype.split('/')[1]
# check this is a mocked download (testing)
if mocked:
log.debug('Mocked download %s', fullpath)
return fullpath
# save the file to disk
log.info('Downloading: %s', fullpath)
if showstatus: # pragma: no cover
total = int(response.headers.get('content-length', 0))
bar = tqdm(unit='B', unit_scale=True, total=total, desc=filename)
with open(fullpath, 'wb') as handle:
for chunk in response.iter_content(chunk_size=chunksize):
handle.write(chunk)
if showstatus:
bar.update(len(chunk))
if showstatus: # pragma: no cover
bar.close()
# check we want to unzip the contents
if fullpath.endswith('zip') and unpack:
with zipfile.ZipFile(fullpath, 'r') as handle:
handle.extractall(savepath)
return fullpath | [
"def",
"download",
"(",
"url",
",",
"token",
",",
"filename",
"=",
"None",
",",
"savepath",
"=",
"None",
",",
"session",
"=",
"None",
",",
"chunksize",
"=",
"4024",
",",
"unpack",
"=",
"False",
",",
"mocked",
"=",
"False",
",",
"showstatus",
"=",
"Fa... | Helper to download a thumb, videofile or other media item. Returns the local
path to the downloaded file.
Parameters:
url (str): URL where the content be reached.
token (str): Plex auth token to include in headers.
filename (str): Filename of the downloaded file, default None.
savepath (str): Defaults to current working dir.
chunksize (int): What chunksize read/write at the time.
mocked (bool): Helper to do evertything except write the file.
unpack (bool): Unpack the zip file.
showstatus(bool): Display a progressbar.
Example:
>>> download(a_episode.getStreamURL(), a_episode.location)
/path/to/file | [
"Helper",
"to",
"download",
"a",
"thumb",
"videofile",
"or",
"other",
"media",
"item",
".",
"Returns",
"the",
"local",
"path",
"to",
"the",
"downloaded",
"file",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L236-L303 | train | 210,534 |
pkkid/python-plexapi | plexapi/utils.py | tag_helper | def tag_helper(tag, items, locked=True, remove=False):
""" Simple tag helper for editing a object. """
if not isinstance(items, list):
items = [items]
data = {}
if not remove:
for i, item in enumerate(items):
tagname = '%s[%s].tag.tag' % (tag, i)
data[tagname] = item
if remove:
tagname = '%s[].tag.tag-' % tag
data[tagname] = ','.join(items)
data['%s.locked' % tag] = 1 if locked else 0
return data | python | def tag_helper(tag, items, locked=True, remove=False):
""" Simple tag helper for editing a object. """
if not isinstance(items, list):
items = [items]
data = {}
if not remove:
for i, item in enumerate(items):
tagname = '%s[%s].tag.tag' % (tag, i)
data[tagname] = item
if remove:
tagname = '%s[].tag.tag-' % tag
data[tagname] = ','.join(items)
data['%s.locked' % tag] = 1 if locked else 0
return data | [
"def",
"tag_helper",
"(",
"tag",
",",
"items",
",",
"locked",
"=",
"True",
",",
"remove",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"items",
"=",
"[",
"items",
"]",
"data",
"=",
"{",
"}",
"if",
"not",... | Simple tag helper for editing a object. | [
"Simple",
"tag",
"helper",
"for",
"editing",
"a",
"object",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L306-L319 | train | 210,535 |
pkkid/python-plexapi | plexapi/utils.py | choose | def choose(msg, items, attr): # pragma: no cover
""" Command line helper to display a list of choices, asking the
user to choose one of the options.
"""
# Return the first item if there is only one choice
if len(items) == 1:
return items[0]
# Print all choices to the command line
print()
for index, i in enumerate(items):
name = attr(i) if callable(attr) else getattr(i, attr)
print(' %s: %s' % (index, name))
print()
# Request choice from the user
while True:
try:
inp = input('%s: ' % msg)
if any(s in inp for s in (':', '::', '-')):
idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':')))
return items[idx]
else:
return items[int(inp)]
except (ValueError, IndexError):
pass | python | def choose(msg, items, attr): # pragma: no cover
""" Command line helper to display a list of choices, asking the
user to choose one of the options.
"""
# Return the first item if there is only one choice
if len(items) == 1:
return items[0]
# Print all choices to the command line
print()
for index, i in enumerate(items):
name = attr(i) if callable(attr) else getattr(i, attr)
print(' %s: %s' % (index, name))
print()
# Request choice from the user
while True:
try:
inp = input('%s: ' % msg)
if any(s in inp for s in (':', '::', '-')):
idx = slice(*map(lambda x: int(x.strip()) if x.strip() else None, inp.split(':')))
return items[idx]
else:
return items[int(inp)]
except (ValueError, IndexError):
pass | [
"def",
"choose",
"(",
"msg",
",",
"items",
",",
"attr",
")",
":",
"# pragma: no cover",
"# Return the first item if there is only one choice",
"if",
"len",
"(",
"items",
")",
"==",
"1",
":",
"return",
"items",
"[",
"0",
"]",
"# Print all choices to the command line"... | Command line helper to display a list of choices, asking the
user to choose one of the options. | [
"Command",
"line",
"helper",
"to",
"display",
"a",
"list",
"of",
"choices",
"asking",
"the",
"user",
"to",
"choose",
"one",
"of",
"the",
"options",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/utils.py#L349-L373 | train | 210,536 |
pkkid/python-plexapi | tools/plex-backupwatched.py | _find_server | def _find_server(account, servername=None):
""" Find and return a PlexServer object. """
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == servername:
return server.connect()
raise SystemExit('Unknown server name: %s' % servername)
# If servername not specified; allow user to choose
return utils.choose('Choose a Server', servers, 'name').connect() | python | def _find_server(account, servername=None):
""" Find and return a PlexServer object. """
servers = servers = [s for s in account.resources() if 'server' in s.provides]
# If servername specified find and return it
if servername is not None:
for server in servers:
if server.name == servername:
return server.connect()
raise SystemExit('Unknown server name: %s' % servername)
# If servername not specified; allow user to choose
return utils.choose('Choose a Server', servers, 'name').connect() | [
"def",
"_find_server",
"(",
"account",
",",
"servername",
"=",
"None",
")",
":",
"servers",
"=",
"servers",
"=",
"[",
"s",
"for",
"s",
"in",
"account",
".",
"resources",
"(",
")",
"if",
"'server'",
"in",
"s",
".",
"provides",
"]",
"# If servername specif... | Find and return a PlexServer object. | [
"Find",
"and",
"return",
"a",
"PlexServer",
"object",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/tools/plex-backupwatched.py#L13-L23 | train | 210,537 |
pkkid/python-plexapi | tools/plex-backupwatched.py | backup_watched | def backup_watched(plex, opts):
""" Backup watched status to the specified filepath. """
data = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Fetching watched status for %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
if not opts.watchedonly or item.isWatched:
ikey = _item_key(item)
data[skey][ikey] = item.isWatched
import pprint; pprint.pprint(item.__dict__); break
print('Writing backup file to %s' % opts.filepath)
with open(opts.filepath, 'w') as handle:
json.dump(dict(data), handle, sort_keys=True, indent=2) | python | def backup_watched(plex, opts):
""" Backup watched status to the specified filepath. """
data = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Fetching watched status for %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
if not opts.watchedonly or item.isWatched:
ikey = _item_key(item)
data[skey][ikey] = item.isWatched
import pprint; pprint.pprint(item.__dict__); break
print('Writing backup file to %s' % opts.filepath)
with open(opts.filepath, 'w') as handle:
json.dump(dict(data), handle, sort_keys=True, indent=2) | [
"def",
"backup_watched",
"(",
"plex",
",",
"opts",
")",
":",
"data",
"=",
"defaultdict",
"(",
"lambda",
":",
"dict",
"(",
")",
")",
"for",
"section",
"in",
"_iter_sections",
"(",
"plex",
",",
"opts",
")",
":",
"print",
"(",
"'Fetching watched status for %s... | Backup watched status to the specified filepath. | [
"Backup",
"watched",
"status",
"to",
"the",
"specified",
"filepath",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/tools/plex-backupwatched.py#L52-L65 | train | 210,538 |
pkkid/python-plexapi | tools/plex-backupwatched.py | restore_watched | def restore_watched(plex, opts):
""" Restore watched status from the specified filepath. """
with open(opts.filepath, 'r') as handle:
source = json.load(handle)
# Find the differences
differences = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Finding differences in %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
ikey = _item_key(item)
sval = source.get(skey,{}).get(ikey)
if sval is None:
raise SystemExit('%s not found' % ikey)
if (sval is not None and item.isWatched != sval) and (not opts.watchedonly or sval):
differences[skey][ikey] = {'isWatched':sval, 'item':item}
print('Applying %s differences to destination' % len(differences))
import pprint; pprint.pprint(differences) | python | def restore_watched(plex, opts):
""" Restore watched status from the specified filepath. """
with open(opts.filepath, 'r') as handle:
source = json.load(handle)
# Find the differences
differences = defaultdict(lambda: dict())
for section in _iter_sections(plex, opts):
print('Finding differences in %s..' % section.title)
skey = section.title.lower()
for item in _iter_items(section):
ikey = _item_key(item)
sval = source.get(skey,{}).get(ikey)
if sval is None:
raise SystemExit('%s not found' % ikey)
if (sval is not None and item.isWatched != sval) and (not opts.watchedonly or sval):
differences[skey][ikey] = {'isWatched':sval, 'item':item}
print('Applying %s differences to destination' % len(differences))
import pprint; pprint.pprint(differences) | [
"def",
"restore_watched",
"(",
"plex",
",",
"opts",
")",
":",
"with",
"open",
"(",
"opts",
".",
"filepath",
",",
"'r'",
")",
"as",
"handle",
":",
"source",
"=",
"json",
".",
"load",
"(",
"handle",
")",
"# Find the differences",
"differences",
"=",
"defau... | Restore watched status from the specified filepath. | [
"Restore",
"watched",
"status",
"from",
"the",
"specified",
"filepath",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/tools/plex-backupwatched.py#L68-L85 | train | 210,539 |
pkkid/python-plexapi | plexapi/alert.py | AlertListener._onMessage | def _onMessage(self, ws, message):
""" Called when websocket message is recieved. """
try:
data = json.loads(message)['NotificationContainer']
log.debug('Alert: %s %s %s', *data)
if self._callback:
self._callback(data)
except Exception as err: # pragma: no cover
log.error('AlertListener Msg Error: %s', err) | python | def _onMessage(self, ws, message):
""" Called when websocket message is recieved. """
try:
data = json.loads(message)['NotificationContainer']
log.debug('Alert: %s %s %s', *data)
if self._callback:
self._callback(data)
except Exception as err: # pragma: no cover
log.error('AlertListener Msg Error: %s', err) | [
"def",
"_onMessage",
"(",
"self",
",",
"ws",
",",
"message",
")",
":",
"try",
":",
"data",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"[",
"'NotificationContainer'",
"]",
"log",
".",
"debug",
"(",
"'Alert: %s %s %s'",
",",
"*",
"data",
")",
"if",
... | Called when websocket message is recieved. | [
"Called",
"when",
"websocket",
"message",
"is",
"recieved",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/alert.py#L58-L66 | train | 210,540 |
pkkid/python-plexapi | plexapi/settings.py | Setting._cast | def _cast(self, value):
""" Cast the specifief value to the type of this setting. """
if self.type != 'text':
value = utils.cast(self.TYPES.get(self.type)['cast'], value)
return value | python | def _cast(self, value):
""" Cast the specifief value to the type of this setting. """
if self.type != 'text':
value = utils.cast(self.TYPES.get(self.type)['cast'], value)
return value | [
"def",
"_cast",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"type",
"!=",
"'text'",
":",
"value",
"=",
"utils",
".",
"cast",
"(",
"self",
".",
"TYPES",
".",
"get",
"(",
"self",
".",
"type",
")",
"[",
"'cast'",
"]",
",",
"value",
")"... | Cast the specifief value to the type of this setting. | [
"Cast",
"the",
"specifief",
"value",
"to",
"the",
"type",
"of",
"this",
"setting",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/settings.py#L126-L130 | train | 210,541 |
pkkid/python-plexapi | plexapi/settings.py | Setting._getEnumValues | def _getEnumValues(self, data):
""" Returns a list of dictionary of valis value for this setting. """
enumstr = data.attrib.get('enumValues')
if not enumstr:
return None
if ':' in enumstr:
return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split('|')]}
return enumstr.split('|') | python | def _getEnumValues(self, data):
""" Returns a list of dictionary of valis value for this setting. """
enumstr = data.attrib.get('enumValues')
if not enumstr:
return None
if ':' in enumstr:
return {self._cast(k): v for k, v in [kv.split(':') for kv in enumstr.split('|')]}
return enumstr.split('|') | [
"def",
"_getEnumValues",
"(",
"self",
",",
"data",
")",
":",
"enumstr",
"=",
"data",
".",
"attrib",
".",
"get",
"(",
"'enumValues'",
")",
"if",
"not",
"enumstr",
":",
"return",
"None",
"if",
"':'",
"in",
"enumstr",
":",
"return",
"{",
"self",
".",
"_... | Returns a list of dictionary of valis value for this setting. | [
"Returns",
"a",
"list",
"of",
"dictionary",
"of",
"valis",
"value",
"for",
"this",
"setting",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/settings.py#L132-L139 | train | 210,542 |
pkkid/python-plexapi | plexapi/server.py | PlexServer._headers | def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """
headers = BASE_HEADERS.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
return headers | python | def _headers(self, **kwargs):
""" Returns dict containing base headers for all requests to the server. """
headers = BASE_HEADERS.copy()
if self._token:
headers['X-Plex-Token'] = self._token
headers.update(kwargs)
return headers | [
"def",
"_headers",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"BASE_HEADERS",
".",
"copy",
"(",
")",
"if",
"self",
".",
"_token",
":",
"headers",
"[",
"'X-Plex-Token'",
"]",
"=",
"self",
".",
"_token",
"headers",
".",
"update",
"... | Returns dict containing base headers for all requests to the server. | [
"Returns",
"dict",
"containing",
"base",
"headers",
"for",
"all",
"requests",
"to",
"the",
"server",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L151-L157 | train | 210,543 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.library | def library(self):
""" Library to browse or search your media. """
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query('/library/sections/')
# Only the owner has access to /library
# so just return the library without the data.
return Library(self, data)
return self._library | python | def library(self):
""" Library to browse or search your media. """
if not self._library:
try:
data = self.query(Library.key)
self._library = Library(self, data)
except BadRequest:
data = self.query('/library/sections/')
# Only the owner has access to /library
# so just return the library without the data.
return Library(self, data)
return self._library | [
"def",
"library",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_library",
":",
"try",
":",
"data",
"=",
"self",
".",
"query",
"(",
"Library",
".",
"key",
")",
"self",
".",
"_library",
"=",
"Library",
"(",
"self",
",",
"data",
")",
"except",
... | Library to browse or search your media. | [
"Library",
"to",
"browse",
"or",
"search",
"your",
"media",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L160-L171 | train | 210,544 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.settings | def settings(self):
""" Returns a list of all server settings. """
if not self._settings:
data = self.query(Settings.key)
self._settings = Settings(self, data)
return self._settings | python | def settings(self):
""" Returns a list of all server settings. """
if not self._settings:
data = self.query(Settings.key)
self._settings = Settings(self, data)
return self._settings | [
"def",
"settings",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_settings",
":",
"data",
"=",
"self",
".",
"query",
"(",
"Settings",
".",
"key",
")",
"self",
".",
"_settings",
"=",
"Settings",
"(",
"self",
",",
"data",
")",
"return",
"self",
"... | Returns a list of all server settings. | [
"Returns",
"a",
"list",
"of",
"all",
"server",
"settings",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L174-L179 | train | 210,545 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.downloadDatabases | def downloadDatabases(self, savepath=None, unpack=False):
""" Download databases.
Parameters:
savepath (str): Defaults to current working dir.
unpack (bool): Unpack the zip file.
"""
url = self.url('/diagnostics/databases')
filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack)
return filepath | python | def downloadDatabases(self, savepath=None, unpack=False):
""" Download databases.
Parameters:
savepath (str): Defaults to current working dir.
unpack (bool): Unpack the zip file.
"""
url = self.url('/diagnostics/databases')
filepath = utils.download(url, self._token, None, savepath, self._session, unpack=unpack)
return filepath | [
"def",
"downloadDatabases",
"(",
"self",
",",
"savepath",
"=",
"None",
",",
"unpack",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"url",
"(",
"'/diagnostics/databases'",
")",
"filepath",
"=",
"utils",
".",
"download",
"(",
"url",
",",
"self",
".",
... | Download databases.
Parameters:
savepath (str): Defaults to current working dir.
unpack (bool): Unpack the zip file. | [
"Download",
"databases",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L262-L271 | train | 210,546 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.installUpdate | def installUpdate(self):
""" Install the newest version of Plex Media Server. """
# We can add this but dunno how useful this is since it sometimes
# requires user action using a gui.
part = '/updater/apply'
release = self.check_for_update(force=True, download=True)
if release and release.version != self.version:
# figure out what method this is..
return self.query(part, method=self._session.put) | python | def installUpdate(self):
""" Install the newest version of Plex Media Server. """
# We can add this but dunno how useful this is since it sometimes
# requires user action using a gui.
part = '/updater/apply'
release = self.check_for_update(force=True, download=True)
if release and release.version != self.version:
# figure out what method this is..
return self.query(part, method=self._session.put) | [
"def",
"installUpdate",
"(",
"self",
")",
":",
"# We can add this but dunno how useful this is since it sometimes",
"# requires user action using a gui.",
"part",
"=",
"'/updater/apply'",
"release",
"=",
"self",
".",
"check_for_update",
"(",
"force",
"=",
"True",
",",
"down... | Install the newest version of Plex Media Server. | [
"Install",
"the",
"newest",
"version",
"of",
"Plex",
"Media",
"Server",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L303-L311 | train | 210,547 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.startAlertListener | def startAlertListener(self, callback=None):
""" Creates a websocket connection to the Plex Server to optionally recieve
notifications. These often include messages from Plex about media scans
as well as updates to currently running Transcode Sessions.
NOTE: You need websocket-client installed in order to use this feature.
>> pip install websocket-client
Parameters:
callback (func): Callback function to call on recieved messages.
raises:
:class:`plexapi.exception.Unsupported`: Websocket-client not installed.
"""
notifier = AlertListener(self, callback)
notifier.start()
return notifier | python | def startAlertListener(self, callback=None):
""" Creates a websocket connection to the Plex Server to optionally recieve
notifications. These often include messages from Plex about media scans
as well as updates to currently running Transcode Sessions.
NOTE: You need websocket-client installed in order to use this feature.
>> pip install websocket-client
Parameters:
callback (func): Callback function to call on recieved messages.
raises:
:class:`plexapi.exception.Unsupported`: Websocket-client not installed.
"""
notifier = AlertListener(self, callback)
notifier.start()
return notifier | [
"def",
"startAlertListener",
"(",
"self",
",",
"callback",
"=",
"None",
")",
":",
"notifier",
"=",
"AlertListener",
"(",
"self",
",",
"callback",
")",
"notifier",
".",
"start",
"(",
")",
"return",
"notifier"
] | Creates a websocket connection to the Plex Server to optionally recieve
notifications. These often include messages from Plex about media scans
as well as updates to currently running Transcode Sessions.
NOTE: You need websocket-client installed in order to use this feature.
>> pip install websocket-client
Parameters:
callback (func): Callback function to call on recieved messages.
raises:
:class:`plexapi.exception.Unsupported`: Websocket-client not installed. | [
"Creates",
"a",
"websocket",
"connection",
"to",
"the",
"Plex",
"Server",
"to",
"optionally",
"recieve",
"notifications",
".",
"These",
"often",
"include",
"messages",
"from",
"Plex",
"about",
"media",
"scans",
"as",
"well",
"as",
"updates",
"to",
"currently",
... | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L385-L401 | train | 210,548 |
pkkid/python-plexapi | plexapi/server.py | PlexServer.url | def url(self, key, includeToken=None):
""" Build a URL string with proper token argument. Token will be appended to the URL
if either includeToken is True or CONFIG.log.show_secrets is 'true'.
"""
if self._token and (includeToken or self._showSecrets):
delim = '&' if '?' in key else '?'
return '%s%s%sX-Plex-Token=%s' % (self._baseurl, key, delim, self._token)
return '%s%s' % (self._baseurl, key) | python | def url(self, key, includeToken=None):
""" Build a URL string with proper token argument. Token will be appended to the URL
if either includeToken is True or CONFIG.log.show_secrets is 'true'.
"""
if self._token and (includeToken or self._showSecrets):
delim = '&' if '?' in key else '?'
return '%s%s%sX-Plex-Token=%s' % (self._baseurl, key, delim, self._token)
return '%s%s' % (self._baseurl, key) | [
"def",
"url",
"(",
"self",
",",
"key",
",",
"includeToken",
"=",
"None",
")",
":",
"if",
"self",
".",
"_token",
"and",
"(",
"includeToken",
"or",
"self",
".",
"_showSecrets",
")",
":",
"delim",
"=",
"'&'",
"if",
"'?'",
"in",
"key",
"else",
"'?'",
"... | Build a URL string with proper token argument. Token will be appended to the URL
if either includeToken is True or CONFIG.log.show_secrets is 'true'. | [
"Build",
"a",
"URL",
"string",
"with",
"proper",
"token",
"argument",
".",
"Token",
"will",
"be",
"appended",
"to",
"the",
"URL",
"if",
"either",
"includeToken",
"is",
"True",
"or",
"CONFIG",
".",
"log",
".",
"show_secrets",
"is",
"true",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/server.py#L419-L426 | train | 210,549 |
pkkid/python-plexapi | plexapi/video.py | Video.thumbUrl | def thumbUrl(self):
""" Return the first first thumbnail url starting on
the most specific thumbnail for that item.
"""
thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(thumb, includeToken=True) if thumb else None | python | def thumbUrl(self):
""" Return the first first thumbnail url starting on
the most specific thumbnail for that item.
"""
thumb = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(thumb, includeToken=True) if thumb else None | [
"def",
"thumbUrl",
"(",
"self",
")",
":",
"thumb",
"=",
"self",
".",
"firstAttr",
"(",
"'thumb'",
",",
"'parentThumb'",
",",
"'granparentThumb'",
")",
"return",
"self",
".",
"_server",
".",
"url",
"(",
"thumb",
",",
"includeToken",
"=",
"True",
")",
"if"... | Return the first first thumbnail url starting on
the most specific thumbnail for that item. | [
"Return",
"the",
"first",
"first",
"thumbnail",
"url",
"starting",
"on",
"the",
"most",
"specific",
"thumbnail",
"for",
"that",
"item",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L52-L57 | train | 210,550 |
pkkid/python-plexapi | plexapi/video.py | Video.artUrl | def artUrl(self):
""" Return the first first art url starting on the most specific for that item."""
art = self.firstAttr('art', 'grandparentArt')
return self._server.url(art, includeToken=True) if art else None | python | def artUrl(self):
""" Return the first first art url starting on the most specific for that item."""
art = self.firstAttr('art', 'grandparentArt')
return self._server.url(art, includeToken=True) if art else None | [
"def",
"artUrl",
"(",
"self",
")",
":",
"art",
"=",
"self",
".",
"firstAttr",
"(",
"'art'",
",",
"'grandparentArt'",
")",
"return",
"self",
".",
"_server",
".",
"url",
"(",
"art",
",",
"includeToken",
"=",
"True",
")",
"if",
"art",
"else",
"None"
] | Return the first first art url starting on the most specific for that item. | [
"Return",
"the",
"first",
"first",
"art",
"url",
"starting",
"on",
"the",
"most",
"specific",
"for",
"that",
"item",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L60-L63 | train | 210,551 |
pkkid/python-plexapi | plexapi/video.py | Video.url | def url(self, part):
""" Returns the full url for something. Typically used for getting a specific image. """
return self._server.url(part, includeToken=True) if part else None | python | def url(self, part):
""" Returns the full url for something. Typically used for getting a specific image. """
return self._server.url(part, includeToken=True) if part else None | [
"def",
"url",
"(",
"self",
",",
"part",
")",
":",
"return",
"self",
".",
"_server",
".",
"url",
"(",
"part",
",",
"includeToken",
"=",
"True",
")",
"if",
"part",
"else",
"None"
] | Returns the full url for something. Typically used for getting a specific image. | [
"Returns",
"the",
"full",
"url",
"for",
"something",
".",
"Typically",
"used",
"for",
"getting",
"a",
"specific",
"image",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L65-L67 | train | 210,552 |
pkkid/python-plexapi | plexapi/video.py | Video.markWatched | def markWatched(self):
""" Mark video as watched. """
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | python | def markWatched(self):
""" Mark video as watched. """
key = '/:/scrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | [
"def",
"markWatched",
"(",
"self",
")",
":",
"key",
"=",
"'/:/scrobble?key=%s&identifier=com.plexapp.plugins.library'",
"%",
"self",
".",
"ratingKey",
"self",
".",
"_server",
".",
"query",
"(",
"key",
")",
"self",
".",
"reload",
"(",
")"
] | Mark video as watched. | [
"Mark",
"video",
"as",
"watched",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L69-L73 | train | 210,553 |
pkkid/python-plexapi | plexapi/video.py | Video.markUnwatched | def markUnwatched(self):
""" Mark video unwatched. """
key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | python | def markUnwatched(self):
""" Mark video unwatched. """
key = '/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library' % self.ratingKey
self._server.query(key)
self.reload() | [
"def",
"markUnwatched",
"(",
"self",
")",
":",
"key",
"=",
"'/:/unscrobble?key=%s&identifier=com.plexapp.plugins.library'",
"%",
"self",
".",
"ratingKey",
"self",
".",
"_server",
".",
"query",
"(",
"key",
")",
"self",
".",
"reload",
"(",
")"
] | Mark video unwatched. | [
"Mark",
"video",
"unwatched",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/video.py#L75-L79 | train | 210,554 |
pkkid/python-plexapi | plexapi/config.py | PlexConfig._asDict | def _asDict(self):
""" Returns all configuration values as a dictionary. """
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config) | python | def _asDict(self):
""" Returns all configuration values as a dictionary. """
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config) | [
"def",
"_asDict",
"(",
"self",
")",
":",
"config",
"=",
"defaultdict",
"(",
"dict",
")",
"for",
"section",
"in",
"self",
".",
"_sections",
":",
"for",
"name",
",",
"value",
"in",
"self",
".",
"_sections",
"[",
"section",
"]",
".",
"items",
"(",
")",
... | Returns all configuration values as a dictionary. | [
"Returns",
"all",
"configuration",
"values",
"as",
"a",
"dictionary",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/config.py#L41-L48 | train | 210,555 |
pkkid/python-plexapi | plexapi/media.py | MediaPartStream.parse | def parse(server, data, initpath): # pragma: no cover seems to be dead code.
""" Factory method returns a new MediaPartStream from xml data. """
STREAMCLS = {1: VideoStream, 2: AudioStream, 3: SubtitleStream}
stype = cast(int, data.attrib.get('streamType'))
cls = STREAMCLS.get(stype, MediaPartStream)
return cls(server, data, initpath) | python | def parse(server, data, initpath): # pragma: no cover seems to be dead code.
""" Factory method returns a new MediaPartStream from xml data. """
STREAMCLS = {1: VideoStream, 2: AudioStream, 3: SubtitleStream}
stype = cast(int, data.attrib.get('streamType'))
cls = STREAMCLS.get(stype, MediaPartStream)
return cls(server, data, initpath) | [
"def",
"parse",
"(",
"server",
",",
"data",
",",
"initpath",
")",
":",
"# pragma: no cover seems to be dead code.",
"STREAMCLS",
"=",
"{",
"1",
":",
"VideoStream",
",",
"2",
":",
"AudioStream",
",",
"3",
":",
"SubtitleStream",
"}",
"stype",
"=",
"cast",
"(",... | Factory method returns a new MediaPartStream from xml data. | [
"Factory",
"method",
"returns",
"a",
"new",
"MediaPartStream",
"from",
"xml",
"data",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/media.py#L191-L196 | train | 210,556 |
pkkid/python-plexapi | plexapi/sync.py | SyncItem.delete | def delete(self):
""" Removes current SyncItem """
url = SyncList.key.format(clientId=self.clientIdentifier)
url += '/' + str(self.id)
self._server.query(url, self._server._session.delete) | python | def delete(self):
""" Removes current SyncItem """
url = SyncList.key.format(clientId=self.clientIdentifier)
url += '/' + str(self.id)
self._server.query(url, self._server._session.delete) | [
"def",
"delete",
"(",
"self",
")",
":",
"url",
"=",
"SyncList",
".",
"key",
".",
"format",
"(",
"clientId",
"=",
"self",
".",
"clientIdentifier",
")",
"url",
"+=",
"'/'",
"+",
"str",
"(",
"self",
".",
"id",
")",
"self",
".",
"_server",
".",
"query"... | Removes current SyncItem | [
"Removes",
"current",
"SyncItem"
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/sync.py#L103-L107 | train | 210,557 |
pkkid/python-plexapi | plexapi/base.py | PlexObject._buildItem | def _buildItem(self, elem, cls=None, initpath=None):
""" Factory function to build objects based on registered PLEXOBJECTS. """
# cls is specified, build the object and return
initpath = initpath or self._initpath
if cls is not None:
return cls(self._server, elem, initpath)
# cls is not specified, try looking it up in PLEXOBJECTS
etype = elem.attrib.get('type', elem.attrib.get('streamType'))
ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag
ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))
# log.debug('Building %s as %s', elem.tag, ecls.__name__)
if ecls is not None:
return ecls(self._server, elem, initpath)
raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype)) | python | def _buildItem(self, elem, cls=None, initpath=None):
""" Factory function to build objects based on registered PLEXOBJECTS. """
# cls is specified, build the object and return
initpath = initpath or self._initpath
if cls is not None:
return cls(self._server, elem, initpath)
# cls is not specified, try looking it up in PLEXOBJECTS
etype = elem.attrib.get('type', elem.attrib.get('streamType'))
ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag
ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))
# log.debug('Building %s as %s', elem.tag, ecls.__name__)
if ecls is not None:
return ecls(self._server, elem, initpath)
raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype)) | [
"def",
"_buildItem",
"(",
"self",
",",
"elem",
",",
"cls",
"=",
"None",
",",
"initpath",
"=",
"None",
")",
":",
"# cls is specified, build the object and return",
"initpath",
"=",
"initpath",
"or",
"self",
".",
"_initpath",
"if",
"cls",
"is",
"not",
"None",
... | Factory function to build objects based on registered PLEXOBJECTS. | [
"Factory",
"function",
"to",
"build",
"objects",
"based",
"on",
"registered",
"PLEXOBJECTS",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L67-L80 | train | 210,558 |
pkkid/python-plexapi | plexapi/base.py | PlexObject.fetchItem | def fetchItem(self, ekey, cls=None, **kwargs):
""" Load the specified key to find and build the first item with the
specified tag and attrs. If no tag or attrs are specified then
the first item in the result set is returned.
Parameters:
ekey (str or int): Path in Plex to fetch items from. If an int is passed
in, the key will be translated to /library/metadata/<key>. This allows
fetching an item only knowing its key-id.
cls (:class:`~plexapi.base.PlexObject`): If you know the class of the
items to be fetched, passing this in will help the parser ensure
it only returns those items. By default we convert the xml elements
with the best guess PlexObjects based on tag and type attrs.
etag (str): Only fetch items with the specified tag.
**kwargs (dict): Optionally add attribute filters on the items to fetch. For
example, passing in viewCount=0 will only return matching items. Filtering
is done before the Python objects are built to help keep things speedy.
Note: Because some attribute names are already used as arguments to this
function, such as 'tag', you may still reference the attr tag byappending
an underscore. For example, passing in _tag='foobar' will return all items
where tag='foobar'. Also Note: Case very much matters when specifying kwargs
-- Optionally, operators can be specified by append it
to the end of the attribute name for more complex lookups. For example,
passing in viewCount__gte=0 will return all items where viewCount >= 0.
Available operations include:
* __contains: Value contains specified arg.
* __endswith: Value ends with specified arg.
* __exact: Value matches specified arg.
* __exists (bool): Value is or is not present in the attrs.
* __gt: Value is greater than specified arg.
* __gte: Value is greater than or equal to specified arg.
* __icontains: Case insensative value contains specified arg.
* __iendswith: Case insensative value ends with specified arg.
* __iexact: Case insensative value matches specified arg.
* __in: Value is in a specified list or tuple.
* __iregex: Case insensative value matches the specified regular expression.
* __istartswith: Case insensative value starts with specified arg.
* __lt: Value is less than specified arg.
* __lte: Value is less than or equal to specified arg.
* __regex: Value matches the specified regular expression.
* __startswith: Value starts with specified arg.
"""
if isinstance(ekey, int):
ekey = '/library/metadata/%s' % ekey
for elem in self._server.query(ekey):
if self._checkAttrs(elem, **kwargs):
return self._buildItem(elem, cls, ekey)
clsname = cls.__name__ if cls else 'None'
raise NotFound('Unable to find elem: cls=%s, attrs=%s' % (clsname, kwargs)) | python | def fetchItem(self, ekey, cls=None, **kwargs):
""" Load the specified key to find and build the first item with the
specified tag and attrs. If no tag or attrs are specified then
the first item in the result set is returned.
Parameters:
ekey (str or int): Path in Plex to fetch items from. If an int is passed
in, the key will be translated to /library/metadata/<key>. This allows
fetching an item only knowing its key-id.
cls (:class:`~plexapi.base.PlexObject`): If you know the class of the
items to be fetched, passing this in will help the parser ensure
it only returns those items. By default we convert the xml elements
with the best guess PlexObjects based on tag and type attrs.
etag (str): Only fetch items with the specified tag.
**kwargs (dict): Optionally add attribute filters on the items to fetch. For
example, passing in viewCount=0 will only return matching items. Filtering
is done before the Python objects are built to help keep things speedy.
Note: Because some attribute names are already used as arguments to this
function, such as 'tag', you may still reference the attr tag byappending
an underscore. For example, passing in _tag='foobar' will return all items
where tag='foobar'. Also Note: Case very much matters when specifying kwargs
-- Optionally, operators can be specified by append it
to the end of the attribute name for more complex lookups. For example,
passing in viewCount__gte=0 will return all items where viewCount >= 0.
Available operations include:
* __contains: Value contains specified arg.
* __endswith: Value ends with specified arg.
* __exact: Value matches specified arg.
* __exists (bool): Value is or is not present in the attrs.
* __gt: Value is greater than specified arg.
* __gte: Value is greater than or equal to specified arg.
* __icontains: Case insensative value contains specified arg.
* __iendswith: Case insensative value ends with specified arg.
* __iexact: Case insensative value matches specified arg.
* __in: Value is in a specified list or tuple.
* __iregex: Case insensative value matches the specified regular expression.
* __istartswith: Case insensative value starts with specified arg.
* __lt: Value is less than specified arg.
* __lte: Value is less than or equal to specified arg.
* __regex: Value matches the specified regular expression.
* __startswith: Value starts with specified arg.
"""
if isinstance(ekey, int):
ekey = '/library/metadata/%s' % ekey
for elem in self._server.query(ekey):
if self._checkAttrs(elem, **kwargs):
return self._buildItem(elem, cls, ekey)
clsname = cls.__name__ if cls else 'None'
raise NotFound('Unable to find elem: cls=%s, attrs=%s' % (clsname, kwargs)) | [
"def",
"fetchItem",
"(",
"self",
",",
"ekey",
",",
"cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"ekey",
",",
"int",
")",
":",
"ekey",
"=",
"'/library/metadata/%s'",
"%",
"ekey",
"for",
"elem",
"in",
"self",
".",
"... | Load the specified key to find and build the first item with the
specified tag and attrs. If no tag or attrs are specified then
the first item in the result set is returned.
Parameters:
ekey (str or int): Path in Plex to fetch items from. If an int is passed
in, the key will be translated to /library/metadata/<key>. This allows
fetching an item only knowing its key-id.
cls (:class:`~plexapi.base.PlexObject`): If you know the class of the
items to be fetched, passing this in will help the parser ensure
it only returns those items. By default we convert the xml elements
with the best guess PlexObjects based on tag and type attrs.
etag (str): Only fetch items with the specified tag.
**kwargs (dict): Optionally add attribute filters on the items to fetch. For
example, passing in viewCount=0 will only return matching items. Filtering
is done before the Python objects are built to help keep things speedy.
Note: Because some attribute names are already used as arguments to this
function, such as 'tag', you may still reference the attr tag byappending
an underscore. For example, passing in _tag='foobar' will return all items
where tag='foobar'. Also Note: Case very much matters when specifying kwargs
-- Optionally, operators can be specified by append it
to the end of the attribute name for more complex lookups. For example,
passing in viewCount__gte=0 will return all items where viewCount >= 0.
Available operations include:
* __contains: Value contains specified arg.
* __endswith: Value ends with specified arg.
* __exact: Value matches specified arg.
* __exists (bool): Value is or is not present in the attrs.
* __gt: Value is greater than specified arg.
* __gte: Value is greater than or equal to specified arg.
* __icontains: Case insensative value contains specified arg.
* __iendswith: Case insensative value ends with specified arg.
* __iexact: Case insensative value matches specified arg.
* __in: Value is in a specified list or tuple.
* __iregex: Case insensative value matches the specified regular expression.
* __istartswith: Case insensative value starts with specified arg.
* __lt: Value is less than specified arg.
* __lte: Value is less than or equal to specified arg.
* __regex: Value matches the specified regular expression.
* __startswith: Value starts with specified arg. | [
"Load",
"the",
"specified",
"key",
"to",
"find",
"and",
"build",
"the",
"first",
"item",
"with",
"the",
"specified",
"tag",
"and",
"attrs",
".",
"If",
"no",
"tag",
"or",
"attrs",
"are",
"specified",
"then",
"the",
"first",
"item",
"in",
"the",
"result",
... | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L91-L140 | train | 210,559 |
pkkid/python-plexapi | plexapi/base.py | PlexObject.firstAttr | def firstAttr(self, *attrs):
""" Return the first attribute in attrs that is not None. """
for attr in attrs:
value = self.__dict__.get(attr)
if value is not None:
return value | python | def firstAttr(self, *attrs):
""" Return the first attribute in attrs that is not None. """
for attr in attrs:
value = self.__dict__.get(attr)
if value is not None:
return value | [
"def",
"firstAttr",
"(",
"self",
",",
"*",
"attrs",
")",
":",
"for",
"attr",
"in",
"attrs",
":",
"value",
"=",
"self",
".",
"__dict__",
".",
"get",
"(",
"attr",
")",
"if",
"value",
"is",
"not",
"None",
":",
"return",
"value"
] | Return the first attribute in attrs that is not None. | [
"Return",
"the",
"first",
"attribute",
"in",
"attrs",
"that",
"is",
"not",
"None",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L174-L179 | train | 210,560 |
pkkid/python-plexapi | plexapi/base.py | PlexObject.reload | def reload(self, key=None):
""" Reload the data for this object from self.key. """
key = key or self._details_key or self.key
if not key:
raise Unsupported('Cannot reload an object not built from a URL.')
self._initpath = key
data = self._server.query(key)
self._loadData(data[0])
return self | python | def reload(self, key=None):
""" Reload the data for this object from self.key. """
key = key or self._details_key or self.key
if not key:
raise Unsupported('Cannot reload an object not built from a URL.')
self._initpath = key
data = self._server.query(key)
self._loadData(data[0])
return self | [
"def",
"reload",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"key",
"=",
"key",
"or",
"self",
".",
"_details_key",
"or",
"self",
".",
"key",
"if",
"not",
"key",
":",
"raise",
"Unsupported",
"(",
"'Cannot reload an object not built from a URL.'",
")",
"... | Reload the data for this object from self.key. | [
"Reload",
"the",
"data",
"for",
"this",
"object",
"from",
"self",
".",
"key",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L189-L197 | train | 210,561 |
pkkid/python-plexapi | plexapi/base.py | PlexPartialObject.edit | def edit(self, **kwargs):
""" Edit an object.
Parameters:
kwargs (dict): Dict of settings to edit.
Example:
{'type': 1,
'id': movie.ratingKey,
'collection[0].tag.tag': 'Super',
'collection.locked': 0}
"""
if 'id' not in kwargs:
kwargs['id'] = self.ratingKey
if 'type' not in kwargs:
kwargs['type'] = utils.searchType(self.type)
part = '/library/sections/%s/all?%s' % (self.librarySectionID,
urlencode(kwargs))
self._server.query(part, method=self._server._session.put) | python | def edit(self, **kwargs):
""" Edit an object.
Parameters:
kwargs (dict): Dict of settings to edit.
Example:
{'type': 1,
'id': movie.ratingKey,
'collection[0].tag.tag': 'Super',
'collection.locked': 0}
"""
if 'id' not in kwargs:
kwargs['id'] = self.ratingKey
if 'type' not in kwargs:
kwargs['type'] = utils.searchType(self.type)
part = '/library/sections/%s/all?%s' % (self.librarySectionID,
urlencode(kwargs))
self._server.query(part, method=self._server._session.put) | [
"def",
"edit",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'id'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'id'",
"]",
"=",
"self",
".",
"ratingKey",
"if",
"'type'",
"not",
"in",
"kwargs",
":",
"kwargs",
"[",
"'type'",
"]",
"=",
"ut... | Edit an object.
Parameters:
kwargs (dict): Dict of settings to edit.
Example:
{'type': 1,
'id': movie.ratingKey,
'collection[0].tag.tag': 'Super',
'collection.locked': 0} | [
"Edit",
"an",
"object",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L325-L344 | train | 210,562 |
pkkid/python-plexapi | plexapi/base.py | PlexPartialObject._edit_tags | def _edit_tags(self, tag, items, locked=True, remove=False):
""" Helper to edit and refresh a tags.
Parameters:
tag (str): tag name
items (list): list of tags to add
locked (bool): lock this field.
remove (bool): If this is active remove the tags in items.
"""
if not isinstance(items, list):
items = [items]
value = getattr(self, tag + 's')
existing_cols = [t.tag for t in value if t and remove is False]
d = tag_helper(tag, existing_cols + items, locked, remove)
self.edit(**d)
self.refresh() | python | def _edit_tags(self, tag, items, locked=True, remove=False):
""" Helper to edit and refresh a tags.
Parameters:
tag (str): tag name
items (list): list of tags to add
locked (bool): lock this field.
remove (bool): If this is active remove the tags in items.
"""
if not isinstance(items, list):
items = [items]
value = getattr(self, tag + 's')
existing_cols = [t.tag for t in value if t and remove is False]
d = tag_helper(tag, existing_cols + items, locked, remove)
self.edit(**d)
self.refresh() | [
"def",
"_edit_tags",
"(",
"self",
",",
"tag",
",",
"items",
",",
"locked",
"=",
"True",
",",
"remove",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"items",
",",
"list",
")",
":",
"items",
"=",
"[",
"items",
"]",
"value",
"=",
"getattr",... | Helper to edit and refresh a tags.
Parameters:
tag (str): tag name
items (list): list of tags to add
locked (bool): lock this field.
remove (bool): If this is active remove the tags in items. | [
"Helper",
"to",
"edit",
"and",
"refresh",
"a",
"tags",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L346-L361 | train | 210,563 |
pkkid/python-plexapi | plexapi/base.py | Playable.getStreamURL | def getStreamURL(self, **params):
""" Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrate, videoResolution
offset, copyts, protocol, mediaIndex, platform.
Raises:
:class:`plexapi.exceptions.Unsupported`: When the item doesn't support fetching a stream URL.
"""
if self.TYPE not in ('movie', 'episode', 'track'):
raise Unsupported('Fetching stream URL for %s is unsupported.' % self.TYPE)
mvb = params.get('maxVideoBitrate')
vr = params.get('videoResolution', '')
params = {
'path': self.key,
'offset': params.get('offset', 0),
'copyts': params.get('copyts', 1),
'protocol': params.get('protocol'),
'mediaIndex': params.get('mediaIndex', 0),
'X-Plex-Platform': params.get('platform', 'Chrome'),
'maxVideoBitrate': max(mvb, 64) if mvb else None,
'videoResolution': vr if re.match('^\d+x\d+$', vr) else None
}
# remove None values
params = {k: v for k, v in params.items() if v is not None}
streamtype = 'audio' if self.TYPE in ('track', 'album') else 'video'
# sort the keys since the randomness fucks with my tests..
sorted_params = sorted(params.items(), key=lambda val: val[0])
return self._server.url('/%s/:/transcode/universal/start.m3u8?%s' %
(streamtype, urlencode(sorted_params)), includeToken=True) | python | def getStreamURL(self, **params):
""" Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrate, videoResolution
offset, copyts, protocol, mediaIndex, platform.
Raises:
:class:`plexapi.exceptions.Unsupported`: When the item doesn't support fetching a stream URL.
"""
if self.TYPE not in ('movie', 'episode', 'track'):
raise Unsupported('Fetching stream URL for %s is unsupported.' % self.TYPE)
mvb = params.get('maxVideoBitrate')
vr = params.get('videoResolution', '')
params = {
'path': self.key,
'offset': params.get('offset', 0),
'copyts': params.get('copyts', 1),
'protocol': params.get('protocol'),
'mediaIndex': params.get('mediaIndex', 0),
'X-Plex-Platform': params.get('platform', 'Chrome'),
'maxVideoBitrate': max(mvb, 64) if mvb else None,
'videoResolution': vr if re.match('^\d+x\d+$', vr) else None
}
# remove None values
params = {k: v for k, v in params.items() if v is not None}
streamtype = 'audio' if self.TYPE in ('track', 'album') else 'video'
# sort the keys since the randomness fucks with my tests..
sorted_params = sorted(params.items(), key=lambda val: val[0])
return self._server.url('/%s/:/transcode/universal/start.m3u8?%s' %
(streamtype, urlencode(sorted_params)), includeToken=True) | [
"def",
"getStreamURL",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"self",
".",
"TYPE",
"not",
"in",
"(",
"'movie'",
",",
"'episode'",
",",
"'track'",
")",
":",
"raise",
"Unsupported",
"(",
"'Fetching stream URL for %s is unsupported.'",
"%",
"self... | Returns a stream url that may be used by external applications such as VLC.
Parameters:
**params (dict): optional parameters to manipulate the playback when accessing
the stream. A few known parameters include: maxVideoBitrate, videoResolution
offset, copyts, protocol, mediaIndex, platform.
Raises:
:class:`plexapi.exceptions.Unsupported`: When the item doesn't support fetching a stream URL. | [
"Returns",
"a",
"stream",
"url",
"that",
"may",
"be",
"used",
"by",
"external",
"applications",
"such",
"as",
"VLC",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L465-L496 | train | 210,564 |
pkkid/python-plexapi | plexapi/base.py | Playable.split | def split(self):
"""Split a duplicate."""
key = '%s/split' % self.key
return self._server.query(key, method=self._server._session.put) | python | def split(self):
"""Split a duplicate."""
key = '%s/split' % self.key
return self._server.query(key, method=self._server._session.put) | [
"def",
"split",
"(",
"self",
")",
":",
"key",
"=",
"'%s/split'",
"%",
"self",
".",
"key",
"return",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"put",
")"
] | Split a duplicate. | [
"Split",
"a",
"duplicate",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L504-L507 | train | 210,565 |
pkkid/python-plexapi | plexapi/base.py | Playable.unmatch | def unmatch(self):
"""Unmatch a media file."""
key = '%s/unmatch' % self.key
return self._server.query(key, method=self._server._session.put) | python | def unmatch(self):
"""Unmatch a media file."""
key = '%s/unmatch' % self.key
return self._server.query(key, method=self._server._session.put) | [
"def",
"unmatch",
"(",
"self",
")",
":",
"key",
"=",
"'%s/unmatch'",
"%",
"self",
".",
"key",
"return",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"put",
")"
] | Unmatch a media file. | [
"Unmatch",
"a",
"media",
"file",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L509-L512 | train | 210,566 |
pkkid/python-plexapi | plexapi/base.py | Playable.download | def download(self, savepath=None, keep_original_name=False, **kwargs):
""" Downloads this items media to the specified location. Returns a list of
filepaths that have been saved to disk.
Parameters:
savepath (str): Title of the track to return.
keep_original_name (bool): Set True to keep the original filename as stored in
the Plex server. False will create a new filename with the format
"<Artist> - <Album> <Track>".
kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will
be returned and the additional arguments passed in will be sent to that
function. If kwargs is not specified, the media items will be downloaded
and saved to disk.
"""
filepaths = []
locations = [i for i in self.iterParts() if i]
for location in locations:
filename = location.file
if keep_original_name is False:
filename = '%s.%s' % (self._prettyfilename(), location.container)
# So this seems to be a alot slower but allows transcode.
if kwargs:
download_url = self.getStreamURL(**kwargs)
else:
download_url = self._server.url('%s?download=1' % location.key)
filepath = utils.download(download_url, self._server._token, filename=filename,
savepath=savepath, session=self._server._session)
if filepath:
filepaths.append(filepath)
return filepaths | python | def download(self, savepath=None, keep_original_name=False, **kwargs):
""" Downloads this items media to the specified location. Returns a list of
filepaths that have been saved to disk.
Parameters:
savepath (str): Title of the track to return.
keep_original_name (bool): Set True to keep the original filename as stored in
the Plex server. False will create a new filename with the format
"<Artist> - <Album> <Track>".
kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will
be returned and the additional arguments passed in will be sent to that
function. If kwargs is not specified, the media items will be downloaded
and saved to disk.
"""
filepaths = []
locations = [i for i in self.iterParts() if i]
for location in locations:
filename = location.file
if keep_original_name is False:
filename = '%s.%s' % (self._prettyfilename(), location.container)
# So this seems to be a alot slower but allows transcode.
if kwargs:
download_url = self.getStreamURL(**kwargs)
else:
download_url = self._server.url('%s?download=1' % location.key)
filepath = utils.download(download_url, self._server._token, filename=filename,
savepath=savepath, session=self._server._session)
if filepath:
filepaths.append(filepath)
return filepaths | [
"def",
"download",
"(",
"self",
",",
"savepath",
"=",
"None",
",",
"keep_original_name",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"filepaths",
"=",
"[",
"]",
"locations",
"=",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"iterParts",
"(",
")",
... | Downloads this items media to the specified location. Returns a list of
filepaths that have been saved to disk.
Parameters:
savepath (str): Title of the track to return.
keep_original_name (bool): Set True to keep the original filename as stored in
the Plex server. False will create a new filename with the format
"<Artist> - <Album> <Track>".
kwargs (dict): If specified, a :func:`~plexapi.audio.Track.getStreamURL()` will
be returned and the additional arguments passed in will be sent to that
function. If kwargs is not specified, the media items will be downloaded
and saved to disk. | [
"Downloads",
"this",
"items",
"media",
"to",
"the",
"specified",
"location",
".",
"Returns",
"a",
"list",
"of",
"filepaths",
"that",
"have",
"been",
"saved",
"to",
"disk",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L522-L551 | train | 210,567 |
pkkid/python-plexapi | plexapi/base.py | Playable.stop | def stop(self, reason=''):
""" Stop playback for a media item. """
key = '/status/sessions/terminate?sessionId=%s&reason=%s' % (self.session[0].id, quote_plus(reason))
return self._server.query(key) | python | def stop(self, reason=''):
""" Stop playback for a media item. """
key = '/status/sessions/terminate?sessionId=%s&reason=%s' % (self.session[0].id, quote_plus(reason))
return self._server.query(key) | [
"def",
"stop",
"(",
"self",
",",
"reason",
"=",
"''",
")",
":",
"key",
"=",
"'/status/sessions/terminate?sessionId=%s&reason=%s'",
"%",
"(",
"self",
".",
"session",
"[",
"0",
"]",
".",
"id",
",",
"quote_plus",
"(",
"reason",
")",
")",
"return",
"self",
"... | Stop playback for a media item. | [
"Stop",
"playback",
"for",
"a",
"media",
"item",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L553-L556 | train | 210,568 |
pkkid/python-plexapi | plexapi/base.py | Playable.updateProgress | def updateProgress(self, time, state='stopped'):
""" Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
"""
key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % (self.ratingKey,
time, state)
self._server.query(key)
self.reload() | python | def updateProgress(self, time, state='stopped'):
""" Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
"""
key = '/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s' % (self.ratingKey,
time, state)
self._server.query(key)
self.reload() | [
"def",
"updateProgress",
"(",
"self",
",",
"time",
",",
"state",
"=",
"'stopped'",
")",
":",
"key",
"=",
"'/:/progress?key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s'",
"%",
"(",
"self",
".",
"ratingKey",
",",
"time",
",",
"state",
")",
"self",
"."... | Set the watched progress for this video.
Note that setting the time to 0 will not work.
Use `markWatched` or `markUnwatched` to achieve
that goal.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped' | [
"Set",
"the",
"watched",
"progress",
"for",
"this",
"video",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L558-L572 | train | 210,569 |
pkkid/python-plexapi | plexapi/base.py | Playable.updateTimeline | def updateTimeline(self, time, state='stopped', duration=None):
""" Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item
"""
durationStr = '&duration='
if duration is not None:
durationStr = durationStr + str(duration)
else:
durationStr = durationStr + str(self.duration)
key = '/:/timeline?ratingKey=%s&key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s%s'
key %= (self.ratingKey, self.key, time, state, durationStr)
self._server.query(key)
self.reload() | python | def updateTimeline(self, time, state='stopped', duration=None):
""" Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item
"""
durationStr = '&duration='
if duration is not None:
durationStr = durationStr + str(duration)
else:
durationStr = durationStr + str(self.duration)
key = '/:/timeline?ratingKey=%s&key=%s&identifier=com.plexapp.plugins.library&time=%d&state=%s%s'
key %= (self.ratingKey, self.key, time, state, durationStr)
self._server.query(key)
self.reload() | [
"def",
"updateTimeline",
"(",
"self",
",",
"time",
",",
"state",
"=",
"'stopped'",
",",
"duration",
"=",
"None",
")",
":",
"durationStr",
"=",
"'&duration='",
"if",
"duration",
"is",
"not",
"None",
":",
"durationStr",
"=",
"durationStr",
"+",
"str",
"(",
... | Set the timeline progress for this video.
Parameters:
time (int): milliseconds watched
state (string): state of the video, default 'stopped'
duration (int): duration of the item | [
"Set",
"the",
"timeline",
"progress",
"for",
"this",
"video",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/base.py#L574-L590 | train | 210,570 |
pkkid/python-plexapi | plexapi/library.py | Library.all | def all(self, **kwargs):
""" Returns a list of all media from all library sections.
This may be a very large dataset to retrieve.
"""
items = []
for section in self.sections():
for item in section.all(**kwargs):
items.append(item)
return items | python | def all(self, **kwargs):
""" Returns a list of all media from all library sections.
This may be a very large dataset to retrieve.
"""
items = []
for section in self.sections():
for item in section.all(**kwargs):
items.append(item)
return items | [
"def",
"all",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"items",
"=",
"[",
"]",
"for",
"section",
"in",
"self",
".",
"sections",
"(",
")",
":",
"for",
"item",
"in",
"section",
".",
"all",
"(",
"*",
"*",
"kwargs",
")",
":",
"items",
".",
... | Returns a list of all media from all library sections.
This may be a very large dataset to retrieve. | [
"Returns",
"a",
"list",
"of",
"all",
"media",
"from",
"all",
"library",
"sections",
".",
"This",
"may",
"be",
"a",
"very",
"large",
"dataset",
"to",
"retrieve",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L67-L75 | train | 210,571 |
pkkid/python-plexapi | plexapi/library.py | Library.search | def search(self, title=None, libtype=None, **kwargs):
""" Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
such as actor=<id> seem to work, but require you already know the id of the actor.
TLDR: This is untested but seems to work. Use library section search when you can.
"""
args = {}
if title:
args['title'] = title
if libtype:
args['type'] = utils.searchType(libtype)
for attr, value in kwargs.items():
args[attr] = value
key = '/library/all%s' % utils.joinArgs(args)
return self.fetchItems(key) | python | def search(self, title=None, libtype=None, **kwargs):
""" Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
such as actor=<id> seem to work, but require you already know the id of the actor.
TLDR: This is untested but seems to work. Use library section search when you can.
"""
args = {}
if title:
args['title'] = title
if libtype:
args['type'] = utils.searchType(libtype)
for attr, value in kwargs.items():
args[attr] = value
key = '/library/all%s' % utils.joinArgs(args)
return self.fetchItems(key) | [
"def",
"search",
"(",
"self",
",",
"title",
"=",
"None",
",",
"libtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"{",
"}",
"if",
"title",
":",
"args",
"[",
"'title'",
"]",
"=",
"title",
"if",
"libtype",
":",
"args",
"[",
"'... | Searching within a library section is much more powerful. It seems certain
attributes on the media objects can be targeted to filter this search down
a bit, but I havent found the documentation for it.
Example: "studio=Comedy%20Central" or "year=1999" "title=Kung Fu" all work. Other items
such as actor=<id> seem to work, but require you already know the id of the actor.
TLDR: This is untested but seems to work. Use library section search when you can. | [
"Searching",
"within",
"a",
"library",
"section",
"is",
"much",
"more",
"powerful",
".",
"It",
"seems",
"certain",
"attributes",
"on",
"the",
"media",
"objects",
"can",
"be",
"targeted",
"to",
"filter",
"this",
"search",
"down",
"a",
"bit",
"but",
"I",
"ha... | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L85-L102 | train | 210,572 |
pkkid/python-plexapi | plexapi/library.py | Library.add | def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):
""" Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): movie, show, # check me
location (str): /path/to/files
language (str): Two letter language fx en
kwargs (dict): Advanced options should be passed as a dict. where the id is the key.
**Photo Preferences**
* **agent** (str): com.plexapp.agents.none
* **enableAutoPhotoTags** (bool): Tag photos. Default value false.
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Photo Scanner
**Movie Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Movie Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source, Default value 0 Possible options:
0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,
16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,
22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,
29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,
35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,
40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,
46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 Possible
options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,
9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,
42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,
49:Venezuela.
**Show Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.
* **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Series Scanner
**TheTVDB Show Options** (com.plexapp.agents.thetvdb)
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
**TheMovieDB Show Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 options
0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,
10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,
41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,
48:Uruguay, 49:Venezuela.
**Other Video Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Other Video Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source Default value 0 Possible options:
0:Rotten Tomatoes,1:IMDb,2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,
17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,
24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,
31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,
37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,
45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default
value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,
6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,
13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,
19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,
25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,
31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,
40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,
46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela.
"""
part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (
quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location)) # noqa E126
if kwargs:
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post) | python | def add(self, name='', type='', agent='', scanner='', location='', language='en', *args, **kwargs):
""" Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): movie, show, # check me
location (str): /path/to/files
language (str): Two letter language fx en
kwargs (dict): Advanced options should be passed as a dict. where the id is the key.
**Photo Preferences**
* **agent** (str): com.plexapp.agents.none
* **enableAutoPhotoTags** (bool): Tag photos. Default value false.
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Photo Scanner
**Movie Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Movie Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source, Default value 0 Possible options:
0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,
16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,
22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,
29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,
35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,
40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,
46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 Possible
options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,
9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,
42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,
49:Venezuela.
**Show Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.
* **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Series Scanner
**TheTVDB Show Options** (com.plexapp.agents.thetvdb)
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
**TheMovieDB Show Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 options
0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,
10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,
41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,
48:Uruguay, 49:Venezuela.
**Other Video Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Other Video Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source Default value 0 Possible options:
0:Rotten Tomatoes,1:IMDb,2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,
17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,
24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,
31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,
37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,
45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default
value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,
6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,
13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,
19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,
25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,
31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,
40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,
46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela.
"""
part = '/library/sections?name=%s&type=%s&agent=%s&scanner=%s&language=%s&location=%s' % (
quote_plus(name), type, agent, quote_plus(scanner), language, quote_plus(location)) # noqa E126
if kwargs:
part += urlencode(kwargs)
return self._server.query(part, method=self._server._session.post) | [
"def",
"add",
"(",
"self",
",",
"name",
"=",
"''",
",",
"type",
"=",
"''",
",",
"agent",
"=",
"''",
",",
"scanner",
"=",
"''",
",",
"location",
"=",
"''",
",",
"language",
"=",
"'en'",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"par... | Simplified add for the most common options.
Parameters:
name (str): Name of the library
agent (str): Example com.plexapp.agents.imdb
type (str): movie, show, # check me
location (str): /path/to/files
language (str): Two letter language fx en
kwargs (dict): Advanced options should be passed as a dict. where the id is the key.
**Photo Preferences**
* **agent** (str): com.plexapp.agents.none
* **enableAutoPhotoTags** (bool): Tag photos. Default value false.
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Photo Scanner
**Movie Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Movie Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source, Default value 0 Possible options:
0:Rotten Tomatoes, 1:IMDb, 2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Default value 46 Possible options 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador,
16:France, 17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland,
22:Italy, 23:Jamaica, 24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands,
29:New Zealand, 30:Nicaragua, 31:Panama, 32:Paraguay, 33:Peru, 34:Portugal,
35:Peoples Republic of China, 36:Puerto Rico, 37:Russia, 38:Singapore, 39:South Africa,
40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad, 45:United Kingdom,
46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Movie Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 Possible
options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada,
9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa, 41:Spain,
42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States, 48:Uruguay,
49:Venezuela.
**Show Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.thetvdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **episodeSort** (int): Episode order. Default -1 Possible options: 0:Oldest first, 1:Newest first.
* **flattenSeasons** (int): Seasons. Default value 0 Possible options: 0:Show,1:Hide.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Series Scanner
**TheTVDB Show Options** (com.plexapp.agents.thetvdb)
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
**TheMovieDB Show Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default value 47 options
0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize, 6:Bolivia, 7:Brazil, 8:Canada, 9:Chile,
10:Colombia, 11:Costa Rica, 12:Czech Republic, 13:Denmark, 14:Dominican Republic, 15:Ecuador,
16:El Salvador, 17:France, 18:Germany, 19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland,
23:Italy, 24:Jamaica, 25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands,
30:New Zealand, 31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore, 40:South Africa,
41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad, 46:United Kingdom, 47:United States,
48:Uruguay, 49:Venezuela.
**Other Video Preferences**
* **agent** (str): com.plexapp.agents.none, com.plexapp.agents.imdb, com.plexapp.agents.themoviedb
* **enableBIFGeneration** (bool): Enable video preview thumbnails. Default value true.
* **enableCinemaTrailers** (bool): Enable Cinema Trailers. Default value true.
* **includeInGlobal** (bool): Include in dashboard. Default value true.
* **scanner** (str): Plex Movie Scanner, Plex Video Files Scanner
**IMDB Other Video Options** (com.plexapp.agents.imdb)
* **title** (bool): Localized titles. Default value false.
* **extras** (bool): Find trailers and extras automatically (Plex Pass required). Default value true.
* **only_trailers** (bool): Skip extras which aren't trailers. Default value false.
* **redband** (bool): Use red band (restricted audiences) trailers when available. Default value false.
* **native_subs** (bool): Include extras with subtitles in Library language. Default value false.
* **cast_list** (int): Cast List Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **ratings** (int): Ratings Source Default value 0 Possible options:
0:Rotten Tomatoes,1:IMDb,2:The Movie Database.
* **summary** (int): Plot Summary Source: Default value 1 Possible options: 0:IMDb,1:The Movie Database.
* **country** (int): Country: Default value 46 Possible options: 0:Argentina, 1:Australia, 2:Austria,
3:Belgium, 4:Belize, 5:Bolivia, 6:Brazil, 7:Canada, 8:Chile, 9:Colombia, 10:Costa Rica,
11:Czech Republic, 12:Denmark, 13:Dominican Republic, 14:Ecuador, 15:El Salvador, 16:France,
17:Germany, 18:Guatemala, 19:Honduras, 20:Hong Kong SAR, 21:Ireland, 22:Italy, 23:Jamaica,
24:Korea, 25:Liechtenstein, 26:Luxembourg, 27:Mexico, 28:Netherlands, 29:New Zealand, 30:Nicaragua,
31:Panama, 32:Paraguay, 33:Peru, 34:Portugal, 35:Peoples Republic of China, 36:Puerto Rico,
37:Russia, 38:Singapore, 39:South Africa, 40:Spain, 41:Sweden, 42:Switzerland, 43:Taiwan, 44:Trinidad,
45:United Kingdom, 46:United States, 47:Uruguay, 48:Venezuela.
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **usage** (bool): Send anonymous usage data to Plex. Default value true.
**TheMovieDB Other Video Options** (com.plexapp.agents.themoviedb)
* **collections** (bool): Use collection info from The Movie Database. Default value false.
* **localart** (bool): Prefer artwork based on library language. Default value true.
* **adult** (bool): Include adult content. Default value false.
* **country** (int): Country (used for release date and content rating). Default
value 47 Possible options 0:, 1:Argentina, 2:Australia, 3:Austria, 4:Belgium, 5:Belize,
6:Bolivia, 7:Brazil, 8:Canada, 9:Chile, 10:Colombia, 11:Costa Rica, 12:Czech Republic,
13:Denmark, 14:Dominican Republic, 15:Ecuador, 16:El Salvador, 17:France, 18:Germany,
19:Guatemala, 20:Honduras, 21:Hong Kong SAR, 22:Ireland, 23:Italy, 24:Jamaica,
25:Korea, 26:Liechtenstein, 27:Luxembourg, 28:Mexico, 29:Netherlands, 30:New Zealand,
31:Nicaragua, 32:Panama, 33:Paraguay, 34:Peru, 35:Portugal,
36:Peoples Republic of China, 37:Puerto Rico, 38:Russia, 39:Singapore,
40:South Africa, 41:Spain, 42:Sweden, 43:Switzerland, 44:Taiwan, 45:Trinidad,
46:United Kingdom, 47:United States, 48:Uruguay, 49:Venezuela. | [
"Simplified",
"add",
"for",
"the",
"most",
"common",
"options",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L147-L295 | train | 210,573 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.delete | def delete(self):
""" Delete a library section. """
try:
return self._server.query('/library/sections/%s' % self.key, method=self._server._session.delete)
except BadRequest: # pragma: no cover
msg = 'Failed to delete library %s' % self.key
msg += 'You may need to allow this permission in your Plex settings.'
log.error(msg)
raise | python | def delete(self):
""" Delete a library section. """
try:
return self._server.query('/library/sections/%s' % self.key, method=self._server._session.delete)
except BadRequest: # pragma: no cover
msg = 'Failed to delete library %s' % self.key
msg += 'You may need to allow this permission in your Plex settings.'
log.error(msg)
raise | [
"def",
"delete",
"(",
"self",
")",
":",
"try",
":",
"return",
"self",
".",
"_server",
".",
"query",
"(",
"'/library/sections/%s'",
"%",
"self",
".",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"delete",
")",
"except",
"BadR... | Delete a library section. | [
"Delete",
"a",
"library",
"section",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L347-L355 | train | 210,574 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.get | def get(self, title):
""" Returns the media item with the specified title.
Parameters:
title (str): Title of the item to return.
"""
key = '/library/sections/%s/all' % self.key
return self.fetchItem(key, title__iexact=title) | python | def get(self, title):
""" Returns the media item with the specified title.
Parameters:
title (str): Title of the item to return.
"""
key = '/library/sections/%s/all' % self.key
return self.fetchItem(key, title__iexact=title) | [
"def",
"get",
"(",
"self",
",",
"title",
")",
":",
"key",
"=",
"'/library/sections/%s/all'",
"%",
"self",
".",
"key",
"return",
"self",
".",
"fetchItem",
"(",
"key",
",",
"title__iexact",
"=",
"title",
")"
] | Returns the media item with the specified title.
Parameters:
title (str): Title of the item to return. | [
"Returns",
"the",
"media",
"item",
"with",
"the",
"specified",
"title",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L371-L378 | train | 210,575 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.all | def all(self, sort=None, **kwargs):
""" Returns a list of media from this library section.
Parameters:
sort (string): The sort string
"""
sortStr = ''
if sort is not None:
sortStr = '?sort=' + sort
key = '/library/sections/%s/all%s' % (self.key, sortStr)
return self.fetchItems(key, **kwargs) | python | def all(self, sort=None, **kwargs):
""" Returns a list of media from this library section.
Parameters:
sort (string): The sort string
"""
sortStr = ''
if sort is not None:
sortStr = '?sort=' + sort
key = '/library/sections/%s/all%s' % (self.key, sortStr)
return self.fetchItems(key, **kwargs) | [
"def",
"all",
"(",
"self",
",",
"sort",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"sortStr",
"=",
"''",
"if",
"sort",
"is",
"not",
"None",
":",
"sortStr",
"=",
"'?sort='",
"+",
"sort",
"key",
"=",
"'/library/sections/%s/all%s'",
"%",
"(",
"self... | Returns a list of media from this library section.
Parameters:
sort (string): The sort string | [
"Returns",
"a",
"list",
"of",
"media",
"from",
"this",
"library",
"section",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L380-L391 | train | 210,576 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.emptyTrash | def emptyTrash(self):
""" If a section has items in the Trash, use this option to empty the Trash. """
key = '/library/sections/%s/emptyTrash' % self.key
self._server.query(key, method=self._server._session.put) | python | def emptyTrash(self):
""" If a section has items in the Trash, use this option to empty the Trash. """
key = '/library/sections/%s/emptyTrash' % self.key
self._server.query(key, method=self._server._session.put) | [
"def",
"emptyTrash",
"(",
"self",
")",
":",
"key",
"=",
"'/library/sections/%s/emptyTrash'",
"%",
"self",
".",
"key",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"put",
")"
] | If a section has items in the Trash, use this option to empty the Trash. | [
"If",
"a",
"section",
"has",
"items",
"in",
"the",
"Trash",
"use",
"this",
"option",
"to",
"empty",
"the",
"Trash",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L413-L416 | train | 210,577 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.cancelUpdate | def cancelUpdate(self):
""" Cancel update of this Library Section. """
key = '/library/sections/%s/refresh' % self.key
self._server.query(key, method=self._server._session.delete) | python | def cancelUpdate(self):
""" Cancel update of this Library Section. """
key = '/library/sections/%s/refresh' % self.key
self._server.query(key, method=self._server._session.delete) | [
"def",
"cancelUpdate",
"(",
"self",
")",
":",
"key",
"=",
"'/library/sections/%s/refresh'",
"%",
"self",
".",
"key",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"delete",
")"
] | Cancel update of this Library Section. | [
"Cancel",
"update",
"of",
"this",
"Library",
"Section",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L423-L426 | train | 210,578 |
pkkid/python-plexapi | plexapi/library.py | LibrarySection.deleteMediaPreviews | def deleteMediaPreviews(self):
""" Delete the preview thumbnails for items in this library. This cannot
be undone. Recreating media preview files can take hours or even days.
"""
key = '/library/sections/%s/indexes' % self.key
self._server.query(key, method=self._server._session.delete) | python | def deleteMediaPreviews(self):
""" Delete the preview thumbnails for items in this library. This cannot
be undone. Recreating media preview files can take hours or even days.
"""
key = '/library/sections/%s/indexes' % self.key
self._server.query(key, method=self._server._session.delete) | [
"def",
"deleteMediaPreviews",
"(",
"self",
")",
":",
"key",
"=",
"'/library/sections/%s/indexes'",
"%",
"self",
".",
"key",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"method",
"=",
"self",
".",
"_server",
".",
"_session",
".",
"delete",
")"
] | Delete the preview thumbnails for items in this library. This cannot
be undone. Recreating media preview files can take hours or even days. | [
"Delete",
"the",
"preview",
"thumbnails",
"for",
"items",
"in",
"this",
"library",
".",
"This",
"cannot",
"be",
"undone",
".",
"Recreating",
"media",
"preview",
"files",
"can",
"take",
"hours",
"or",
"even",
"days",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L435-L440 | train | 210,579 |
pkkid/python-plexapi | plexapi/library.py | ShowSection.recentlyAdded | def recentlyAdded(self, libtype='episode', maxresults=50):
""" Returns a list of recently added episodes from this library section.
Parameters:
maxresults (int): Max number of items to return (default 50).
"""
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults) | python | def recentlyAdded(self, libtype='episode', maxresults=50):
""" Returns a list of recently added episodes from this library section.
Parameters:
maxresults (int): Max number of items to return (default 50).
"""
return self.search(sort='addedAt:desc', libtype=libtype, maxresults=maxresults) | [
"def",
"recentlyAdded",
"(",
"self",
",",
"libtype",
"=",
"'episode'",
",",
"maxresults",
"=",
"50",
")",
":",
"return",
"self",
".",
"search",
"(",
"sort",
"=",
"'addedAt:desc'",
",",
"libtype",
"=",
"libtype",
",",
"maxresults",
"=",
"maxresults",
")"
] | Returns a list of recently added episodes from this library section.
Parameters:
maxresults (int): Max number of items to return (default 50). | [
"Returns",
"a",
"list",
"of",
"recently",
"added",
"episodes",
"from",
"this",
"library",
"section",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/library.py#L728-L734 | train | 210,580 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexAccount.inviteFriend | def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections ([Section]): Library sections, names or ids to be shared (default None shares all sections).
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']}
"""
username = user.username if isinstance(user, MyPlexUser) else user
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
params = {
'server_id': machineId,
'shared_server': {'library_section_ids': sectionIds, 'invited_email': username},
'sharing_settings': {
'allowSync': ('1' if allowSync else '0'),
'allowCameraUpload': ('1' if allowCameraUpload else '0'),
'allowChannels': ('1' if allowChannels else '0'),
'filterMovies': self._filterDictToStr(filterMovies or {}),
'filterTelevision': self._filterDictToStr(filterTelevision or {}),
'filterMusic': self._filterDictToStr(filterMusic or {}),
},
}
headers = {'Content-Type': 'application/json'}
url = self.FRIENDINVITE.format(machineId=machineId)
return self.query(url, self._session.post, json=params, headers=headers) | python | def inviteFriend(self, user, server, sections=None, allowSync=False, allowCameraUpload=False,
allowChannels=False, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections ([Section]): Library sections, names or ids to be shared (default None shares all sections).
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']}
"""
username = user.username if isinstance(user, MyPlexUser) else user
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
params = {
'server_id': machineId,
'shared_server': {'library_section_ids': sectionIds, 'invited_email': username},
'sharing_settings': {
'allowSync': ('1' if allowSync else '0'),
'allowCameraUpload': ('1' if allowCameraUpload else '0'),
'allowChannels': ('1' if allowChannels else '0'),
'filterMovies': self._filterDictToStr(filterMovies or {}),
'filterTelevision': self._filterDictToStr(filterTelevision or {}),
'filterMusic': self._filterDictToStr(filterMusic or {}),
},
}
headers = {'Content-Type': 'application/json'}
url = self.FRIENDINVITE.format(machineId=machineId)
return self.query(url, self._session.post, json=params, headers=headers) | [
"def",
"inviteFriend",
"(",
"self",
",",
"user",
",",
"server",
",",
"sections",
"=",
"None",
",",
"allowSync",
"=",
"False",
",",
"allowCameraUpload",
"=",
"False",
",",
"allowChannels",
"=",
"False",
",",
"filterMovies",
"=",
"None",
",",
"filterTelevision... | Share library content with the specified user.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections ([Section]): Library sections, names or ids to be shared (default None shares all sections).
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']} | [
"Share",
"library",
"content",
"with",
"the",
"specified",
"user",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L196-L231 | train | 210,581 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexAccount.removeFriend | def removeFriend(self, user):
""" Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
"""
user = self.user(user)
url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE
url = url.format(userId=user.id)
return self.query(url, self._session.delete) | python | def removeFriend(self, user):
""" Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
"""
user = self.user(user)
url = self.FRIENDUPDATE if user.friend else self.REMOVEINVITE
url = url.format(userId=user.id)
return self.query(url, self._session.delete) | [
"def",
"removeFriend",
"(",
"self",
",",
"user",
")",
":",
"user",
"=",
"self",
".",
"user",
"(",
"user",
")",
"url",
"=",
"self",
".",
"FRIENDUPDATE",
"if",
"user",
".",
"friend",
"else",
"self",
".",
"REMOVEINVITE",
"url",
"=",
"url",
".",
"format"... | Remove the specified user from all sharing.
Parameters:
user (str): MyPlexUser, username, email of the user to be added. | [
"Remove",
"the",
"specified",
"user",
"from",
"all",
"sharing",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L233-L242 | train | 210,582 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexAccount.updateFriend | def updateFriend(self, user, server, sections=None, removeSections=False, allowSync=None, allowCameraUpload=None,
allowChannels=None, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Update the specified user's share settings.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections: ([Section]): Library sections, names or ids to be shared (default None shares all sections).
removeSections (Bool): Set True to remove all shares. Supersedes sections.
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']}
"""
# Update friend servers
response_filters = ''
response_servers = ''
user = user if isinstance(user, MyPlexUser) else self.user(user)
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
headers = {'Content-Type': 'application/json'}
# Determine whether user has access to the shared server.
user_servers = [s for s in user.servers if s.machineIdentifier == machineId]
if user_servers and sectionIds:
serverId = user_servers[0].id
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds}}
url = self.FRIENDSERVERS.format(machineId=machineId, serverId=serverId)
else:
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds,
"invited_id": user.id}}
url = self.FRIENDINVITE.format(machineId=machineId)
# Remove share sections, add shares to user without shares, or update shares
if not user_servers or sectionIds:
if removeSections is True:
response_servers = self.query(url, self._session.delete, json=params, headers=headers)
elif 'invited_id' in params.get('shared_server', ''):
response_servers = self.query(url, self._session.post, json=params, headers=headers)
else:
response_servers = self.query(url, self._session.put, json=params, headers=headers)
else:
log.warning('Section name, number of section object is required changing library sections')
# Update friend filters
url = self.FRIENDUPDATE.format(userId=user.id)
params = {}
if isinstance(allowSync, bool):
params['allowSync'] = '1' if allowSync else '0'
if isinstance(allowCameraUpload, bool):
params['allowCameraUpload'] = '1' if allowCameraUpload else '0'
if isinstance(allowChannels, bool):
params['allowChannels'] = '1' if allowChannels else '0'
if isinstance(filterMovies, dict):
params['filterMovies'] = self._filterDictToStr(filterMovies or {}) # '1' if allowChannels else '0'
if isinstance(filterTelevision, dict):
params['filterTelevision'] = self._filterDictToStr(filterTelevision or {})
if isinstance(allowChannels, dict):
params['filterMusic'] = self._filterDictToStr(filterMusic or {})
if params:
url += joinArgs(params)
response_filters = self.query(url, self._session.put)
return response_servers, response_filters | python | def updateFriend(self, user, server, sections=None, removeSections=False, allowSync=None, allowCameraUpload=None,
allowChannels=None, filterMovies=None, filterTelevision=None, filterMusic=None):
""" Update the specified user's share settings.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections: ([Section]): Library sections, names or ids to be shared (default None shares all sections).
removeSections (Bool): Set True to remove all shares. Supersedes sections.
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']}
"""
# Update friend servers
response_filters = ''
response_servers = ''
user = user if isinstance(user, MyPlexUser) else self.user(user)
machineId = server.machineIdentifier if isinstance(server, PlexServer) else server
sectionIds = self._getSectionIds(machineId, sections)
headers = {'Content-Type': 'application/json'}
# Determine whether user has access to the shared server.
user_servers = [s for s in user.servers if s.machineIdentifier == machineId]
if user_servers and sectionIds:
serverId = user_servers[0].id
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds}}
url = self.FRIENDSERVERS.format(machineId=machineId, serverId=serverId)
else:
params = {'server_id': machineId, 'shared_server': {'library_section_ids': sectionIds,
"invited_id": user.id}}
url = self.FRIENDINVITE.format(machineId=machineId)
# Remove share sections, add shares to user without shares, or update shares
if not user_servers or sectionIds:
if removeSections is True:
response_servers = self.query(url, self._session.delete, json=params, headers=headers)
elif 'invited_id' in params.get('shared_server', ''):
response_servers = self.query(url, self._session.post, json=params, headers=headers)
else:
response_servers = self.query(url, self._session.put, json=params, headers=headers)
else:
log.warning('Section name, number of section object is required changing library sections')
# Update friend filters
url = self.FRIENDUPDATE.format(userId=user.id)
params = {}
if isinstance(allowSync, bool):
params['allowSync'] = '1' if allowSync else '0'
if isinstance(allowCameraUpload, bool):
params['allowCameraUpload'] = '1' if allowCameraUpload else '0'
if isinstance(allowChannels, bool):
params['allowChannels'] = '1' if allowChannels else '0'
if isinstance(filterMovies, dict):
params['filterMovies'] = self._filterDictToStr(filterMovies or {}) # '1' if allowChannels else '0'
if isinstance(filterTelevision, dict):
params['filterTelevision'] = self._filterDictToStr(filterTelevision or {})
if isinstance(allowChannels, dict):
params['filterMusic'] = self._filterDictToStr(filterMusic or {})
if params:
url += joinArgs(params)
response_filters = self.query(url, self._session.put)
return response_servers, response_filters | [
"def",
"updateFriend",
"(",
"self",
",",
"user",
",",
"server",
",",
"sections",
"=",
"None",
",",
"removeSections",
"=",
"False",
",",
"allowSync",
"=",
"None",
",",
"allowCameraUpload",
"=",
"None",
",",
"allowChannels",
"=",
"None",
",",
"filterMovies",
... | Update the specified user's share settings.
Parameters:
user (str): MyPlexUser, username, email of the user to be added.
server (PlexServer): PlexServer object or machineIdentifier containing the library sections to share.
sections: ([Section]): Library sections, names or ids to be shared (default None shares all sections).
removeSections (Bool): Set True to remove all shares. Supersedes sections.
allowSync (Bool): Set True to allow user to sync content.
allowCameraUpload (Bool): Set True to allow user to upload photos.
allowChannels (Bool): Set True to allow user to utilize installed channels.
filterMovies (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterTelevision (Dict): Dict containing key 'contentRating' and/or 'label' each set to a list of
values to be filtered. ex: {'contentRating':['G'], 'label':['foo']}
filterMusic (Dict): Dict containing key 'label' set to a list of values to be filtered.
ex: {'label':['foo']} | [
"Update",
"the",
"specified",
"user",
"s",
"share",
"settings",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L244-L308 | train | 210,583 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexAccount._getSectionIds | def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
if not sections: return []
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
data = self.query(url, self._session.get)
for elem in data[0]:
allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id')
log.debug(allSectionIds)
# Convert passed in section items to section ids from above lookup
sectionIds = []
for section in sections:
sectionKey = section.key if isinstance(section, LibrarySection) else section
sectionIds.append(allSectionIds[sectionKey.lower()])
return sectionIds | python | def _getSectionIds(self, server, sections):
""" Converts a list of section objects or names to sectionIds needed for library sharing. """
if not sections: return []
# Get a list of all section ids for looking up each section.
allSectionIds = {}
machineIdentifier = server.machineIdentifier if isinstance(server, PlexServer) else server
url = self.PLEXSERVERS.replace('{machineId}', machineIdentifier)
data = self.query(url, self._session.get)
for elem in data[0]:
allSectionIds[elem.attrib.get('id', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('title', '').lower()] = elem.attrib.get('id')
allSectionIds[elem.attrib.get('key', '').lower()] = elem.attrib.get('id')
log.debug(allSectionIds)
# Convert passed in section items to section ids from above lookup
sectionIds = []
for section in sections:
sectionKey = section.key if isinstance(section, LibrarySection) else section
sectionIds.append(allSectionIds[sectionKey.lower()])
return sectionIds | [
"def",
"_getSectionIds",
"(",
"self",
",",
"server",
",",
"sections",
")",
":",
"if",
"not",
"sections",
":",
"return",
"[",
"]",
"# Get a list of all section ids for looking up each section.",
"allSectionIds",
"=",
"{",
"}",
"machineIdentifier",
"=",
"server",
".",... | Converts a list of section objects or names to sectionIds needed for library sharing. | [
"Converts",
"a",
"list",
"of",
"section",
"objects",
"or",
"names",
"to",
"sectionIds",
"needed",
"for",
"library",
"sharing",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L336-L354 | train | 210,584 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexAccount._filterDictToStr | def _filterDictToStr(self, filterDict):
""" Converts friend filters to a string representation for transport. """
values = []
for key, vals in filterDict.items():
if key not in ('contentRating', 'label'):
raise BadRequest('Unknown filter key: %s', key)
values.append('%s=%s' % (key, '%2C'.join(vals)))
return '|'.join(values) | python | def _filterDictToStr(self, filterDict):
""" Converts friend filters to a string representation for transport. """
values = []
for key, vals in filterDict.items():
if key not in ('contentRating', 'label'):
raise BadRequest('Unknown filter key: %s', key)
values.append('%s=%s' % (key, '%2C'.join(vals)))
return '|'.join(values) | [
"def",
"_filterDictToStr",
"(",
"self",
",",
"filterDict",
")",
":",
"values",
"=",
"[",
"]",
"for",
"key",
",",
"vals",
"in",
"filterDict",
".",
"items",
"(",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'contentRating'",
",",
"'label'",
")",
":",
"rai... | Converts friend filters to a string representation for transport. | [
"Converts",
"friend",
"filters",
"to",
"a",
"string",
"representation",
"for",
"transport",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L356-L363 | train | 210,585 |
pkkid/python-plexapi | plexapi/myplex.py | MyPlexDevice.delete | def delete(self):
""" Remove this device from your account. """
key = 'https://plex.tv/devices/%s.xml' % self.id
self._server.query(key, self._server._session.delete) | python | def delete(self):
""" Remove this device from your account. """
key = 'https://plex.tv/devices/%s.xml' % self.id
self._server.query(key, self._server._session.delete) | [
"def",
"delete",
"(",
"self",
")",
":",
"key",
"=",
"'https://plex.tv/devices/%s.xml'",
"%",
"self",
".",
"id",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"self",
".",
"_server",
".",
"_session",
".",
"delete",
")"
] | Remove this device from your account. | [
"Remove",
"this",
"device",
"from",
"your",
"account",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/myplex.py#L808-L811 | train | 210,586 |
pkkid/python-plexapi | plexapi/audio.py | Audio.thumbUrl | def thumbUrl(self):
""" Return url to for the thumbnail image. """
key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(key, includeToken=True) if key else None | python | def thumbUrl(self):
""" Return url to for the thumbnail image. """
key = self.firstAttr('thumb', 'parentThumb', 'granparentThumb')
return self._server.url(key, includeToken=True) if key else None | [
"def",
"thumbUrl",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"firstAttr",
"(",
"'thumb'",
",",
"'parentThumb'",
",",
"'granparentThumb'",
")",
"return",
"self",
".",
"_server",
".",
"url",
"(",
"key",
",",
"includeToken",
"=",
"True",
")",
"if",
... | Return url to for the thumbnail image. | [
"Return",
"url",
"to",
"for",
"the",
"thumbnail",
"image",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/plexapi/audio.py#L49-L52 | train | 210,587 |
pkkid/python-plexapi | tools/plex-autodelete.py | keep_episodes | def keep_episodes(show, keep):
""" Delete all but last count episodes in show. """
deleted = 0
print('%s Cleaning %s to %s episodes.' % (datestr(), show.title, keep))
sort = lambda x:x.originallyAvailableAt or x.addedAt
items = sorted(show.episodes(), key=sort, reverse=True)
for episode in items[keep:]:
delete_episode(episode)
deleted += 1
return deleted | python | def keep_episodes(show, keep):
""" Delete all but last count episodes in show. """
deleted = 0
print('%s Cleaning %s to %s episodes.' % (datestr(), show.title, keep))
sort = lambda x:x.originallyAvailableAt or x.addedAt
items = sorted(show.episodes(), key=sort, reverse=True)
for episode in items[keep:]:
delete_episode(episode)
deleted += 1
return deleted | [
"def",
"keep_episodes",
"(",
"show",
",",
"keep",
")",
":",
"deleted",
"=",
"0",
"print",
"(",
"'%s Cleaning %s to %s episodes.'",
"%",
"(",
"datestr",
"(",
")",
",",
"show",
".",
"title",
",",
"keep",
")",
")",
"sort",
"=",
"lambda",
"x",
":",
"x",
... | Delete all but last count episodes in show. | [
"Delete",
"all",
"but",
"last",
"count",
"episodes",
"in",
"show",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/tools/plex-autodelete.py#L39-L48 | train | 210,588 |
pkkid/python-plexapi | tools/plex-autodelete.py | keep_season | def keep_season(show, keep):
""" Keep only the latest season. """
deleted = 0
print('%s Cleaning %s to latest season.' % (datestr(), show.title))
for season in show.seasons()[:-1]:
for episode in season.episodes():
delete_episode(episode)
deleted += 1
return deleted | python | def keep_season(show, keep):
""" Keep only the latest season. """
deleted = 0
print('%s Cleaning %s to latest season.' % (datestr(), show.title))
for season in show.seasons()[:-1]:
for episode in season.episodes():
delete_episode(episode)
deleted += 1
return deleted | [
"def",
"keep_season",
"(",
"show",
",",
"keep",
")",
":",
"deleted",
"=",
"0",
"print",
"(",
"'%s Cleaning %s to latest season.'",
"%",
"(",
"datestr",
"(",
")",
",",
"show",
".",
"title",
")",
")",
"for",
"season",
"in",
"show",
".",
"seasons",
"(",
"... | Keep only the latest season. | [
"Keep",
"only",
"the",
"latest",
"season",
"."
] | 9efbde96441c2bfbf410eacfb46e811e108e8bbc | https://github.com/pkkid/python-plexapi/blob/9efbde96441c2bfbf410eacfb46e811e108e8bbc/tools/plex-autodelete.py#L51-L59 | train | 210,589 |
sklarsa/django-sendgrid-v5 | sendgrid_backend/mail.py | SendgridBackend._create_sg_attachment | def _create_sg_attachment(self, django_attch):
"""
Handles the conversion between a django attachment object and a sendgrid attachment object.
Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure
that attachments get properly instantiated.
"""
def set_prop(attachment, prop_name, value):
if SENDGRID_VERSION < '6':
setattr(attachment, prop_name, value)
else:
if prop_name == "filename":
prop_name = "name"
setattr(attachment, 'file_{}'.format(prop_name), value)
sg_attch = Attachment()
if isinstance(django_attch, MIMEBase):
filename = django_attch.get_filename()
if not filename:
ext = mimetypes.guess_extension(django_attch.get_content_type())
filename = "part-{0}{1}".format(uuid.uuid4().hex, ext)
set_prop(sg_attch, "filename", filename)
# todo: Read content if stream?
set_prop(sg_attch, "content", django_attch.get_payload().replace("\n", ""))
set_prop(sg_attch, "type", django_attch.get_content_type())
content_id = django_attch.get("Content-ID")
if content_id:
# Strip brackets since sendgrid's api adds them
if content_id.startswith("<") and content_id.endswith(">"):
content_id = content_id[1:-1]
# These 2 properties did not change in v6, so we set them the usual way
sg_attch.content_id = content_id
sg_attch.disposition = "inline"
else:
filename, content, mimetype = django_attch
set_prop(sg_attch, "filename", filename)
# Convert content from chars to bytes, in both Python 2 and 3.
# todo: Read content if stream?
if isinstance(content, str):
content = content.encode('utf-8')
set_prop(sg_attch, "content", base64.b64encode(content).decode())
set_prop(sg_attch, "type", mimetype)
return sg_attch | python | def _create_sg_attachment(self, django_attch):
"""
Handles the conversion between a django attachment object and a sendgrid attachment object.
Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure
that attachments get properly instantiated.
"""
def set_prop(attachment, prop_name, value):
if SENDGRID_VERSION < '6':
setattr(attachment, prop_name, value)
else:
if prop_name == "filename":
prop_name = "name"
setattr(attachment, 'file_{}'.format(prop_name), value)
sg_attch = Attachment()
if isinstance(django_attch, MIMEBase):
filename = django_attch.get_filename()
if not filename:
ext = mimetypes.guess_extension(django_attch.get_content_type())
filename = "part-{0}{1}".format(uuid.uuid4().hex, ext)
set_prop(sg_attch, "filename", filename)
# todo: Read content if stream?
set_prop(sg_attch, "content", django_attch.get_payload().replace("\n", ""))
set_prop(sg_attch, "type", django_attch.get_content_type())
content_id = django_attch.get("Content-ID")
if content_id:
# Strip brackets since sendgrid's api adds them
if content_id.startswith("<") and content_id.endswith(">"):
content_id = content_id[1:-1]
# These 2 properties did not change in v6, so we set them the usual way
sg_attch.content_id = content_id
sg_attch.disposition = "inline"
else:
filename, content, mimetype = django_attch
set_prop(sg_attch, "filename", filename)
# Convert content from chars to bytes, in both Python 2 and 3.
# todo: Read content if stream?
if isinstance(content, str):
content = content.encode('utf-8')
set_prop(sg_attch, "content", base64.b64encode(content).decode())
set_prop(sg_attch, "type", mimetype)
return sg_attch | [
"def",
"_create_sg_attachment",
"(",
"self",
",",
"django_attch",
")",
":",
"def",
"set_prop",
"(",
"attachment",
",",
"prop_name",
",",
"value",
")",
":",
"if",
"SENDGRID_VERSION",
"<",
"'6'",
":",
"setattr",
"(",
"attachment",
",",
"prop_name",
",",
"value... | Handles the conversion between a django attachment object and a sendgrid attachment object.
Due to differences between sendgrid's API versions, use this method when constructing attachments to ensure
that attachments get properly instantiated. | [
"Handles",
"the",
"conversion",
"between",
"a",
"django",
"attachment",
"object",
"and",
"a",
"sendgrid",
"attachment",
"object",
".",
"Due",
"to",
"differences",
"between",
"sendgrid",
"s",
"API",
"versions",
"use",
"this",
"method",
"when",
"constructing",
"at... | 187b9b98192bdd9a5d68a1c7ad55a37ca1c3e89a | https://github.com/sklarsa/django-sendgrid-v5/blob/187b9b98192bdd9a5d68a1c7ad55a37ca1c3e89a/sendgrid_backend/mail.py#L122-L168 | train | 210,590 |
akesterson/dpath-python | dpath/path.py | validate | def validate(path, regex=None):
"""
Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given.
"""
validated = []
for elem in path:
key = elem[0]
strkey = str(key)
if (regex and (not regex.findall(strkey))):
raise dpath.exceptions.InvalidKeyName("{} at {} does not match the expression {}"
"".format(strkey,
validated,
regex.pattern))
validated.append(strkey) | python | def validate(path, regex=None):
"""
Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given.
"""
validated = []
for elem in path:
key = elem[0]
strkey = str(key)
if (regex and (not regex.findall(strkey))):
raise dpath.exceptions.InvalidKeyName("{} at {} does not match the expression {}"
"".format(strkey,
validated,
regex.pattern))
validated.append(strkey) | [
"def",
"validate",
"(",
"path",
",",
"regex",
"=",
"None",
")",
":",
"validated",
"=",
"[",
"]",
"for",
"elem",
"in",
"path",
":",
"key",
"=",
"elem",
"[",
"0",
"]",
"strkey",
"=",
"str",
"(",
"key",
")",
"if",
"(",
"regex",
"and",
"(",
"not",
... | Validate that all the keys in the given list of path components are valid, given that they do not contain the separator, and match any optional regex given. | [
"Validate",
"that",
"all",
"the",
"keys",
"in",
"the",
"given",
"list",
"of",
"path",
"components",
"are",
"valid",
"given",
"that",
"they",
"do",
"not",
"contain",
"the",
"separator",
"and",
"match",
"any",
"optional",
"regex",
"given",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L46-L59 | train | 210,591 |
akesterson/dpath-python | dpath/path.py | paths | def paths(obj, dirs=True, leaves=True, path=[], skip=False):
"""Yield all paths of the object.
Arguments:
obj -- An object to get paths from.
Keyword Arguments:
dirs -- Yield intermediate paths.
leaves -- Yield the paths with leaf objects.
path -- A list of keys representing the path.
skip -- Skip special keys beginning with '+'.
"""
if isinstance(obj, MutableMapping):
# Python 3 support
if PY3:
iteritems = obj.items()
string_class = str
else: # Default to PY2
iteritems = obj.iteritems()
string_class = basestring
for (k, v) in iteritems:
if issubclass(k.__class__, (string_class)):
if (not k) and (not dpath.options.ALLOW_EMPTY_STRING_KEYS):
raise dpath.exceptions.InvalidKeyName("Empty string keys not allowed without "
"dpath.options.ALLOW_EMPTY_STRING_KEYS=True")
elif (skip and k[0] == '+'):
continue
newpath = path + [[k, v.__class__]]
validate(newpath)
if dirs:
yield newpath
for child in paths(v, dirs, leaves, newpath, skip):
yield child
elif isinstance(obj, MutableSequence):
for (i, v) in enumerate(obj):
newpath = path + [[i, v.__class__]]
if dirs:
yield newpath
for child in paths(obj[i], dirs, leaves, newpath, skip):
yield child
elif leaves:
yield path + [[obj, obj.__class__]]
elif not dirs:
yield path | python | def paths(obj, dirs=True, leaves=True, path=[], skip=False):
"""Yield all paths of the object.
Arguments:
obj -- An object to get paths from.
Keyword Arguments:
dirs -- Yield intermediate paths.
leaves -- Yield the paths with leaf objects.
path -- A list of keys representing the path.
skip -- Skip special keys beginning with '+'.
"""
if isinstance(obj, MutableMapping):
# Python 3 support
if PY3:
iteritems = obj.items()
string_class = str
else: # Default to PY2
iteritems = obj.iteritems()
string_class = basestring
for (k, v) in iteritems:
if issubclass(k.__class__, (string_class)):
if (not k) and (not dpath.options.ALLOW_EMPTY_STRING_KEYS):
raise dpath.exceptions.InvalidKeyName("Empty string keys not allowed without "
"dpath.options.ALLOW_EMPTY_STRING_KEYS=True")
elif (skip and k[0] == '+'):
continue
newpath = path + [[k, v.__class__]]
validate(newpath)
if dirs:
yield newpath
for child in paths(v, dirs, leaves, newpath, skip):
yield child
elif isinstance(obj, MutableSequence):
for (i, v) in enumerate(obj):
newpath = path + [[i, v.__class__]]
if dirs:
yield newpath
for child in paths(obj[i], dirs, leaves, newpath, skip):
yield child
elif leaves:
yield path + [[obj, obj.__class__]]
elif not dirs:
yield path | [
"def",
"paths",
"(",
"obj",
",",
"dirs",
"=",
"True",
",",
"leaves",
"=",
"True",
",",
"path",
"=",
"[",
"]",
",",
"skip",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"MutableMapping",
")",
":",
"# Python 3 support",
"if",
"PY3",
"... | Yield all paths of the object.
Arguments:
obj -- An object to get paths from.
Keyword Arguments:
dirs -- Yield intermediate paths.
leaves -- Yield the paths with leaf objects.
path -- A list of keys representing the path.
skip -- Skip special keys beginning with '+'. | [
"Yield",
"all",
"paths",
"of",
"the",
"object",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L61-L108 | train | 210,592 |
akesterson/dpath-python | dpath/path.py | match | def match(path, glob):
"""Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path.
"""
path_len = len(path)
glob_len = len(glob)
ss = -1
ss_glob = glob
if '**' in glob:
ss = glob.index('**')
if '**' in glob[ss + 1:]:
raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.")
if path_len >= glob_len:
# Just right or more stars.
more_stars = ['*'] * (path_len - glob_len + 1)
ss_glob = glob[:ss] + more_stars + glob[ss + 1:]
elif path_len == glob_len - 1:
# Need one less star.
ss_glob = glob[:ss] + glob[ss + 1:]
if path_len == len(ss_glob):
# Python 3 support
if PY3:
return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob))))
else: # Default to Python 2
return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob)))
return False | python | def match(path, glob):
"""Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path.
"""
path_len = len(path)
glob_len = len(glob)
ss = -1
ss_glob = glob
if '**' in glob:
ss = glob.index('**')
if '**' in glob[ss + 1:]:
raise dpath.exceptions.InvalidGlob("Invalid glob. Only one '**' is permitted per glob.")
if path_len >= glob_len:
# Just right or more stars.
more_stars = ['*'] * (path_len - glob_len + 1)
ss_glob = glob[:ss] + more_stars + glob[ss + 1:]
elif path_len == glob_len - 1:
# Need one less star.
ss_glob = glob[:ss] + glob[ss + 1:]
if path_len == len(ss_glob):
# Python 3 support
if PY3:
return all(map(fnmatch.fnmatch, list(map(str, paths_only(path))), list(map(str, ss_glob))))
else: # Default to Python 2
return all(map(fnmatch.fnmatch, map(str, paths_only(path)), map(str, ss_glob)))
return False | [
"def",
"match",
"(",
"path",
",",
"glob",
")",
":",
"path_len",
"=",
"len",
"(",
"path",
")",
"glob_len",
"=",
"len",
"(",
"glob",
")",
"ss",
"=",
"-",
"1",
"ss_glob",
"=",
"glob",
"if",
"'**'",
"in",
"glob",
":",
"ss",
"=",
"glob",
".",
"index... | Match the path with the glob.
Arguments:
path -- A list of keys representing the path.
glob -- A list of globs to match against the path. | [
"Match",
"the",
"path",
"with",
"the",
"glob",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L110-L144 | train | 210,593 |
akesterson/dpath-python | dpath/path.py | set | def set(obj, path, value, create_missing=True, afilter=None):
"""Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then any
missing path components in the dictionary are made silently.
Otherwise, if False, an exception is thrown if path
components are missing.
"""
cur = obj
traversed = []
def _presence_test_dict(obj, elem):
return (elem[0] in obj)
def _create_missing_dict(obj, elem):
obj[elem[0]] = elem[1]()
def _presence_test_list(obj, elem):
return (int(str(elem[0])) < len(obj))
def _create_missing_list(obj, elem):
idx = int(str(elem[0]))
while (len(obj)-1) < idx:
obj.append(None)
def _accessor_dict(obj, elem):
return obj[elem[0]]
def _accessor_list(obj, elem):
return obj[int(str(elem[0]))]
def _assigner_dict(obj, elem, value):
obj[elem[0]] = value
def _assigner_list(obj, elem, value):
obj[int(str(elem[0]))] = value
elem = None
for elem in path:
elem_value = elem[0]
elem_type = elem[1]
tester = None
creator = None
accessor = None
assigner = None
if issubclass(obj.__class__, (MutableMapping)):
tester = _presence_test_dict
creator = _create_missing_dict
accessor = _accessor_dict
assigner = _assigner_dict
elif issubclass(obj.__class__, MutableSequence):
if not str(elem_value).isdigit():
raise TypeError("Can only create integer indexes in lists, "
"not {}, in {}".format(type(obj),
traversed
)
)
tester = _presence_test_list
creator = _create_missing_list
accessor = _accessor_list
assigner = _assigner_list
else:
raise TypeError("Unable to path into elements of type {} "
"at {}".format(obj, traversed))
if (not tester(obj, elem)) and (create_missing):
creator(obj, elem)
elif (not tester(obj, elem)):
raise dpath.exceptions.PathNotFound(
"{} does not exist in {}".format(
elem,
traversed
)
)
traversed.append(elem_value)
if len(traversed) < len(path):
obj = accessor(obj, elem)
if elem is None:
return
if (afilter and afilter(accessor(obj, elem))) or (not afilter):
assigner(obj, elem, value) | python | def set(obj, path, value, create_missing=True, afilter=None):
"""Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then any
missing path components in the dictionary are made silently.
Otherwise, if False, an exception is thrown if path
components are missing.
"""
cur = obj
traversed = []
def _presence_test_dict(obj, elem):
return (elem[0] in obj)
def _create_missing_dict(obj, elem):
obj[elem[0]] = elem[1]()
def _presence_test_list(obj, elem):
return (int(str(elem[0])) < len(obj))
def _create_missing_list(obj, elem):
idx = int(str(elem[0]))
while (len(obj)-1) < idx:
obj.append(None)
def _accessor_dict(obj, elem):
return obj[elem[0]]
def _accessor_list(obj, elem):
return obj[int(str(elem[0]))]
def _assigner_dict(obj, elem, value):
obj[elem[0]] = value
def _assigner_list(obj, elem, value):
obj[int(str(elem[0]))] = value
elem = None
for elem in path:
elem_value = elem[0]
elem_type = elem[1]
tester = None
creator = None
accessor = None
assigner = None
if issubclass(obj.__class__, (MutableMapping)):
tester = _presence_test_dict
creator = _create_missing_dict
accessor = _accessor_dict
assigner = _assigner_dict
elif issubclass(obj.__class__, MutableSequence):
if not str(elem_value).isdigit():
raise TypeError("Can only create integer indexes in lists, "
"not {}, in {}".format(type(obj),
traversed
)
)
tester = _presence_test_list
creator = _create_missing_list
accessor = _accessor_list
assigner = _assigner_list
else:
raise TypeError("Unable to path into elements of type {} "
"at {}".format(obj, traversed))
if (not tester(obj, elem)) and (create_missing):
creator(obj, elem)
elif (not tester(obj, elem)):
raise dpath.exceptions.PathNotFound(
"{} does not exist in {}".format(
elem,
traversed
)
)
traversed.append(elem_value)
if len(traversed) < len(path):
obj = accessor(obj, elem)
if elem is None:
return
if (afilter and afilter(accessor(obj, elem))) or (not afilter):
assigner(obj, elem, value) | [
"def",
"set",
"(",
"obj",
",",
"path",
",",
"value",
",",
"create_missing",
"=",
"True",
",",
"afilter",
"=",
"None",
")",
":",
"cur",
"=",
"obj",
"traversed",
"=",
"[",
"]",
"def",
"_presence_test_dict",
"(",
"obj",
",",
"elem",
")",
":",
"return",
... | Set the value of the given path in the object. Path
must be a list of specific path elements, not a glob.
You can use dpath.util.set for globs, but the paths must
slready exist.
If create_missing is True (the default behavior), then any
missing path components in the dictionary are made silently.
Otherwise, if False, an exception is thrown if path
components are missing. | [
"Set",
"the",
"value",
"of",
"the",
"given",
"path",
"in",
"the",
"object",
".",
"Path",
"must",
"be",
"a",
"list",
"of",
"specific",
"path",
"elements",
"not",
"a",
"glob",
".",
"You",
"can",
"use",
"dpath",
".",
"util",
".",
"set",
"for",
"globs",
... | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L149-L234 | train | 210,594 |
akesterson/dpath-python | dpath/path.py | get | def get(obj, path, view=False, afilter=None):
"""Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object.
"""
index = 0
path_count = len(path) - 1
target = obj
head = type(target)()
tail = head
up = None
for pair in path:
key = pair[0]
target = target[key]
if view:
if isinstance(tail, MutableMapping):
if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count:
tail[key] = pair[1]()
else:
tail[key] = target
up = tail
tail = tail[key]
elif issubclass(tail.__class__, MutableSequence):
if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count:
tail.append(pair[1]())
else:
tail.append(target)
up = tail
tail = tail[-1]
if not issubclass(target.__class__, (MutableSequence, MutableMapping)):
if (afilter and (not afilter(target))):
raise dpath.exceptions.FilteredValue
index += 1
if view:
return head
else:
return target | python | def get(obj, path, view=False, afilter=None):
"""Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object.
"""
index = 0
path_count = len(path) - 1
target = obj
head = type(target)()
tail = head
up = None
for pair in path:
key = pair[0]
target = target[key]
if view:
if isinstance(tail, MutableMapping):
if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count:
tail[key] = pair[1]()
else:
tail[key] = target
up = tail
tail = tail[key]
elif issubclass(tail.__class__, MutableSequence):
if issubclass(pair[1], (MutableSequence, MutableMapping)) and index != path_count:
tail.append(pair[1]())
else:
tail.append(target)
up = tail
tail = tail[-1]
if not issubclass(target.__class__, (MutableSequence, MutableMapping)):
if (afilter and (not afilter(target))):
raise dpath.exceptions.FilteredValue
index += 1
if view:
return head
else:
return target | [
"def",
"get",
"(",
"obj",
",",
"path",
",",
"view",
"=",
"False",
",",
"afilter",
"=",
"None",
")",
":",
"index",
"=",
"0",
"path_count",
"=",
"len",
"(",
"path",
")",
"-",
"1",
"target",
"=",
"obj",
"head",
"=",
"type",
"(",
"target",
")",
"("... | Get the value of the given path.
Arguments:
obj -- Object to look in.
path -- A list of keys representing the path.
Keyword Arguments:
view -- Return a view of the object. | [
"Get",
"the",
"value",
"of",
"the",
"given",
"path",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/path.py#L236-L284 | train | 210,595 |
akesterson/dpath-python | dpath/util.py | delete | def delete(obj, glob, separator="/", afilter=None):
"""
Given a path glob, delete all elements that match the glob.
Returns the number of deleted objects. Raises PathNotFound if no paths are
found to delete.
"""
deleted = 0
paths = []
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
# These are yielded back, don't mess up the dict.
paths.append(path)
for path in paths:
cur = obj
prev = None
for item in path:
prev = cur
try:
cur = cur[item[0]]
except AttributeError as e:
# This only happens when we delete X/Y and the next
# item in the paths is X/Y/Z
pass
if (not afilter) or (afilter and afilter(prev[item[0]])):
prev.pop(item[0])
deleted += 1
if not deleted:
raise dpath.exceptions.PathNotFound("Could not find {0} to delete it".format(glob))
return deleted | python | def delete(obj, glob, separator="/", afilter=None):
"""
Given a path glob, delete all elements that match the glob.
Returns the number of deleted objects. Raises PathNotFound if no paths are
found to delete.
"""
deleted = 0
paths = []
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
# These are yielded back, don't mess up the dict.
paths.append(path)
for path in paths:
cur = obj
prev = None
for item in path:
prev = cur
try:
cur = cur[item[0]]
except AttributeError as e:
# This only happens when we delete X/Y and the next
# item in the paths is X/Y/Z
pass
if (not afilter) or (afilter and afilter(prev[item[0]])):
prev.pop(item[0])
deleted += 1
if not deleted:
raise dpath.exceptions.PathNotFound("Could not find {0} to delete it".format(glob))
return deleted | [
"def",
"delete",
"(",
"obj",
",",
"glob",
",",
"separator",
"=",
"\"/\"",
",",
"afilter",
"=",
"None",
")",
":",
"deleted",
"=",
"0",
"paths",
"=",
"[",
"]",
"globlist",
"=",
"__safe_path__",
"(",
"glob",
",",
"separator",
")",
"for",
"path",
"in",
... | Given a path glob, delete all elements that match the glob.
Returns the number of deleted objects. Raises PathNotFound if no paths are
found to delete. | [
"Given",
"a",
"path",
"glob",
"delete",
"all",
"elements",
"that",
"match",
"the",
"glob",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/util.py#L49-L79 | train | 210,596 |
akesterson/dpath-python | dpath/util.py | set | def set(obj, glob, value, separator="/", afilter=None):
"""
Given a path glob, set all existing elements in the document
to the given value. Returns the number of elements changed.
"""
changed = 0
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
changed += 1
dpath.path.set(obj, path, value, create_missing=False, afilter=afilter)
return changed | python | def set(obj, glob, value, separator="/", afilter=None):
"""
Given a path glob, set all existing elements in the document
to the given value. Returns the number of elements changed.
"""
changed = 0
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator):
changed += 1
dpath.path.set(obj, path, value, create_missing=False, afilter=afilter)
return changed | [
"def",
"set",
"(",
"obj",
",",
"glob",
",",
"value",
",",
"separator",
"=",
"\"/\"",
",",
"afilter",
"=",
"None",
")",
":",
"changed",
"=",
"0",
"globlist",
"=",
"__safe_path__",
"(",
"glob",
",",
"separator",
")",
"for",
"path",
"in",
"_inner_search",... | Given a path glob, set all existing elements in the document
to the given value. Returns the number of elements changed. | [
"Given",
"a",
"path",
"glob",
"set",
"all",
"existing",
"elements",
"in",
"the",
"document",
"to",
"the",
"given",
"value",
".",
"Returns",
"the",
"number",
"of",
"elements",
"changed",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/util.py#L81-L91 | train | 210,597 |
akesterson/dpath-python | dpath/util.py | get | def get(obj, glob, separator="/"):
"""
Given an object which contains only one possible match for the given glob,
return the value for the leaf matching the given glob.
If more than one leaf matches the glob, ValueError is raised. If the glob is
not found, KeyError is raised.
"""
ret = None
found = False
for item in search(obj, glob, yielded=True, separator=separator):
if ret is not None:
raise ValueError("dpath.util.get() globs must match only one leaf : %s" % glob)
ret = item[1]
found = True
if found is False:
raise KeyError(glob)
return ret | python | def get(obj, glob, separator="/"):
"""
Given an object which contains only one possible match for the given glob,
return the value for the leaf matching the given glob.
If more than one leaf matches the glob, ValueError is raised. If the glob is
not found, KeyError is raised.
"""
ret = None
found = False
for item in search(obj, glob, yielded=True, separator=separator):
if ret is not None:
raise ValueError("dpath.util.get() globs must match only one leaf : %s" % glob)
ret = item[1]
found = True
if found is False:
raise KeyError(glob)
return ret | [
"def",
"get",
"(",
"obj",
",",
"glob",
",",
"separator",
"=",
"\"/\"",
")",
":",
"ret",
"=",
"None",
"found",
"=",
"False",
"for",
"item",
"in",
"search",
"(",
"obj",
",",
"glob",
",",
"yielded",
"=",
"True",
",",
"separator",
"=",
"separator",
")"... | Given an object which contains only one possible match for the given glob,
return the value for the leaf matching the given glob.
If more than one leaf matches the glob, ValueError is raised. If the glob is
not found, KeyError is raised. | [
"Given",
"an",
"object",
"which",
"contains",
"only",
"one",
"possible",
"match",
"for",
"the",
"given",
"glob",
"return",
"the",
"value",
"for",
"the",
"leaf",
"matching",
"the",
"given",
"glob",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/util.py#L93-L110 | train | 210,598 |
akesterson/dpath-python | dpath/util.py | search | def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True):
"""
Given a path glob, return a dictionary containing all keys
that matched the given glob.
If 'yielded' is true, then a dictionary will not be returned.
Instead tuples will be yielded in the form of (path, value) for
every element in the document that matched the glob.
"""
def _search_view(obj, glob, separator, afilter, dirs):
view = {}
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator, dirs=dirs):
try:
val = dpath.path.get(obj, path, afilter=afilter, view=True)
merge(view, val)
except dpath.exceptions.FilteredValue:
pass
return view
def _search_yielded(obj, glob, separator, afilter, dirs):
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator, dirs=dirs):
try:
val = dpath.path.get(obj, path, view=False, afilter=afilter)
yield (separator.join(map(str, dpath.path.paths_only(path))), val)
except dpath.exceptions.FilteredValue:
pass
if afilter is not None:
dirs = False
if yielded:
return _search_yielded(obj, glob, separator, afilter, dirs)
return _search_view(obj, glob, separator, afilter, dirs) | python | def search(obj, glob, yielded=False, separator="/", afilter=None, dirs = True):
"""
Given a path glob, return a dictionary containing all keys
that matched the given glob.
If 'yielded' is true, then a dictionary will not be returned.
Instead tuples will be yielded in the form of (path, value) for
every element in the document that matched the glob.
"""
def _search_view(obj, glob, separator, afilter, dirs):
view = {}
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator, dirs=dirs):
try:
val = dpath.path.get(obj, path, afilter=afilter, view=True)
merge(view, val)
except dpath.exceptions.FilteredValue:
pass
return view
def _search_yielded(obj, glob, separator, afilter, dirs):
globlist = __safe_path__(glob, separator)
for path in _inner_search(obj, globlist, separator, dirs=dirs):
try:
val = dpath.path.get(obj, path, view=False, afilter=afilter)
yield (separator.join(map(str, dpath.path.paths_only(path))), val)
except dpath.exceptions.FilteredValue:
pass
if afilter is not None:
dirs = False
if yielded:
return _search_yielded(obj, glob, separator, afilter, dirs)
return _search_view(obj, glob, separator, afilter, dirs) | [
"def",
"search",
"(",
"obj",
",",
"glob",
",",
"yielded",
"=",
"False",
",",
"separator",
"=",
"\"/\"",
",",
"afilter",
"=",
"None",
",",
"dirs",
"=",
"True",
")",
":",
"def",
"_search_view",
"(",
"obj",
",",
"glob",
",",
"separator",
",",
"afilter",... | Given a path glob, return a dictionary containing all keys
that matched the given glob.
If 'yielded' is true, then a dictionary will not be returned.
Instead tuples will be yielded in the form of (path, value) for
every element in the document that matched the glob. | [
"Given",
"a",
"path",
"glob",
"return",
"a",
"dictionary",
"containing",
"all",
"keys",
"that",
"matched",
"the",
"given",
"glob",
"."
] | 2d9117c5fc6870d546aadefb5bf3ab194f4c7411 | https://github.com/akesterson/dpath-python/blob/2d9117c5fc6870d546aadefb5bf3ab194f4c7411/dpath/util.py#L121-L155 | train | 210,599 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.