code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
r
elem = strel.copy()
x_dim, y_dim, z_dim = im.shape
x_min = x-r
x_max = x+r+1
y_min = y-r
y_max = y+r+1
z_min = z-r
z_max = z+r+1
if x_min < 0:
x_adj = -x_min
elem = elem[x_adj:, :, :]
x_min = 0
elif x_max > x_dim:
x_adj = x_max - x_dim
... | def _fit_strel_to_im_3d(im, strel, r, x, y, z) | r"""
Helper function to add a structuring element to a 2D image.
Used by RSA. Makes sure if center is less than r pixels from edge of image
that the strel is sliced to fit. | 1.487343 | 1.434385 | 1.03692 |
r'''
Fill in the edges of the input image.
Used by RSA to ensure that no elements are placed too close to the edge.
'''
edge = sp.ones_like(im)
if len(im.shape) == 2:
sx, sy = im.shape
edge[r:sx-r, r:sy-r] = im[r:sx-r, r:sy-r]
else:
sx, sy, sz = im.shape
edge[... | def _remove_edge(im, r) | r'''
Fill in the edges of the input image.
Used by RSA to ensure that no elements are placed too close to the edge. | 2.965395 | 1.86811 | 1.587377 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
im = sp.copy(im)
if im.ndim == 2:
im = (sp.swapaxes(im, ... | def align_image_with_openpnm(im) | r"""
Rotates an image to agree with the coordinates used in OpenPNM. It is
unclear why they are not in agreement to start with. This is necessary
for overlaying the image and the network in Paraview.
Parameters
----------
im : ND-array
The image to be rotated. Can be the Boolean imag... | 3.741484 | 3.899988 | 0.959358 |
r
def erode(im, strel):
t = fftconvolve(im, strel, mode='same') > (strel.sum() - 0.1)
return t
def dilate(im, strel):
t = fftconvolve(im, strel, mode='same') > 0.1
return t
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' +... | def fftmorphology(im, strel, mode='opening') | r"""
Perform morphological operations on binary images using fft approach for
improved performance
Parameters
----------
im : nd-array
The binary image on which to perform the morphological operation
strel : nd-array
The structuring element to use. Must have the same dims as `... | 2.6736 | 2.681887 | 0.99691 |
r
# Expand scalar divs
if isinstance(divs, int):
divs = [divs for i in range(im.ndim)]
s = shape_split(im.shape, axis=divs)
return s | def subdivide(im, divs=2) | r"""
Returns slices into an image describing the specified number of sub-arrays.
This function is useful for performing operations on smaller images for
memory or speed. Note that for most typical operations this will NOT work,
since the image borders would cause artifacts (e.g. ``distance_transform``... | 8.589875 | 12.124369 | 0.70848 |
r
if len(bbox) == 4:
ret = (slice(bbox[0], bbox[2]),
slice(bbox[1], bbox[3]))
else:
ret = (slice(bbox[0], bbox[3]),
slice(bbox[1], bbox[4]),
slice(bbox[2], bbox[5]))
return ret | def bbox_to_slices(bbox) | r"""
Given a tuple containing bounding box coordinates, return a tuple of slice
objects.
A bounding box in the form of a straight list is returned by several
functions in skimage, but these cannot be used to direct index into an
image. This function returns a tuples of slices can be, such as:
... | 2.110756 | 2.288972 | 0.922142 |
r
p = sp.ones(shape=im.ndim, dtype=int) * sp.array(pad)
s = sp.ones(shape=im.ndim, dtype=int) * sp.array(size)
slc = []
for dim in range(im.ndim):
lower_im = sp.amax((center[dim] - s[dim] - p[dim], 0))
upper_im = sp.amin((center[dim] + s[dim] + 1 + p[dim], im.shape[dim]))
slc... | def get_slice(im, center, size, pad=0) | r"""
Given a ``center`` location and ``radius`` of a feature, returns the slice
object into the ``im`` that bounds the feature but does not extend beyond
the image boundaries.
Parameters
----------
im : ND-image
The image of the porous media
center : array_like
The coordina... | 2.636213 | 2.90515 | 0.907428 |
r
if r == 0:
dt = spim.distance_transform_edt(input=im)
r = int(sp.amax(dt)) * 2
im_padded = sp.pad(array=im, pad_width=r, mode='constant',
constant_values=True)
dt = spim.distance_transform_edt(input=im_padded)
seeds = (dt >= r) + get_border(shape=im_padded.sh... | def find_outer_region(im, r=0) | r"""
Finds regions of the image that are outside of the solid matrix.
This function uses the rolling ball method to define where the outer region
ends and the void space begins.
This function is particularly useful for samples that do not fill the
entire rectangular image, such as cylindrical core... | 4.932724 | 4.950382 | 0.996433 |
r
if r is None:
a = list(im.shape)
a.pop(axis)
r = sp.floor(sp.amin(a) / 2)
dim = [range(int(-s / 2), int(s / 2) + s % 2) for s in im.shape]
inds = sp.meshgrid(*dim, indexing='ij')
inds[axis] = inds[axis] * 0
d = sp.sqrt(sp.sum(sp.square(inds), axis=0))
mask = d < r
... | def extract_cylinder(im, r=None, axis=0) | r"""
Returns a cylindrical section of the image of specified radius.
This is useful for making square images look like cylindrical cores such
as those obtained from X-ray tomography.
Parameters
----------
im : ND-array
The image of the porous material. Can be any data type.
r : s... | 3.77168 | 3.89712 | 0.967812 |
r
# Check if shape was given as a fraction
shape = sp.array(shape)
if shape[0] < 1:
shape = sp.array(im.shape) * shape
center = sp.array(im.shape) / 2
s_im = []
for dim in range(im.ndim):
r = shape[dim] / 2
lower_im = sp.amax((center[dim] - r, 0))
upper_im = s... | def extract_subsection(im, shape) | r"""
Extracts the middle section of a image
Parameters
----------
im : ND-array
Image from which to extract the subsection
shape : array_like
Can either specify the size of the extracted section or the fractional
size of the image to extact.
Returns
-------
ima... | 2.924827 | 3.075852 | 0.9509 |
r
x, y, z = (sp.array(im.shape) / 2).astype(int)
planes = [im[x, :, :], im[:, y, :], im[:, :, z]]
if not squeeze:
imx = planes[0]
planes[0] = sp.reshape(imx, [1, imx.shape[0], imx.shape[1]])
imy = planes[1]
planes[1] = sp.reshape(imy, [imy.shape[0], 1, imy.shape[1]])
... | def get_planes(im, squeeze=True) | r"""
Extracts three planar images from the volumetric image, one for each
principle axis. The planes are taken from the middle of the domain.
Parameters
----------
im : ND-array
The volumetric image from which the 3 planar images are to be obtained
squeeze : boolean, optional
... | 1.892924 | 2.029765 | 0.932583 |
r
pad = int(pad)
a = []
for i, dim in zip(s, shape):
start = 0
stop = dim
if i.start - pad >= 0:
start = i.start - pad
if i.stop + pad < dim:
stop = i.stop + pad
a.append(slice(start, stop, None))
return tuple(a) | def extend_slice(s, shape, pad=1) | r"""
Adjust slice indices to include additional voxles around the slice.
This function does bounds checking to ensure the indices don't extend
outside the image.
Parameters
----------
s : list of slice objects
A list (or tuple) of N slice objects, where N is the number of
dim... | 2.694649 | 3.490949 | 0.771896 |
r
im = sp.copy(im)
if keep_zeros:
mask = (im == 0)
im[mask] = im.min() - 1
im = im - im.min()
im_flat = im.flatten()
im_vals = sp.unique(im_flat)
im_map = sp.zeros(shape=sp.amax(im_flat) + 1)
im_map[im_vals] = sp.arange(0, sp.size(sp.unique(im_flat)))
im_new = im_map[... | def make_contiguous(im, keep_zeros=True) | r"""
Take an image with arbitrary greyscale values and adjust them to ensure
all values fall in a contiguous range starting at 0.
This function will handle negative numbers such that most negative number
will become 0, *unless* ``keep_zeros`` is ``True`` in which case it will
become 1, and all 0's ... | 2.493434 | 2.925436 | 0.852329 |
r
ndims = len(shape)
t = thickness
border = sp.ones(shape, dtype=bool)
if mode == 'faces':
if ndims == 2:
border[t:-t, t:-t] = False
if ndims == 3:
border[t:-t, t:-t, t:-t] = False
elif mode == 'edges':
if ndims == 2:
border[t:-t, t:-t]... | def get_border(shape, thickness=1, mode='edges', return_indices=False) | r"""
Creates an array of specified size with corners, edges or faces labelled as
True. This can be used as mask to manipulate values laying on the
perimeter of an image.
Parameters
----------
shape : array_like
The shape of the array to return. Can be either 2D or 3D.
thickness : ... | 1.625586 | 1.742179 | 0.933077 |
from scipy.spatial import Delaunay, ConvexHull
if isinstance(hull, ConvexHull):
hull = hull.points
hull = Delaunay(hull)
return hull.find_simplex(points) >= 0 | def in_hull(points, hull) | Test if a list of coordinates are inside a given convex hull
Parameters
----------
points : array_like (N x ndims)
The spatial coordinates of the points to check
hull : scipy.spatial.ConvexHull object **OR** array_like
Can be either a convex hull object as returned by
``scipy.s... | 2.066545 | 2.648057 | 0.7804 |
r
if scale is None:
scale = [im.min(), im.max()]
im = (im - sp.mean(im)) / sp.std(im)
im = 1 / 2 * sp.special.erfc(-im / sp.sqrt(2))
im = (im - im.min()) / (im.max() - im.min())
im = im * (scale[1] - scale[0]) + scale[0]
return im | def norm_to_uniform(im, scale=None) | r"""
Take an image with normally distributed greyscale values and converts it to
a uniform (i.e. flat) distribution. It's also possible to specify the
lower and upper limits of the uniform distribution.
Parameters
----------
im : ND-image
The image containing the normally distributed s... | 2.651742 | 2.949622 | 0.899011 |
r
temp = mod.__dir__()
funcs = [i for i in temp if not i[0].startswith('_')]
funcs.sort()
row = '+' + '-'*colwidth[0] + '+' + '-'*colwidth[1] + '+'
fmt = '{0:1s} {1:' + str(colwidth[0]-2) + 's} {2:1s} {3:' \
+ str(colwidth[1]-2) + 's} {4:1s}'
lines = []
lines.append(row)
li... | def functions_to_table(mod, colwidth=[27, 48]) | r"""
Given a module of functions, returns a ReST formatted text string that
outputs a table when printed.
Parameters
----------
mod : module
The module containing the functions to be included in the table, such
as 'porespy.filters'.
colwidths : list of ints
The width of... | 2.535796 | 2.507451 | 1.011304 |
r
im = region
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
if strel is None:
if region.ndim == 3:
... | def mesh_region(region: bool, strel=None) | r"""
Creates a tri-mesh of the provided region using the marching cubes
algorithm
Parameters
----------
im : ND-array
A boolean image with ``True`` values indicating the region of interest
strel : ND-array
The structuring element to use when blurring the region. The blur is
... | 3.207792 | 2.988902 | 1.073234 |
r
rad = int(sp.ceil(radius))
other = sp.ones((2 * rad + 1, 2 * rad + 1), dtype=bool)
other[rad, rad] = False
disk = spim.distance_transform_edt(other) < radius
return disk | def ps_disk(radius) | r"""
Creates circular disk structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 2D-array
A 2D numpy bool array of the structring element | 4.946869 | 5.50753 | 0.898201 |
r
rad = int(sp.ceil(radius))
other = sp.ones((2 * rad + 1, 2 * rad + 1, 2 * rad + 1), dtype=bool)
other[rad, rad, rad] = False
ball = spim.distance_transform_edt(other) < radius
return ball | def ps_ball(radius) | r"""
Creates spherical ball structuring element for morphological operations
Parameters
----------
radius : float or int
The desired radius of the structuring element
Returns
-------
strel : 3D-array
A 3D numpy array of the structuring element | 4.341214 | 4.47913 | 0.969209 |
r
shape = im2.shape
for ni in shape:
if ni % 2 == 0:
raise Exception("Structuring element must be odd-voxeled...")
nx, ny, nz = [(ni - 1) // 2 for ni in shape]
cx, cy, cz = c
im1[cx-nx:cx+nx+1, cy-ny:cy+ny+1, cz-nz:cz+nz+1] += im2
return im1 | def overlay(im1, im2, c) | r"""
Overlays ``im2`` onto ``im1``, given voxel coords of center of ``im2``
in ``im1``.
Parameters
----------
im1 : ND-array
Original voxelated image
im2 : ND-array
Template voxelated image
c : array_like
[x, y, z] coordinates in ``im1`` where ``im2`` will be centere... | 4.500708 | 4.6383 | 0.970336 |
r
c = sp.array(c, dtype=int)
if c.size != im.ndim:
raise Exception('Coordinates do not match dimensionality of image')
bbox = []
[bbox.append(sp.clip(c[i] - r, 0, im.shape[i])) for i in range(im.ndim)]
[bbox.append(sp.clip(c[i] + r, 0, im.shape[i])) for i in range(im.ndim)]
bbox = s... | def insert_sphere(im, c, r) | r"""
Inserts a sphere of a specified radius into a given image
Parameters
----------
im : array_like
Image into which the sphere should be inserted
c : array_like
The [x, y, z] coordinate indicating the center of the sphere
r : int
The radius of sphere to insert
Ret... | 3.307784 | 3.449698 | 0.958862 |
r
if im.ndim != 3:
raise Exception('This function is only implemented for 3D images')
# Converting coordinates to numpy array
xyz0, xyz1 = [sp.array(xyz).astype(int) for xyz in (xyz0, xyz1)]
r = int(r)
L = sp.absolute(xyz0 - xyz1).max() + 1
xyz_line = [sp.linspace(xyz0[i], xyz1[i], L... | def insert_cylinder(im, xyz0, xyz1, r) | r"""
Inserts a cylinder of given radius onto a given image
Parameters
----------
im : array_like
Original voxelated image
xyz0, xyz1 : 3-by-1 array_like
Voxel coordinates of the two end points of the cylinder
r : int
Radius of the cylinder
Returns
-------
im... | 2.687209 | 2.617791 | 1.026518 |
r
if im.ndim != im.squeeze().ndim:
warnings.warn('Input image conains a singleton axis:' + str(im.shape) +
' Reduce dimensionality with np.squeeze(im) to avoid' +
' unexpected behavior.')
f = faces
if f is not None:
if im.ndim == 2:
... | def pad_faces(im, faces) | r"""
Pads the input image at specified faces. This shape of image is
same as the output image of add_boundary_regions function.
Parameters
----------
im : ND_array
The image that needs to be padded
faces : list of strings
Labels indicating where image needs to be padded. Given ... | 2.875158 | 2.992656 | 0.960738 |
r
# -------------------------------------------------------------------------
# Get alias if provided by user
phases_num = sp.unique(im * 1)
phases_num = sp.trim_zeros(phases_num)
al = {}
for values in phases_num:
al[values] = 'phase{}'.format(values)
if alias is not None:
... | def _create_alias_map(im, alias=None) | r"""
Creates an alias mapping between phases in original image and identifyable
names. This mapping is used during network extraction to label
interconnection between and properties of each phase.
Parameters
----------
im : ND-array
Image of porous material where each phase is represent... | 6.830304 | 5.79519 | 1.178616 |
if hosts_entry and isinstance(hosts_entry, str):
entry = hosts_entry.strip()
if not entry or not entry[0] or entry[0] == "\n":
return 'blank'
if entry[0] == "#":
return 'comment'
entry_chunks = entry.split()
if ... | def get_entry_type(hosts_entry=None) | Return the type of entry for the line of hosts file passed
:param hosts_entry: A line from the hosts file
:return: 'comment' | 'blank' | 'ipv4' | 'ipv6' | 2.515836 | 2.392822 | 1.05141 |
line_parts = entry.strip().split()
if is_ipv4(line_parts[0]) and valid_hostnames(line_parts[1:]):
return HostsEntry(entry_type='ipv4',
address=line_parts[0],
names=line_parts[1:])
elif is_ipv6(line_parts[0]) and val... | def str_to_hostentry(entry) | Transform a line from a hosts file into an instance of HostsEntry
:param entry: A line from the hosts file
:return: An instance of HostsEntry | 2.210713 | 2.097427 | 1.054012 |
if not platform:
platform = sys.platform
if platform.startswith('win'):
result = r"c:\windows\system32\drivers\etc\hosts"
return result
else:
return '/etc/hosts' | def determine_hosts_path(platform=None) | Return the hosts file path based on the supplied
or detected platform.
:param platform: a string used to identify the platform
:return: detected filesystem path of the hosts file | 3.043882 | 3.29111 | 0.92488 |
written_count = 0
comments_written = 0
blanks_written = 0
ipv4_entries_written = 0
ipv6_entries_written = 0
if path:
output_file_path = path
else:
output_file_path = self.hosts_path
try:
with open(output_file_pa... | def write(self, path=None) | Write all of the HostsEntry instances back to the hosts file
:param path: override the write path
:return: Dictionary containing counts | 1.977646 | 1.87665 | 1.053817 |
for entry in self.entries:
if entry.entry_type in ('ipv4', 'ipv6'):
if address and address == entry.address:
return True
if names:
for name in names:
if name in entry.names:
... | def exists(self, address=None, names=None, comment=None) | Determine if the supplied address and/or names, or comment, exists in a HostsEntry within Hosts
:param address: An ipv4 or ipv6 address to search for
:param names: A list of names to search for
:param comment: A comment to search for
:return: True if a supplied address, name, or comment ... | 2.470503 | 2.446151 | 1.009955 |
if self.entries:
if address and name:
func = lambda entry: not entry.is_real_entry() or (entry.address != address and name not in entry.names)
elif address:
func = lambda entry: not entry.is_real_entry() or entry.address != address
eli... | def remove_all_matching(self, address=None, name=None) | Remove all HostsEntry instances from the Hosts object
where the supplied ip address or name matches
:param address: An ipv4 or ipv6 address
:param name: A host name
:return: None | 2.484693 | 2.554989 | 0.972487 |
file_contents = self.get_hosts_by_url(url=url).decode('utf-8')
file_contents = file_contents.rstrip().replace('^M', '\n')
file_contents = file_contents.rstrip().replace('\r\n', '\n')
lines = file_contents.split('\n')
skipped = 0
import_entries = []
for li... | def import_url(self, url=None, force=None) | Read a list of host entries from a URL, convert them into instances of HostsEntry and
then append to the list of entries in Hosts
:param url: The URL of where to download a hosts file
:return: Counts reflecting the attempted additions | 2.792755 | 2.548225 | 1.095961 |
skipped = 0
invalid_count = 0
if is_readable(import_file_path):
import_entries = []
with open(import_file_path, 'r') as infile:
for line in infile:
stripped_entry = line.strip()
if (not stripped_entry) or (s... | def import_file(self, import_file_path=None) | Read a list of host entries from a file, convert them into instances
of HostsEntry and then append to the list of entries in Hosts
:param import_file_path: The path to the file containing the host entries
:return: Counts reflecting the attempted additions | 2.621667 | 2.405975 | 1.089648 |
ipv4_count = 0
ipv6_count = 0
comment_count = 0
invalid_count = 0
duplicate_count = 0
replaced_count = 0
import_entries = []
existing_addresses = [x.address for x in self.entries if x.address]
existing_names = []
for item in self.e... | def add(self, entries=None, force=False, allow_address_duplication=False) | Add instances of HostsEntry to the instance of Hosts.
:param entries: A list of instances of HostsEntry
:param force: Remove matching before adding
:param allow_address_duplication: Allow using multiple entries for same address
:return: The counts of successes and failures | 1.962433 | 1.936411 | 1.013438 |
try:
with open(self.hosts_path, 'r') as hosts_file:
hosts_entries = [line for line in hosts_file]
for hosts_entry in hosts_entries:
entry_type = HostsEntry.get_entry_type(hosts_entry)
if entry_type == "comment":
... | def populate_entries(self) | Called by the initialiser of Hosts. This reads the entries from the local hosts file,
converts them into instances of HostsEntry and adds them to the Hosts list of entries.
:return: None | 2.457922 | 2.38126 | 1.032194 |
try:
if socket.inet_pton(socket.AF_INET6, entry):
return True
except socket.error:
return False | def is_ipv6(entry) | Check if the string provided is a valid ipv6 address
:param entry: A string representation of an IP address
:return: True if valid, False if invalid | 2.353022 | 2.509048 | 0.937815 |
for entry in hostname_list:
if len(entry) > 255:
return False
allowed = re.compile('(?!-)[A-Z\d-]{1,63}(?<!-)$', re.IGNORECASE)
if not all(allowed.match(x) for x in entry.split(".")):
return False
return True | def valid_hostnames(hostname_list) | Check if the supplied list of strings are valid hostnames
:param hostname_list: A list of strings
:return: True if the strings are valid hostnames, False if not | 1.767279 | 1.830593 | 0.965413 |
if os.path.isfile(path) and os.access(path, os.R_OK):
return True
return False | def is_readable(path=None) | Test if the supplied filesystem path can be read
:param path: A filesystem path
:return: True if the path is a file that can be read. Otherwise, False | 2.511409 | 3.563263 | 0.704806 |
seen = set()
return [x for x in seq if not (x in seen or seen.add(x))] | def dedupe_list(seq) | Utility function to remove duplicates from a list
:param seq: The sequence (list) to deduplicate
:return: A list with original duplicates removed | 2.209254 | 3.035071 | 0.727909 |
sha = hashlib.sha256()
with open(filepath, 'rb') as fp:
while 1:
data = fp.read(blocksize)
if data:
sha.update(data)
else:
break
return sha | def _filehash(filepath, blocksize=4096) | Return the hash object for the file `filepath', processing the file
by chunk of `blocksize'.
:type filepath: str
:param filepath: Path to file
:type blocksize: int
:param blocksize: Size of the chunk when processing the file | 1.916465 | 2.215985 | 0.864837 |
data = {}
data['deleted'] = list(set(dir_cmp['files']) - set(dir_base['files']))
data['created'] = list(set(dir_base['files']) - set(dir_cmp['files']))
data['updated'] = []
data['deleted_dirs'] = list(set(dir_cmp['subdirs']) - set(dir_base['subdirs']))
for f in set(dir_cmp['files']).inters... | def compute_diff(dir_base, dir_cmp) | Compare `dir_base' and `dir_cmp' and returns a list with
the following keys:
- deleted files `deleted'
- created files `created'
- updated files `updated'
- deleted directories `deleted_dirs' | 2.112083 | 2.010282 | 1.05064 |
if archive_path is None:
archive = tempfile.NamedTemporaryFile(delete=False)
tar_args = ()
tar_kwargs = {'fileobj': archive}
_return = archive.name
else:
tar_args = (archive_path)
tar_kwargs = {}
_return = archi... | def compress_to(self, archive_path=None) | Compress the directory with gzip using tarlib.
:type archive_path: str
:param archive_path: Path to the archive, if None, a tempfile is created | 2.716097 | 2.706393 | 1.003586 |
# TODO alternative to filehash => mtime as a faster alternative
shadir = hashlib.sha256()
for f in self.files():
try:
shadir.update(str(index_func(os.path.join(self.path, f))))
except (IOError, OSError):
pass
return shadir.... | def hash(self, index_func=os.path.getmtime) | Hash for the entire directory (except excluded files) recursively.
Use mtime instead of sha256 by default for a faster hash.
>>> dir.hash(index_func=dirtools.filehash) | 5.371937 | 4.849203 | 1.107798 |
if pattern is not None:
globster = Globster([pattern])
for root, dirs, files in self.walk():
for f in files:
if pattern is None or (pattern is not None and globster.match(f)):
if abspath:
yield os.path.join(root... | def iterfiles(self, pattern=None, abspath=False) | Generator for all the files not excluded recursively.
Return relative path.
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern | 2.484056 | 3.100078 | 0.801288 |
return sorted(self.iterfiles(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse) | def files(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False) | Return a sorted list containing relative path of all files (recursively).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
:param sort_key: key argument for sorted
:param sort_reverse: reverse argument for sorted
:rtype: list
:return: L... | 3.089569 | 4.168935 | 0.741093 |
if pattern is not None:
globster = Globster([pattern])
for root, dirs, files in self.walk():
for d in dirs:
if pattern is None or (pattern is not None and globster.match(d)):
if abspath:
yield os.path.join(root,... | def itersubdirs(self, pattern=None, abspath=False) | Generator for all subdirs (except excluded).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern | 2.564496 | 3.107946 | 0.825142 |
return sorted(self.itersubdirs(pattern, abspath=abspath), key=sort_key, reverse=sort_reverse) | def subdirs(self, pattern=None, sort_key=lambda k: k, sort_reverse=False, abspath=False) | Return a sorted list containing relative path of all subdirs (recursively).
:type pattern: str
:param pattern: Unix style (glob like/gitignore like) pattern
:param sort_key: key argument for sorted
:param sort_reverse: reverse argument for sorted
:rtype: list
:return:... | 3.524673 | 4.428846 | 0.795844 |
dir_size = 0
for f in self.iterfiles(abspath=True):
dir_size += os.path.getsize(f)
return dir_size | def size(self) | Return directory size in bytes.
:rtype: int
:return: Total directory size in bytes. | 4.25145 | 4.220238 | 1.007396 |
match = self.globster.match(self.relpath(path))
if match:
log.debug("{0} matched {1} for exclusion".format(path, match))
return True
return False | def is_excluded(self, path) | Return True if `path' should be excluded
given patterns in the `exclude_file'. | 5.189888 | 4.954308 | 1.047551 |
projects = []
for d in self.subdirs():
project_file = os.path.join(self.directory, d, file_identifier)
if os.path.isfile(project_file):
projects.append(d)
return projects | def find_projects(self, file_identifier=".project") | Search all directory recursively for subdirs
with `file_identifier' in it.
:type file_identifier: str
:param file_identifier: File identier, .project by default.
:rtype: list
:return: The list of subdirs with a `file_identifier' in it. | 2.589478 | 3.109457 | 0.832775 |
return os.path.relpath(path, start=self.path) | def relpath(self, path) | Return a relative filepath to path from Dir path. | 4.174272 | 3.20276 | 1.303336 |
data = {}
data['directory'] = self._dir.path
data['files'] = list(self._dir.files())
data['subdirs'] = list(self._dir.subdirs())
data['index'] = self.index()
return data | def compute_state(self) | Generate the index. | 4.082477 | 3.633605 | 1.123533 |
exitcode = 0
running = []
progress = {}
def progress_cb(report):
pid, count, success, *_, stats = report
print('\x1b[%sA' % (1+len(running)))
if pid not in progress:
running.append(pid)
progress[pid] = count, success
for pid in running:
... | def run(pipeline_id, verbose, use_cache, dirty, force, concurrency, slave) | Run a pipeline by pipeline-id.
pipeline-id supports '%' wildcard for any-suffix matching,
'all' for running all pipelines and
comma-delimited list of pipeline ids | 2.848778 | 2.896526 | 0.983515 |
@wraps(view_func)
def wrapper(*args, **kwargs):
if app.config.get('BASIC_AUTH_ACTIVE', False):
if basic_auth.authenticate():
return view_func(*args, **kwargs)
else:
return basic_auth.challenge()
else:
return view_func(*args... | def basic_auth_required(view_func) | A decorator that can be used to protect specific views with HTTP basic
access authentication. Conditional on having BASIC_AUTH_USERNAME and
BASIC_AUTH_PASSWORD set as env vars. | 1.935249 | 1.964154 | 0.985284 |
'''An individual pipeline status'''
if not pipeline_id.startswith('./'):
pipeline_id = './' + pipeline_id
pipeline_status = status.get(pipeline_id)
status_color = 'lightgray'
if pipeline_status.pipeline_details:
status_text = pipeline_status.state().lower()
last_execution = ... | def badge(pipeline_id) | An individual pipeline status | 3.664458 | 3.65842 | 1.00165 |
'''Status badge for a collection of pipelines.'''
all_pipeline_ids = sorted(status.all_pipeline_ids())
if not pipeline_path.startswith('./'):
pipeline_path = './' + pipeline_path
# Filter pipeline ids to only include those that start with pipeline_path.
path_pipeline_ids = \
[p for... | def badge_collection(pipeline_path) | Status badge for a collection of pipelines. | 2.67312 | 2.649379 | 1.008961 |
with concurrent.futures.ThreadPoolExecutor(max_workers=concurrency,
thread_name_prefix='T') as executor:
try:
results = []
pending_futures = set()
done_futures = set()
finished_futures = []
progre... | def run_pipelines(pipeline_id_pattern,
root_dir,
use_cache=True,
dirty=False,
force=False,
concurrency=1,
verbose_logs=True,
progress_cb=None,
slave=False) | Run a pipeline by pipeline-id.
pipeline-id supports the '%' wildcard for any-suffix matching.
Use 'all' or '%' for running all pipelines | 2.964543 | 3.012438 | 0.984101 |
if key in self.map:
return
# compute the right index
size = len(self.items)
if index < 0:
index = size + index if size + index > 0 else 0
else:
index = index if index < size else size
# insert the value
self.items.insert(index, key)
for k, v in self.map.items... | def insert(self, index, key) | Adds an element at a dedicated position in an OrderedSet.
This implementation is meant for the OrderedSet from the ordered_set
package only. | 2.802553 | 2.773077 | 1.010629 |
if not self.items:
raise KeyError('Set is empty')
def remove_index(i):
elem = self.items[i]
del self.items[i]
del self.map[elem]
return elem
if index is None:
elem = remove_index(-1)
else:
size = len(self.items)
if index < 0:
... | def pop(self, index=None) | Removes an element at the tail of the OrderedSet or at a dedicated
position.
This implementation is meant for the OrderedSet from the ordered_set
package only. | 2.756614 | 2.579231 | 1.068774 |
if isinstance(uri, str):
uri = URI(uri)
try:
resource = self.resource_factory[uri.extension](uri)
except KeyError:
resource = self.resource_factory['*'](uri)
self.resources[uri.normalize()] = resource
resource.resource_set = self
... | def create_resource(self, uri) | Creates a new Resource.
The created ressource type depends on the used URI.
:param uri: the resource URI
:type uri: URI
:return: a new Resource
:rtype: Resource
.. seealso:: URI, Resource, XMIResource | 3.841715 | 4.096101 | 0.937896 |
superclass = cls.__bases__
if not issubclass(cls, EObject):
sclasslist = list(superclass)
if object in superclass:
index = sclasslist.index(object)
sclasslist.insert(index, EObject)
sclasslist.remove(object)
else:
sclasslist.insert(0, ... | def EMetaclass(cls) | Class decorator for creating PyEcore metaclass. | 2.095057 | 2.055397 | 1.019296 |
for annotation in self.eAnnotations:
if annotation.source == source:
return annotation
return None | def getEAnnotation(self, source) | Return the annotation with a matching source attribute. | 3.422228 | 2.771515 | 1.234786 |
if day < 1:
day = 1
date = datetime(year=date.year, month=date.month, day=day, tzinfo=utc)
return reverse('calendar_week', kwargs={'year': date.isocalendar()[0],
'week': date.isocalendar()[1]}) | def get_week_URL(date, day=0) | Returns the week view URL for a given date.
:param date: A date instance.
:param day: Day number in a month. | 2.863419 | 3.167993 | 0.903859 |
str_time = time.strptime('{0} {1} 1'.format(year, week), '%Y %W %w')
date = timezone.datetime(year=str_time.tm_year, month=str_time.tm_mon,
day=str_time.tm_mday, tzinfo=timezone.utc)
if timezone.datetime(year, 1, 4).isoweekday() > 4:
# ISO 8601 where week 1 is the f... | def monday_of_week(year, week) | Returns a datetime for the monday of the given week of the given year. | 2.919583 | 2.778164 | 1.050904 |
return self.lookup.pop(
(occ.event, occ.original_start, occ.original_end),
occ) | def get_occurrence(self, occ) | Return a persisted occurrences matching the occ and remove it from
lookup since it has already been matched | 10.712315 | 6.73102 | 1.591485 |
return [occ for key, occ in self.lookup.items() if (
(end and occ.start < end) and
occ.end >= start and not occ.cancelled)] | def get_additional_occurrences(self, start, end) | Return persisted occurrences which are now in the period | 9.274688 | 8.409698 | 1.102856 |
# make up to three attempts to dance with the API, use a jittered
# exponential back-off delay
for i in range(3):
try:
full_url = '{b}{u}'.format(b=self.api_url, u=uri)
response = None
if method == 'POST':
... | def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None) | Robustness wrapper. Tries up to 3 times to dance with the Sandbox API.
:type uri: str
:param uri: URI to append to base_url.
:type params: dict
:param params: Optional parameters for API.
:type files: dict
:param files: Optional dictionary of files for m... | 3.602015 | 3.423135 | 1.052256 |
response = self._request("tasks/list")
return json.loads(response.content.decode('utf-8'))['tasks'] | def analyses(self) | Retrieve a list of analyzed samples.
:rtype: list
:return: List of objects referencing each analyzed file. | 7.724145 | 9.070184 | 0.851597 |
# multipart post files.
files = {"file": (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
response = self._request("tasks/create/file", method='POST', files=files)
# return task id; try v1.3 and v2.0 API response formats
try:
... | def analyze(self, handle, filename) | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string | 5.274661 | 6.054318 | 0.871223 |
response = self._request("tasks/view/{id}".format(id=item_id))
if response.status_code == 404:
# probably an unknown task id
return False
try:
content = json.loads(response.content.decode('utf-8'))
status = content['task']["status"]
... | def check(self, item_id) | Check if an analysis is complete
:type item_id: int
:param item_id: task_id to check.
:rtype: bool
:return: Boolean indicating if a report is done or not. | 4.45198 | 4.422399 | 1.006689 |
try:
response = self._request("tasks/delete/{id}".format(id=item_id))
if response.status_code == 200:
return True
except sandboxapi.SandboxError:
pass
return False | def delete(self, item_id) | Delete the reports associated with the given item_id.
:type item_id: int
:param item_id: Report ID to delete.
:rtype: bool
:return: True on success, False otherwise. | 5.198609 | 5.379163 | 0.966435 |
# if the availability flag is raised, return True immediately.
# NOTE: subsequent API failures will lower this flag. we do this here
# to ensure we don't keep hitting Cuckoo with requests while
# availability is there.
if self.server_available:
return True
... | def is_available(self) | Determine if the Cuckoo Sandbox API servers are alive or in maintenance mode.
:rtype: bool
:return: True if service is available, False otherwise. | 8.351388 | 7.638336 | 1.093352 |
response = self._request("tasks/list")
tasks = json.loads(response.content.decode('utf-8'))["tasks"]
return len([t for t in tasks if t['status'] == 'pending']) | def queue_size(self) | Determine Cuckoo sandbox queue length
There isn't a built in way to do this like with Joe
:rtype: int
:return: Number of submissions in sandbox queue. | 4.754285 | 4.940178 | 0.962371 |
report_format = report_format.lower()
response = self._request("tasks/report/{id}/{format}".format(id=item_id, format=report_format))
# if response is JSON, return it as an object
if report_format == "json":
try:
return json.loads(response.content.d... | def report(self, item_id, report_format="json") | Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json, html, all, dropped, package_files.
:type item_id: int
:param item_id: Task ID number
:type report_format: str
:param report_format: Return format
... | 2.952808 | 3.664842 | 0.805712 |
score = 0
try:
# cuckoo-modified format
score = report['malscore']
except KeyError:
# cuckoo-2.0 format
score = report.get('info', {}).get('score', 0)
return score | def score(self, report) | Pass in the report from self.report(), get back an int. | 7.133331 | 6.700836 | 1.064543 |
if params:
params['environment_id'] = self.env_id
else:
params = {
'environment_id': self.env_id,
}
if headers:
headers['api-key'] = self.key
headers['User-Agent'] = 'Falcon Sandbox'
headers['Accept... | def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None) | Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps. | 2.380741 | 2.305008 | 1.032856 |
# multipart post files.
files = {"file" : (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
response = self._request("/submit/file", method='POST', files=files)
try:
if response.status_code == 201:
# good respon... | def analyze(self, handle, filename) | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File hash as a string | 4.494201 | 5.040288 | 0.891656 |
report_format = report_format.lower()
response = self._request("/report/{job_id}/summary".format(job_id=item_id))
if response.status_code == 429:
raise sandboxapi.SandboxError('API rate limit exceeded while fetching report')
# if response is JSON, return it as an ... | def report(self, item_id, report_format="json") | Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json, html.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: D... | 3.544217 | 4.168504 | 0.850237 |
try:
threatlevel = int(report['threat_level'])
threatscore = int(report['threat_score'])
except (KeyError, IndexError, ValueError, TypeError) as e:
raise sandboxapi.SandboxError(e)
# from falcon docs:
# threatlevel is the verdict field with ... | def score(self, report) | Pass in the report from self.report(), get back an int 0-10. | 3.883609 | 3.810736 | 1.019123 |
# multipart post files.
files = {"sample_file": (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
response = self._request("/sample/submit", method='POST', files=files, headers=self.headers)
try:
if response.status_code == 200 ... | def analyze(self, handle, filename) | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File ID as a string | 4.736 | 5.325421 | 0.889319 |
response = self._request("/submission/sample/{sample_id}".format(sample_id=item_id), headers=self.headers)
if response.status_code == 404:
# unknown id
return False
try:
finished = False
for submission in response.json()['data']:
... | def check(self, item_id) | Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not. | 4.579677 | 4.896771 | 0.935244 |
if report_format == "html":
return "Report Unavailable"
# grab an analysis id from the submission id.
response = self._request("/analysis/sample/{sample_id}".format(sample_id=item_id),
headers=self.headers)
try:
# the highest score is pr... | def report(self, item_id, report_format="json") | Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dic... | 5.389826 | 5.647145 | 0.954434 |
if headers:
headers['Accept'] = 'application/json'
else:
headers = {
'Accept': 'application/json',
}
if not self.api_token:
# need to log in
response = sandboxapi.SandboxAPI._request(self, '/auth/login', 'POST'... | def _request(self, uri, method='GET', params=None, files=None, headers=None, auth=None) | Override the parent _request method.
We have to do this here because FireEye requires some extra
authentication steps. On each request we pass the auth headers, and
if the session has expired, we automatically reauthenticate. | 3.004364 | 2.910311 | 1.032317 |
# multipart post files.
files = {"file": (filename, handle)}
# ensure the handle is at offset 0.
handle.seek(0)
# add submission options
data = {
#FIXME: These may need to change, see docs page 36
'options': '{"application":"0","timeout"... | def analyze(self, handle, filename) | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: File ID as a string | 6.066097 | 6.387113 | 0.94974 |
response = self._request("/submissions/status/{file_id}".format(file_id=item_id))
if response.status_code == 404:
# unknown id
return False
try:
status = response.json()['submissionStatus']
if status == 'Done':
return Tru... | def check(self, item_id) | Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not. | 5.00181 | 5.046407 | 0.991162 |
if report_format == "html":
return "Report Unavailable"
# else we try JSON
response = self._request("/submissions/results/{file_id}?info_level=extended".format(file_id=item_id))
# if response is JSON, return it as an object
try:
return response.... | def report(self, item_id, report_format="json") | Retrieves the specified report for the analyzed item, referenced by item_id.
Available formats include: json.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
:rtype: dict
:return: Dic... | 6.432623 | 6.916763 | 0.930005 |
# ensure the handle is at offset 0.
handle.seek(0)
try:
return self.jbx.submit_sample(handle)['webids'][0]
except (jbxapi.JoeException, KeyError, IndexError) as e:
raise sandboxapi.SandboxError("error in analyze: {e}".format(e=e)) | def analyze(self, handle, filename) | Submit a file for analysis.
:type handle: File handle
:param handle: Handle to file to upload for analysis.
:type filename: str
:param filename: File name.
:rtype: str
:return: Task ID as a string | 11.658891 | 13.892957 | 0.839194 |
try:
return self.jbx.info(item_id).get('status').lower() == 'finished'
except jbxapi.JoeException:
return False
return False | def check(self, item_id) | Check if an analysis is complete.
:type item_id: str
:param item_id: File ID to check.
:rtype: bool
:return: Boolean indicating if a report is done or not. | 10.704586 | 11.849408 | 0.903386 |
# if the availability flag is raised, return True immediately.
# NOTE: subsequent API failures will lower this flag. we do this here
# to ensure we don't keep hitting Joe with requests while availability
# is there.
if self.server_available:
return True
... | def is_available(self) | Determine if the Joe Sandbox API server is alive.
:rtype: bool
:return: True if service is available, False otherwise. | 10.800068 | 9.846586 | 1.096834 |
if report_format == "json":
report_format = "jsonfixed"
try:
return json.loads(self.jbx.download(item_id, report_format)[1].decode('utf-8'))
except (jbxapi.JoeException, ValueError, IndexError) as e:
raise sandboxapi.SandboxError("error in report fet... | def report(self, item_id, report_format="json") | Retrieves the specified report for the analyzed item, referenced by item_id.
For available report formats, see online Joe Sandbox documentation.
:type item_id: str
:param item_id: File ID number
:type report_format: str
:param report_format: Return format
... | 6.618678 | 6.348575 | 1.042545 |
# The cpu/isolated sysfs was added in Linux 4.2
# (commit 59f30abe94bff50636c8cad45207a01fdcb2ee49)
path = sysfs_path('devices/system/cpu/isolated')
isolated = read_first_line(path)
if isolated:
return parse_cpu_list(isolated)
cmdline = read_first_line(proc_path('cmdline'))
if ... | def get_isolated_cpus() | Get the list of isolated CPUs.
Return a sorted list of CPU identifiers, or return None if no CPU is
isolated. | 6.524326 | 6.214969 | 1.049776 |
inner_loops = kwargs.pop('inner_loops', None)
metadata = kwargs.pop('metadata', None)
self._no_keyword_argument(kwargs)
if not self._check_worker_task():
return None
if args:
func = functools.partial(func, *args)
def task_func(task, lo... | def bench_func(self, name, func, *args, **kwargs) | Benchmark func(*args). | 4.261943 | 4.290844 | 0.993264 |
"True if all suites have one benchmark with the same name"
if any(len(suite) > 1 for suite in self.suites):
return False
names = self.suites[0].get_benchmark_names()
return all(suite.get_benchmark_names() == names
for suite in self.suites[1:]) | def has_same_unique_benchmark(self) | True if all suites have one benchmark with the same name | 3.693968 | 2.618262 | 1.410848 |
client.capture(
'Message',
message=message,
params=tuple(params),
data={
'site': site,
'logger': logger,
},
) | def send_message(message, params, site, logger) | Send a message to the Sentry server | 5.191024 | 3.942485 | 1.316689 |
parser = argparse.ArgumentParser(description='Send logs to Django Sentry.')
parser.add_argument('--sentryconfig', '-c', default=None,
help='A configuration file (.ini, .yaml) of some '
'Sentry integration to extract the Sentry DSN from')
parser.add_... | def get_command_line_args() | CLI command line arguments handling | 4.165234 | 4.112759 | 1.012759 |
if args.sentryconfig:
print('Parsing DSN from %s' % args.sentryconfig)
os.environ['SENTRY_DSN'] = parse_sentry_configuration(args.sentryconfig)
if args.sentrydsn:
print('Using the DSN %s' % args.sentrydsn)
os.environ['SENTRY_DSN'] = args.sentrydsn
if args.nginxerrorpat... | def process_arguments(args) | Deal with arguments passed on the command line | 3.1998 | 3.110461 | 1.028722 |
filetype = os.path.splitext(filename)[-1][1:].lower()
if filetype == 'ini': # Pyramid, Pylons
config = ConfigParser()
config.read(filename)
ini_key = 'dsn'
ini_sections = ['sentry', 'filter:raven']
for section in ini_sections:
if section in config:
... | def parse_sentry_configuration(filename) | Parse Sentry DSN out of an application or Sentry configuration file | 3.907422 | 3.753406 | 1.041033 |
try:
follower = tailhead.follow_path(self.filepath)
except (FileNotFoundError, PermissionError) as err:
raise SystemExit("Error: Can't read logfile %s (%s)" %
(self.filepath, err))
for line in follower:
self.message = No... | def follow_tail(self) | Read (tail and follow) the log file, parse entries and send messages
to Sentry using Raven. | 5.320967 | 4.511196 | 1.179503 |
for item in glob(file_glob, recursive=True):
try:
os.remove(item)
print('%s removed ...' % item)
except OSError:
try:
shutil.rmtree(item)
print('%s/ removed ...' % item)
except OSError as err:
print(... | def rmtree_glob(file_glob) | Platform independent rmtree, which also allows wildcards (globbing) | 2.665666 | 2.719558 | 0.980184 |
with open(join(abspath(dirname(__file__)), filename)) as file:
return file.read() | def read_file(filename) | Read the contents of a file located relative to setup.py | 3.938998 | 3.172203 | 1.241723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.